1 Commits

Author SHA1 Message Date
Sebastian 879bed86d8 chore(deps): update dependency @vue/tsconfig to ^0.9.0
renovate/artifacts Artifact file update failure
2026-05-15 12:51:27 +00:00
55 changed files with 2773 additions and 7543 deletions
-42
View File
@@ -1,42 +0,0 @@
name: Build Test
on:
pull_request:
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: Retrieve Server Install Action
uses: actions/checkout@v6.0.2
with:
repository: Nodarx/action-server-install
ref: main
path: action-server-install
github-server-url: https://git.ktrix.dev
- name: Install Server
uses: ./action-server-install
with:
install-php: 'false'
install-node: 'true'
php-version: '8.5'
node-version: '24'
server-path: './server'
- name: Checkout Pull Request
uses: actions/checkout@v6.0.2
with:
repository: ${{ github.repository }}
ref: ${{ github.event.pull_request.head.sha }}
path: server/modules/chrono_manager
github-server-url: https://git.ktrix.dev
- name: Install dependencies
run: npm ci
working-directory: server/modules/chrono_manager
- name: Build
run: npm run build
working-directory: server/modules/chrono_manager
-42
View File
@@ -1,42 +0,0 @@
name: JS Unit Tests
on:
pull_request:
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: Retrieve Server Install Action
uses: actions/checkout@v6.0.2
with:
repository: Nodarx/action-server-install
ref: main
path: action-server-install
github-server-url: https://git.ktrix.dev
- name: Install Server
uses: ./action-server-install
with:
install-php: 'false'
install-node: 'true'
php-version: '8.5'
node-version: '24'
server-path: './server'
- name: Checkout Pull Request
uses: actions/checkout@v6.0.2
with:
repository: ${{ github.repository }}
ref: ${{ github.event.pull_request.head.sha }}
path: server/modules/chrono_manager
github-server-url: https://git.ktrix.dev
- name: Install dependencies
run: npm ci
working-directory: server/modules/chrono_manager
- name: Run tests
run: npm run test:unit
working-directory: server/modules/chrono_manager
@@ -1,59 +0,0 @@
name: PHP Integration Tests
on:
pull_request:
workflow_dispatch:
jobs:
test:
name: Integration Tests
runs-on: ubuntu-latest
services:
mongo:
image: mongo:8
options: >-
--health-cmd "mongosh --quiet --eval \"db.adminCommand('ping')\""
--health-interval 5s
--health-timeout 5s
--health-retries 12
steps:
- name: Retrieve Server Install Action
uses: actions/checkout@v6.0.2
with:
repository: Nodarx/action-server-install
ref: main
path: action-server-install
github-server-url: https://git.ktrix.dev
- name: Install server
uses: ./action-server-install
with:
install-php: 'true'
php-version: '8.5'
server-path: './server'
database-uri: 'mongodb://mongo:27017/?tls=false'
database-name: 'ktrix_ci'
app-environment: 'test'
- name: Checkout module under test
uses: actions/checkout@v6.0.2
with:
repository: ${{ github.repository }}
ref: ${{ github.event.pull_request.head.sha || github.sha }}
path: server/modules/chrono_manager
github-server-url: https://git.ktrix.dev
- name: Install module dependencies
run: composer install --prefer-dist --no-progress
working-directory: server/modules/chrono_manager
- name: Install and enable module
working-directory: server
run: |
php bin/console module:install chrono_manager
php bin/console module:enable chrono_manager
- name: Run integration tests
working-directory: server/modules/chrono_manager
run: composer test:integration
-42
View File
@@ -1,42 +0,0 @@
name: PHP Unit Tests
on:
pull_request:
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: Retrieve Server Install Action
uses: actions/checkout@v6.0.2
with:
repository: Nodarx/action-server-install
ref: main
path: action-server-install
github-server-url: https://git.ktrix.dev
- name: Install Server
uses: ./action-server-install
with:
install-php: 'true'
install-node: 'false'
php-version: '8.5'
node-version: '24'
server-path: './server'
- name: Checkout Pull Request
uses: actions/checkout@v6.0.2
with:
repository: ${{ github.repository }}
ref: ${{ github.event.pull_request.head.sha }}
path: server/modules/chrono_manager
github-server-url: https://git.ktrix.dev
- name: Install dependencies
run: composer install --prefer-dist --no-progress
working-directory: server/modules/chrono_manager
- name: Run tests
run: composer test:unit
working-directory: server/modules/chrono_manager
+2 -8
View File
@@ -25,17 +25,11 @@ jobs:
tools: composer:v2 tools: composer:v2
- name: Install Renovate - name: Install Renovate
run: | run: npm install -g renovate
npm install --global --no-audit --fund=false \
--prefix "${{ runner.temp }}/renovate-npm" \
--cache "${{ runner.temp }}/renovate-npm-cache" \
renovate
"${{ runner.temp }}/renovate-npm/bin/renovate" --version
- name: Run Renovate - name: Run Renovate
env: env:
RENOVATE_TOKEN: ${{ secrets.RENOVATE_TOKEN }} RENOVATE_TOKEN: ${{ secrets.RENOVATE_TOKEN }}
RENOVATE_PLATFORM: gitea RENOVATE_PLATFORM: gitea
RENOVATE_ENDPOINT: https://git.ktrix.dev/api/v1 RENOVATE_ENDPOINT: https://git.ktrix.dev/api/v1
run: | run: renovate ${{ gitea.repository }}
"${{ runner.temp }}/renovate-npm/bin/renovate" ${{ gitea.repository }}
+4 -1
View File
@@ -14,7 +14,10 @@ node_modules/
# Backend development # Backend development
/lib/vendor/ /lib/vendor/
coverage/ coverage/
*.cache phpunit.xml.cache
.phpunit.result.cache
.php-cs-fixer.cache
.phpstan.cache
.phpactor/ .phpactor/
# Editors # Editors
+2 -15
View File
@@ -10,30 +10,17 @@
"config": { "config": {
"optimize-autoloader": true, "optimize-autoloader": true,
"platform": { "platform": {
"php": "8.3" "php": "8.2"
}, },
"autoloader-suffix": "ChronoManager", "autoloader-suffix": "ChronoManager",
"vendor-dir": "lib/vendor" "vendor-dir": "lib/vendor"
}, },
"require": { "require": {
"php": ">=8.3 <=8.5", "php": ">=8.2 <=8.5"
"sabre/vobject": "^5.0"
},
"require-dev": {
"phpunit/phpunit": "^12.0"
}, },
"autoload": { "autoload": {
"psr-4": { "psr-4": {
"KTXM\\ChronoManager\\": "lib/" "KTXM\\ChronoManager\\": "lib/"
} }
},
"autoload-dev": {
"psr-4": {
"KTXT\\ChronoManager\\Tests\\": "tests/php/"
}
},
"scripts": {
"test:unit": "phpunit --configuration tests/php/phpunit.xml --testsuite \"Unit Tests\" --colors=always --testdox",
"test:integration": "phpunit --configuration tests/php/phpunit.xml --testsuite \"Integration Tests\" --colors=always --testdox"
} }
} }
Generated
+8 -1934
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
-310
View File
@@ -1,310 +0,0 @@
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: Sebastian Krupinski <krupinski01@gmail.com>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace KTXM\ChronoManager\Conversion;
use DateInterval;
use DateTimeImmutable;
use DateTimeZone;
use InvalidArgumentException;
use KTXF\Chrono\Entity as E;
use KTXF\Chrono\Entity\Property as P;
use Sabre\VObject\Component;
use Sabre\VObject\Component\VEvent;
use Sabre\VObject\Component\VJournal;
use Sabre\VObject\Component\VTodo;
use Throwable;
/** Decodes the three RFC 5545 calendar object types into Chrono entities. */
class IcalDecoder {
public function fromComponent(Component $component): E\EventObject|E\TaskObject|E\JournalObject {
return match (true) {
$component instanceof VEvent => $this->mapEvent($component),
$component instanceof VTodo => $this->mapTask($component),
$component instanceof VJournal => $this->mapJournal($component),
default => throw new InvalidArgumentException('Unsupported iCalendar component: ' . $component->name),
};
}
private function mapEvent(VEvent $event): E\EventObject {
$object = new E\EventObject();
$this->mapCommon($event, $object);
$startProperty = $event->DTSTART ?? null;
$object->startsOn = $this->dateTime($event, 'DTSTART');
$object->endsOn = $this->dateTime($event, 'DTEND');
$object->duration = $this->duration($event);
if ($object->endsOn === null && $object->startsOn !== null && $object->duration !== null) {
$object->endsOn = $object->startsOn->add($object->duration);
}
$object->timeless = $startProperty !== null && !$startProperty->hasTime();
$object->sequence = isset($event->SEQUENCE) ? (int)(string)$event->SEQUENCE : null;
$object->timeZone = $this->timeZone($startProperty);
$object->startsTZ = $this->timeZone($startProperty);
$object->endsTZ = $this->timeZone($event->DTEND ?? null);
$object->priority = isset($event->PRIORITY) ? (int)(string)$event->PRIORITY : null;
$object->color = $this->text($event, 'COLOR');
$object->availability = strtoupper($this->text($event, 'TRANSP') ?? '') === 'TRANSPARENT'
? P\EventAvailabilityTypes::Free
: P\EventAvailabilityTypes::Busy;
$object->sensitivity = $this->eventSensitivity($event);
if ($location = $this->text($event, 'LOCATION')) {
$physical = new P\EventLocationPhysicalObject();
$physical->label = $location;
$physical->relation = 'start';
$object->locationsPhysical->add($physical, $this->key());
}
if ($url = $this->text($event, 'URL')) {
$virtual = new P\EventLocationVirtualObject();
$virtual->location = $url;
$object->locationsVirtual->add($virtual, $this->key());
}
$this->mapOrganizer($event, $object);
$this->mapParticipants($event, $object);
$object->pattern = $this->eventRecurrence($event);
return $object;
}
private function mapTask(VTodo $task): E\TaskObject {
$object = new E\TaskObject();
$this->mapCommon($task, $object);
$object->startsOn = $this->dateTime($task, 'DTSTART');
$object->dueOn = $this->dateTime($task, 'DUE');
$object->completedOn = $this->dateTime($task, 'COMPLETED');
if ($object->dueOn === null && $object->startsOn !== null && ($duration = $this->duration($task)) !== null) {
$object->dueOn = $object->startsOn->add($duration);
}
$object->status = match (strtoupper($this->text($task, 'STATUS') ?? '')) {
'NEEDS-ACTION' => P\TaskStatusTypes::NeedsAction,
'IN-PROCESS' => P\TaskStatusTypes::InProcess,
'COMPLETED' => P\TaskStatusTypes::Completed,
'CANCELLED' => P\TaskStatusTypes::Cancelled,
default => null,
};
$object->priority = isset($task->PRIORITY) ? (int)(string)$task->PRIORITY : null;
$progress = $task->{'PERCENT-COMPLETE'} ?? $task->PERCENT ?? null;
$object->progress = $progress !== null ? max(0, min(100, (int)(string)$progress)) : null;
$object->color = $this->text($task, 'COLOR');
$object->notes = $this->joinedText($task, 'COMMENT');
$object->recurrence = $this->taskRecurrence($task);
$this->mapAttachments($task, $object->attachments);
return $object;
}
private function mapJournal(VJournal $journal): E\JournalObject {
$object = new E\JournalObject();
$this->mapCommon($journal, $object);
$object->content = $this->joinedText($journal, 'DESCRIPTION');
$object->startsOn = $this->dateTime($journal, 'DTSTART');
$object->endsOn = $this->dateTime($journal, 'DTEND');
if ($object->endsOn === null && $object->startsOn !== null && isset($journal->DTSTART) && !$journal->DTSTART->hasTime()) {
$object->endsOn = $object->startsOn->modify('+1 day');
}
$object->status = match (strtoupper($this->text($journal, 'STATUS') ?? '')) {
'DRAFT' => P\JournalStatusTypes::Draft,
'FINAL' => P\JournalStatusTypes::Final,
'CANCELLED' => P\JournalStatusTypes::Cancelled,
default => null,
};
$object->visibility = match (strtoupper($this->text($journal, 'CLASS') ?? '')) {
'PUBLIC' => P\JournalVisibilityTypes::Public,
'PRIVATE' => P\JournalVisibilityTypes::Private,
'CONFIDENTIAL' => P\JournalVisibilityTypes::Confidential,
default => null,
};
$this->mapAttachments($journal, $object->attachments);
return $object;
}
private function mapCommon(
Component $component,
E\EventObject|E\TaskObject|E\JournalObject $object,
): void {
$object->urid = $this->text($component, 'UID');
$object->created = $this->dateTime($component, 'CREATED');
$object->modified = $this->dateTime($component, 'LAST-MODIFIED');
$object->label = $this->text($component, 'SUMMARY');
$object->description = $this->text($component, 'DESCRIPTION');
foreach ($this->categories($component) as $tag) {
$object->tags->add($tag);
}
}
private function mapOrganizer(VEvent $event, E\EventObject $object): void {
if (!isset($event->ORGANIZER)) return;
$object->organizer->realm = P\EventParticipantRealm::External;
$object->organizer->address = $this->address((string)$event->ORGANIZER);
$object->organizer->name = $this->parameter($event->ORGANIZER, 'CN');
}
private function mapParticipants(VEvent $event, E\EventObject $object): void {
foreach ($event->select('ATTENDEE') as $attendee) {
$participant = new P\EventParticipantObject();
$participant->realm = P\EventParticipantRealm::External;
$participant->address = $this->address((string)$attendee);
$participant->name = $this->parameter($attendee, 'CN');
$participant->language = $this->parameter($attendee, 'LANGUAGE');
$participant->type = match (strtoupper($this->parameter($attendee, 'CUTYPE') ?? '')) {
'GROUP' => P\EventParticipantTypes::Group,
'RESOURCE' => P\EventParticipantTypes::Resource,
'ROOM' => P\EventParticipantTypes::Location,
default => P\EventParticipantTypes::Individual,
};
$participant->status = match (strtoupper($this->parameter($attendee, 'PARTSTAT') ?? '')) {
'ACCEPTED' => P\EventParticipantStatusTypes::Accepted,
'DECLINED' => P\EventParticipantStatusTypes::Declined,
'TENTATIVE' => P\EventParticipantStatusTypes::Tentative,
'DELEGATED' => P\EventParticipantStatusTypes::Delegated,
default => P\EventParticipantStatusTypes::None,
};
$participant->roles->add(match (strtoupper($this->parameter($attendee, 'ROLE') ?? '')) {
'CHAIR' => P\EventParticipantRoleTypes::Chair,
'OPT-PARTICIPANT' => P\EventParticipantRoleTypes::Optional,
'NON-PARTICIPANT' => P\EventParticipantRoleTypes::Informational,
default => P\EventParticipantRoleTypes::Attendee,
});
$object->participants->add($participant, $this->key());
}
}
private function eventRecurrence(VEvent $event): ?P\EventOccurrenceObject {
if (!isset($event->RRULE)) return null;
$rule = $event->RRULE->getParts();
$precision = match (strtoupper((string)($rule['FREQ'] ?? ''))) {
'YEARLY' => P\EventOccurrencePrecisionTypes::Yearly,
'MONTHLY' => P\EventOccurrencePrecisionTypes::Monthly,
'WEEKLY' => P\EventOccurrencePrecisionTypes::Weekly,
'DAILY' => P\EventOccurrencePrecisionTypes::Daily,
'HOURLY' => P\EventOccurrencePrecisionTypes::Hourly,
'MINUTELY' => P\EventOccurrencePrecisionTypes::Minutely,
'SECONDLY' => P\EventOccurrencePrecisionTypes::Secondly,
default => null,
};
if ($precision === null) return null;
$object = new P\EventOccurrenceObject();
$object->pattern = P\EventOccurrencePatternTypes::Relative;
$object->precision = $precision;
$object->interval = (int)($rule['INTERVAL'] ?? 1);
$object->iterations = isset($rule['COUNT']) ? (int)$rule['COUNT'] : null;
$object->concludes = isset($rule['UNTIL']) ? $this->parseDate((string)$rule['UNTIL']) : null;
$object->onDayOfWeek = $this->weekdays($rule['BYDAY'] ?? []);
$object->onDayOfMonth = $this->integers($rule['BYMONTHDAY'] ?? []);
$object->onDayOfYear = $this->integers($rule['BYYEARDAY'] ?? []);
$object->onWeekOfYear = $this->integers($rule['BYWEEKNO'] ?? []);
$object->onMonthOfYear = $this->integers($rule['BYMONTH'] ?? []);
$object->onHour = $this->integers($rule['BYHOUR'] ?? []);
$object->onMinute = $this->integers($rule['BYMINUTE'] ?? []);
$object->onSecond = $this->integers($rule['BYSECOND'] ?? []);
$object->onPosition = $this->integers($rule['BYSETPOS'] ?? []);
return $object;
}
private function taskRecurrence(VTodo $task): ?P\TaskRecurrenceObject {
if (!isset($task->RRULE)) return null;
$rule = $task->RRULE->getParts();
$frequency = strtolower((string)($rule['FREQ'] ?? ''));
if ($frequency === '') return null;
$object = new P\TaskRecurrenceObject();
$object->frequency = $frequency;
$object->interval = (int)($rule['INTERVAL'] ?? 1);
$object->count = isset($rule['COUNT']) ? (int)$rule['COUNT'] : null;
$object->until = isset($rule['UNTIL']) ? $this->parseDate((string)$rule['UNTIL']) : null;
$object->byDay = array_map('strval', $this->values($rule['BYDAY'] ?? []));
$object->byMonthDay = $this->integers($rule['BYMONTHDAY'] ?? []);
$object->byMonth = $this->integers($rule['BYMONTH'] ?? []);
return $object;
}
private function mapAttachments(Component $component, $attachments): void {
foreach ($component->select('ATTACH') as $property) {
$attachment = new P\AttachmentObject();
$attachment->uri = trim((string)$property) ?: null;
$attachment->type = $this->parameter($property, 'FMTTYPE');
$attachment->label = $this->parameter($property, 'FILENAME') ?? $this->parameter($property, 'X-FILENAME');
$attachments->add($attachment, $this->key());
}
}
private function eventSensitivity(VEvent $event): ?P\EventSensitivityTypes {
return match (strtoupper($this->text($event, 'CLASS') ?? '')) {
'PUBLIC' => P\EventSensitivityTypes::Public,
'PRIVATE', 'CONFIDENTIAL' => P\EventSensitivityTypes::Private,
default => null,
};
}
private function dateTime(Component $component, string $name): ?DateTimeImmutable {
if (!isset($component->$name)) return null;
try { return $component->$name->getDateTime(); }
catch (Throwable) { return $this->parseDate((string)$component->$name); }
}
private function duration(Component $component): ?DateInterval {
if (!isset($component->DURATION)) return null;
try { return $component->DURATION->getDateInterval(); }
catch (Throwable) { try { return new DateInterval((string)$component->DURATION); } catch (Throwable) { return null; } }
}
private function timeZone($property): ?DateTimeZone {
$tzid = $property?->offsetGet('TZID');
if ($tzid === null || trim((string)$tzid) === '') return null;
try { return new DateTimeZone((string)$tzid); } catch (Throwable) { return null; }
}
private function parseDate(string $value): ?DateTimeImmutable {
try { return new DateTimeImmutable($value); } catch (Throwable) { return null; }
}
private function text(Component $component, string $name): ?string {
$value = isset($component->$name) ? trim((string)$component->$name) : '';
return $value !== '' ? $value : null;
}
private function joinedText(Component $component, string $name): ?string {
$values = array_values(array_filter(array_map(static fn($property): string => trim((string)$property), $component->select($name))));
return $values !== [] ? implode("\n\n", $values) : null;
}
private function parameter($property, string $name): ?string {
$value = $property[$name] ?? null;
return $value !== null && trim((string)$value) !== '' ? trim((string)$value) : null;
}
private function address(string $value): string {
return preg_replace('/^mailto:/i', '', trim($value)) ?? trim($value);
}
/** @return list<string> */
private function categories(Component $component): array {
$result = [];
foreach ($component->select('CATEGORIES') as $property) {
foreach ($property->getParts() as $part) {
if (trim((string)$part) !== '') $result[] = trim((string)$part);
}
}
return array_values(array_unique($result));
}
private function values(string|array $values): array { return is_array($values) ? $values : [$values]; }
private function integers(string|array $values): array { return array_map('intval', $this->values($values)); }
private function weekdays(string|array $values): array {
$days = ['MO' => 1, 'TU' => 2, 'WE' => 3, 'TH' => 4, 'FR' => 5, 'SA' => 6, 'SU' => 7];
$result = [];
foreach ($this->values($values) as $value) {
$day = strtoupper(substr((string)$value, -2));
if (isset($days[$day])) $result[] = $days[$day];
}
return $result;
}
private function key(): string { return bin2hex(random_bytes(8)); }
}
-387
View File
@@ -1,387 +0,0 @@
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: Sebastian Krupinski <krupinski01@gmail.com>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace KTXM\ChronoManager\Conversion;
use DateTime;
use DateTimeInterface;
use DateTimeZone;
use Generator;
use KTXF\Chrono\Entity as E;
use KTXF\Chrono\Entity\Property as P;
use Sabre\VObject\Component;
use Sabre\VObject\Component\VCalendar;
/**
* Encodes Chrono entities into the three RFC 5545 calendar object types.
*
* Mirror image of {@see IcalDecoder}: every property the decoder reads is
* written back, so decode -> encode -> decode is stable.
*/
class IcalEncoder {
private const PRODID = '-//KTX//Chrono//EN';
/**
* Streams a complete iCalendar document, one chunk per component, so large
* exports never hold the whole document in memory.
*
* @param iterable<E\EventObject|E\TaskObject|E\JournalObject> $entities
* @return Generator<string>
*/
public function toIcs(iterable $entities): Generator {
yield "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:" . self::PRODID . "\r\nCALSCALE:GREGORIAN\r\n";
$document = new VCalendar();
foreach ($entities as $entity) {
$component = $this->toComponent($entity, $document);
yield $component->serialize();
$document->remove($component);
}
yield "END:VCALENDAR\r\n";
}
/** Convenience wrapper around {@see toIcs()} for single-document callers. */
public function toIcsString(iterable $entities): string {
return implode('', iterator_to_array($this->toIcs($entities), false));
}
/**
* Adds the entity to $document as a VEVENT/VTODO/VJOURNAL and returns it.
*
* $uidFallback is used when the entity carries no urid (e.g. entities that
* were never imported); DAV passes the provider entity identifier here so
* object UIDs stay stable across requests.
*/
public function toComponent(
E\EventObject|E\TaskObject|E\JournalObject $entity,
VCalendar $document,
?string $uidFallback = null,
): Component {
return match (true) {
$entity instanceof E\EventObject => $this->encodeEvent($entity, $document, $uidFallback),
$entity instanceof E\TaskObject => $this->encodeTask($entity, $document, $uidFallback),
$entity instanceof E\JournalObject => $this->encodeJournal($entity, $document, $uidFallback),
};
}
private function encodeEvent(E\EventObject $entity, VCalendar $document, ?string $uidFallback): Component {
$event = $this->createComponent($document, 'VEVENT', $entity, $uidFallback);
$this->addDate($event, 'DTSTART', $entity->startsOn, (bool)$entity->timeless);
$this->addDate($event, 'DTEND', $entity->endsOn, (bool)$entity->timeless);
if ($entity->sequence !== null) {
$event->add('SEQUENCE', (string)$entity->sequence);
}
if ($entity->priority !== null) {
$event->add('PRIORITY', (string)$entity->priority);
}
if ($entity->color !== null) {
$event->add('COLOR', $entity->color);
}
// OPAQUE is the RFC 5545 default and what the decoder assumes when
// TRANSP is absent, so only the non-default value is emitted.
if ($entity->availability === P\EventAvailabilityTypes::Free) {
$event->add('TRANSP', 'TRANSPARENT');
}
if ($entity->sensitivity !== null) {
$event->add('CLASS', match ($entity->sensitivity) {
P\EventSensitivityTypes::Public => 'PUBLIC',
P\EventSensitivityTypes::Private => 'PRIVATE',
P\EventSensitivityTypes::Secret => 'CONFIDENTIAL',
});
}
foreach ($entity->locationsPhysical as $location) {
if ($location->label !== null && $location->label !== '') {
$event->add('LOCATION', $location->label);
break;
}
}
foreach ($entity->locationsVirtual as $location) {
if ($location->location !== null && $location->location !== '') {
$event->add('URL', $location->location);
break;
}
}
$this->encodeOrganizer($event, $entity->organizer);
foreach ($entity->participants as $participant) {
$this->encodeParticipant($event, $participant);
}
if ($entity->pattern !== null && ($rule = $this->eventRecurrenceRule($entity->pattern)) !== null) {
$event->add('RRULE', $rule);
}
return $event;
}
private function encodeTask(E\TaskObject $entity, VCalendar $document, ?string $uidFallback): Component {
$task = $this->createComponent($document, 'VTODO', $entity, $uidFallback);
$this->addDate($task, 'DTSTART', $entity->startsOn);
$this->addDate($task, 'DUE', $entity->dueOn);
$this->addDate($task, 'COMPLETED', $entity->completedOn);
if ($entity->status !== null) {
$task->add('STATUS', strtoupper($entity->status->value));
}
if ($entity->priority !== null) {
$task->add('PRIORITY', (string)$entity->priority);
}
if ($entity->progress !== null) {
$task->add('PERCENT-COMPLETE', (string)$entity->progress);
}
if ($entity->color !== null) {
$task->add('COLOR', $entity->color);
}
if ($entity->notes !== null) {
$task->add('COMMENT', $entity->notes);
}
if ($entity->recurrence !== null && ($rule = $this->taskRecurrenceRule($entity->recurrence)) !== null) {
$task->add('RRULE', $rule);
}
$this->encodeAttachments($task, $entity->attachments);
return $task;
}
private function encodeJournal(E\JournalObject $entity, VCalendar $document, ?string $uidFallback): Component {
$journal = $this->createComponent($document, 'VJOURNAL', $entity, $uidFallback, description: false);
// The decoder fills both content and description from DESCRIPTION;
// content is the journal body and wins on the way out.
if (($body = $entity->content ?? $entity->description) !== null) {
$journal->add('DESCRIPTION', $body);
}
$this->addDate($journal, 'DTSTART', $entity->startsOn);
if ($entity->status !== null) {
$journal->add('STATUS', strtoupper($entity->status->value));
}
if ($entity->visibility !== null) {
$journal->add('CLASS', strtoupper($entity->visibility->value));
}
$this->encodeAttachments($journal, $entity->attachments);
return $journal;
}
/**
* Creates the bare component and writes the properties common to all
* three types: UID, DTSTAMP, CREATED, LAST-MODIFIED, SUMMARY,
* DESCRIPTION, CATEGORIES.
*/
private function createComponent(
VCalendar $document,
string $name,
E\EventObject|E\TaskObject|E\JournalObject $entity,
?string $uidFallback,
bool $description = true,
): Component {
// Suppress sabre's auto-generated UID/DTSTAMP defaults: UID is set
// explicitly below and DTSTAMP must be deterministic — the DAV ETag is
// md5 of the serialized output, and a "now" DTSTAMP makes an unchanged
// entity produce a new ETag on every request (perpetual client syncs).
/** @var Component $component */
$component = $document->add($name, [], false);
$uid = $entity->urid ?? $uidFallback;
if ($uid !== null && $uid !== '') {
$component->add('UID', $uid);
}
$stamp = $entity->modified ?? $entity->created;
$component->add('DTSTAMP', $stamp !== null ? $this->utc($stamp) : (new DateTime('@0'))->setTimezone(new DateTimeZone('UTC')));
if ($entity->created !== null) {
$component->add('CREATED', $this->utc($entity->created));
}
if ($entity->modified !== null) {
$component->add('LAST-MODIFIED', $this->utc($entity->modified));
}
if ($entity->label !== null) {
$component->add('SUMMARY', $entity->label);
}
if ($description && $entity->description !== null) {
$component->add('DESCRIPTION', $entity->description);
}
$tags = array_values(array_filter(array_map('strval', $entity->tags->getArrayCopy()), static fn(string $tag): bool => $tag !== ''));
if ($tags !== []) {
$component->add('CATEGORIES', $tags);
}
return $component;
}
private function encodeOrganizer(Component $component, P\EventOrganizerObject $organizer): void {
if ($organizer->address === null || $organizer->address === '') {
return;
}
$parameters = [];
if ($organizer->name !== null && $organizer->name !== '') {
$parameters['CN'] = $organizer->name;
}
$component->add('ORGANIZER', 'mailto:' . $organizer->address, $parameters);
}
private function encodeParticipant(Component $component, P\EventParticipantObject $participant): void {
if ($participant->address === null || $participant->address === '') {
return;
}
$parameters = [];
if ($participant->name !== null && $participant->name !== '') {
$parameters['CN'] = $participant->name;
}
if ($participant->language !== null && $participant->language !== '') {
$parameters['LANGUAGE'] = $participant->language;
}
// Defaults (INDIVIDUAL / no PARTSTAT / ATTENDEE role) are what the
// decoder assumes for absent parameters, so only non-defaults are emitted.
$type = match ($participant->type) {
P\EventParticipantTypes::Group => 'GROUP',
P\EventParticipantTypes::Resource => 'RESOURCE',
P\EventParticipantTypes::Location => 'ROOM',
default => null,
};
if ($type !== null) {
$parameters['CUTYPE'] = $type;
}
$status = match ($participant->status) {
P\EventParticipantStatusTypes::Accepted => 'ACCEPTED',
P\EventParticipantStatusTypes::Declined => 'DECLINED',
P\EventParticipantStatusTypes::Tentative => 'TENTATIVE',
P\EventParticipantStatusTypes::Delegated => 'DELEGATED',
default => null,
};
if ($status !== null) {
$parameters['PARTSTAT'] = $status;
}
foreach ($participant->roles as $role) {
$token = match ($role) {
P\EventParticipantRoleTypes::Chair => 'CHAIR',
P\EventParticipantRoleTypes::Optional => 'OPT-PARTICIPANT',
P\EventParticipantRoleTypes::Informational => 'NON-PARTICIPANT',
default => null,
};
if ($token !== null) {
$parameters['ROLE'] = $token;
}
break;
}
$component->add('ATTENDEE', 'mailto:' . $participant->address, $parameters);
}
private function eventRecurrenceRule(P\EventOccurrenceObject $pattern): ?string {
$frequency = match ($pattern->precision) {
P\EventOccurrencePrecisionTypes::Yearly => 'YEARLY',
P\EventOccurrencePrecisionTypes::Monthly => 'MONTHLY',
P\EventOccurrencePrecisionTypes::Weekly => 'WEEKLY',
P\EventOccurrencePrecisionTypes::Daily => 'DAILY',
P\EventOccurrencePrecisionTypes::Hourly => 'HOURLY',
P\EventOccurrencePrecisionTypes::Minutely => 'MINUTELY',
P\EventOccurrencePrecisionTypes::Secondly => 'SECONDLY',
default => null,
};
if ($frequency === null) {
return null;
}
$parts = ['FREQ=' . $frequency];
if ($pattern->interval !== null && $pattern->interval > 1) {
$parts[] = 'INTERVAL=' . $pattern->interval;
}
if ($pattern->iterations !== null) {
$parts[] = 'COUNT=' . $pattern->iterations;
}
if ($pattern->concludes !== null) {
$parts[] = 'UNTIL=' . $this->utc($pattern->concludes)->format('Ymd\THis\Z');
}
$this->appendRulePart($parts, 'BYDAY', $this->weekdayTokens($pattern->onDayOfWeek));
$this->appendRulePart($parts, 'BYMONTHDAY', $pattern->onDayOfMonth);
$this->appendRulePart($parts, 'BYYEARDAY', $pattern->onDayOfYear);
$this->appendRulePart($parts, 'BYWEEKNO', $pattern->onWeekOfYear);
$this->appendRulePart($parts, 'BYMONTH', $pattern->onMonthOfYear);
$this->appendRulePart($parts, 'BYHOUR', $pattern->onHour);
$this->appendRulePart($parts, 'BYMINUTE', $pattern->onMinute);
$this->appendRulePart($parts, 'BYSECOND', $pattern->onSecond);
$this->appendRulePart($parts, 'BYSETPOS', $pattern->onPosition);
return implode(';', $parts);
}
private function taskRecurrenceRule(P\TaskRecurrenceObject $recurrence): ?string {
if ($recurrence->frequency === null || $recurrence->frequency === '') {
return null;
}
$parts = ['FREQ=' . strtoupper($recurrence->frequency)];
if ($recurrence->interval !== null && $recurrence->interval > 1) {
$parts[] = 'INTERVAL=' . $recurrence->interval;
}
if ($recurrence->count !== null) {
$parts[] = 'COUNT=' . $recurrence->count;
}
if ($recurrence->until !== null) {
$parts[] = 'UNTIL=' . $this->utc($recurrence->until)->format('Ymd\THis\Z');
}
$this->appendRulePart($parts, 'BYDAY', array_map('strval', $recurrence->byDay));
$this->appendRulePart($parts, 'BYMONTHDAY', $recurrence->byMonthDay);
$this->appendRulePart($parts, 'BYMONTH', $recurrence->byMonth);
return implode(';', $parts);
}
private function appendRulePart(array &$parts, string $name, array $values): void {
if ($values !== []) {
$parts[] = $name . '=' . implode(',', $values);
}
}
/** @return list<string> inverse of the decoder's MO..SU => 1..7 map */
private function weekdayTokens(array $days): array {
$tokens = [1 => 'MO', 2 => 'TU', 3 => 'WE', 4 => 'TH', 5 => 'FR', 6 => 'SA', 7 => 'SU'];
$result = [];
foreach ($days as $day) {
if (isset($tokens[(int)$day])) {
$result[] = $tokens[(int)$day];
}
}
return $result;
}
private function encodeAttachments(Component $component, $attachments): void {
foreach ($attachments as $attachment) {
if ($attachment->uri === null || $attachment->uri === '') {
continue;
}
$parameters = [];
if ($attachment->type !== null && $attachment->type !== '') {
$parameters['FMTTYPE'] = $attachment->type;
}
if ($attachment->label !== null && $attachment->label !== '') {
$parameters['FILENAME'] = $attachment->label;
}
$component->add('ATTACH', $attachment->uri, $parameters);
}
}
/**
* Date-times are always emitted in UTC ("...Z"): a value carrying a fixed
* numeric offset (e.g. from an RFC3339 string) would otherwise serialize
* as a TZID with no matching VTIMEZONE, which clients reject. Timeless
* (all-day) values are emitted as DATE.
*/
private function addDate(Component $component, string $name, ?DateTimeInterface $value, bool $dateOnly = false): void {
if ($value === null) {
return;
}
if ($dateOnly) {
$component->add($name, $value->format('Ymd'), ['VALUE' => 'DATE']);
} else {
$component->add($name, $this->utc($value));
}
}
private function utc(DateTimeInterface $value): DateTime {
return (new DateTime('@' . $value->getTimestamp()))->setTimezone(new DateTimeZone('UTC'));
}
}
-93
View File
@@ -1,93 +0,0 @@
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: Sebastian Krupinski <krupinski01@gmail.com>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace KTXM\ChronoManager\Export;
use Generator;
use KTXF\Chrono\Entity\EventObject;
use KTXF\Chrono\Entity\JournalObject;
use KTXF\Chrono\Entity\TaskObject;
use KTXF\Resource\Identifier\CollectionIdentifier;
use KTXF\Resource\Identifier\EntityIdentifier;
use KTXF\Resource\Identifier\ResourceIdentifiers;
use KTXM\ChronoManager\Manager;
use KTXM\ChronoManager\Conversion\IcalEncoder;
use Psr\Log\LoggerInterface;
use Throwable;
/** Exports Chrono entities as a streamed RFC 5545 iCalendar document. */
class ExportService {
public function __construct(
private readonly Manager $manager,
private readonly IcalEncoder $encoder,
private readonly LoggerInterface $logger,
) {}
/**
* @param ResourceIdentifiers $sources collection and/or entity identifiers
* @return Generator<string> iCalendar document chunks
*/
public function export(ResourceIdentifiers $sources, string $tenantId, string $userId): Generator {
yield from $this->encoder->toIcs($this->entities($sources, $tenantId, $userId));
}
/** @return Generator<EventObject|TaskObject|JournalObject> */
private function entities(ResourceIdentifiers $sources, string $tenantId, string $userId): Generator {
$collections = [];
$entities = [];
foreach ($sources as $source) {
if ($source instanceof EntityIdentifier) {
$entities[] = $source;
} elseif ($source instanceof CollectionIdentifier) {
$collections[] = $source;
}
}
if ($collections !== []) {
$listed = $this->manager->entityListBulk($tenantId, $userId, new ResourceIdentifiers($collections));
foreach ($listed as $services) {
foreach ($services as $collectionSets) {
foreach ($collectionSets as $set) {
foreach ((array)$set as $entity) {
if (($hydrated = $this->hydrate($entity)) !== null) {
yield $hydrated;
}
}
}
}
}
}
if ($entities !== []) {
foreach ($this->manager->entityFetchBulk($tenantId, $userId, ...$entities) as $entity) {
if (($hydrated = $this->hydrate($entity)) !== null) {
yield $hydrated;
}
}
}
}
/** Skip-and-continue on per-entity failure, matching import's error-tolerant posture. */
private function hydrate(mixed $entity): EventObject|TaskObject|JournalObject|null {
if (!is_object($entity)) {
return null;
}
try {
$hydrated = $entity->getProperties();
// DAV-created entities may carry no urid; the provider identifier
// keeps exported UIDs stable in that case.
$hydrated->urid ??= (string)$entity->identifier();
return $hydrated;
} catch (Throwable $t) {
$this->logger->warning('Skipping entity during export', ['exception' => $t]);
return null;
}
}
}
-25
View File
@@ -1,25 +0,0 @@
<?php
declare(strict_types=1);
namespace KTXM\ChronoManager\Import;
use KTXM\ChronoManager\Stream\ExpectedTotal;
final readonly class ImportCountEvent implements ImportEvent, ExpectedTotal {
public function __construct(
public int $total,
) {}
public function expectedTotal(): int {
return $this->total;
}
/**
* @return array{total: int}
*/
public function jsonSerialize(): array {
return ['total' => $this->total];
}
}
-17
View File
@@ -1,17 +0,0 @@
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: Sebastian Krupinski <krupinski01@gmail.com>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace KTXM\ChronoManager\Import;
enum ImportDisposition: string {
case Created = 'created';
case Updated = 'updated';
case Exists = 'exists';
case Error = 'error';
}
-15
View File
@@ -1,15 +0,0 @@
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: Sebastian Krupinski <krupinski01@gmail.com>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace KTXM\ChronoManager\Import;
use JsonSerializable;
interface ImportEvent extends JsonSerializable {
}
-37
View File
@@ -1,37 +0,0 @@
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: Sebastian Krupinski <krupinski01@gmail.com>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace KTXM\ChronoManager\Import;
final readonly class ImportObjectEvent implements ImportEvent {
/**
* @param list<string> $errors
*/
public function __construct(
public ?string $identifier,
public ImportDisposition $disposition,
public array $errors = [],
) {}
public function isError(): bool {
return $this->disposition === ImportDisposition::Error;
}
/**
* @return array{identifier: ?string, disposition: string, errors: list<string>}
*/
public function jsonSerialize(): array {
return [
'identifier' => $this->identifier,
'disposition' => $this->disposition->value,
'errors' => $this->errors,
];
}
}
-66
View File
@@ -1,66 +0,0 @@
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: Sebastian Krupinski <krupinski01@gmail.com>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace KTXM\ChronoManager\Import;
use InvalidArgumentException;
final class ImportOptions {
public const ERROR_CONTINUE = 0;
public const ERROR_FAIL = 1;
public const ERROR_OPTIONS = [self::ERROR_CONTINUE, self::ERROR_FAIL];
/** Overwrite an existing entity when the same UID is already present. */
private bool $supersede = false;
/** Emit an ImportCountEvent (discovered total) before the object stream. */
private bool $counts = true;
/** How to handle per-object errors. */
private int $errors = self::ERROR_CONTINUE;
public function getSupersede(): bool {
return $this->supersede;
}
public function setSupersede(bool $value): void {
$this->supersede = $value;
}
public function getCounts(): bool {
return $this->counts;
}
public function setCounts(bool $value): void {
$this->counts = $value;
}
public function getErrors(): int {
return $this->errors;
}
public function setErrors(int $value): void {
if (!in_array($value, self::ERROR_OPTIONS, true)) {
throw new InvalidArgumentException('Invalid errors option specified');
}
$this->errors = $value;
}
public static function fromArray(array $data): self {
$options = new self();
$options->supersede = (bool)($data['supersede'] ?? false);
$options->counts = (bool)($data['counts'] ?? true);
$options->errors = (int)($data['errors'] ?? self::ERROR_CONTINUE);
if (!in_array($options->errors, [self::ERROR_CONTINUE, self::ERROR_FAIL], true)) {
throw new InvalidArgumentException('Invalid errors option specified');
}
return $options;
}
}
-75
View File
@@ -1,75 +0,0 @@
<?php
declare(strict_types=1);
namespace KTXM\ChronoManager\Import;
use Generator;
use InvalidArgumentException;
use KTXF\Resource\Identifier\CollectionIdentifier;
use KTXM\ChronoManager\Manager;
use KTXM\ChronoManager\Conversion\IcalDecoder;
use Sabre\VObject\Component\VCalendar;
use Sabre\VObject\Component\VEvent;
use Sabre\VObject\Component\VJournal;
use Sabre\VObject\Component\VTodo;
use Sabre\VObject\Parser\MimeDir;
use Sabre\VObject\Reader;
use Throwable;
/** Imports the three RFC 5545 calendar object types into Chrono entities. */
class ImportService {
public function __construct(
private readonly Manager $manager,
private readonly IcalDecoder $decoder,
) {}
/**
* @param resource $source readable, seekable iCalendar resource
* @return Generator<int, ImportEvent>
*/
public function import($source, CollectionIdentifier $target, ImportOptions $options, string $tenantId, string $userId): Generator {
if (!is_resource($source)) {
throw new InvalidArgumentException('Invalid import source: must be a file resource');
}
try {
rewind($source);
$calendar = Reader::read($source, MimeDir::OPTION_FORGIVING | MimeDir::OPTION_IGNORE_INVALID_LINES);
if (!$calendar instanceof VCalendar) {
throw new InvalidArgumentException('Supplied input is not an iCalendar document');
}
} catch (Throwable $e) {
if ($options->getCounts()) {
yield new ImportCountEvent(0);
}
yield new ImportObjectEvent(null, ImportDisposition::Error, ['Malformed iCalendar: ' . $e->getMessage()]);
return;
}
$components = array_values(array_filter(
$calendar->children(),
static fn($component): bool => $component instanceof VEvent
|| $component instanceof VTodo
|| $component instanceof VJournal,
));
if ($options->getCounts()) {
yield new ImportCountEvent(count($components));
}
foreach ($components as $component) {
$uid = isset($component->UID) ? (trim((string)$component->UID) ?: null) : null;
try {
$this->manager->entityCreate($tenantId, $userId, $target, $this->decoder->fromComponent($component));
yield new ImportObjectEvent($uid, ImportDisposition::Created);
} catch (Throwable $e) {
yield new ImportObjectEvent($uid, ImportDisposition::Error, [$e->getMessage()]);
if ($options->getErrors() === ImportOptions::ERROR_FAIL) {
return;
}
}
}
}
}
+430 -592
View File
File diff suppressed because it is too large Load Diff
-9
View File
@@ -14,15 +14,6 @@ class Module extends ModuleInstanceAbstract implements ModuleBrowserInterface
public function __construct() public function __construct()
{ } { }
public function boot(): void
{
// Load module-local vendored dependencies used by iCalendar import.
$vendorAutoload = __DIR__ . '/vendor/autoload.php';
if (file_exists($vendorAutoload)) {
require_once $vendorAutoload;
}
}
public function handle(): string public function handle(): string
{ {
return 'chrono_manager'; return 'chrono_manager';
-20
View File
@@ -1,20 +0,0 @@
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: Sebastian Krupinski <krupinski01@gmail.com>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace KTXM\ChronoManager\Stream;
/**
* Implemented by a stream event that declares, up front, how many data frames
* are expected to follow. When such an event leads a stream generator, the
* envelope writer folds its value into the `control:start` frame's `total`
* (the progress denominator) instead of emitting it as a `data` frame.
*/
interface ExpectedTotal {
public function expectedTotal(): int;
}
+839 -1711
View File
File diff suppressed because it is too large Load Diff
+4 -11
View File
@@ -7,24 +7,17 @@
"build": "vite build --mode production --config vite.config.ts", "build": "vite build --mode production --config vite.config.ts",
"dev": "vite build --mode development --config vite.config.ts", "dev": "vite build --mode development --config vite.config.ts",
"watch": "vite build --mode development --watch --config vite.config.ts", "watch": "vite build --mode development --watch --config vite.config.ts",
"typecheck": "vue-tsc --noEmit", "typecheck": "vue-tsc --noEmit"
"test": "vitest run --config tests/js/vitest.config.ts",
"test:unit": "vitest run --config tests/js/vitest.config.ts",
"test:watch": "vitest watch --config tests/js/vitest.config.ts",
"test:coverage": "vitest run --coverage --config tests/js/vitest.config.ts"
}, },
"dependencies": { "dependencies": {
"pinia": "^4.0.0", "pinia": "^3.0.0",
"vue": "^3.5.13" "vue": "^3.5.13"
}, },
"devDependencies": { "devDependencies": {
"@tsconfig/node24": "^24.0.0", "@tsconfig/node24": "^24.0.0",
"@types/node": "^24.0.0", "@types/node": "^24.0.0",
"@vue/tsconfig": "^0.9.0", "@vue/tsconfig": "^0.9.0",
"typescript": "~6.0.0", "typescript": "~5.7.2",
"vite": "^8.0.0", "vite": "^6.0.3"
"@vitest/coverage-v8": "^4.1.6",
"jsdom": "^29.1.1",
"vitest": "^4.1.6"
} }
} }
-27
View File
@@ -1,27 +0,0 @@
import { isProxy, toRaw } from 'vue';
function normalizeCloneable<T>(value: T): T {
if (value === null || value === undefined) {
return value;
}
if (typeof value !== 'object') {
return value;
}
const rawValue = isProxy(value) ? toRaw(value) : value;
if (Array.isArray(rawValue)) {
return rawValue.map(item => normalizeCloneable(item)) as T;
}
const plainObject = Object.fromEntries(
Object.entries(rawValue).map(([key, nestedValue]) => [key, normalizeCloneable(nestedValue)])
);
return plainObject as T;
}
export function clonePlain<T>(value: T): T {
return structuredClone(normalizeCloneable(value));
}
+60 -51
View File
@@ -1,52 +1,47 @@
/** /**
* Class models for Collection interfaces * Class model for Collection Interface
*/ */
import type { import type { CollectionContentTypes, CollectionInterface, CollectionPropertiesInterface } from "@/types/collection";
CollectionContentTypes,
CollectionInterface,
CollectionModelInterface,
CollectionPropertiesInterface,
CollectionPropertiesModelInterface
} from '@/types/collection';
import type {
CollectionIdentifier,
ServiceIdentifier
} from '@/types/common';
import { clonePlain } from './clone-plain';
export class CollectionObject implements CollectionModelInterface { export class CollectionObject implements CollectionInterface {
private _data: CollectionInterface<CollectionPropertiesInterface>; _data!: CollectionInterface;
private _properties: CollectionPropertiesObject | undefined = undefined;
constructor() { constructor() {
this._data = { this._data = {
'@type': 'people:collection',
version: 1,
provider: '', provider: '',
service: '' as ServiceIdentifier, service: '',
collection: null as CollectionIdentifier | null, collection: null,
identifier: '' as CollectionIdentifier, identifier: '',
properties: new CollectionPropertiesObject().toJson(), signature: null,
created: null,
modified: null,
properties: new CollectionPropertiesObject(),
}; };
} }
fromJson(data: CollectionInterface): CollectionObject { fromJson(data: CollectionInterface): CollectionObject {
this._data = clonePlain(data); this._data = data;
this._properties = undefined; if (data.properties) {
this._data.properties = new CollectionPropertiesObject().fromJson(data.properties as CollectionPropertiesInterface);
}
return this; return this;
} }
toJson(): CollectionInterface { toJson(): CollectionInterface {
const json = this._properties const json = { ...this._data };
? { ...this._data, properties: this._properties.toJson() } if (this._data.properties instanceof CollectionPropertiesObject) {
: this._data; json.properties = this._data.properties.toJson();
return clonePlain(json); }
return json;
} }
clone(): CollectionObject { clone(): CollectionObject {
return new CollectionObject().fromJson(this.toJson()); const cloned = new CollectionObject();
cloned._data = { ...this._data };
cloned._data.properties = this.properties.clone();
return cloned;
} }
/** Immutable Properties */ /** Immutable Properties */
@@ -55,16 +50,16 @@ export class CollectionObject implements CollectionModelInterface {
return this._data.provider; return this._data.provider;
} }
get service(): ServiceIdentifier { get service(): string | number {
return this._data.service as ServiceIdentifier; return this._data.service;
} }
get collection(): CollectionIdentifier | null { get collection(): string | number | null {
return this._data.collection as CollectionIdentifier | null; return this._data.collection;
} }
get identifier(): CollectionIdentifier { get identifier(): string | number {
return this._data.identifier as CollectionIdentifier; return this._data.identifier;
} }
get signature(): string | null | undefined { get signature(): string | null | undefined {
@@ -79,33 +74,37 @@ export class CollectionObject implements CollectionModelInterface {
return this._data.modified; return this._data.modified;
} }
/** Mutable Properties */
get properties(): CollectionPropertiesObject { get properties(): CollectionPropertiesObject {
if (this._properties) { if (this._data.properties instanceof CollectionPropertiesObject) {
return this._properties; return this._data.properties;
} }
else if (this._data.properties) {
const properties = new CollectionPropertiesObject().fromJson(this._data.properties as CollectionPropertiesInterface); if (this._data.properties) {
this._properties = properties; const hydrated = new CollectionPropertiesObject().fromJson(this._data.properties as CollectionPropertiesInterface);
return properties; this._data.properties = hydrated;
return hydrated;
} }
return new CollectionPropertiesObject(); return new CollectionPropertiesObject();
} }
set properties(value: CollectionPropertiesObject) { set properties(value: CollectionPropertiesObject) {
this._properties = value; if (value instanceof CollectionPropertiesObject) {
this._data.properties = value as any;
} else {
this._data.properties = value;
}
} }
} }
export class CollectionPropertiesObject implements CollectionPropertiesModelInterface { export class CollectionPropertiesObject implements CollectionPropertiesInterface {
private _data: CollectionPropertiesInterface; _data!: CollectionPropertiesInterface;
constructor() { constructor() {
this._data = { this._data = {
'@type': 'chrono:calendar', '@type': 'chrono:collection',
version: 1,
content: [], content: [],
label: '', label: '',
description: null, description: null,
@@ -116,22 +115,32 @@ export class CollectionPropertiesObject implements CollectionPropertiesModelInte
} }
fromJson(data: CollectionPropertiesInterface): CollectionPropertiesObject { fromJson(data: CollectionPropertiesInterface): CollectionPropertiesObject {
this._data = clonePlain(data); this._data = data;
return this; return this;
} }
toJson(): CollectionPropertiesInterface { toJson(): CollectionPropertiesInterface {
return clonePlain(this._data); return this._data;
} }
clone(): CollectionPropertiesObject { clone(): CollectionPropertiesObject {
return new CollectionPropertiesObject().fromJson(this.toJson()); const cloned = new CollectionPropertiesObject();
cloned._data = { ...this._data };
return cloned;
} }
/** Immutable Properties */ /** Immutable Properties */
get '@type'(): string {
return this._data['@type'];
}
get version(): number {
return this._data.version;
}
get content(): CollectionContentTypes[] { get content(): CollectionContentTypes[] {
return this._data.content ?? []; return this._data.content || [];
} }
/** Mutable Properties */ /** Mutable Properties */
+55 -51
View File
@@ -1,102 +1,106 @@
/** /**
* Class model for Entity Interface * Class model for Entity Interface
*/ */
import type { EntityInterface } from "@/types/entity";
import type { EventInterface } from "@/types/event";
import type { TaskInterface } from "@/types/task";
import type { JournalInterface } from "@/types/journal";
import { EventObject } from "./event";
import { TaskObject } from "./task";
import { JournalObject } from "./journal";
import type { CollectionIdentifier, EntityIdentifier } from '@/types/common'; export class EntityObject implements EntityInterface {
import type { EntityInterface, EntityModelInterface, EntityPropertiesInterface } from '@/types/entity';
import type { EventInterface } from '@/types/event';
import type { JournalInterface } from '@/types/journal';
import type { TaskInterface } from '@/types/task';
import { EventObject } from './event';
import { JournalObject } from './journal';
import { TaskObject } from './task';
import { clonePlain } from './clone-plain';
export type EntityPropertiesObject = EventObject | TaskObject | JournalObject; _data!: EntityInterface;
export class EntityObject implements EntityModelInterface {
private _data: EntityInterface<EntityPropertiesInterface>;
private _properties: EntityPropertiesObject | undefined;
constructor() { constructor() {
this._data = { this._data = {
'@type': 'chrono:entity',
version: 1,
provider: '', provider: '',
service: '', service: '',
collection: '' as CollectionIdentifier, collection: '',
identifier: '' as EntityIdentifier, identifier: '',
signature: null, signature: null,
created: null, created: null,
modified: null, modified: null,
properties: new EventObject().toJson(), properties: new EventObject(),
}; };
} }
fromJson(data: EntityInterface): EntityObject { fromJson(data: EntityInterface): EntityObject {
this._data = clonePlain(data); this._data = data
this._properties = undefined; if (data.properties) {
const type = data.properties.type
if (type === 'task') {
this._data.properties = new TaskObject().fromJson(data.properties as TaskInterface);
} else if (type === 'journal') {
this._data.properties = new JournalObject().fromJson(data.properties as JournalInterface);
} else {
this._data.properties = new EventObject().fromJson(data.properties as EventInterface);
}
}
return this; return this;
} }
toJson(): EntityInterface { toJson(): EntityInterface {
const json = this._properties const json = { ...this._data }
? { ...this._data, properties: this._properties.toJson() } if (this._data.properties instanceof EventObject ||
: this._data; this._data.properties instanceof TaskObject ||
return clonePlain(json); this._data.properties instanceof JournalObject) {
json.properties = this._data.properties.toJson();
}
return json as EntityInterface
} }
clone(): EntityObject { clone(): EntityObject {
return new EntityObject().fromJson(this.toJson()); const cloned = new EntityObject()
cloned._data = { ...this._data }
return cloned
} }
/** Metadata Properties */ /** Immutable Properties */
get provider(): string { get provider(): string {
return this._data.provider; return this._data.provider
} }
get service(): string { get service(): string {
return this._data.service; return this._data.service
} }
get collection(): CollectionIdentifier { get collection(): string | number {
return this._data.collection; return this._data.collection
} }
get identifier(): EntityIdentifier { get identifier(): string | number {
return this._data.identifier; return this._data.identifier
} }
get signature(): string | null { get signature(): string | null {
return this._data.signature; return this._data.signature
} }
get created(): string | null { get created(): string | null {
return this._data.created; return this._data.created
} }
get modified(): string | null { get modified(): string | null {
return this._data.modified; return this._data.modified
} }
/** Entity Properties (individual | organization | group) */ get properties(): EventObject | TaskObject | JournalObject {
if (this._data.properties instanceof EventObject ||
get properties(): EntityPropertiesObject { this._data.properties instanceof TaskObject ||
if (this._properties) return this._properties; this._data.properties instanceof JournalObject) {
return this._data.properties
const raw = this._data.properties;
if (raw.type === 'task') {
this._properties = new TaskObject().fromJson(raw as TaskInterface);
} else if (raw.type === 'journal') {
this._properties = new JournalObject().fromJson(raw as JournalInterface);
} else {
this._properties = new EventObject().fromJson(raw as EventInterface);
} }
return this._properties;
const defaultProperties = new EventObject();
this._data.properties = defaultProperties;
return defaultProperties
} }
set properties(value: EntityPropertiesObject) { set properties(value: EventObject | TaskObject | JournalObject) {
this._properties = value; this._data.properties = value
} }
} }
+1 -8
View File
@@ -114,15 +114,8 @@ export class EventObject implements EventInterface {
} }
toJson(): EventInterface { toJson(): EventInterface {
const data = {
...this._data,
pattern: this._data.pattern instanceof EventOccurrenceObject
? this._data.pattern.toJson()
: this._data.pattern,
};
// Return a deep copy to avoid external modifications // Return a deep copy to avoid external modifications
return JSON.parse(JSON.stringify(data)); return JSON.parse(JSON.stringify(this._data));
} }
clone(): EventObject { clone(): EventObject {
+174 -102
View File
@@ -1,124 +1,196 @@
/** /**
* Identity models for Chrono Manager services * Identity implementation classes for Mail Manager services
*/ */
import type { import type {
ServiceIdentity, ServiceIdentity,
ServiceIdentityBasic, ServiceIdentityNone,
ServiceIdentityCertificate, ServiceIdentityBasic,
ServiceIdentityNone, ServiceIdentityToken,
ServiceIdentityOAuth, ServiceIdentityOAuth,
ServiceIdentityToken ServiceIdentityCertificate
} from '@/types/service'; } from '@/types/service';
import { clonePlain } from './clone-plain';
import { MutationProxy } from './mutation-proxy';
export abstract class Identity<T extends ServiceIdentity = ServiceIdentity> { /**
protected _original: T; * Base Identity class
protected _mutated: Partial<T>; */
protected _mutationProxy: MutationProxy<T>; export abstract class Identity {
protected _data: T; abstract toJson(): ServiceIdentity;
protected constructor(initial: T) { static fromJson(data: ServiceIdentity): Identity {
this._original = clonePlain(initial); switch (data.type) {
this._mutated = {}; case 'NA':
this._mutationProxy = new MutationProxy<T>(() => this._original, () => this._mutated); return IdentityNone.fromJson(data);
this._data = this._mutationProxy.create(); case 'BA':
} return IdentityBasic.fromJson(data);
case 'TA':
protected load(data: T): this { return IdentityToken.fromJson(data);
this._original = clonePlain(data); case 'OA':
this._mutated = {}; return IdentityOAuth.fromJson(data);
this._data = this._mutationProxy.create(); case 'CC':
return this; return IdentityCertificate.fromJson(data);
} default:
throw new Error(`Unknown identity type: ${(data as any).type}`);
toJSON(): ServiceIdentity { return this.toJson(); }
toJson(): T;
toJson(delta: true): Partial<T>;
toJson(delta?: boolean): T | Partial<T> {
return delta
? clonePlain(this._mutated)
: { ...clonePlain(this._original), ...clonePlain(this._mutated) };
}
abstract clone(): Identity;
mutated(): boolean { return Reflect.ownKeys(this._mutated).length > 0; }
static fromJson(data: ServiceIdentity): Identity {
switch (data.type) {
case 'NA': return IdentityNone.fromJson(data);
case 'BA': return IdentityBasic.fromJson(data);
case 'TA': return IdentityToken.fromJson(data);
case 'OA': return IdentityOAuth.fromJson(data);
case 'CC': return IdentityCertificate.fromJson(data);
default: throw new Error(`Unknown identity type: ${(data as any).type}`);
}
} }
}
} }
export class IdentityNone extends Identity<ServiceIdentityNone> { /**
constructor() { super({ type: 'NA' }); } * No authentication
static fromJson(_data: ServiceIdentityNone): IdentityNone { return new IdentityNone(); } */
clone(): IdentityNone { return IdentityNone.fromJson(this.toJson()); } export class IdentityNone extends Identity {
get type(): 'NA' { return this._data.type; } readonly type = 'NA' as const;
static fromJson(_data: ServiceIdentityNone): IdentityNone {
return new IdentityNone();
}
toJson(): ServiceIdentityNone {
return {
type: this.type
};
}
} }
export class IdentityBasic extends Identity<ServiceIdentityBasic> { /**
constructor(identity: string = '', secret: string = '') { super({ type: 'BA', identity, secret }); } * Basic authentication (username/password)
static fromJson(data: ServiceIdentityBasic): IdentityBasic { return new IdentityBasic().load(data); } */
clone(): IdentityBasic { return IdentityBasic.fromJson(this.toJson()); } export class IdentityBasic extends Identity {
get type(): 'BA' { return this._data.type; } readonly type = 'BA' as const;
get identity(): string { return this._data.identity; } identity: string;
set identity(value: string) { this._data.identity = value; } secret: string;
get secret(): string { return this._data.secret; }
set secret(value: string) { this._data.secret = value; } constructor(identity: string = '', secret: string = '') {
super();
this.identity = identity;
this.secret = secret;
}
static fromJson(data: ServiceIdentityBasic): IdentityBasic {
return new IdentityBasic(data.identity, data.secret);
}
toJson(): ServiceIdentityBasic {
return {
type: this.type,
identity: this.identity,
secret: this.secret
};
}
} }
export class IdentityToken extends Identity<ServiceIdentityToken> { /**
constructor(token: string = '') { super({ type: 'TA', token }); } * Token authentication (API key, static token)
static fromJson(data: ServiceIdentityToken): IdentityToken { return new IdentityToken().load(data); } */
clone(): IdentityToken { return IdentityToken.fromJson(this.toJson()); } export class IdentityToken extends Identity {
get type(): 'TA' { return this._data.type; } readonly type = 'TA' as const;
get token(): string { return this._data.token; } token: string;
set token(value: string) { this._data.token = value; }
constructor(token: string = '') {
super();
this.token = token;
}
static fromJson(data: ServiceIdentityToken): IdentityToken {
return new IdentityToken(data.token);
}
toJson(): ServiceIdentityToken {
return {
type: this.type,
token: this.token
};
}
} }
export class IdentityOAuth extends Identity<ServiceIdentityOAuth> { /**
constructor(accessToken: string = '', accessScope?: string[], accessExpiry?: number, refreshToken?: string, refreshLocation?: string) { * OAuth authentication
super({ type: 'OA', accessToken, accessScope, accessExpiry, refreshToken, refreshLocation }); */
} export class IdentityOAuth extends Identity {
readonly type = 'OA' as const;
accessToken: string;
accessScope?: string[];
accessExpiry?: number;
refreshToken?: string;
refreshLocation?: string;
static fromJson(data: ServiceIdentityOAuth): IdentityOAuth { return new IdentityOAuth().load(data); } constructor(
clone(): IdentityOAuth { return IdentityOAuth.fromJson(this.toJson()); } accessToken: string = '',
isExpired(): boolean { return this.accessExpiry ? Date.now() / 1000 >= this.accessExpiry : false; } accessScope?: string[],
expiresIn(): number { return this.accessExpiry ? Math.max(0, this.accessExpiry - Date.now() / 1000) : Infinity; } accessExpiry?: number,
refreshToken?: string,
refreshLocation?: string
) {
super();
this.accessToken = accessToken;
this.accessScope = accessScope;
this.accessExpiry = accessExpiry;
this.refreshToken = refreshToken;
this.refreshLocation = refreshLocation;
}
get type(): 'OA' { return this._data.type; } static fromJson(data: ServiceIdentityOAuth): IdentityOAuth {
get accessToken(): string { return this._data.accessToken; } return new IdentityOAuth(
set accessToken(value: string) { this._data.accessToken = value; } data.accessToken,
get accessScope(): string[] | undefined { return this._data.accessScope ? [...this._data.accessScope] : undefined; } data.accessScope,
set accessScope(value: string[] | undefined) { this._data.accessScope = value ? [...value] : undefined; } data.accessExpiry,
get accessExpiry(): number | undefined { return this._data.accessExpiry; } data.refreshToken,
set accessExpiry(value: number | undefined) { this._data.accessExpiry = value; } data.refreshLocation
get refreshToken(): string | undefined { return this._data.refreshToken; } );
set refreshToken(value: string | undefined) { this._data.refreshToken = value; } }
get refreshLocation(): string | undefined { return this._data.refreshLocation; }
set refreshLocation(value: string | undefined) { this._data.refreshLocation = value; } toJson(): ServiceIdentityOAuth {
return {
type: this.type,
accessToken: this.accessToken,
...(this.accessScope && { accessScope: this.accessScope }),
...(this.accessExpiry && { accessExpiry: this.accessExpiry }),
...(this.refreshToken && { refreshToken: this.refreshToken }),
...(this.refreshLocation && { refreshLocation: this.refreshLocation })
};
}
isExpired(): boolean {
if (!this.accessExpiry) return false;
return Date.now() / 1000 >= this.accessExpiry;
}
expiresIn(): number {
if (!this.accessExpiry) return Infinity;
return Math.max(0, this.accessExpiry - Date.now() / 1000);
}
} }
export class IdentityCertificate extends Identity<ServiceIdentityCertificate> { /**
constructor(certificate: string = '', privateKey: string = '', passphrase?: string) { * Client certificate authentication (mTLS)
super({ type: 'CC', certificate, privateKey, passphrase }); */
} export class IdentityCertificate extends Identity {
readonly type = 'CC' as const;
certificate: string;
privateKey: string;
passphrase?: string;
static fromJson(data: ServiceIdentityCertificate): IdentityCertificate { return new IdentityCertificate().load(data); } constructor(certificate: string = '', privateKey: string = '', passphrase?: string) {
clone(): IdentityCertificate { return IdentityCertificate.fromJson(this.toJson()); } super();
get type(): 'CC' { return this._data.type; } this.certificate = certificate;
get certificate(): string { return this._data.certificate; } this.privateKey = privateKey;
set certificate(value: string) { this._data.certificate = value; } this.passphrase = passphrase;
get privateKey(): string { return this._data.privateKey; } }
set privateKey(value: string) { this._data.privateKey = value; }
get passphrase(): string | undefined { return this._data.passphrase; } static fromJson(data: ServiceIdentityCertificate): IdentityCertificate {
set passphrase(value: string | undefined) { this._data.passphrase = value; } return new IdentityCertificate(
data.certificate,
data.privateKey,
data.passphrase
);
}
toJson(): ServiceIdentityCertificate {
return {
type: this.type,
certificate: this.certificate,
privateKey: this.privateKey,
...(this.passphrase && { passphrase: this.passphrase })
};
}
} }
+3 -2
View File
@@ -1,6 +1,6 @@
export { ProviderObject } from './provider'; export { ProviderObject } from './provider';
export { ServiceObject } from './service'; export { ServiceObject } from './service';
export { CollectionObject, CollectionPropertiesObject } from './collection'; export { CollectionObject } from './collection';
export { EntityObject } from './entity'; export { EntityObject } from './entity';
export { EventObject } from './event'; export { EventObject } from './event';
export { TaskObject } from './task'; export { TaskObject } from './task';
@@ -16,6 +16,7 @@ export {
export { export {
Location, Location,
LocationUri, LocationUri,
LocationSocketSole,
LocationSocketSplit,
LocationFile LocationFile
} from './location'; } from './location';
export { MutationProxy } from './mutation-proxy';
+226 -77
View File
@@ -1,91 +1,240 @@
/** /**
* Location models for Chrono Manager services * Location implementation classes for Mail Manager services
*/ */
import type { ServiceLocation, ServiceLocationFile, ServiceLocationUri } from '@/types/service'; import type {
import { clonePlain } from './clone-plain'; ServiceLocation,
import { MutationProxy } from './mutation-proxy'; ServiceLocationUri,
ServiceLocationSocketSole,
ServiceLocationSocketSplit,
ServiceLocationFile
} from '@/types/service';
export abstract class Location<T extends ServiceLocation = ServiceLocation> { /**
protected _original: T; * Base Location class
protected _mutated: Partial<T>; */
protected _mutationProxy: MutationProxy<T>; export abstract class Location {
protected _data: T; abstract toJson(): ServiceLocation;
protected constructor(initial: T) { static fromJson(data: ServiceLocation): Location {
this._original = clonePlain(initial); switch (data.type) {
this._mutated = {}; case 'URI':
this._mutationProxy = new MutationProxy<T>(() => this._original, () => this._mutated); return LocationUri.fromJson(data);
this._data = this._mutationProxy.create(); case 'SOCKET_SOLE':
} return LocationSocketSole.fromJson(data);
case 'SOCKET_SPLIT':
protected load(data: T): this { return LocationSocketSplit.fromJson(data);
this._original = clonePlain(data); case 'FILE':
this._mutated = {}; return LocationFile.fromJson(data);
this._data = this._mutationProxy.create(); default:
return this; throw new Error(`Unknown location type: ${(data as any).type}`);
}
toJson(): T;
toJson(delta: true): Partial<T>;
toJson(delta?: boolean): T | Partial<T> {
return delta
? clonePlain(this._mutated)
: { ...clonePlain(this._original), ...clonePlain(this._mutated) };
}
abstract clone(): Location;
mutated(): boolean {
return Reflect.ownKeys(this._mutated).length > 0;
}
static fromJson(data: ServiceLocation): Location {
switch (data.type) {
case 'URI': return LocationUri.fromJson(data);
case 'FILE': return LocationFile.fromJson(data);
default: throw new Error(`Unknown location type: ${(data as any).type}`);
}
} }
}
} }
export class LocationUri extends Location<ServiceLocationUri> { /**
constructor( * URI-based service location for API and web services
scheme: string = 'https', * Used by: JMAP, Gmail API, etc.
host: string = '', */
port: number = 443, export class LocationUri extends Location {
path?: string, readonly type = 'URI' as const;
verifyPeer: boolean = true, scheme: string;
verifyHost: boolean = true host: string;
) { port: number;
super({ type: 'URI', scheme, host, port, ...(path !== undefined && { path }), verifyPeer, verifyHost }); path?: string;
} verifyPeer: boolean;
verifyHost: boolean;
static fromJson(data: ServiceLocationUri): LocationUri { return new LocationUri().load(data); } constructor(
clone(): LocationUri { return LocationUri.fromJson(this.toJson()); } scheme: string = 'https',
getUrl(): string { return `${this.scheme}://${this.host}:${this.port}${this.path || ''}`; } host: string = '',
port: number = 443,
path?: string,
verifyPeer: boolean = true,
verifyHost: boolean = true
) {
super();
this.scheme = scheme;
this.host = host;
this.port = port;
this.path = path;
this.verifyPeer = verifyPeer;
this.verifyHost = verifyHost;
}
get type(): 'URI' { return this._data.type; } static fromJson(data: ServiceLocationUri): LocationUri {
get scheme(): string { return this._data.scheme; } return new LocationUri(
set scheme(value: string) { this._data.scheme = value; } data.scheme,
get host(): string { return this._data.host; } data.host,
set host(value: string) { this._data.host = value; } data.port,
get port(): number { return this._data.port; } data.path,
set port(value: number) { this._data.port = value; } data.verifyPeer ?? true,
get path(): string | undefined { return this._data.path; } data.verifyHost ?? true
set path(value: string | undefined) { this._data.path = value; } );
get verifyPeer(): boolean { return this._data.verifyPeer ?? true; } }
set verifyPeer(value: boolean) { this._data.verifyPeer = value; }
get verifyHost(): boolean { return this._data.verifyHost ?? true; } toJson(): ServiceLocationUri {
set verifyHost(value: boolean) { this._data.verifyHost = value; } return {
type: this.type,
scheme: this.scheme,
host: this.host,
port: this.port,
...(this.path && { path: this.path }),
...(this.verifyPeer !== undefined && { verifyPeer: this.verifyPeer }),
...(this.verifyHost !== undefined && { verifyHost: this.verifyHost })
};
}
getUrl(): string {
const path = this.path || '';
return `${this.scheme}://${this.host}:${this.port}${path}`;
}
} }
export class LocationFile extends Location<ServiceLocationFile> { /**
constructor(path: string = '') { super({ type: 'FILE', path }); } * Single socket-based service location
static fromJson(data: ServiceLocationFile): LocationFile { return new LocationFile().load(data); } * Used by: services using a single host/port combination
clone(): LocationFile { return LocationFile.fromJson(this.toJson()); } */
export class LocationSocketSole extends Location {
readonly type = 'SOCKET_SOLE' as const;
host: string;
port: number;
encryption: 'none' | 'ssl' | 'tls' | 'starttls';
verifyPeer: boolean;
verifyHost: boolean;
get type(): 'FILE' { return this._data.type; } constructor(
get path(): string { return this._data.path; } host: string = '',
set path(value: string) { this._data.path = value; } port: number = 993,
encryption: 'none' | 'ssl' | 'tls' | 'starttls' = 'ssl',
verifyPeer: boolean = true,
verifyHost: boolean = true
) {
super();
this.host = host;
this.port = port;
this.encryption = encryption;
this.verifyPeer = verifyPeer;
this.verifyHost = verifyHost;
}
static fromJson(data: ServiceLocationSocketSole): LocationSocketSole {
return new LocationSocketSole(
data.host,
data.port,
data.encryption,
data.verifyPeer ?? true,
data.verifyHost ?? true
);
}
toJson(): ServiceLocationSocketSole {
return {
type: this.type,
host: this.host,
port: this.port,
encryption: this.encryption,
...(this.verifyPeer !== undefined && { verifyPeer: this.verifyPeer }),
...(this.verifyHost !== undefined && { verifyHost: this.verifyHost })
};
}
}
/**
* Split socket-based service location
* Used by: traditional IMAP/SMTP configurations
*/
export class LocationSocketSplit extends Location {
readonly type = 'SOCKET_SPLIT' as const;
inboundHost: string;
inboundPort: number;
inboundEncryption: 'none' | 'ssl' | 'tls' | 'starttls';
outboundHost: string;
outboundPort: number;
outboundEncryption: 'none' | 'ssl' | 'tls' | 'starttls';
inboundVerifyPeer: boolean;
inboundVerifyHost: boolean;
outboundVerifyPeer: boolean;
outboundVerifyHost: boolean;
constructor(
inboundHost: string = '',
inboundPort: number = 993,
inboundEncryption: 'none' | 'ssl' | 'tls' | 'starttls' = 'ssl',
outboundHost: string = '',
outboundPort: number = 465,
outboundEncryption: 'none' | 'ssl' | 'tls' | 'starttls' = 'ssl',
inboundVerifyPeer: boolean = true,
inboundVerifyHost: boolean = true,
outboundVerifyPeer: boolean = true,
outboundVerifyHost: boolean = true
) {
super();
this.inboundHost = inboundHost;
this.inboundPort = inboundPort;
this.inboundEncryption = inboundEncryption;
this.outboundHost = outboundHost;
this.outboundPort = outboundPort;
this.outboundEncryption = outboundEncryption;
this.inboundVerifyPeer = inboundVerifyPeer;
this.inboundVerifyHost = inboundVerifyHost;
this.outboundVerifyPeer = outboundVerifyPeer;
this.outboundVerifyHost = outboundVerifyHost;
}
static fromJson(data: ServiceLocationSocketSplit): LocationSocketSplit {
return new LocationSocketSplit(
data.inboundHost,
data.inboundPort,
data.inboundEncryption,
data.outboundHost,
data.outboundPort,
data.outboundEncryption,
data.inboundVerifyPeer ?? true,
data.inboundVerifyHost ?? true,
data.outboundVerifyPeer ?? true,
data.outboundVerifyHost ?? true
);
}
toJson(): ServiceLocationSocketSplit {
return {
type: this.type,
inboundHost: this.inboundHost,
inboundPort: this.inboundPort,
inboundEncryption: this.inboundEncryption,
outboundHost: this.outboundHost,
outboundPort: this.outboundPort,
outboundEncryption: this.outboundEncryption,
...(this.inboundVerifyPeer !== undefined && { inboundVerifyPeer: this.inboundVerifyPeer }),
...(this.inboundVerifyHost !== undefined && { inboundVerifyHost: this.inboundVerifyHost }),
...(this.outboundVerifyPeer !== undefined && { outboundVerifyPeer: this.outboundVerifyPeer }),
...(this.outboundVerifyHost !== undefined && { outboundVerifyHost: this.outboundVerifyHost })
};
}
}
/**
* File-based service location
* Used by: local file system providers
*/
export class LocationFile extends Location {
readonly type = 'FILE' as const;
path: string;
constructor(path: string = '') {
super();
this.path = path;
}
static fromJson(data: ServiceLocationFile): LocationFile {
return new LocationFile(data.path);
}
toJson(): ServiceLocationFile {
return {
type: this.type,
path: this.path
};
}
} }
-36
View File
@@ -1,36 +0,0 @@
import { clonePlain } from './clone-plain';
export class MutationProxy<T extends object> {
constructor(
private readonly getOriginal: () => T,
private readonly getMutated: () => Partial<T>,
) {}
create(): T {
return new Proxy({} as T, {
get: (_target, prop: string | symbol) => {
if (typeof prop !== 'string') return undefined;
const key = prop as keyof T;
const mutated = this.getMutated();
return key in mutated ? mutated[key] : this.getOriginal()[key];
},
set: (_target, prop: string | symbol, value: unknown) => {
if (typeof prop === 'string') {
const key = prop as keyof T;
(this.getMutated() as Record<keyof T, unknown>)[key] = clonePlain(value);
}
return true;
},
has: (_target, prop: string | symbol) => {
if (typeof prop !== 'string') return false;
return prop in this.getMutated() || prop in this.getOriginal();
},
ownKeys: () => Array.from(new Set([
...Reflect.ownKeys(this.getOriginal()),
...Reflect.ownKeys(this.getMutated()),
])),
getOwnPropertyDescriptor: () => ({ enumerable: true, configurable: true }),
});
}
}
+9 -11
View File
@@ -4,12 +4,10 @@
import type { import type {
ProviderInterface, ProviderInterface,
ProviderCapabilitiesInterface, ProviderCapabilitiesInterface
ProviderModelInterface
} from "@/types/provider"; } from "@/types/provider";
import { clonePlain } from './clone-plain';
export class ProviderObject implements ProviderModelInterface { export class ProviderObject implements ProviderInterface {
_data!: ProviderInterface; _data!: ProviderInterface;
@@ -23,16 +21,12 @@ export class ProviderObject implements ProviderModelInterface {
} }
fromJson(data: ProviderInterface): ProviderObject { fromJson(data: ProviderInterface): ProviderObject {
this._data = clonePlain(data); this._data = data;
return this; return this;
} }
toJson(): ProviderInterface { toJson(): ProviderInterface {
return clonePlain(this._data); return this._data;
}
clone(): ProviderObject {
return new ProviderObject().fromJson(this.toJson());
} }
capable(capability: keyof ProviderCapabilitiesInterface): boolean { capable(capability: keyof ProviderCapabilitiesInterface): boolean {
@@ -49,6 +43,10 @@ export class ProviderObject implements ProviderModelInterface {
/** Immutable Properties */ /** Immutable Properties */
get '@type'(): string {
return this._data['@type'];
}
get identifier(): string { get identifier(): string {
return this._data.identifier; return this._data.identifier;
} }
@@ -58,7 +56,7 @@ export class ProviderObject implements ProviderModelInterface {
} }
get capabilities(): ProviderCapabilitiesInterface { get capabilities(): ProviderCapabilitiesInterface {
return clonePlain(this._data.capabilities); return this._data.capabilities;
} }
} }
+81 -86
View File
@@ -5,26 +5,18 @@
import type { import type {
ServiceInterface, ServiceInterface,
ServiceCapabilitiesInterface, ServiceCapabilitiesInterface,
ServiceLocation, ServiceIdentity,
ServiceModelInterface ServiceLocation
} from "@/types/service"; } from "@/types/service";
import { Identity } from './identity'; import { Identity } from './identity';
import { Location } from './location'; import { Location } from './location';
import { MutationProxy } from './mutation-proxy';
import { clonePlain } from './clone-plain';
export class ServiceObject implements ServiceModelInterface { export class ServiceObject implements ServiceInterface {
private _original: ServiceInterface;
private _mutated: Partial<ServiceInterface>;
private _mutationProxy = new MutationProxy<ServiceInterface>(() => this._original, () => this._mutated);
_data!: ServiceInterface; _data!: ServiceInterface;
private _location: Location | null | undefined = undefined;
private _identity: Identity | null | undefined = undefined;
private _locationAssigned = false;
private _identityAssigned = false;
constructor() { constructor() {
this._original = { this._data = {
'@type': 'chrono:service', '@type': 'chrono:service',
provider: '', provider: '',
identifier: null, identifier: null,
@@ -32,59 +24,15 @@ export class ServiceObject implements ServiceModelInterface {
enabled: false, enabled: false,
capabilities: {} capabilities: {}
}; };
this._mutated = {};
this._data = this._mutationProxy.create();
} }
fromJson(data: ServiceInterface): ServiceObject { fromJson(data: ServiceInterface): ServiceObject {
this._original = clonePlain(data); this._data = data;
this._mutated = {};
this._data = this._mutationProxy.create();
this._location = undefined;
this._identity = undefined;
this._locationAssigned = false;
this._identityAssigned = false;
return this; return this;
} }
toJson(): ServiceInterface; toJson(): ServiceInterface {
toJson(delta: true): Partial<ServiceInterface>; return this._data;
toJson(delta?: boolean): ServiceInterface | Partial<ServiceInterface> {
if (delta) {
const json = clonePlain(this._mutated);
if (this._locationAssigned) {
json.location = this._location ? this._location.toJson() : null;
} else if (this._location?.mutated()) {
json.location = this._location.toJson(true) as ServiceInterface['location'];
}
if (this._identityAssigned) {
json.identity = this._identity ? this._identity.toJson() : null;
} else if (this._identity?.mutated()) {
json.identity = this._identity.toJson(true) as ServiceInterface['identity'];
}
return json;
}
const json: ServiceInterface = {
...clonePlain(this._original),
...clonePlain(this._mutated),
};
if (this._location !== undefined) json.location = this._location ? this._location.toJson() : null;
if (this._identity !== undefined) json.identity = this._identity ? this._identity.toJson() : null;
return json;
}
clone(): ServiceObject {
return new ServiceObject().fromJson(this.toJson());
}
mutated(): boolean {
return Reflect.ownKeys(this._mutated).length > 0
|| this._locationAssigned
|| this._identityAssigned
|| (this._location?.mutated() ?? false)
|| (this._identity?.mutated() ?? false);
} }
capable(capability: keyof ServiceCapabilitiesInterface): boolean { capable(capability: keyof ServiceCapabilitiesInterface): boolean {
@@ -93,41 +41,88 @@ export class ServiceObject implements ServiceModelInterface {
} }
capability(capability: keyof ServiceCapabilitiesInterface): any | null { capability(capability: keyof ServiceCapabilitiesInterface): any | null {
return this._data.capabilities?.[capability] ?? null; if (this._data.capabilities) {
return this._data.capabilities[capability];
}
return null;
} }
get provider(): string { return this._data.provider; } /** Immutable Properties */
get identifier(): string | number | null { return this._data.identifier; }
get capabilities(): ServiceCapabilitiesInterface { return this._data.capabilities ?? {}; }
get label(): string | null { return this._data.label; } get '@type'(): string {
set label(value: string | null) { this._data.label = value; } return this._data['@type'];
get enabled(): boolean { return this._data.enabled; }
set enabled(value: boolean) { this._data.enabled = value; }
get location(): Location | null {
if (this._location !== undefined) return this._location;
this._location = this._data.location ? Location.fromJson(this._data.location as ServiceLocation) : null;
return this._location;
} }
set location(value: Location | null) { get provider(): string {
this._location = value; return this._data.provider;
this._locationAssigned = true;
} }
get identity(): Identity | null { get identifier(): string | number | null {
if (this._identity !== undefined) return this._identity; return this._data.identifier;
this._identity = this._data.identity ? Identity.fromJson(this._data.identity) : null;
return this._identity;
} }
set identity(value: Identity | null) { get capabilities(): ServiceCapabilitiesInterface | undefined {
this._identity = value; return this._data.capabilities;
this._identityAssigned = true; }
/** Mutable Properties */
get label(): string | null {
return this._data.label;
}
set label(value: string | null) {
this._data.label = value;
}
get enabled(): boolean {
return this._data.enabled;
}
set enabled(value: boolean) {
this._data.enabled = value;
}
get location(): ServiceLocation | null {
return this._data.location ?? null;
}
set location(value: ServiceLocation | null) {
this._data.location = value;
}
get identity(): ServiceIdentity | null {
return this._data.identity ?? null;
}
set identity(value: ServiceIdentity | null) {
this._data.identity = value;
}
get auxiliary(): Record<string, any> {
return this._data.auxiliary ?? {};
}
set auxiliary(value: Record<string, any>) {
this._data.auxiliary = value;
}
/** Helper Methods */
/**
* Get identity as a class instance for easier manipulation
*/
getIdentity(): Identity | null {
if (!this._data.identity) return null;
return Identity.fromJson(this._data.identity);
}
/**
* Get location as a class instance for easier manipulation
*/
getLocation(): Location | null {
if (!this._data.location) return null;
return Location.fromJson(this._data.location);
} }
get auxiliary(): Record<string, any> { return this._data.auxiliary ?? {}; }
set auxiliary(value: Record<string, any>) { this._data.auxiliary = value; }
} }
+4 -16
View File
@@ -70,15 +70,9 @@ export const collectionService = {
* *
* @returns Promise with collection object * @returns Promise with collection object
*/ */
async fetch(request: CollectionFetchRequest): Promise<Record<string, CollectionObject>> { async fetch(request: CollectionFetchRequest): Promise<CollectionObject> {
const response = await transceivePost<CollectionFetchRequest, CollectionFetchResponse>('collection.fetch', request); const response = await transceivePost<CollectionFetchRequest, CollectionFetchResponse>('collection.fetch', request);
return createCollectionObject(response);
const list: Record<string, CollectionObject> = {};
Object.entries(response).forEach(([, collection]) => {
list[collection.identifier] = createCollectionObject(collection);
});
return list;
}, },
/** /**
@@ -129,14 +123,8 @@ export const collectionService = {
* *
* @returns Promise with deletion result * @returns Promise with deletion result
*/ */
async delete(request: CollectionDeleteRequest): Promise<boolean | CollectionObject> { async delete(request: CollectionDeleteRequest): Promise<CollectionDeleteResponse> {
const response = await transceivePost<CollectionDeleteRequest, CollectionDeleteResponse>('collection.delete', request); return await transceivePost<CollectionDeleteRequest, CollectionDeleteResponse>('collection.delete', request);
if (response.disposition === 'moved' && response.mutation) {
return createCollectionObject(response.mutation);
}
return true;
}, },
}; };
+41 -59
View File
@@ -2,12 +2,10 @@
* Entity management service * Entity management service
*/ */
import { transceivePost, transceiveStream } from './transceive'; import { transceivePost } from './transceive';
import type { import type {
EntityListBulkRequest, EntityListRequest,
EntityListBulkResponse, EntityListResponse,
EntityListStreamRequest,
EntityListStreamResponse,
EntityFetchRequest, EntityFetchRequest,
EntityFetchResponse, EntityFetchResponse,
EntityExtantRequest, EntityExtantRequest,
@@ -20,10 +18,6 @@ import type {
EntityDeleteResponse, EntityDeleteResponse,
EntityDeltaRequest, EntityDeltaRequest,
EntityDeltaResponse, EntityDeltaResponse,
EntityMoveRequest,
EntityMoveResponse,
EntityImportRequest,
EntityImportResponse,
EntityInterface, EntityInterface,
} from '../types/entity'; } from '../types/entity';
import { useIntegrationStore } from '@KTXC/stores/integrationStore'; import { useIntegrationStore } from '@KTXC/stores/integrationStore';
@@ -45,11 +39,16 @@ function createEntityObject(data: EntityInterface): EntityObject {
export const entityService = { export const entityService = {
/** /**
* Retrieve list of entities, optionally filtered by source collection identifiers * Retrieve list of entities, optionally filtered by source selector
*
* @param request - list request parameters
*
* @returns Promise with entity object list grouped by provider, service, collection, and entity identifier
*/ */
async listBulk(request: EntityListBulkRequest = {}): Promise<Record<string, Record<string, Record<string, Record<string, EntityObject>>>>> { async list(request: EntityListRequest = {}): Promise<Record<string, Record<string, Record<string, Record<string, EntityObject>>>>> {
const response = await transceivePost<EntityListBulkRequest, EntityListBulkResponse>('entity.listBulk', request); const response = await transceivePost<EntityListRequest, EntityListResponse>('entity.list', request);
// Convert nested response to EntityObject instances
const providerList: Record<string, Record<string, Record<string, Record<string, EntityObject>>>> = {}; const providerList: Record<string, Record<string, Record<string, Record<string, EntityObject>>>> = {};
Object.entries(response).forEach(([providerId, providerServices]) => { Object.entries(response).forEach(([providerId, providerServices]) => {
const serviceList: Record<string, Record<string, Record<string, EntityObject>>> = {}; const serviceList: Record<string, Record<string, Record<string, EntityObject>>> = {};
@@ -71,34 +70,30 @@ export const entityService = {
}, },
/** /**
* Stream entities as NDJSON, invoking onEntity for each entity as it arrives. * Retrieve a specific entity by provider and identifier
*/ *
async listStream(request: EntityListStreamRequest, onEntity: (entity: EntityObject) => void): Promise<{ total: number }> { * @param request - fetch request parameters
return await transceiveStream<EntityListStreamRequest, EntityListStreamResponse>( *
'entity.listStream', * @returns Promise with entity objects keyed by identifier
request,
(entity) => {
onEntity(createEntityObject(entity));
}
);
},
/**
* Retrieve specific entities by their identifiers
*/ */
async fetch(request: EntityFetchRequest): Promise<Record<string, EntityObject>> { async fetch(request: EntityFetchRequest): Promise<Record<string, EntityObject>> {
const response = await transceivePost<EntityFetchRequest, EntityFetchResponse>('entity.fetch', request); const response = await transceivePost<EntityFetchRequest, EntityFetchResponse>('entity.fetch', request);
// Convert response to EntityObject instances
const list: Record<string, EntityObject> = {}; const list: Record<string, EntityObject> = {};
Object.entries(response).forEach(([, entity]) => { Object.entries(response).forEach(([identifier, entityData]) => {
list[entity.identifier] = createEntityObject(entity); list[identifier] = createEntityObject(entityData);
}); });
return list; return list;
}, },
/** /**
* Retrieve entity availability status for a given set of entity identifiers * Retrieve entity availability status for a given source selector
*
* @param request - extant request parameters
*
* @returns Promise with entity availability status
*/ */
async extant(request: EntityExtantRequest): Promise<EntityExtantResponse> { async extant(request: EntityExtantRequest): Promise<EntityExtantResponse> {
return await transceivePost<EntityExtantRequest, EntityExtantResponse>('entity.extant', request); return await transceivePost<EntityExtantRequest, EntityExtantResponse>('entity.extant', request);
@@ -106,6 +101,10 @@ export const entityService = {
/** /**
* Create a new entity * Create a new entity
*
* @param request - create request parameters
*
* @returns Promise with created entity object
*/ */
async create(request: EntityCreateRequest): Promise<EntityObject> { async create(request: EntityCreateRequest): Promise<EntityObject> {
const response = await transceivePost<EntityCreateRequest, EntityCreateResponse>('entity.create', request); const response = await transceivePost<EntityCreateRequest, EntityCreateResponse>('entity.create', request);
@@ -114,6 +113,10 @@ export const entityService = {
/** /**
* Update an existing entity * Update an existing entity
*
* @param request - update request parameters
*
* @returns Promise with updated entity object
*/ */
async update(request: EntityUpdateRequest): Promise<EntityObject> { async update(request: EntityUpdateRequest): Promise<EntityObject> {
const response = await transceivePost<EntityUpdateRequest, EntityUpdateResponse>('entity.update', request); const response = await transceivePost<EntityUpdateRequest, EntityUpdateResponse>('entity.update', request);
@@ -121,7 +124,11 @@ export const entityService = {
}, },
/** /**
* Delete entities by their identifiers * Delete an entity
*
* @param request - delete request parameters
*
* @returns Promise with deletion result
*/ */
async delete(request: EntityDeleteRequest): Promise<EntityDeleteResponse> { async delete(request: EntityDeleteRequest): Promise<EntityDeleteResponse> {
return await transceivePost<EntityDeleteRequest, EntityDeleteResponse>('entity.delete', request); return await transceivePost<EntityDeleteRequest, EntityDeleteResponse>('entity.delete', request);
@@ -129,40 +136,15 @@ export const entityService = {
/** /**
* Retrieve delta changes for entities * Retrieve delta changes for entities
*
* @param request - delta request parameters
*
* @returns Promise with delta changes (created, modified, deleted)
*/ */
async delta(request: EntityDeltaRequest): Promise<EntityDeltaResponse> { async delta(request: EntityDeltaRequest): Promise<EntityDeltaResponse> {
return await transceivePost<EntityDeltaRequest, EntityDeltaResponse>('entity.delta', request); return await transceivePost<EntityDeltaRequest, EntityDeltaResponse>('entity.delta', request);
}, },
/**
* Move entities to a target collection
*/
async move(request: EntityMoveRequest): Promise<EntityMoveResponse> {
return await transceivePost<EntityMoveRequest, EntityMoveResponse>('entity.move', request);
},
/**
* Import vCards into a collection, streaming progress as it arrives.
*
* @param request - import request (target collection, raw data, options)
* @param onObject - called synchronously for each per-contact result frame
* @param onDiscovered - called once with the discovered total (progress denominator)
*
* @returns Promise resolving to { total } (objects processed) when the stream completes
*/
async import(
request: EntityImportRequest,
onObject: (object: EntityImportResponse) => void,
onDiscovered: (expected: number) => void,
): Promise<{ total: number }> {
return await transceiveStream<EntityImportRequest, EntityImportResponse>(
'entity.import',
request,
onObject,
{ onStart: (expected) => { if (expected !== undefined) onDiscovered(expected); } },
);
},
}; };
export default entityService; export default entityService;
+1 -80
View File
@@ -4,7 +4,7 @@
*/ */
import { createFetchWrapper } from '@KTXC'; import { createFetchWrapper } from '@KTXC';
import type { ApiRequest, ApiResponse, ApiStreamResponse } from '../types/common'; import type { ApiRequest, ApiResponse } from '../types/common';
const fetchWrapper = createFetchWrapper(); const fetchWrapper = createFetchWrapper();
const API_URL = '/m/chrono_manager/v1'; const API_URL = '/m/chrono_manager/v1';
@@ -48,82 +48,3 @@ export async function transceivePost<TRequest, TResponse>(
return response.data; return response.data;
} }
/**
* Stream an NDJSON API response, unwrapping data frames for the caller.
*
* @param operation - Operation name, e.g. 'entity.listStream'
* @param data - Operation-specific request data
* @param onData - Synchronous callback invoked for every unwrapped data payload.
* @param options - Optional `user` override and an `onStart` hook.
* @returns Promise resolving to the final stream total from the control/end frame
*/
export async function transceiveStream<TRequest, TData>(
operation: string,
data: TRequest,
onData: (data: TData) => void,
options?: { user?: string; onStart?: (expected?: number) => void }
): Promise<{ total: number }> {
const request: ApiRequest<TRequest> = {
version: API_VERSION,
transaction: generateTransactionId(),
operation,
data,
user: options?.user,
};
let total = 0;
const dispatch = (line: string): void => {
const message = JSON.parse(line) as ApiStreamResponse<TData>;
if (message.type === 'control') {
if (message.status === 'start') {
options?.onStart?.(message.total);
} else if (message.status === 'end') {
total = message.total;
}
return;
}
if (message.type === 'error') {
throw new Error(`[${operation}] ${message.message}`);
}
onData(message.data);
};
await fetchWrapper.post(API_URL, request, {
headers: { 'Accept': 'application/json' },
onStream: async (response: Response) => {
if (!response.body) {
throw new Error(`[${operation}] Response body is not readable`);
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop()!;
for (const line of lines) {
if (line.trim()) dispatch(line);
}
}
if (buffer.trim()) dispatch(buffer);
} finally {
reader.releaseLock();
}
},
});
return { total };
}
+127 -61
View File
@@ -4,14 +4,9 @@
import { ref, computed, readonly } from 'vue' import { ref, computed, readonly } from 'vue'
import { defineStore } from 'pinia' import { defineStore } from 'pinia'
import {
type ServiceIdentifier,
type CollectionIdentifier,
type ListFilter,
type ListSort,
} from '../types'
import { collectionService } from '../services' import { collectionService } from '../services'
import { CollectionObject, CollectionPropertiesObject } from '../models/collection' import { CollectionObject, CollectionPropertiesObject } from '../models/collection'
import type { SourceSelector, ListFilter, ListSort } from '../types'
export const useCollectionsStore = defineStore('chronoCollectionsStore', () => { export const useCollectionsStore = defineStore('chronoCollectionsStore', () => {
// State // State
@@ -41,8 +36,10 @@ export const useCollectionsStore = defineStore('chronoCollectionsStore', () => {
Object.values(_collections.value).forEach((collection) => { Object.values(_collections.value).forEach((collection) => {
const serviceKey = `${collection.provider}:${collection.service}` const serviceKey = `${collection.provider}:${collection.service}`
const serviceCollections = (groups[serviceKey] ??= []) if (!groups[serviceKey]) {
serviceCollections.push(collection) groups[serviceKey] = []
}
groups[serviceKey].push(collection)
}) })
return groups return groups
@@ -50,49 +47,87 @@ export const useCollectionsStore = defineStore('chronoCollectionsStore', () => {
/** /**
* Get a specific collection from store, with optional retrieval * Get a specific collection from store, with optional retrieval
*
* @param provider - provider identifier
* @param service - service identifier
* @param identifier - collection identifier
* @param retrieve - Retrieve behavior: true = fetch if missing or refresh, false = cache only
*
* @returns Collection object or null
*/ */
function collection(target: CollectionIdentifier, retrieve: boolean = false): CollectionObject | null { function collection(provider: string, service: string | number, identifier: string | number, retrieve: boolean = false): CollectionObject | null {
if (retrieve === true && !_collections.value[target]) { const key = identifierKey(provider, service, identifier)
console.debug(`[Chrono Manager][Store] - Force fetching collection "${target}"`) if (retrieve === true && !_collections.value[key]) {
fetch([target]) console.debug(`[Chrono Manager][Store] - Force fetching collection "${key}"`)
fetch(provider, service, identifier)
} }
return _collections.value[target] || null return _collections.value[key] || null
} }
/** /**
* Get all collections for a specific service * Get all collections for a specific service
*
* @param provider - provider identifier
* @param service - service identifier
* @param retrieve - Retrieve behavior: true = fetch if missing or refresh, false = cache only
*
* @returns Array of collection objects
*/ */
function collectionsForService(provider: string, service: string | number, retrieve: boolean = false): CollectionObject[] { function collectionsForService(provider: string, service: string | number, retrieve: boolean = false): CollectionObject[] {
const serviceIdentifier = `${provider}:${service}` as ServiceIdentifier const serviceKeyPrefix = `${provider}:${service}:`
const serviceCollections = Object.values(_collections.value) const serviceCollections = Object.entries(_collections.value)
.filter(collection => `${collection.provider}:${collection.service}` === serviceIdentifier) .filter(([key]) => key.startsWith(serviceKeyPrefix))
.map(([_, collection]) => collection)
if (retrieve === true && serviceCollections.length === 0) { if (retrieve === true && serviceCollections.length === 0) {
console.debug(`[Chrono Manager][Store] - Force fetching collections for service "${serviceIdentifier}"`) console.debug(`[Chrono Manager][Store] - Force fetching collections for service "${provider}:${service}"`)
list([serviceIdentifier]) const sources: SourceSelector = {
[provider]: {
[String(service)]: true
}
}
list(sources)
} }
return serviceCollections return serviceCollections
} }
/** /**
* Retrieve all or specific collections, optionally filtered by service/collection identifiers * Create unique key for a collection
*/ */
async function list(sources?: ServiceIdentifier[] | CollectionIdentifier[], filter?: ListFilter, sort?: ListSort): Promise<Record<string, CollectionObject>> { function identifierKey(provider: string, service: string | number | null, identifier: string | number | null): string {
return `${provider}:${service ?? ''}:${identifier ?? ''}`
}
// Actions
/**
* Retrieve all or specific collections, optionally filtered by source selector
*
* @param sources - optional source selector
* @param filter - optional list filter
* @param sort - optional list sort
*
* @returns Promise with collection object list keyed by provider, service, and collection identifier
*/
async function list(sources?: SourceSelector, filter?: ListFilter, sort?: ListSort): Promise<Record<string, CollectionObject>> {
transceiving.value = true transceiving.value = true
try { try {
const response = await collectionService.list({ sources, filter, sort }) const response = await collectionService.list({ sources, filter, sort })
// Flatten nested structure: provider:service:collection -> "provider:service:collection": object
const collections: Record<string, CollectionObject> = {} const collections: Record<string, CollectionObject> = {}
Object.entries(response).forEach(([_providerId, providerServices]) => { Object.entries(response).forEach(([_providerId, providerServices]) => {
Object.entries(providerServices).forEach(([_serviceId, serviceCollections]) => { Object.entries(providerServices).forEach(([_serviceId, serviceCollections]) => {
Object.entries(serviceCollections).forEach(([_collectionId, collectionObj]) => { Object.entries(serviceCollections).forEach(([_collectionId, collectionObj]) => {
collections[collectionObj.identifier] = collectionObj const key = identifierKey(collectionObj.provider, collectionObj.service, collectionObj.identifier)
collections[key] = collectionObj
}) })
}) })
}) })
// Merge retrieved collections into state
_collections.value = { ..._collections.value, ...collections } _collections.value = { ..._collections.value, ...collections }
console.debug('[Chrono Manager][Store] - Successfully retrieved', Object.keys(collections).length, 'collections') console.debug('[Chrono Manager][Store] - Successfully retrieved', Object.keys(collections).length, 'collections')
@@ -106,21 +141,27 @@ export const useCollectionsStore = defineStore('chronoCollectionsStore', () => {
} }
/** /**
* Retrieve specific collections by their identifiers * Retrieve a specific collection by provider, service, and identifier
*
* @param provider - provider identifier
* @param service - service identifier
* @param identifier - collection identifier
*
* @returns Promise with collection object
*/ */
async function fetch(targets: CollectionIdentifier[]): Promise<Record<string, CollectionObject>> { async function fetch(provider: string, service: string | number, identifier: string | number): Promise<CollectionObject> {
transceiving.value = true transceiving.value = true
try { try {
const response = await collectionService.fetch({ targets }) const response = await collectionService.fetch({ provider, service, collection: identifier })
Object.values(response).forEach(collectionObj => { // Merge fetched collection into state
_collections.value[collectionObj.identifier] = collectionObj const key = identifierKey(response.provider, response.service, response.identifier)
}) _collections.value[key] = response
console.debug('[Chrono Manager][Store] - Successfully fetched collections:', Object.keys(response).join(', ')) console.debug('[Chrono Manager][Store] - Successfully fetched collection:', key)
return response return response
} catch (error: any) { } catch (error: any) {
console.error('[Chrono Manager][Store] - Failed to fetch collections:', error) console.error('[Chrono Manager][Store] - Failed to fetch collection:', error)
throw error throw error
} finally { } finally {
transceiving.value = false transceiving.value = false
@@ -128,14 +169,18 @@ export const useCollectionsStore = defineStore('chronoCollectionsStore', () => {
} }
/** /**
* Retrieve collection availability status for the given collection identifiers * Retrieve collection availability status for a given source selector
*
* @param sources - source selector to check availability for
*
* @returns Promise with collection availability status
*/ */
async function extant(targets: CollectionIdentifier[]): Promise<Record<string, Record<string, Record<string, boolean>>>> { async function extant(sources: SourceSelector) {
transceiving.value = true transceiving.value = true
try { try {
const response = await collectionService.extant({ targets }) const response = await collectionService.extant({ sources })
console.debug('[Chrono Manager][Store] - Successfully checked', targets ? targets.length : 0, 'collections') console.debug('[Chrono Manager][Store] - Successfully checked', sources ? Object.keys(sources).length : 0, 'collections')
return response return response
} catch (error: any) { } catch (error: any) {
console.error('[Chrono Manager][Store] - Failed to check collections:', error) console.error('[Chrono Manager][Store] - Failed to check collections:', error)
@@ -146,20 +191,30 @@ export const useCollectionsStore = defineStore('chronoCollectionsStore', () => {
} }
/** /**
* Create a new collection with given provider, service, and properties * Create a new collection with given provider, service, and data
*
* @param provider - provider identifier for the new collection
* @param service - service identifier for the new collection
* @param collection - optional parent collection identifier
* @param data - collection properties for creation
*
* @returns Promise with created collection object
*/ */
async function create(provider: string, service: string | number, properties: CollectionPropertiesObject): Promise<CollectionObject> { async function create(provider: string, service: string | number, collection: string | number | null, data: CollectionPropertiesObject): Promise<CollectionObject> {
transceiving.value = true transceiving.value = true
try { try {
const response = await collectionService.create({ const response = await collectionService.create({
provider, provider,
service, service,
properties: properties.toJson(), collection,
properties: data
}) })
_collections.value[response.identifier] = response // Merge created collection into state
const key = identifierKey(response.provider, response.service, response.identifier)
_collections.value[key] = response
console.debug('[Chrono Manager][Store] - Successfully created collection:', response.identifier) console.debug('[Chrono Manager][Store] - Successfully created collection:', key)
return response return response
} catch (error: any) { } catch (error: any) {
console.error('[Chrono Manager][Store] - Failed to create collection:', error) console.error('[Chrono Manager][Store] - Failed to create collection:', error)
@@ -170,19 +225,30 @@ export const useCollectionsStore = defineStore('chronoCollectionsStore', () => {
} }
/** /**
* Update an existing collection with given target and properties * Update an existing collection with given provider, service, identifier, and data
*
* @param provider - provider identifier for the collection to update
* @param service - service identifier for the collection to update
* @param identifier - collection identifier for the collection to update
* @param data - collection properties for update
*
* @returns Promise with updated collection object
*/ */
async function update(target: CollectionIdentifier, properties: CollectionPropertiesObject): Promise<CollectionObject> { async function update(provider: string, service: string | number, identifier: string | number, data: CollectionPropertiesObject): Promise<CollectionObject> {
transceiving.value = true transceiving.value = true
try { try {
const response = await collectionService.update({ const response = await collectionService.update({
target, provider,
properties: properties.toJson(), service,
identifier,
properties: data
}) })
_collections.value[response.identifier] = response // Merge updated collection into state
const key = identifierKey(response.provider, response.service, response.identifier)
_collections.value[key] = response
console.debug('[Chrono Manager][Store] - Successfully updated collection:', response.identifier) console.debug('[Chrono Manager][Store] - Successfully updated collection:', key)
return response return response
} catch (error: any) { } catch (error: any) {
console.error('[Chrono Manager][Store] - Failed to update collection:', error) console.error('[Chrono Manager][Store] - Failed to update collection:', error)
@@ -193,28 +259,24 @@ export const useCollectionsStore = defineStore('chronoCollectionsStore', () => {
} }
/** /**
* Delete a collection by identifier. * Delete a collection by provider, service, and identifier
*
* @param provider - provider identifier for the collection to delete
* @param service - service identifier for the collection to delete
* @param identifier - collection identifier for the collection to delete
*
* @returns Promise with deletion result
*/ */
async function remove(target: CollectionIdentifier, force?: boolean): Promise<CollectionObject | boolean> { async function remove(provider: string, service: string | number, identifier: string | number): Promise<any> {
transceiving.value = true transceiving.value = true
try { try {
const response = await collectionService.delete({ target, options: { force } }) await collectionService.delete({ provider, service, identifier })
if (response !== true && !(response instanceof CollectionObject)) { // Remove deleted collection from state
console.warn('[Chrono Manager][Store] - Delete failed. Received unexpected response from delete operation:', response) const key = identifierKey(provider, service, identifier)
return false delete _collections.value[key]
}
delete _collections.value[target] console.debug('[Chrono Manager][Store] - Successfully deleted collection:', key)
if (response instanceof CollectionObject) {
_collections.value[response.identifier] = response
console.debug('[Chrono Manager][Store] - Successfully moved collection', target, '->', response.identifier)
return response
}
console.debug('[Chrono Manager][Store] - Successfully deleted collection:', target)
return response
} catch (error: any) { } catch (error: any) {
console.error('[Chrono Manager][Store] - Failed to delete collection:', error) console.error('[Chrono Manager][Store] - Failed to delete collection:', error)
throw error throw error
@@ -223,13 +285,17 @@ export const useCollectionsStore = defineStore('chronoCollectionsStore', () => {
} }
} }
// Return public API
return { return {
// State (readonly)
transceiving: readonly(transceiving), transceiving: readonly(transceiving),
// Getters
count, count,
has, has,
collections, collections,
collectionsByService, collectionsByService,
collectionsForService, collectionsForService,
// Actions
collection, collection,
list, list,
fetch, fetch,
+204 -185
View File
@@ -6,14 +6,7 @@ import { ref, computed, readonly } from 'vue'
import { defineStore } from 'pinia' import { defineStore } from 'pinia'
import { entityService } from '../services' import { entityService } from '../services'
import { EntityObject } from '../models' import { EntityObject } from '../models'
import type { import type { SourceSelector, ListFilter, ListSort, ListRange } from '../types/common'
CollectionIdentifier,
EntityIdentifier,
ListFilter,
ListRange,
ListSort,
} from '../types/common'
import type { EntityPropertiesInterface } from '@/types/entity'
export const useEntitiesStore = defineStore('chronoEntitiesStore', () => { export const useEntitiesStore = defineStore('chronoEntitiesStore', () => {
// State // State
@@ -37,45 +30,96 @@ export const useEntitiesStore = defineStore('chronoEntitiesStore', () => {
/** /**
* Get a specific entity from store, with optional retrieval * Get a specific entity from store, with optional retrieval
*
* @param provider - provider identifier
* @param service - service identifier
* @param collection - collection identifier
* @param identifier - entity identifier
* @param retrieve - Retrieve behavior: true = fetch if missing or refresh, false = cache only
*
* @returns Entity object or null
*/ */
function entity(target: EntityIdentifier, retrieve: boolean = false): EntityObject | null { function entity(provider: string, service: string | number, collection: string | number, identifier: string | number, retrieve: boolean = false): EntityObject | null {
if (retrieve === true && !_entities.value[target]) { const key = identifierKey(provider, service, collection, identifier)
console.debug(`[Chrono Manager][Store] - Force fetching entity "${target}"`) if (retrieve === true && !_entities.value[key]) {
fetch([target]) console.debug(`[Chrono Manager][Store] - Force fetching entity "${key}"`)
fetch(provider, service, collection, [identifier])
} }
return _entities.value[target] || null return _entities.value[key] || null
} }
/** /**
* Get all entities for a specific collection * Get all entities for a specific collection
*
* @param provider - provider identifier
* @param service - service identifier
* @param collection - collection identifier
* @param retrieve - Retrieve behavior: true = fetch if missing or refresh, false = cache only
*
* @returns Array of entity objects
*/ */
function entitiesForCollection(target: CollectionIdentifier, retrieve: boolean = false): EntityObject[] { function entitiesForCollection(provider: string, service: string | number, collection: string | number, retrieve: boolean = false): EntityObject[] {
const collectionKeyPrefix = `${provider}:${service}:${collection}:`
const collectionEntities = Object.entries(_entities.value) const collectionEntities = Object.entries(_entities.value)
.filter(([key]) => key.startsWith(`${target}:`)) .filter(([key]) => key.startsWith(collectionKeyPrefix))
.map(([_, entity]) => entity) .map(([_, entity]) => entity)
if (retrieve === true && collectionEntities.length === 0) { if (retrieve === true && collectionEntities.length === 0) {
console.debug(`[Chrono Manager][Store] - Force fetching entities for collection "${target}"`) console.debug(`[Chrono Manager][Store] - Force fetching entities for collection "${provider}:${service}:${collection}"`)
list([target]) const sources: SourceSelector = {
[provider]: {
[String(service)]: {
[String(collection)]: true
}
}
}
list(sources)
} }
return collectionEntities return collectionEntities
} }
/** /**
* Retrieve all or specific entities, optionally filtered by source collection identifiers * Create unique key for an entity
*/ */
async function list(sources: CollectionIdentifier[], filter?: ListFilter, sort?: ListSort, range?: ListRange): Promise<Record<string, EntityObject>> { function identifierKey(provider: string, service: string | number, collection: string | number, identifier: string | number): string {
return `${provider}:${service}:${collection}:${identifier}`
}
// Actions
/**
* Retrieve all or specific entities, optionally filtered by source selector
*
* @param sources - optional source selector
* @param filter - optional list filter
* @param sort - optional list sort
* @param range - optional list range
*
* @returns Promise with entity object list keyed by identifier
*/
async function list(sources?: SourceSelector, filter?: ListFilter, sort?: ListSort, range?: ListRange): Promise<Record<string, EntityObject>> {
transceiving.value = true transceiving.value = true
try { try {
const entities: Record<string, EntityObject> = {} const response = await entityService.list({ sources, filter, sort, range })
await entityService.listStream({ sources, filter, sort, range }, (entity: EntityObject) => { // Flatten nested structure: provider:service:collection:entity -> "provider:service:collection:entity": object
_entities.value[entity.identifier] = entity const entities: Record<string, EntityObject> = {}
entities[entity.identifier] = entity Object.entries(response).forEach(([providerId, providerServices]) => {
Object.entries(providerServices).forEach(([serviceId, serviceCollections]) => {
Object.entries(serviceCollections).forEach(([collectionId, collectionEntities]) => {
Object.entries(collectionEntities).forEach(([entityId, entityData]) => {
const key = identifierKey(providerId, serviceId, collectionId, entityId)
entities[key] = entityData
})
})
})
}) })
// Merge retrieved entities into state
_entities.value = { ..._entities.value, ...entities }
console.debug('[Chrono Manager][Store] - Successfully retrieved', Object.keys(entities).length, 'entities') console.debug('[Chrono Manager][Store] - Successfully retrieved', Object.keys(entities).length, 'entities')
return entities return entities
} catch (error: any) { } catch (error: any) {
@@ -87,17 +131,26 @@ export const useEntitiesStore = defineStore('chronoEntitiesStore', () => {
} }
/** /**
* Retrieve specific entities by their identifiers * Retrieve specific entities by provider, service, collection, and identifiers
*
* @param provider - provider identifier
* @param service - service identifier
* @param collection - collection identifier
* @param identifiers - array of entity identifiers to fetch
*
* @returns Promise with entity objects keyed by identifier
*/ */
async function fetch(targets: EntityIdentifier[]): Promise<Record<string, EntityObject>> { async function fetch(provider: string, service: string | number, collection: string | number, identifiers: (string | number)[]): Promise<Record<string, EntityObject>> {
transceiving.value = true transceiving.value = true
try { try {
const response = await entityService.fetch({ targets }) const response = await entityService.fetch({ provider, service, collection, identifiers })
// Merge fetched entities into state
const entities: Record<string, EntityObject> = {} const entities: Record<string, EntityObject> = {}
Object.entries(response).forEach(([identifier, entity]) => { Object.entries(response).forEach(([identifier, entityData]) => {
entities[identifier] = entity const key = identifierKey(provider, service, collection, identifier)
_entities.value[identifier] = entity entities[key] = entityData
_entities.value[key] = entityData
}) })
console.debug('[Chrono Manager][Store] - Successfully fetched', Object.keys(entities).length, 'entities') console.debug('[Chrono Manager][Store] - Successfully fetched', Object.keys(entities).length, 'entities')
@@ -111,12 +164,16 @@ export const useEntitiesStore = defineStore('chronoEntitiesStore', () => {
} }
/** /**
* Retrieve entity availability status for a given set of entity identifiers * Retrieve entity availability status for a given source selector
*
* @param sources - source selector to check availability for
*
* @returns Promise with entity availability status
*/ */
async function extant(targets: EntityIdentifier[]) { async function extant(sources: SourceSelector) {
transceiving.value = true transceiving.value = true
try { try {
const response = await entityService.extant({ targets }) const response = await entityService.extant({ sources })
console.debug('[Chrono Manager][Store] - Successfully checked entity availability') console.debug('[Chrono Manager][Store] - Successfully checked entity availability')
return response return response
} catch (error: any) { } catch (error: any) {
@@ -128,27 +185,131 @@ export const useEntitiesStore = defineStore('chronoEntitiesStore', () => {
} }
/** /**
* Retrieve delta changes for entities * Create a new entity with given provider, service, collection, and data
*
* @param provider - provider identifier for the new entity
* @param service - service identifier for the new entity
* @param collection - collection identifier for the new entity
* @param data - entity properties for creation
*
* @returns Promise with created entity object
*/ */
async function delta(targets: (CollectionIdentifier | EntityIdentifier)[]) { async function create(provider: string, service: string | number, collection: string | number, data: any): Promise<EntityObject> {
transceiving.value = true transceiving.value = true
try { try {
const response = await entityService.delta({ targets }) const response = await entityService.create({ provider, service, collection, properties: data })
Object.entries(response).forEach(([, providerData]) => { // Add created entity to state
const key = identifierKey(response.provider, response.service, response.collection, response.identifier)
_entities.value[key] = response
console.debug('[Chrono Manager][Store] - Successfully created entity:', key)
return response
} catch (error: any) {
console.error('[Chrono Manager][Store] - Failed to create entity:', error)
throw error
} finally {
transceiving.value = false
}
}
/**
* Update an existing entity with given provider, service, collection, identifier, and data
*
* @param provider - provider identifier for the entity to update
* @param service - service identifier for the entity to update
* @param collection - collection identifier for the entity to update
* @param identifier - entity identifier for the entity to update
* @param data - entity properties for update
*
* @returns Promise with updated entity object
*/
async function update(provider: string, service: string | number, collection: string | number, identifier: string | number, data: any): Promise<EntityObject> {
transceiving.value = true
try {
const response = await entityService.update({ provider, service, collection, identifier, properties: data })
// Update entity in state
const key = identifierKey(response.provider, response.service, response.collection, response.identifier)
_entities.value[key] = response
console.debug('[Chrono Manager][Store] - Successfully updated entity:', key)
return response
} catch (error: any) {
console.error('[Chrono Manager][Store] - Failed to update entity:', error)
throw error
} finally {
transceiving.value = false
}
}
/**
* Delete an entity by provider, service, collection, and identifier
*
* @param provider - provider identifier for the entity to delete
* @param service - service identifier for the entity to delete
* @param collection - collection identifier for the entity to delete
* @param identifier - entity identifier for the entity to delete
*
* @returns Promise with deletion result
*/
async function remove(provider: string, service: string | number, collection: string | number, identifier: string | number): Promise<any> {
transceiving.value = true
try {
const response = await entityService.delete({ provider, service, collection, identifier })
// Remove entity from state
const key = identifierKey(provider, service, collection, identifier)
delete _entities.value[key]
console.debug('[Chrono Manager][Store] - Successfully deleted entity:', key)
return response
} catch (error: any) {
console.error('[Chrono Manager][Store] - Failed to delete entity:', error)
throw error
} finally {
transceiving.value = false
}
}
/**
* Retrieve delta changes for entities
*
* @param sources - source selector for delta check
*
* @returns Promise with delta changes (additions, modifications, deletions)
*
* Note: Delta returns only identifiers, not full entities.
* Caller should fetch full entities for additions/modifications separately.
*/
async function delta(sources: SourceSelector) {
transceiving.value = true
try {
const response = await entityService.delta({ sources })
// Process delta and update store
Object.entries(response).forEach(([provider, providerData]) => {
// Skip if no changes for provider
if (providerData === false) return if (providerData === false) return
Object.entries(providerData).forEach(([, serviceData]) => { Object.entries(providerData).forEach(([service, serviceData]) => {
// Skip if no changes for service
if (serviceData === false) return if (serviceData === false) return
Object.entries(serviceData).forEach(([, collectionData]) => { Object.entries(serviceData).forEach(([collection, collectionData]) => {
// Skip if no changes for collection
if (collectionData === false) return if (collectionData === false) return
// Process deletions (remove from store)
if (collectionData.deletions && collectionData.deletions.length > 0) { if (collectionData.deletions && collectionData.deletions.length > 0) {
collectionData.deletions.forEach((identifier) => { collectionData.deletions.forEach((identifier) => {
delete _entities.value[identifier] const key = identifierKey(provider, service, collection, identifier)
delete _entities.value[key]
}) })
} }
// Note: additions and modifications contain only identifiers
// The caller should fetch full entities using the fetch() method
}) })
}) })
}) })
@@ -163,156 +324,16 @@ export const useEntitiesStore = defineStore('chronoEntitiesStore', () => {
} }
} }
/** // Return public API
* Create a new empty entity object
*/
function fresh(): EntityObject {
return new EntityObject()
}
/**
* Create a new entity with given collection identifier and properties
*/
async function create(target: CollectionIdentifier, properties: EntityPropertiesInterface): Promise<EntityObject> {
transceiving.value = true
try {
const response = await entityService.create({ target, properties })
_entities.value[response.identifier] = response
console.debug('[Chrono Manager][Store] - Successfully created entity:', response.identifier)
return response
} catch (error: any) {
console.error('[Chrono Manager][Store] - Failed to create entity:', error)
throw error
} finally {
transceiving.value = false
}
}
/**
* Update an existing entity with given entity identifier and properties
*/
async function update(target: EntityIdentifier, properties: EntityPropertiesInterface): Promise<EntityObject> {
transceiving.value = true
try {
const response = await entityService.update({ target, properties })
_entities.value[response.identifier] = response
console.debug('[Chrono Manager][Store] - Successfully updated entity:', response.identifier)
return response
} catch (error: any) {
console.error('[Chrono Manager][Store] - Failed to update entity:', error)
throw error
} finally {
transceiving.value = false
}
}
/**
* Delete entities by their identifiers.
*/
async function remove(targets: EntityIdentifier[]): Promise<{ successes: EntityIdentifier[], failures: EntityIdentifier[] }> {
transceiving.value = true
try {
const response = await entityService.delete({ targets })
const successes: EntityIdentifier[] = []
const failures: EntityIdentifier[] = []
Object.entries(response).forEach(([targetIdentifier, result]) => {
const originalIdentifier = targetIdentifier as EntityIdentifier
if (!result.disposition || result.disposition === 'error') {
console.warn(`[Chrono Manager][Store] - Entity delete on "${originalIdentifier}" returned an error: ${result.error})`)
failures.push(originalIdentifier)
return
}
if (result.disposition !== 'moved' && result.disposition !== 'deleted') {
console.warn(`[Chrono Manager][Store] - Entity delete on "${originalIdentifier}" returned invalid disposition: ${result.disposition})`)
failures.push(originalIdentifier)
return
}
const cachedEntity = _entities.value[originalIdentifier]
if (result.disposition === 'moved' && cachedEntity && result.mutation) {
const movedEntity = cachedEntity.clone().fromJson({
...cachedEntity.toJson(),
collection: result.destination,
identifier: result.mutation,
})
_entities.value[result.mutation] = movedEntity
}
delete _entities.value[originalIdentifier]
successes.push(originalIdentifier)
})
console.debug('[Chrono Manager][Store] - Successfully deleted', successes.length, 'entities')
return { successes, failures }
} catch (error: any) {
console.error('[Chrono Manager][Store] - Failed to delete entities:', error)
throw error
} finally {
transceiving.value = false
}
}
/**
* Move entities to another collection.
*/
async function move(target: CollectionIdentifier, sources: EntityIdentifier[]): Promise<{ successes: EntityIdentifier[], failures: EntityIdentifier[] }> {
transceiving.value = true
try {
const response = await entityService.move({ target, sources })
const successes: EntityIdentifier[] = []
const failures: EntityIdentifier[] = []
Object.entries(response).forEach(([sourceIdentifier, result]) => {
const originalIdentifier = sourceIdentifier as EntityIdentifier
if (!result.disposition || result.disposition === 'error') {
console.warn(`[Chrono Manager][Store] - Entity move on "${originalIdentifier}" returned an error: ${result.error})`)
failures.push(originalIdentifier)
return
}
if (result.disposition !== 'moved') {
console.warn(`[Chrono Manager][Store] - Entity move on "${originalIdentifier}" returned invalid disposition: ${result.disposition})`)
failures.push(originalIdentifier)
return
}
const cachedEntity = _entities.value[originalIdentifier]
if (cachedEntity && result.mutation) {
const movedEntity = cachedEntity.clone().fromJson({
...cachedEntity.toJson(),
collection: result.destination,
identifier: result.mutation,
})
_entities.value[result.mutation] = movedEntity
delete _entities.value[originalIdentifier]
}
successes.push(originalIdentifier)
})
console.debug('[Chrono Manager][Store] - Successfully moved', successes.length, 'entities')
return { successes, failures }
} catch (error: any) {
console.error('[Chrono Manager][Store] - Failed to move entities:', error)
throw error
} finally {
transceiving.value = false
}
}
return { return {
// State (readonly)
transceiving: readonly(transceiving), transceiving: readonly(transceiving),
// Getters
count, count,
has, has,
entities, entities,
entitiesForCollection, entitiesForCollection,
// Actions
entity, entity,
list, list,
fetch, fetch,
@@ -321,7 +342,5 @@ export const useEntitiesStore = defineStore('chronoEntitiesStore', () => {
update, update,
delete: remove, delete: remove,
delta, delta,
fresh,
move,
} }
}) })
-124
View File
@@ -1,124 +0,0 @@
/**
* Contact Import Store
*/
import { computed, ref } from 'vue'
import { defineStore } from 'pinia'
import { entityService } from '../services/entityService'
import type { CollectionIdentifier } from '../types/common'
import type { EntityImportResponse } from '../types/entity'
import type {
ImportCounters,
ImportFileAdd,
ImportFileEntry,
ImportFileOptions,
ImportSession,
ImportSessionStage
} from '../types/import'
const RECENT_RESULTS_CAP = 25
const emptyCounters = (): ImportCounters => ({ discovered: 0, processed: 0, created: 0, updated: 0, exists: 0, error: 0 })
export const useImportStore = defineStore('chronoImportStore', () => {
// State
const nextId = ref(0)
const files = ref<ImportFileEntry[]>([])
const stage = ref<ImportSessionStage>('idle')
const running = ref(false)
const sessions = ref<Record<number, ImportSession>>({})
const order = ref<number[]>([])
// Computed
const totals = computed(() => order.value.reduce((total, id) => {
const counters = sessions.value[id]?.counters
if (counters) Object.keys(total).forEach(key => {
total[key as keyof ImportCounters] += counters[key as keyof ImportCounters]
})
return total
}, emptyCounters()))
// Actions
function addFile(file: ImportFileAdd): number {
const id = nextId.value++
files.value.push({
file: { id, ...file },
collectionId: null,
options: { supersede: false }
})
return id
}
function removeAllFiles() {
files.value = []
}
function reset() {
stage.value = 'idle';
running.value = false;
sessions.value = {};
order.value = [];
}
function entryFor(id: number) {
return files.value.find(entry => entry.file.id === id)
}
/** Set the destination collection for a queued file. */
function setCollectionForFile(id: number, collectionId: CollectionIdentifier | null) {
const entry = entryFor(id);
if (entry) entry.collectionId = collectionId;
}
/** Merge option changes for a queued file without dropping untouched keys. */
function setOptionsForFile(id: number, options: Partial<ImportFileOptions>) {
const entry = entryFor(id);
if (entry) entry.options = { ...entry.options, ...options };
}
async function startImport(): Promise<ImportCounters> {
const entries = [...files.value]
sessions.value = {}
order.value = entries.map(entry => entry.file.id)
for (const entry of entries) sessions.value[entry.file.id] = {
fileId: entry.file.id, fileName: entry.file.name, targetIdentifier: entry.collectionId,
status: 'pending', counters: emptyCounters(), recentResults: [], lastError: null,
}
running.value = true
stage.value = 'importing'
try {
for (const entry of entries) {
const session = sessions.value[entry.file.id]!
if (!entry.collectionId) throw new Error(`No calendar selected for "${entry.file.name}"`)
session.status = 'importing'
try {
await entityService.import(
{ target: entry.collectionId, data: entry.file.contents, options: entry.options },
(object: EntityImportResponse) => {
session.counters.processed++
session.counters[object.disposition]++
session.recentResults = [object, ...session.recentResults].slice(0, RECENT_RESULTS_CAP)
},
expected => { session.counters.discovered = expected },
)
session.status = session.counters.error ? 'error' : 'completed'
} catch (error) {
session.status = 'error'
session.lastError = error instanceof Error ? error.message : String(error)
throw error
}
}
stage.value = 'completed'
return totals.value
} catch (error) {
stage.value = 'error'
throw error
} finally { running.value = false }
}
return { files, stage, running, sessions, order, totals, addFile, removeAllFiles, reset, setCollectionForFile, setOptionsForFile, startImport }
})
-1
View File
@@ -2,4 +2,3 @@ export { useProvidersStore } from './providersStore';
export { useServicesStore } from './servicesStore'; export { useServicesStore } from './servicesStore';
export { useCollectionsStore } from './collectionsStore'; export { useCollectionsStore } from './collectionsStore';
export { useEntitiesStore } from './entitiesStore'; export { useEntitiesStore } from './entitiesStore';
export { useImportStore } from './importStore';
+7 -7
View File
@@ -6,7 +6,7 @@ import { ref, computed, readonly } from 'vue'
import { defineStore } from 'pinia' import { defineStore } from 'pinia'
import { providerService } from '../services' import { providerService } from '../services'
import { ProviderObject } from '../models/provider' import { ProviderObject } from '../models/provider'
import type { ProviderIdentifier } from '../types' import type { SourceSelector } from '../types'
export const useProvidersStore = defineStore('chronoProvidersStore', () => { export const useProvidersStore = defineStore('chronoProvidersStore', () => {
// State // State
@@ -54,10 +54,10 @@ export const useProvidersStore = defineStore('chronoProvidersStore', () => {
* *
* @returns Promise with provider object list keyed by provider identifier * @returns Promise with provider object list keyed by provider identifier
*/ */
async function list(targets?: ProviderIdentifier[]): Promise<Record<string, ProviderObject>> { async function list(sources?: SourceSelector): Promise<Record<string, ProviderObject>> {
transceiving.value = true transceiving.value = true
try { try {
const providers = await providerService.list({ targets }) const providers = await providerService.list({ sources })
// Merge retrieved providers into state // Merge retrieved providers into state
_providers.value = { ..._providers.value, ...providers } _providers.value = { ..._providers.value, ...providers }
@@ -82,7 +82,7 @@ export const useProvidersStore = defineStore('chronoProvidersStore', () => {
async function fetch(identifier: string): Promise<ProviderObject> { async function fetch(identifier: string): Promise<ProviderObject> {
transceiving.value = true transceiving.value = true
try { try {
const provider = await providerService.fetch({ target: identifier }) const provider = await providerService.fetch({ identifier })
// Merge fetched provider into state // Merge fetched provider into state
_providers.value[provider.identifier] = provider _providers.value[provider.identifier] = provider
@@ -104,10 +104,10 @@ export const useProvidersStore = defineStore('chronoProvidersStore', () => {
* *
* @returns Promise with provider availability status * @returns Promise with provider availability status
*/ */
async function extant(targets: ProviderIdentifier[]) { async function extant(sources: SourceSelector) {
transceiving.value = true transceiving.value = true
try { try {
const response = await providerService.extant({ targets }) const response = await providerService.extant({ sources })
Object.entries(response).forEach(([providerId, providerStatus]) => { Object.entries(response).forEach(([providerId, providerStatus]) => {
if (providerStatus === false) { if (providerStatus === false) {
@@ -115,7 +115,7 @@ export const useProvidersStore = defineStore('chronoProvidersStore', () => {
} }
}) })
console.debug('[Chrono Manager][Store] - Successfully checked', targets ? targets.length : 0, 'providers') console.debug('[Chrono Manager][Store] - Successfully checked', sources ? Object.keys(sources).length : 0, 'providers')
return response return response
} catch (error: any) { } catch (error: any) {
console.error('[Chrono Manager][Store] - Failed to check providers:', error) console.error('[Chrono Manager][Store] - Failed to check providers:', error)
+15 -31
View File
@@ -7,8 +7,7 @@ import { defineStore } from 'pinia'
import { serviceService } from '../services' import { serviceService } from '../services'
import { ServiceObject } from '../models/service' import { ServiceObject } from '../models/service'
import type { import type {
CollectionIdentifier, SourceSelector,
ServiceIdentifier,
ServiceInterface, ServiceInterface,
} from '../types' } from '../types'
@@ -56,30 +55,20 @@ export const useServicesStore = defineStore('chronoServicesStore', () => {
* @returns Service object or null * @returns Service object or null
*/ */
function service(provider: string, identifier: string | number, retrieve: boolean = false): ServiceObject | null { function service(provider: string, identifier: string | number, retrieve: boolean = false): ServiceObject | null {
return serviceByIdentifier(identifierKey(provider, identifier), retrieve) const key = identifierKey(provider, identifier)
} if (retrieve === true && !_services.value[key]) {
console.debug(`[Chrono Manager][Store] - Force fetching service "${key}"`)
/** fetch(provider, identifier)
* Get a service from store by its unique identifier, with optional retrieval
*/
function serviceByIdentifier(identifier: ServiceIdentifier, retrieve: boolean = false): ServiceObject | null {
if (retrieve === true && !_services.value[identifier]) {
console.debug(`[Chrono Manager][Store] - Force fetching service "${identifier}"`)
const separatorIndex = identifier.indexOf(':')
const provider = identifier.slice(0, separatorIndex)
const serviceIdentifier = identifier.slice(separatorIndex + 1)
void fetch(provider, serviceIdentifier)
} }
return _services.value[identifier] ?? null return _services.value[key] || null
} }
/** /**
* Unique key for a service * Unique key for a service
*/ */
function identifierKey(provider: string, identifier: string | number | null): ServiceIdentifier { function identifierKey(provider: string, identifier: string | number | null): string {
return `${provider}:${identifier ?? ''}` as ServiceIdentifier return `${provider}:${identifier ?? ''}`
} }
// Actions // Actions
@@ -91,10 +80,10 @@ export const useServicesStore = defineStore('chronoServicesStore', () => {
* *
* @returns Promise with service object list keyed by provider and service identifier * @returns Promise with service object list keyed by provider and service identifier
*/ */
async function list(targets?: ServiceIdentifier[] | CollectionIdentifier[]): Promise<Record<string, ServiceObject>> { async function list(sources?: SourceSelector): Promise<Record<string, ServiceObject>> {
transceiving.value = true transceiving.value = true
try { try {
const response = await serviceService.list({ targets }) const response = await serviceService.list({ sources })
// Flatten nested structure: provider-id: { service-id: object } -> "provider-id:service-id": object // Flatten nested structure: provider-id: { service-id: object } -> "provider-id:service-id": object
const services: Record<string, ServiceObject> = {} const services: Record<string, ServiceObject> = {}
@@ -152,12 +141,12 @@ export const useServicesStore = defineStore('chronoServicesStore', () => {
* *
* @returns Promise with service availability status * @returns Promise with service availability status
*/ */
async function extant(targets: ServiceIdentifier[]) { async function extant(sources: SourceSelector) {
transceiving.value = true transceiving.value = true
try { try {
const response = await serviceService.extant({ targets }) const response = await serviceService.extant({ sources })
console.debug('[Chrono Manager][Store] - Successfully checked', targets?.length ?? 0, 'services') console.debug('[Chrono Manager][Store] - Successfully checked', sources ? Object.keys(sources).length : 0, 'services')
return response return response
} catch (error: any) { } catch (error: any) {
console.error('[Chrono Manager][Store] - Failed to check services:', error) console.error('[Chrono Manager][Store] - Failed to check services:', error)
@@ -203,14 +192,10 @@ export const useServicesStore = defineStore('chronoServicesStore', () => {
* *
* @returns Promise with updated service object * @returns Promise with updated service object
*/ */
async function update(provider: string, identifier: string | number, delta: boolean, data: ServiceObject | Partial<ServiceInterface>): Promise<ServiceObject> { async function update(provider: string, identifier: string | number, data: Partial<ServiceInterface>): Promise<ServiceObject> {
transceiving.value = true transceiving.value = true
try { try {
const payload: Partial<ServiceInterface> = data instanceof ServiceObject const service = await serviceService.update({ provider, identifier, data })
? (delta ? data.toJson(true) : data.toJson())
: data
const service = await serviceService.update({ provider, identifier, delta, data: payload })
// Merge updated service into state // Merge updated service into state
const key = identifierKey(service.provider, service.identifier) const key = identifierKey(service.provider, service.identifier)
@@ -264,7 +249,6 @@ export const useServicesStore = defineStore('chronoServicesStore', () => {
// Actions // Actions
service, service,
serviceByIdentifier,
list, list,
fetch, fetch,
extant, extant,
+20 -28
View File
@@ -1,37 +1,27 @@
/** /**
* Collection type definitions * Collection type definitions
*/ */
import type { import type { ListFilter, ListSort, SourceSelector } from './common';
ServiceIdentifier,
CollectionIdentifier,
ListFilter,
ListSort
} from './common';
/** /**
* Collection information * Collection information
*/ */
export interface CollectionInterface<T = CollectionPropertiesInterface> { export interface CollectionInterface {
'@type': string;
version: number;
provider: string; provider: string;
service: string | number; service: string | number;
collection: CollectionIdentifier | null; collection: string | number | null;
identifier: CollectionIdentifier; identifier: string | number;
signature?: string | null; signature?: string | null;
created?: string | null; created?: string | null;
modified?: string | null; modified?: string | null;
properties: T; properties: CollectionPropertiesInterface;
}
export interface CollectionModelInterface extends Omit<CollectionInterface<CollectionPropertiesInterface>, '@type' | 'version' | 'properties'> {
properties: CollectionPropertiesModelInterface;
} }
export type CollectionContentTypes = 'event' | 'task' | 'journal'; export type CollectionContentTypes = 'event' | 'task' | 'journal';
export interface CollectionBaseProperties { export interface CollectionBaseProperties {
'@type': string; '@type': string;
version: number;
} }
export interface CollectionImmutableProperties extends CollectionBaseProperties { export interface CollectionImmutableProperties extends CollectionBaseProperties {
@@ -48,13 +38,11 @@ export interface CollectionMutableProperties extends CollectionBaseProperties {
export interface CollectionPropertiesInterface extends CollectionMutableProperties, CollectionImmutableProperties {} export interface CollectionPropertiesInterface extends CollectionMutableProperties, CollectionImmutableProperties {}
export interface CollectionPropertiesModelInterface extends Omit<CollectionPropertiesInterface, '@type'> {}
/** /**
* Collection list * Collection list
*/ */
export interface CollectionListRequest { export interface CollectionListRequest {
sources?: ServiceIdentifier[] | CollectionIdentifier[]; sources?: SourceSelector;
filter?: ListFilter; filter?: ListFilter;
sort?: ListSort; sort?: ListSort;
} }
@@ -71,18 +59,18 @@ export interface CollectionListResponse {
* Collection fetch * Collection fetch
*/ */
export interface CollectionFetchRequest { export interface CollectionFetchRequest {
targets: CollectionIdentifier[]; provider: string;
service: string | number;
collection: string | number;
} }
export interface CollectionFetchResponse { export interface CollectionFetchResponse extends CollectionInterface {}
[identifier: CollectionIdentifier]: CollectionInterface;
}
/** /**
* Collection extant * Collection extant
*/ */
export interface CollectionExtantRequest { export interface CollectionExtantRequest {
targets: CollectionIdentifier[]; sources: SourceSelector;
} }
export interface CollectionExtantResponse { export interface CollectionExtantResponse {
@@ -99,6 +87,7 @@ export interface CollectionExtantResponse {
export interface CollectionCreateRequest { export interface CollectionCreateRequest {
provider: string; provider: string;
service: string | number; service: string | number;
collection?: string | number | null; // Parent Collection Identifier
properties: CollectionMutableProperties; properties: CollectionMutableProperties;
} }
@@ -108,7 +97,9 @@ export interface CollectionCreateResponse extends CollectionInterface {}
* Collection modify * Collection modify
*/ */
export interface CollectionUpdateRequest { export interface CollectionUpdateRequest {
target: CollectionIdentifier; provider: string;
service: string | number;
identifier: string | number;
properties: CollectionMutableProperties; properties: CollectionMutableProperties;
} }
@@ -118,13 +109,14 @@ export interface CollectionUpdateResponse extends CollectionInterface {}
* Collection delete * Collection delete
*/ */
export interface CollectionDeleteRequest { export interface CollectionDeleteRequest {
target: CollectionIdentifier; provider: string;
service: string | number;
identifier: string | number;
options?: { options?: {
force?: boolean; // Whether to force delete even if collection is not empty force?: boolean; // Whether to force delete even if collection is not empty
}; };
} }
export interface CollectionDeleteResponse { export interface CollectionDeleteResponse {
disposition: 'deleted' | 'moved'; success: boolean;
mutation?: CollectionInterface | null; // If moved, the new location of the collection
} }
+28 -65
View File
@@ -44,57 +44,34 @@ export interface ApiErrorResponse {
export type ApiResponse<T = any> = ApiSuccessResponse<T> | ApiErrorResponse; export type ApiResponse<T = any> = ApiSuccessResponse<T> | ApiErrorResponse;
/** /**
* Stream control start line. * Selector for targeting specific providers, services, collections, or entities in list or extant operations.
*/
export interface ApiStreamStartResponse {
type: 'control';
status: 'start';
version: number;
transaction: string;
total?: number;
}
/**
* Stream control end line
*/
export interface ApiStreamEndResponse {
type: 'control';
status: 'end';
total: number;
}
/**
* Stream error line
*/
export interface ApiStreamErrorResponse {
type: 'error';
message: string;
}
export interface ApiStreamDataResponse<T = any> {
type: 'data';
data: T;
}
/**
* Shared stream control lines
*/
export type ApiStreamResponse<T = any> =
| ApiStreamStartResponse
| ApiStreamEndResponse
| ApiStreamErrorResponse
| ApiStreamDataResponse<T>;
/**
* Identifiers for targeting specific providers, services, collections, or entities in list or extant operations.
* *
* Operations accept flat arrays of colon-separated identifier strings, e.g. * Example usage:
* ["caldav:account1:calendar", "caldav:account1:calendar:1001"]. * {
* "provider1": true, // Select all services/collections/entities under provider1
* "provider2": {
* "serviceA": true, // Select all collections/entities under serviceA of provider2
* "serviceB": {
* "collectionX": true, // Select all entities under collectionX of serviceB of provider2
* "collectionY": [1, 2, 3] // Select entities with identifiers 1, 2, and 3 under collectionY of serviceB of provider2
* }
* }
* }
*/ */
export type ProviderIdentifier = `${string}`; export type SourceSelector = {
export type ServiceIdentifier = `${string}:${string}`; [provider: string]: boolean | ServiceSelector;
export type CollectionIdentifier = `${string}:${string}:${string | number}`; };
export type EntityIdentifier = `${string}:${string}:${string}:${string | number}`;
export type ServiceSelector = {
[service: string]: boolean | CollectionSelector;
};
export type CollectionSelector = {
[collection: string | number]: boolean | EntitySelector;
};
export type EntitySelector = (string | number)[];
/** /**
* Filter comparison for list operations * Filter comparison for list operations
@@ -165,29 +142,15 @@ export interface ListSort {
} }
/** /**
* Tally (pagination) range for list operations * Range for list operations
* *
* Values can be: * Values can be:
* - relative based on item identifier * - relative based on item identifier
* - absolute based on item count * - absolute based on item count
*/ */
export interface ListRangeTally { export interface ListRange {
type: 'tally'; type: 'tally';
anchor: 'relative' | 'absolute'; anchor: 'relative' | 'absolute';
position: string | number; position: string | number;
tally: number; tally: number;
} }
/**
* Date (pagination) range for list operations
*/
export interface ListRangeDate {
type: 'date';
start: number;
end: number;
}
/**
* Range for list operations
*/
export type ListRange = ListRangeTally | ListRangeDate;
+55 -106
View File
@@ -1,86 +1,64 @@
/** /**
* Entity type definitions * Entity type definitions
*/ */
import type { import type { ListFilter, ListRange, ListSort, SourceSelector } from './common';
CollectionIdentifier,
EntityIdentifier,
ListFilter,
ListRange,
ListSort,
} from './common';
import type { EventInterface } from './event'; import type { EventInterface } from './event';
import type { TaskInterface } from './task'; import type { TaskInterface } from './task';
import type { JournalInterface } from './journal'; import type { JournalInterface } from './journal';
import type { ImportDisposition, ImportFileOptions } from './import';
export type EntityPropertiesInterface = EventInterface | TaskInterface | JournalInterface;
/** /**
* Entity definition * Entity definition
*/ */
export interface EntityInterface<T = EntityPropertiesInterface> { export interface EntityInterface<T = EventInterface | TaskInterface | JournalInterface> {
'@type': string;
version: number;
provider: string; provider: string;
service: string; service: string;
collection: CollectionIdentifier; collection: string | number;
identifier: EntityIdentifier; identifier: string | number;
signature: string | null; signature: string | null;
created: string | null; created: string | null;
modified: string | null; modified: string | null;
properties: T; properties: T;
} }
export interface EntityModelInterface extends Omit<EntityInterface<EntityPropertiesInterface>, '@type' | 'version'> {}
/** /**
* Entity list bulk * Entity list
*/ */
export interface EntityListBulkRequest { export interface EntityListRequest {
sources?: CollectionIdentifier[]; sources?: SourceSelector;
filter?: ListFilter; filter?: ListFilter;
sort?: ListSort; sort?: ListSort;
range?: ListRange; range?: ListRange;
} }
export interface EntityListBulkResponse { export interface EntityListResponse {
[providerId: string]: { [providerId: string]: {
[serviceId: string]: { [serviceId: string]: {
[collectionId: string]: { [collectionId: string]: {
[identifier: string]: EntityInterface; [identifier: string]: EntityInterface<EventInterface | TaskInterface | JournalInterface>;
}; };
}; };
}; };
} }
/**
* Entity list stream
*/
export interface EntityListStreamRequest {
sources?: CollectionIdentifier[];
filter?: ListFilter;
sort?: ListSort;
range?: ListRange;
}
export interface EntityListStreamResponse extends EntityInterface {}
/** /**
* Entity fetch * Entity fetch
*/ */
export interface EntityFetchRequest { export interface EntityFetchRequest {
targets: EntityIdentifier[]; provider: string;
service: string | number;
collection: string | number;
identifiers: (string | number)[];
} }
export interface EntityFetchResponse { export interface EntityFetchResponse {
[identifier: string]: EntityInterface; [identifier: string]: EntityInterface<EventInterface | TaskInterface | JournalInterface>;
} }
/** /**
* Entity extant * Entity extant
*/ */
export interface EntityExtantRequest { export interface EntityExtantRequest {
targets: EntityIdentifier[]; sources: SourceSelector;
} }
export interface EntityExtantResponse { export interface EntityExtantResponse {
@@ -93,13 +71,50 @@ export interface EntityExtantResponse {
}; };
} }
/**
* Entity create
*/
export interface EntityCreateRequest<T = EventInterface | TaskInterface | JournalInterface> {
provider: string;
service: string | number;
collection: string | number;
properties: T;
}
export interface EntityCreateResponse<T = EventInterface | TaskInterface | JournalInterface> extends EntityInterface<T> {}
/**
* Entity update
*/
export interface EntityUpdateRequest<T = EventInterface | TaskInterface | JournalInterface> {
provider: string;
service: string | number;
collection: string | number;
identifier: string | number;
properties: T;
}
export interface EntityUpdateResponse<T = EventInterface | TaskInterface | JournalInterface> extends EntityInterface<T> {}
/**
* Entity delete
*/
export interface EntityDeleteRequest {
provider: string;
service: string | number;
collection: string | number;
identifier: string | number;
}
export interface EntityDeleteResponse {
success: boolean;
}
/** /**
* Entity delta * Entity delta
*/ */
export interface EntityDeltaRequest { export interface EntityDeltaRequest {
// Each target is provider:service:collection, or provider:service:collection:signature sources: SourceSelector;
// to request a delta relative to a known signature (the signature is the entity slot).
targets: (CollectionIdentifier | EntityIdentifier)[];
} }
export interface EntityDeltaResponse { export interface EntityDeltaResponse {
@@ -114,69 +129,3 @@ export interface EntityDeltaResponse {
}; };
}; };
} }
/**
* Entity create
*/
export interface EntityCreateRequest<T = EntityPropertiesInterface> {
target: CollectionIdentifier;
properties: T;
options?: Record<string, any>;
}
export interface EntityCreateResponse<T = EntityPropertiesInterface> extends EntityInterface<T> {}
/**
* Entity update
*/
export interface EntityUpdateRequest<T = EntityPropertiesInterface> {
target: EntityIdentifier;
properties: T;
}
export interface EntityUpdateResponse<T = EntityPropertiesInterface> extends EntityInterface<T> {}
/**
* Entity delete
*/
export interface EntityDeleteRequest {
targets: EntityIdentifier[];
}
export interface EntityDeleteResponse {
[targetIdentifier: EntityIdentifier]: {
disposition: 'deleted' | 'moved' | 'error';
destination: CollectionIdentifier | null;
mutation: EntityIdentifier | null;
error?: string;
};
}
/**
* Entity move
*/
export interface EntityMoveRequest {
target: CollectionIdentifier;
sources: EntityIdentifier[];
}
export interface EntityMoveResponse {
[sourceIdentifier: EntityIdentifier]: {
disposition: 'moved' | 'error';
destination: CollectionIdentifier | null;
mutation: EntityIdentifier | null;
error?: string;
};
}
export interface EntityImportRequest {
target: CollectionIdentifier;
data: string;
options: ImportFileOptions;
}
export interface EntityImportResponse {
identifier: string | null;
disposition: ImportDisposition;
errors: string[];
}
-19
View File
@@ -1,19 +0,0 @@
import type { CollectionIdentifier } from './common';
import type { EntityImportResponse } from './entity';
export type ImportDisposition = 'created' | 'updated' | 'exists' | 'error';
export type ImportSessionStage = 'idle' | 'selecting' | 'importing' | 'completed' | 'error';
export interface ImportFileOptions { supersede: boolean; }
export interface ImportFileSource { id: number; name: string; contents: string; size: number; type: string; }
export type ImportFileAdd = Omit<ImportFileSource, 'id'>;
export interface ImportFileEntry { file: ImportFileSource; collectionId: CollectionIdentifier | null; options: ImportFileOptions; }
export interface ImportCounters { discovered: number; processed: number; created: number; updated: number; exists: number; error: number; }
export interface ImportSession {
fileId: number;
fileName: string;
targetIdentifier: CollectionIdentifier | null;
status: 'pending' | 'importing' | 'completed' | 'error';
counters: ImportCounters;
recentResults: EntityImportResponse[];
lastError: string | null;
}
-1
View File
@@ -3,7 +3,6 @@ export type * from './common';
export type * from './entity'; export type * from './entity';
export type * from './event'; export type * from './event';
export type * from './journal'; export type * from './journal';
export type * from './import';
export type * from './provider'; export type * from './provider';
export type * from './service'; export type * from './service';
export type * from './task'; export type * from './task';
+6 -8
View File
@@ -1,7 +1,7 @@
/** /**
* Provider type definitions * Provider type definitions
*/ */
import type { ProviderIdentifier } from './common'; import type { SourceSelector } from "./common";
/** /**
* Provider capabilities * Provider capabilities
@@ -28,24 +28,22 @@ export interface ProviderInterface {
capabilities: ProviderCapabilitiesInterface; capabilities: ProviderCapabilitiesInterface;
} }
export interface ProviderModelInterface extends Omit<ProviderInterface, '@type'> {}
/** /**
* Provider list * Provider list
*/ */
export interface ProviderListRequest { export interface ProviderListRequest {
targets?: ProviderIdentifier[]; sources?: SourceSelector;
} }
export interface ProviderListResponse { export interface ProviderListResponse {
[identifier: ProviderIdentifier]: ProviderInterface; [identifier: string]: ProviderInterface;
} }
/** /**
* Provider fetch * Provider fetch
*/ */
export interface ProviderFetchRequest { export interface ProviderFetchRequest {
target: ProviderIdentifier; identifier: string;
} }
export interface ProviderFetchResponse extends ProviderInterface {} export interface ProviderFetchResponse extends ProviderInterface {}
@@ -54,9 +52,9 @@ export interface ProviderFetchResponse extends ProviderInterface {}
* Provider extant * Provider extant
*/ */
export interface ProviderExtantRequest { export interface ProviderExtantRequest {
targets: ProviderIdentifier[]; sources: SourceSelector;
} }
export interface ProviderExtantResponse { export interface ProviderExtantResponse {
[identifier: ProviderIdentifier]: boolean; [identifier: string]: boolean;
} }
+3 -17
View File
@@ -1,13 +1,7 @@
/** /**
* Service type definitions * Service type definitions
*/ */
import type { import type { SourceSelector, ListFilterComparisonOperator } from './common';
ServiceIdentifier,
CollectionIdentifier,
ListFilterComparisonOperator,
} from './common';
import type { Identity } from '@/models/identity';
import type { Location } from '@/models/location';
/** /**
* Service capabilities * Service capabilities
@@ -53,18 +47,11 @@ export interface ServiceInterface {
auxiliary?: Record<string, any>; // Provider-specific extension data auxiliary?: Record<string, any>; // Provider-specific extension data
} }
export interface ServiceModelInterface extends Omit<{
[K in keyof ServiceInterface]-?: Exclude<ServiceInterface[K], undefined>;
}, '@type' | 'location' | 'identity'> {
location: Location | null;
identity: Identity | null;
}
/** /**
* Service list * Service list
*/ */
export interface ServiceListRequest { export interface ServiceListRequest {
targets?: ServiceIdentifier[] | CollectionIdentifier[]; sources?: SourceSelector;
} }
export interface ServiceListResponse { export interface ServiceListResponse {
@@ -87,7 +74,7 @@ export interface ServiceFetchResponse extends ServiceInterface {}
* Service extant * Service extant
*/ */
export interface ServiceExtantRequest { export interface ServiceExtantRequest {
targets: ServiceIdentifier[]; sources: SourceSelector;
} }
export interface ServiceExtantResponse { export interface ServiceExtantResponse {
@@ -112,7 +99,6 @@ export interface ServiceCreateResponse extends ServiceInterface {}
export interface ServiceUpdateRequest { export interface ServiceUpdateRequest {
provider: string; provider: string;
identifier: string | number; identifier: string | number;
delta?: boolean;
data: Partial<ServiceInterface>; data: Partial<ServiceInterface>;
} }
-30
View File
@@ -1,30 +0,0 @@
import { describe, it, expect } from 'vitest'
describe('Basic Tests', () => {
it('should perform basic assertion', () => {
expect(true).toBe(true)
})
it('should test array operations', () => {
const array = ['foo', 'bar', 'baz']
expect(array).toHaveLength(3)
expect(array).toContain('bar')
expect(array[0]).toBe('foo')
})
it('should test string operations', () => {
const string = 'Hello, World!'
expect(string).toContain('World')
expect(string.length).toBe(13)
})
it('should test object operations', () => {
const obj = { foo: 'bar', count: 42 }
expect(obj).toHaveProperty('foo')
expect(obj.foo).toBe('bar')
expect(obj.count).toBeGreaterThan(40)
})
})
-31
View File
@@ -1,31 +0,0 @@
import { fileURLToPath } from 'node:url'
import { defineConfig, configDefaults } from 'vitest/config'
import path from 'path'
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
export default defineConfig({
resolve: {
alias: {
'@': path.resolve(__dirname, '../../src'),
'@KTXC': path.resolve(__dirname, '../../../../core/src'),
},
},
test: {
environment: 'jsdom',
exclude: [...configDefaults.exclude, 'e2e/**'],
root: fileURLToPath(new URL('../../', import.meta.url)),
coverage: {
provider: 'v8',
reporter: ['text', 'json', 'html'],
exclude: [
'node_modules/',
'tests/',
'**/*.d.ts',
'**/*.config.*',
'**/dist/**',
],
},
},
})
-29
View File
@@ -1,29 +0,0 @@
<?php
namespace KTXT\ChronoManager\Tests\Integration;
use PHPUnit\Framework\TestCase;
class BaseTest extends TestCase
{
public function testBasicAssertion(): void
{
$this->assertTrue(true);
}
public function testArrayOperations(): void
{
$array = ['foo' => 'bar'];
$this->assertArrayHasKey('foo', $array);
$this->assertEquals('bar', $array['foo']);
}
public function testStringOperations(): void
{
$string = 'Hello, World!';
$this->assertStringContainsString('World', $string);
$this->assertEquals(13, strlen($string));
}
}
-29
View File
@@ -1,29 +0,0 @@
<?php
namespace KTXT\ChronoManager\Tests\Unit;
use PHPUnit\Framework\TestCase;
class BaseTest extends TestCase
{
public function testBasicAssertion(): void
{
$this->assertTrue(true);
}
public function testArrayOperations(): void
{
$array = ['foo' => 'bar'];
$this->assertArrayHasKey('foo', $array);
$this->assertEquals('bar', $array['foo']);
}
public function testStringOperations(): void
{
$string = 'Hello, World!';
$this->assertStringContainsString('World', $string);
$this->assertEquals(13, strlen($string));
}
}
-17
View File
@@ -1,17 +0,0 @@
<?php
require dirname(__DIR__, 2).'/lib/vendor/autoload.php';
// When this module is checked out inside a full server (server/modules/<handle>,
// as it is in CI and in this monorepo checkout), also load the server's own
// core/shared autoloader so tests can reference framework (KTXC/KTXF) types.
// Standalone module checkouts without a server alongside them skip this.
define('SERVER_ROOT', dirname(__DIR__, 4));
$serverAutoload = SERVER_ROOT . '/vendor/autoload.php';
if (is_file($serverAutoload)) {
require $serverAutoload;
}
if (isset($_SERVER['APP_DEBUG']) && $_SERVER['APP_DEBUG']) {
umask(0000);
}
-41
View File
@@ -1,41 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- https://phpunit.readthedocs.io/en/latest/configuration.html -->
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="../../lib/vendor/phpunit/phpunit/phpunit.xsd"
colors="true"
failOnDeprecation="true"
failOnNotice="true"
failOnWarning="true"
bootstrap="bootstrap.php"
cacheDirectory="../../.phpunit.cache"
>
<php>
<ini name="display_errors" value="1" />
<ini name="error_reporting" value="-1" />
<server name="APP_ENV" value="test" force="true" />
<server name="SHELL_VERBOSITY" value="-1" />
</php>
<testsuites>
<testsuite name="Unit Tests">
<directory>Unit</directory>
</testsuite>
<testsuite name="Integration Tests">
<directory>Integration</directory>
</testsuite>
</testsuites>
<source ignoreSuppressionOfDeprecations="true"
ignoreIndirectDeprecations="true"
restrictNotices="true"
restrictWarnings="true"
>
<include>
<directory>../../lib</directory>
</include>
</source>
<extensions>
</extensions>
</phpunit>