Compare commits
70 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b3c74ffe38 | |||
| 1f4b627536 | |||
| 0b93f1a183 | |||
| 6a9a7d31e7 | |||
| b5759958a8 | |||
| 1b7bc18b42 | |||
| b6d3610e32 | |||
| 5891e3a070 | |||
| aed6b1bdad | |||
| 39fc49ab07 | |||
| a3d67da88a | |||
| a80df9c580 | |||
| f1288c4cad | |||
| 7614265ac3 | |||
| a6e5098ed4 | |||
| 3d1a07e0ad | |||
| fa5165aa38 | |||
| c0f5867ff3 | |||
| 4da25b6924 | |||
| cc0bc97d9a | |||
| 44ca40cc6e | |||
| e04a23c1f4 | |||
| 34c5b3046c | |||
| f0171941a7 | |||
| df110c83db | |||
| c4e007a017 | |||
| e3c7249186 | |||
| 92deabc880 | |||
| 5d1faf24ea | |||
| 1adb039678 | |||
| 17602f077a | |||
| db748efffd | |||
| b7e12621cd | |||
| 0880bba063 | |||
| 80a8dac2fd | |||
| 08c1de9723 | |||
| c2fe90518f | |||
| ec9f277287 | |||
| 2f7c5b3b67 | |||
| 557f42a06c | |||
| 4a4c1df269 | |||
| b1b657fe6c | |||
| b6065c23fa | |||
| 392a92c5ca | |||
| e5b2ab441b | |||
| 2b556a4835 | |||
| cd61016c90 | |||
| d42dba12c4 | |||
| c97bbf7fc9 | |||
| a2e162d474 | |||
| 35172ef7ba | |||
| 53f34e111e | |||
| 145e0ce0d4 | |||
| d258c4c084 | |||
| 551d80a484 | |||
| cc4ced8e92 | |||
| 672f49458e | |||
| 99d7dab9c6 | |||
| e31f39c5f6 | |||
| fe8316c748 | |||
| 59abed19d7 | |||
| 741f774b55 | |||
| dbb107c98f | |||
| 1a1528c15f | |||
| 751353b637 | |||
| aa9295d752 | |||
| 791225e64a | |||
| 6c16dcd659 | |||
| 4ddcd9cdb6 | |||
| 30de830ace |
@@ -0,0 +1,42 @@
|
||||
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
|
||||
@@ -0,0 +1,42 @@
|
||||
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
|
||||
@@ -0,0 +1,59 @@
|
||||
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
|
||||
@@ -0,0 +1,42 @@
|
||||
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
|
||||
@@ -25,11 +25,17 @@ jobs:
|
||||
tools: composer:v2
|
||||
|
||||
- name: Install Renovate
|
||||
run: npm install -g renovate
|
||||
run: |
|
||||
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
|
||||
env:
|
||||
RENOVATE_TOKEN: ${{ secrets.RENOVATE_TOKEN }}
|
||||
RENOVATE_PLATFORM: gitea
|
||||
RENOVATE_ENDPOINT: https://git.ktrix.dev/api/v1
|
||||
run: renovate ${{ gitea.repository }}
|
||||
run: |
|
||||
"${{ runner.temp }}/renovate-npm/bin/renovate" ${{ gitea.repository }}
|
||||
+1
-4
@@ -14,10 +14,7 @@ node_modules/
|
||||
# Backend development
|
||||
/lib/vendor/
|
||||
coverage/
|
||||
phpunit.xml.cache
|
||||
.phpunit.result.cache
|
||||
.php-cs-fixer.cache
|
||||
.phpstan.cache
|
||||
*.cache
|
||||
.phpactor/
|
||||
|
||||
# Editors
|
||||
|
||||
+15
-2
@@ -10,17 +10,30 @@
|
||||
"config": {
|
||||
"optimize-autoloader": true,
|
||||
"platform": {
|
||||
"php": "8.2"
|
||||
"php": "8.3"
|
||||
},
|
||||
"autoloader-suffix": "ChronoManager",
|
||||
"vendor-dir": "lib/vendor"
|
||||
},
|
||||
"require": {
|
||||
"php": ">=8.2 <=8.5"
|
||||
"php": ">=8.3 <=8.5",
|
||||
"sabre/vobject": "^5.0"
|
||||
},
|
||||
"require-dev": {
|
||||
"phpunit/phpunit": "^12.0"
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"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
+1934
-8
File diff suppressed because it is too large
Load Diff
@@ -11,12 +11,24 @@ namespace KTXM\ChronoManager\Controllers;
|
||||
|
||||
use InvalidArgumentException;
|
||||
use KTXC\Http\Response\JsonResponse;
|
||||
use KTXC\SessionIdentity;
|
||||
use KTXC\SessionTenant;
|
||||
use KTXC\Http\Response\Response;
|
||||
use KTXC\Http\Response\StreamedNdJsonResponse;
|
||||
use KTXC\Http\Response\StreamedResponse;
|
||||
use KTXC\Context\IdentityContextInterface;
|
||||
use KTXC\Context\TenantContextInterface;
|
||||
use KTXF\Controller\ControllerAbstract;
|
||||
use KTXF\Resource\Selector\SourceSelector;
|
||||
use KTXF\Json\JsonSerializable;
|
||||
use KTXF\Resource\Identifier\CollectionIdentifier;
|
||||
use KTXF\Resource\Identifier\EntityIdentifier;
|
||||
use KTXF\Resource\Identifier\ResourceIdentifier;
|
||||
use KTXF\Resource\Identifier\ResourceIdentifiers;
|
||||
use KTXF\Resource\Identifier\ServiceIdentifier;
|
||||
use KTXF\Routing\Attributes\AuthenticatedRoute;
|
||||
use KTXM\ChronoManager\Export\ExportService;
|
||||
use KTXM\ChronoManager\Import\ImportOptions;
|
||||
use KTXM\ChronoManager\Import\ImportService;
|
||||
use KTXM\ChronoManager\Manager;
|
||||
use KTXM\ChronoManager\Stream\ExpectedTotal;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Throwable;
|
||||
|
||||
@@ -25,26 +37,41 @@ class DefaultController extends ControllerAbstract {
|
||||
private const ERR_MISSING_PROVIDER = 'Missing parameter: provider';
|
||||
private const ERR_MISSING_IDENTIFIER = 'Missing parameter: identifier';
|
||||
private const ERR_MISSING_SERVICE = 'Missing parameter: service';
|
||||
private const ERR_MISSING_COLLECTION = 'Missing parameter: collection';
|
||||
private const ERR_MISSING_DATA = 'Missing parameter: data';
|
||||
private const ERR_MISSING_SOURCES = 'Missing parameter: sources';
|
||||
private const ERR_MISSING_IDENTIFIERS = 'Missing parameter: identifiers';
|
||||
private const ERR_MISSING_TARGET = 'Missing parameter: target';
|
||||
private const ERR_MISSING_TARGETS = 'Missing parameter: targets';
|
||||
private const ERR_INVALID_OPERATION = 'Invalid operation: ';
|
||||
private const ERR_INVALID_PROVIDER = 'Invalid parameter: provider must be a string';
|
||||
private const ERR_INVALID_SERVICE = 'Invalid parameter: service must be a string';
|
||||
private const ERR_INVALID_IDENTIFIER = 'Invalid parameter: identifier must be a string';
|
||||
private const ERR_INVALID_COLLECTION = 'Invalid parameter: collection must be a string or integer';
|
||||
private const ERR_INVALID_SOURCES = 'Invalid parameter: sources must be an array';
|
||||
private const ERR_INVALID_IDENTIFIERS = 'Invalid parameter: identifiers must be an array';
|
||||
private const ERR_INVALID_TARGET = 'Invalid parameter: target must be an array';
|
||||
private const ERR_INVALID_TARGETS = 'Invalid parameter: targets must be an array';
|
||||
private const ERR_INVALID_DATA = 'Invalid parameter: data must be an array';
|
||||
|
||||
public function __construct(
|
||||
private readonly SessionTenant $tenantIdentity,
|
||||
private readonly SessionIdentity $userIdentity,
|
||||
private readonly TenantContextInterface $tenantContext,
|
||||
private readonly IdentityContextInterface $identityContext,
|
||||
private readonly Manager $manager,
|
||||
private readonly ImportService $importService,
|
||||
private readonly ExportService $exportService,
|
||||
private readonly LoggerInterface $logger,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Main API endpoint for chrono operations
|
||||
*
|
||||
* Single operation:
|
||||
* {
|
||||
* "version": 1,
|
||||
* "transaction": "tx-1",
|
||||
* "operation": "entity.create",
|
||||
* "data": {...}
|
||||
* }
|
||||
*
|
||||
* @return JsonResponse
|
||||
*/
|
||||
#[AuthenticatedRoute('/v1', name: 'chrono.manager.v1', methods: ['POST'])]
|
||||
public function index(
|
||||
int $version,
|
||||
@@ -52,16 +79,21 @@ class DefaultController extends ControllerAbstract {
|
||||
string|null $operation = null,
|
||||
array|null $data = null,
|
||||
string|null $user = null
|
||||
): JsonResponse {
|
||||
): Response {
|
||||
|
||||
// authorize request
|
||||
$tenantId = $this->tenantIdentity->identifier();
|
||||
$userId = $this->userIdentity->identifier();
|
||||
$tenantId = $this->tenantContext->identifier();
|
||||
$userId = $this->identityContext->identifier();
|
||||
|
||||
try {
|
||||
|
||||
if ($operation !== null) {
|
||||
$result = $this->processOperation($tenantId, $userId, $operation, $data ?? [], []);
|
||||
$result = $this->processOperation($tenantId, $userId, $operation, $data ?? [], $version, $transaction);
|
||||
|
||||
if ($result instanceof Response) {
|
||||
return $result;
|
||||
}
|
||||
|
||||
return new JsonResponse([
|
||||
'version' => $version,
|
||||
'transaction' => $transaction,
|
||||
@@ -88,10 +120,11 @@ class DefaultController extends ControllerAbstract {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Process a single operation
|
||||
*/
|
||||
private function processOperation(string $tenantId, string $userId, string $operation, array $data): mixed {
|
||||
private function processOperation(string $tenantId, string $userId, string $operation, array $data, int $version = 1, string $transaction = ''): mixed {
|
||||
return match ($operation) {
|
||||
// Provider operations
|
||||
'provider.list' => $this->providerList($tenantId, $userId, $data),
|
||||
@@ -105,7 +138,7 @@ class DefaultController extends ControllerAbstract {
|
||||
'service.create' => $this->serviceCreate($tenantId, $userId, $data),
|
||||
'service.update' => $this->serviceUpdate($tenantId, $userId, $data),
|
||||
'service.delete' => $this->serviceDelete($tenantId, $userId, $data),
|
||||
'service.test' => $this->serviceTest($tenantId, $userId, $data),
|
||||
'service.test' => throw new InvalidArgumentException('Operation not implemented: ' . $operation),
|
||||
|
||||
// Collection operations
|
||||
'collection.list' => $this->collectionList($tenantId, $userId, $data),
|
||||
@@ -116,15 +149,17 @@ class DefaultController extends ControllerAbstract {
|
||||
'collection.delete' => $this->collectionDelete($tenantId, $userId, $data),
|
||||
|
||||
// Entity operations
|
||||
'entity.list' => $this->entityList($tenantId, $userId, $data),
|
||||
'entity.listBulk' => $this->entityListBulk($tenantId, $userId, $data),
|
||||
'entity.listStream' => $this->entityListStream($tenantId, $userId, $data, $version, $transaction),
|
||||
'entity.fetch' => $this->entityFetch($tenantId, $userId, $data),
|
||||
'entity.extant' => $this->entityExtant($tenantId, $userId, $data),
|
||||
'entity.delta' => $this->entityDelta($tenantId, $userId, $data),
|
||||
'entity.create' => $this->entityCreate($tenantId, $userId, $data),
|
||||
'entity.update' => $this->entityUpdate($tenantId, $userId, $data),
|
||||
'entity.delete' => $this->entityDelete($tenantId, $userId, $data),
|
||||
'entity.delta' => $this->entityDelta($tenantId, $userId, $data),
|
||||
'entity.move' => throw new InvalidArgumentException('Operation not implemented: ' . $operation),
|
||||
'entity.copy' => throw new InvalidArgumentException('Operation not implemented: ' . $operation),
|
||||
'entity.move' => $this->entityMove($tenantId, $userId, $data),
|
||||
'entity.import' => $this->entityImport($tenantId, $userId, $data, $version, $transaction),
|
||||
'entity.export' => $this->entityExport($tenantId, $userId, $data),
|
||||
|
||||
default => throw new InvalidArgumentException(self::ERR_INVALID_OPERATION . $operation)
|
||||
};
|
||||
@@ -134,40 +169,48 @@ class DefaultController extends ControllerAbstract {
|
||||
|
||||
private function providerList(string $tenantId, string $userId, array $data): mixed {
|
||||
|
||||
$sources = null;
|
||||
if (isset($data['sources']) && is_array($data['sources'])) {
|
||||
$sources = new SourceSelector();
|
||||
$sources->jsonDeserialize($data['sources']);
|
||||
if (isset($data['targets'])) {
|
||||
if (!is_array($data['targets'])) {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_TARGETS);
|
||||
}
|
||||
|
||||
return $this->manager->providerList($tenantId, $userId, $sources);
|
||||
foreach ($data['targets'] as $target) {
|
||||
if (!is_string($target)) {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_TARGETS);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $this->manager->providerList($tenantId, $userId, $data['targets'] ?? []);
|
||||
|
||||
}
|
||||
|
||||
private function providerFetch(string $tenantId, string $userId, array $data): mixed {
|
||||
|
||||
if (!isset($data['identifier'])) {
|
||||
throw new InvalidArgumentException(self::ERR_MISSING_IDENTIFIER);
|
||||
if (!isset($data['target'])) {
|
||||
throw new InvalidArgumentException(self::ERR_MISSING_TARGET);
|
||||
}
|
||||
if (!is_string($data['identifier'])) {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_IDENTIFIER);
|
||||
if (!is_string($data['target'])) {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_TARGET);
|
||||
}
|
||||
|
||||
return $this->manager->providerFetch($tenantId, $userId, $data['identifier']);
|
||||
return $this->manager->providerFetch($tenantId, $userId, $data['target']);
|
||||
|
||||
}
|
||||
|
||||
private function providerExtant(string $tenantId, string $userId, array $data): mixed {
|
||||
|
||||
if (!isset($data['sources'])) {
|
||||
throw new InvalidArgumentException(self::ERR_MISSING_SOURCES);
|
||||
if (!isset($data['targets'])) {
|
||||
throw new InvalidArgumentException(self::ERR_MISSING_TARGETS);
|
||||
}
|
||||
if (!is_array($data['sources'])) {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_SOURCES);
|
||||
}
|
||||
$sources = new SourceSelector();
|
||||
$sources->jsonDeserialize($data['sources']);
|
||||
|
||||
return $this->manager->providerExtant($tenantId, $userId, $sources);
|
||||
foreach ($data['targets'] as $target) {
|
||||
if (!is_string($target)) {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_TARGETS);
|
||||
}
|
||||
}
|
||||
|
||||
return $this->manager->providerExtant($tenantId, $userId, $data['targets']);
|
||||
|
||||
}
|
||||
|
||||
@@ -175,13 +218,17 @@ class DefaultController extends ControllerAbstract {
|
||||
|
||||
private function serviceList(string $tenantId, string $userId, array $data): mixed {
|
||||
|
||||
$sources = null;
|
||||
if (isset($data['sources']) && is_array($data['sources'])) {
|
||||
$sources = new SourceSelector();
|
||||
$sources->jsonDeserialize($data['sources']);
|
||||
$targets = null;
|
||||
if (isset($data['targets']) && is_array($data['targets'])) {
|
||||
$targets = ResourceIdentifiers::fromArray($data['targets']);
|
||||
foreach ($targets as $target) {
|
||||
if (!$target instanceof CollectionIdentifier && !$target instanceof ServiceIdentifier) {
|
||||
throw new InvalidArgumentException('Invalid parameter: targets must contain provider:service, provider:service:collection, or provider:service:collection:entity identifiers');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $this->manager->serviceList($tenantId, $userId, $sources);
|
||||
return $this->manager->serviceList($tenantId, $userId, $targets);
|
||||
|
||||
}
|
||||
|
||||
@@ -205,16 +252,20 @@ class DefaultController extends ControllerAbstract {
|
||||
|
||||
private function serviceExtant(string $tenantId, string $userId, array $data): mixed {
|
||||
|
||||
if (!isset($data['sources'])) {
|
||||
throw new InvalidArgumentException(self::ERR_MISSING_SOURCES);
|
||||
if (!isset($data['targets'])) {
|
||||
throw new InvalidArgumentException(self::ERR_MISSING_TARGETS);
|
||||
}
|
||||
if (!is_array($data['targets'])) {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_TARGETS);
|
||||
}
|
||||
$targets = ResourceIdentifiers::fromArray($data['targets']);
|
||||
foreach ($targets as $target) {
|
||||
if (!$target instanceof ServiceIdentifier) {
|
||||
throw new InvalidArgumentException('Invalid parameter: targets must contain provider:service identifiers');
|
||||
}
|
||||
if (!is_array($data['sources'])) {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_SOURCES);
|
||||
}
|
||||
$sources = new SourceSelector();
|
||||
$sources->jsonDeserialize($data['sources']);
|
||||
|
||||
return $this->manager->serviceExtant($tenantId, $userId, $sources);
|
||||
return $this->manager->serviceExtant($tenantId, $userId, $targets);
|
||||
}
|
||||
|
||||
private function serviceCreate(string $tenantId, string $userId, array $data): mixed {
|
||||
@@ -258,13 +309,17 @@ class DefaultController extends ControllerAbstract {
|
||||
if (!is_array($data['data'])) {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_DATA);
|
||||
}
|
||||
if (isset($data['delta']) && !is_bool($data['delta'])) {
|
||||
throw new InvalidArgumentException('Invalid parameter: delta must be a boolean');
|
||||
}
|
||||
|
||||
return $this->manager->serviceUpdate(
|
||||
$tenantId,
|
||||
$userId,
|
||||
$data['provider'],
|
||||
$data['identifier'],
|
||||
$data['data']
|
||||
$data['data'],
|
||||
$data['delta'] ?? false,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -290,36 +345,17 @@ class DefaultController extends ControllerAbstract {
|
||||
);
|
||||
}
|
||||
|
||||
private function serviceTest(string $tenantId, string $userId, array $data): mixed {
|
||||
|
||||
if (!isset($data['provider'])) {
|
||||
throw new InvalidArgumentException(self::ERR_MISSING_PROVIDER);
|
||||
}
|
||||
if (!is_string($data['provider'])) {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_PROVIDER);
|
||||
}
|
||||
|
||||
if (!isset($data['identifier']) && !isset($data['location']) && !isset($data['identity'])) {
|
||||
throw new InvalidArgumentException('Either a service identifier or location and identity must be provided for service test');
|
||||
}
|
||||
|
||||
return $this->manager->serviceTest(
|
||||
$tenantId,
|
||||
$userId,
|
||||
$data['provider'],
|
||||
$data['identifier'] ?? null,
|
||||
$data['location'] ?? null,
|
||||
$data['identity'] ?? null,
|
||||
);
|
||||
}
|
||||
|
||||
// ==================== Collection Operations ====================
|
||||
|
||||
private function collectionList(string $tenantId, string $userId, array $data): mixed {
|
||||
$sources = null;
|
||||
if (isset($data['sources']) && is_array($data['sources'])) {
|
||||
$sources = new SourceSelector();
|
||||
$sources->jsonDeserialize($data['sources']);
|
||||
$sources = ResourceIdentifiers::fromArray($data['sources']);
|
||||
foreach ($sources as $source) {
|
||||
if (!$source instanceof CollectionIdentifier && !$source instanceof ServiceIdentifier) {
|
||||
throw new InvalidArgumentException('Invalid parameter: sources must contain provider:service, provider:service:collection, or provider:service:collection:entity identifiers');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$filter = $data['filter'] ?? null;
|
||||
@@ -328,47 +364,45 @@ class DefaultController extends ControllerAbstract {
|
||||
return $this->manager->collectionList($tenantId, $userId, $sources, $filter, $sort);
|
||||
}
|
||||
|
||||
private function collectionExtant(string $tenantId, string $userId, array $data): mixed {
|
||||
if (!isset($data['sources'])) {
|
||||
throw new InvalidArgumentException(self::ERR_MISSING_SOURCES);
|
||||
}
|
||||
if (!is_array($data['sources'])) {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_SOURCES);
|
||||
}
|
||||
|
||||
$sources = new SourceSelector();
|
||||
$sources->jsonDeserialize($data['sources']);
|
||||
|
||||
return $this->manager->collectionExtant($tenantId, $userId, $sources);
|
||||
}
|
||||
|
||||
private function collectionFetch(string $tenantId, string $userId, array $data): mixed {
|
||||
if (!isset($data['provider'])) {
|
||||
throw new InvalidArgumentException(self::ERR_MISSING_PROVIDER);
|
||||
if (!isset($data['targets'])) {
|
||||
throw new InvalidArgumentException(self::ERR_MISSING_TARGETS);
|
||||
}
|
||||
if (!is_string($data['provider'])) {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_PROVIDER);
|
||||
}
|
||||
if (!isset($data['service'])) {
|
||||
throw new InvalidArgumentException(self::ERR_MISSING_SERVICE);
|
||||
}
|
||||
if (!is_string($data['service'])) {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_SERVICE);
|
||||
}
|
||||
if (!isset($data['identifier'])) {
|
||||
throw new InvalidArgumentException(self::ERR_MISSING_IDENTIFIER);
|
||||
}
|
||||
if (!is_string($data['identifier']) && !is_int($data['identifier'])) {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_COLLECTION);
|
||||
if (!is_array($data['targets'])) {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_TARGETS);
|
||||
}
|
||||
|
||||
return $this->manager->collectionFetch(
|
||||
$targetIdentifiers = ResourceIdentifiers::fromArray($data['targets']);
|
||||
foreach ($targetIdentifiers as $targetIdentifier) {
|
||||
if (!$targetIdentifier instanceof CollectionIdentifier) {
|
||||
throw new InvalidArgumentException('Invalid parameter: target must be provider:service:collection');
|
||||
}
|
||||
}
|
||||
|
||||
$list = $this->manager->collectionFetch(
|
||||
$tenantId,
|
||||
$userId,
|
||||
$data['provider'],
|
||||
$data['service'],
|
||||
$data['identifier']
|
||||
$targetIdentifier
|
||||
);
|
||||
return $list;
|
||||
}
|
||||
|
||||
private function collectionExtant(string $tenantId, string $userId, array $data): mixed {
|
||||
if (!isset($data['targets'])) {
|
||||
throw new InvalidArgumentException(self::ERR_MISSING_TARGETS);
|
||||
}
|
||||
if (!is_array($data['targets'])) {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_TARGETS);
|
||||
}
|
||||
|
||||
$sources = ResourceIdentifiers::fromArray($data['targets']);
|
||||
foreach ($sources as $source) {
|
||||
if (!$source instanceof CollectionIdentifier) {
|
||||
throw new InvalidArgumentException('Invalid parameter: targets must contain provider:service, provider:service:collection, or provider:service:collection:entity identifiers');
|
||||
}
|
||||
}
|
||||
|
||||
return $this->manager->collectionExtant($tenantId, $userId, $sources);
|
||||
}
|
||||
|
||||
private function collectionCreate(string $tenantId, string $userId, array $data): mixed {
|
||||
@@ -384,8 +418,8 @@ class DefaultController extends ControllerAbstract {
|
||||
if (!is_string($data['service'])) {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_SERVICE);
|
||||
}
|
||||
if (isset($data['collection']) && !is_string($data['collection']) && !is_int($data['collection'])) {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_COLLECTION);
|
||||
if (isset($data['target']) && !is_string($data['target']) && !is_int($data['target'])) {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_TARGET);
|
||||
}
|
||||
if (!isset($data['properties'])) {
|
||||
throw new InvalidArgumentException(self::ERR_MISSING_DATA);
|
||||
@@ -394,34 +428,29 @@ class DefaultController extends ControllerAbstract {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_DATA);
|
||||
}
|
||||
|
||||
if (isset($data['target'])) {
|
||||
$targetIdentifier = ResourceIdentifier::fromString($data['target']);
|
||||
if (!$targetIdentifier instanceof CollectionIdentifier) {
|
||||
throw new InvalidArgumentException('Invalid parameter: target must be provider:service:collection');
|
||||
}
|
||||
}
|
||||
|
||||
return $this->manager->collectionCreate(
|
||||
$tenantId,
|
||||
$userId,
|
||||
$data['provider'],
|
||||
$data['service'],
|
||||
$data['collection'] ?? null,
|
||||
$targetIdentifier ?? null,
|
||||
$data['properties']
|
||||
);
|
||||
}
|
||||
|
||||
private function collectionUpdate(string $tenantId, string $userId, array $data): mixed {
|
||||
if (!isset($data['provider'])) {
|
||||
throw new InvalidArgumentException(self::ERR_MISSING_PROVIDER);
|
||||
if (!isset($data['target'])) {
|
||||
throw new InvalidArgumentException(self::ERR_MISSING_TARGET);
|
||||
}
|
||||
if (!is_string($data['provider'])) {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_PROVIDER);
|
||||
}
|
||||
if (!isset($data['service'])) {
|
||||
throw new InvalidArgumentException(self::ERR_MISSING_SERVICE);
|
||||
}
|
||||
if (!is_string($data['service'])) {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_SERVICE);
|
||||
}
|
||||
if (!isset($data['identifier'])) {
|
||||
throw new InvalidArgumentException(self::ERR_MISSING_IDENTIFIER);
|
||||
}
|
||||
if (!is_string($data['identifier']) && !is_int($data['identifier'])) {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_COLLECTION);
|
||||
if (!is_string($data['target'])) {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_TARGET);
|
||||
}
|
||||
if (!isset($data['properties'])) {
|
||||
throw new InvalidArgumentException(self::ERR_MISSING_DATA);
|
||||
@@ -430,181 +459,375 @@ class DefaultController extends ControllerAbstract {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_DATA);
|
||||
}
|
||||
|
||||
$targetIdentifier = ResourceIdentifier::fromString($data['target']);
|
||||
if (!$targetIdentifier instanceof CollectionIdentifier) {
|
||||
throw new InvalidArgumentException('Invalid parameter: target must be provider:service:collection');
|
||||
}
|
||||
|
||||
return $this->manager->collectionUpdate(
|
||||
$tenantId,
|
||||
$userId,
|
||||
$data['provider'],
|
||||
$data['service'],
|
||||
$data['identifier'],
|
||||
$targetIdentifier,
|
||||
$data['properties']
|
||||
);
|
||||
}
|
||||
|
||||
private function collectionDelete(string $tenantId, string $userId, array $data): mixed {
|
||||
if (!isset($data['provider'])) {
|
||||
throw new InvalidArgumentException(self::ERR_MISSING_PROVIDER);
|
||||
if (!isset($data['target'])) {
|
||||
throw new InvalidArgumentException(self::ERR_MISSING_TARGET);
|
||||
}
|
||||
if (!is_string($data['provider'])) {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_PROVIDER);
|
||||
}
|
||||
if (!isset($data['service'])) {
|
||||
throw new InvalidArgumentException(self::ERR_MISSING_SERVICE);
|
||||
}
|
||||
if (!is_string($data['service'])) {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_SERVICE);
|
||||
}
|
||||
if (!isset($data['identifier'])) {
|
||||
throw new InvalidArgumentException(self::ERR_MISSING_IDENTIFIER);
|
||||
}
|
||||
if (!is_string($data['identifier']) && !is_int($data['identifier'])) {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_IDENTIFIER);
|
||||
if (!is_string($data['target'])) {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_TARGET);
|
||||
}
|
||||
|
||||
return $this->manager->collectionDelete(
|
||||
$tenantId,
|
||||
$userId,
|
||||
$data['provider'],
|
||||
$data['service'],
|
||||
$data['identifier'],
|
||||
$data['options'] ?? []
|
||||
);
|
||||
$targetIdentifier = ResourceIdentifier::fromString($data['target']);
|
||||
if (!$targetIdentifier instanceof CollectionIdentifier) {
|
||||
throw new InvalidArgumentException('Invalid parameter: target must be provider:service:collection');
|
||||
}
|
||||
|
||||
$result = $this->manager->collectionDelete($tenantId, $userId, $targetIdentifier, $data['options'] ?? [] );
|
||||
|
||||
if (is_bool($result)) {
|
||||
return [
|
||||
'disposition' => 'deleted'
|
||||
];
|
||||
}
|
||||
|
||||
if ($result instanceof JsonSerializable) {
|
||||
return [
|
||||
'disposition' => 'moved',
|
||||
'mutation' => $result
|
||||
];
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
// ==================== Entity Operations ====================
|
||||
|
||||
private function entityList(string $tenantId, string $userId, array $data): mixed {
|
||||
if (!isset($data['sources'])) {
|
||||
throw new InvalidArgumentException(self::ERR_MISSING_SOURCES);
|
||||
}
|
||||
private function entityListBulk(string $tenantId, string $userId, array $data): mixed {
|
||||
|
||||
if (isset($data['sources'])) {
|
||||
if (!is_array($data['sources'])) {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_SOURCES);
|
||||
}
|
||||
|
||||
$sources = new SourceSelector();
|
||||
$sources->jsonDeserialize($data['sources']);
|
||||
$sources = ResourceIdentifiers::fromArray($data['sources']);
|
||||
foreach ($sources as $source) {
|
||||
if (!$source instanceof ServiceIdentifier && !$source instanceof CollectionIdentifier) {
|
||||
throw new InvalidArgumentException('Invalid parameter: sources must contain provider:service or provider:service:collection identifiers');
|
||||
}
|
||||
}
|
||||
} else {
|
||||
$sources = null;
|
||||
}
|
||||
|
||||
$filter = $data['filter'] ?? null;
|
||||
$sort = $data['sort'] ?? null;
|
||||
$range = $data['range'] ?? null;
|
||||
|
||||
return $this->manager->entityList($tenantId, $userId, $sources, $filter, $sort, $range);
|
||||
return $this->manager->entityListBulk($tenantId, $userId, $sources, $filter, $sort, $range);
|
||||
|
||||
}
|
||||
|
||||
private function entityListStream(string $tenantId, string $userId, array $data, int $version, string $transaction): StreamedNdJsonResponse {
|
||||
|
||||
if (isset($data['sources'])) {
|
||||
if (!is_array($data['sources'])) {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_SOURCES);
|
||||
}
|
||||
|
||||
$sources = ResourceIdentifiers::fromArray($data['sources']);
|
||||
foreach ($sources as $source) {
|
||||
if (!$source instanceof ServiceIdentifier && !$source instanceof CollectionIdentifier) {
|
||||
throw new InvalidArgumentException('Invalid parameter: sources must contain provider:service or provider:service:collection identifiers');
|
||||
}
|
||||
}
|
||||
} else {
|
||||
$sources = null;
|
||||
}
|
||||
|
||||
$filter = $data['filter'] ?? null;
|
||||
$sort = $data['sort'] ?? null;
|
||||
$range = $data['range'] ?? null;
|
||||
|
||||
$entities = $this->manager->entityListStream($tenantId, $userId, $sources, $filter, $sort, $range);
|
||||
|
||||
return new StreamedNdJsonResponse(
|
||||
$this->streamEnvelope($entities, $version, $transaction),
|
||||
1,
|
||||
200,
|
||||
['Content-Type' => 'application/json'],
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Import iCalendar events into a calendar, streaming one NDJSON event per event.
|
||||
*
|
||||
* Request data: { target: "provider:service:collection", data: "<raw iCalendar string>", options?: {...} }
|
||||
*/
|
||||
private function entityImport(string $tenantId, string $userId, array $data, int $version, string $transaction): StreamedNdJsonResponse {
|
||||
|
||||
if (!isset($data['target'])) {
|
||||
throw new InvalidArgumentException(self::ERR_MISSING_TARGET);
|
||||
}
|
||||
if (!is_string($data['target'])) {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_TARGET);
|
||||
}
|
||||
if (!isset($data['data']) || !is_string($data['data']) || trim($data['data']) === '') {
|
||||
throw new InvalidArgumentException('Invalid parameter: data must be a non-empty string');
|
||||
}
|
||||
|
||||
$target = ResourceIdentifier::fromString($data['target']);
|
||||
if (!$target instanceof CollectionIdentifier) {
|
||||
throw new InvalidArgumentException('Invalid parameter: target must be provider:service:collection');
|
||||
}
|
||||
|
||||
$options = ImportOptions::fromArray($data['options'] ?? []);
|
||||
|
||||
// Spill the payload to a temp file and release the in-memory copy before the
|
||||
// (potentially long) parse and create pass.
|
||||
$tempFile = tmpfile();
|
||||
if ($tempFile === false) {
|
||||
throw new \RuntimeException('Unable to allocate temporary file for import');
|
||||
}
|
||||
fwrite($tempFile, $data['data']);
|
||||
unset($data);
|
||||
rewind($tempFile);
|
||||
|
||||
$events = $this->importService->import($tempFile, $target, $options, $tenantId, $userId);
|
||||
$frames = $this->streamEnvelope($events, $version, $transaction);
|
||||
|
||||
// Stream the envelope, releasing the spilled temp file once it is fully
|
||||
// drained (or the client disconnects) so it never outlives its stream.
|
||||
$response = (function () use ($frames, $tempFile): \Generator {
|
||||
try {
|
||||
yield from $frames;
|
||||
} finally {
|
||||
fclose($tempFile);
|
||||
}
|
||||
})();
|
||||
|
||||
return new StreamedNdJsonResponse($response, 1, 200);
|
||||
}
|
||||
|
||||
/**
|
||||
* Export calendar entities as a streamed iCalendar document.
|
||||
*
|
||||
* Request data: { sources: ["provider:service:collection", "provider:service:collection:entity", ...], filename?: "calendar.ics" }
|
||||
*/
|
||||
private function entityExport(string $tenantId, string $userId, array $data): StreamedResponse {
|
||||
|
||||
if (!isset($data['sources'])) {
|
||||
throw new InvalidArgumentException(self::ERR_MISSING_SOURCES);
|
||||
}
|
||||
if (!is_array($data['sources']) || $data['sources'] === []) {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_SOURCES);
|
||||
}
|
||||
|
||||
$sources = ResourceIdentifiers::fromArray($data['sources']);
|
||||
foreach ($sources as $source) {
|
||||
if (!$source instanceof CollectionIdentifier && !$source instanceof EntityIdentifier) {
|
||||
throw new InvalidArgumentException('Invalid parameter: sources must contain provider:service:collection or provider:service:collection:entity identifiers');
|
||||
}
|
||||
}
|
||||
|
||||
$filename = 'export.ics';
|
||||
if (isset($data['filename']) && is_string($data['filename'])) {
|
||||
$sanitized = preg_replace('/[^A-Za-z0-9._-]+/', '_', trim($data['filename']));
|
||||
if ($sanitized !== '' && $sanitized !== null) {
|
||||
$filename = str_ends_with(strtolower($sanitized), '.ics') ? $sanitized : $sanitized . '.ics';
|
||||
}
|
||||
}
|
||||
|
||||
return new StreamedResponse(
|
||||
$this->exportService->export($sources, $tenantId, $userId),
|
||||
200,
|
||||
[
|
||||
'Content-Type' => 'text/calendar; charset=utf-8',
|
||||
'Content-Disposition' => 'attachment; filename="' . $filename . '"',
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrap a generator of JsonSerializable domain objects in the canonical NDJSON
|
||||
* stream envelope shared by every streaming operation:
|
||||
*
|
||||
* control:start {version, transaction, total?} — total? = expected count
|
||||
* data {data} — one per domain object
|
||||
* error {message} — on failure, then stop
|
||||
* control:end {total} — total = objects emitted
|
||||
*
|
||||
* If the generator leads with an {@see ExpectedTotal} event, its value is
|
||||
* folded into the start frame's `total` (the progress denominator) rather
|
||||
* than emitted as a data frame.
|
||||
*
|
||||
* @param \Generator<\JsonSerializable> $items
|
||||
*/
|
||||
private function streamEnvelope(\Generator $items, int $version, string $transaction): \Generator {
|
||||
// Peek the first event: an expected-total marker rides on the start frame.
|
||||
$expected = null;
|
||||
$items->rewind();
|
||||
if ($items->valid() && $items->current() instanceof ExpectedTotal) {
|
||||
$expected = $items->current()->expectedTotal();
|
||||
$items->next();
|
||||
}
|
||||
|
||||
$start = ['type' => 'control', 'status' => 'start', 'version' => $version, 'transaction' => $transaction];
|
||||
if ($expected !== null) {
|
||||
$start['total'] = $expected;
|
||||
}
|
||||
yield $start;
|
||||
|
||||
$total = 0;
|
||||
try {
|
||||
for (; $items->valid(); $items->next()) {
|
||||
$item = $items->current();
|
||||
if (!$item instanceof \JsonSerializable) {
|
||||
continue;
|
||||
}
|
||||
yield ['type' => 'data', 'data' => $item->jsonSerialize()];
|
||||
$total++;
|
||||
}
|
||||
} catch (\Throwable $t) {
|
||||
$this->logger->error('Error streaming response', ['exception' => $t]);
|
||||
yield ['type' => 'error', 'message' => $t->getMessage()];
|
||||
return;
|
||||
}
|
||||
|
||||
yield ['type' => 'control', 'status' => 'end', 'total' => $total];
|
||||
}
|
||||
|
||||
private function entityFetch(string $tenantId, string $userId, array $data): mixed {
|
||||
if (!isset($data['provider'])) {
|
||||
throw new InvalidArgumentException(self::ERR_MISSING_PROVIDER);
|
||||
if (!isset($data['targets'])) {
|
||||
throw new InvalidArgumentException(self::ERR_MISSING_TARGETS);
|
||||
}
|
||||
if (!is_string($data['provider'])) {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_PROVIDER);
|
||||
}
|
||||
if (!isset($data['service'])) {
|
||||
throw new InvalidArgumentException(self::ERR_MISSING_SERVICE);
|
||||
}
|
||||
if (!is_string($data['service'])) {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_SERVICE);
|
||||
}
|
||||
if (!isset($data['collection'])) {
|
||||
throw new InvalidArgumentException(self::ERR_MISSING_COLLECTION);
|
||||
}
|
||||
if (!is_string($data['collection']) && !is_int($data['collection'])) {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_COLLECTION);
|
||||
}
|
||||
if (!isset($data['identifiers'])) {
|
||||
throw new InvalidArgumentException(self::ERR_MISSING_IDENTIFIERS);
|
||||
}
|
||||
if (!is_array($data['identifiers'])) {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_IDENTIFIERS);
|
||||
if (!is_array($data['targets'])) {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_TARGETS);
|
||||
}
|
||||
|
||||
return $this->manager->entityFetch(
|
||||
$targets = ResourceIdentifiers::fromArray($data['targets']);
|
||||
foreach ($targets as $target) {
|
||||
if (!$target instanceof EntityIdentifier) {
|
||||
throw new InvalidArgumentException('Invalid parameter: targets must contain provider:service:collection:entity identifiers');
|
||||
}
|
||||
}
|
||||
|
||||
return $this->manager->entityFetchBulk(
|
||||
$tenantId,
|
||||
$userId,
|
||||
$data['provider'],
|
||||
$data['service'],
|
||||
$data['collection'],
|
||||
$data['identifiers']
|
||||
...$targets->all()
|
||||
);
|
||||
}
|
||||
|
||||
private function entityExtant(string $tenantId, string $userId, array $data): mixed {
|
||||
if (!isset($data['sources'])) {
|
||||
throw new InvalidArgumentException(self::ERR_MISSING_SOURCES);
|
||||
if (!isset($data['targets'])) {
|
||||
throw new InvalidArgumentException(self::ERR_MISSING_TARGETS);
|
||||
}
|
||||
if (!is_array($data['sources'])) {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_SOURCES);
|
||||
if (!is_array($data['targets'])) {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_TARGETS);
|
||||
}
|
||||
|
||||
$sources = new SourceSelector();
|
||||
$sources->jsonDeserialize($data['sources']);
|
||||
|
||||
return $this->manager->entityExtant($tenantId, $userId, $sources);
|
||||
$targets = ResourceIdentifiers::fromArray($data['targets']);
|
||||
foreach ($targets as $target) {
|
||||
if (!$target instanceof CollectionIdentifier && !$target instanceof EntityIdentifier) {
|
||||
throw new InvalidArgumentException('Invalid parameter: targets must contain provider:service:collection or provider:service:collection:entity identifiers');
|
||||
}
|
||||
}
|
||||
|
||||
private function entityCreate(string $tenantId, string $userId, array $data = []): mixed {
|
||||
|
||||
if (!isset($data['provider']) || !is_string($data['provider'])) {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_PROVIDER);
|
||||
}
|
||||
if (!isset($data['service']) || !is_string($data['service'])) {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_SERVICE);
|
||||
}
|
||||
if (!isset($data['collection'])) {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_COLLECTION);
|
||||
}
|
||||
$properties = $data['properties'] ?? $data['data'] ?? null;
|
||||
if (!is_array($properties)) {
|
||||
throw new InvalidArgumentException('Invalid parameter: properties must be an array');
|
||||
}
|
||||
$options = $data['options'] ?? [];
|
||||
|
||||
return $this->manager->entityCreate($tenantId, $userId, $data['provider'], $data['service'], $data['collection'], $properties, $options);
|
||||
|
||||
}
|
||||
|
||||
private function entityUpdate(string $tenantId, string $userId, array $data = []): mixed {
|
||||
|
||||
if (!isset($data['provider']) || !is_string($data['provider'])) {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_PROVIDER);
|
||||
}
|
||||
if (!isset($data['service']) || !is_string($data['service'])) {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_SERVICE);
|
||||
}
|
||||
if (!isset($data['collection'])) {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_COLLECTION);
|
||||
}
|
||||
if (!isset($data['identifier'])) {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_IDENTIFIER);
|
||||
}
|
||||
$properties = $data['properties'] ?? $data['data'] ?? null;
|
||||
if (!is_array($properties)) {
|
||||
throw new InvalidArgumentException('Invalid parameter: properties must be an array');
|
||||
}
|
||||
|
||||
return $this->manager->entityUpdate($tenantId, $userId, $data['provider'], $data['service'], $data['collection'], $data['identifier'], $properties);
|
||||
|
||||
}
|
||||
|
||||
private function entityDelete(string $tenantId, string $userId, array $data = []): mixed {
|
||||
|
||||
if (!isset($data['provider']) || !is_string($data['provider'])) {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_PROVIDER);
|
||||
}
|
||||
if (!isset($data['service']) || !is_string($data['service'])) {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_SERVICE);
|
||||
}
|
||||
if (!isset($data['collection'])) {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_COLLECTION);
|
||||
}
|
||||
if (!isset($data['identifier'])) {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_IDENTIFIER);
|
||||
}
|
||||
|
||||
return $this->manager->entityDelete($tenantId, $userId, $data['provider'], $data['service'], $data['collection'], $data['identifier']);
|
||||
|
||||
return $this->manager->entityExtant($tenantId, $userId, $targets);
|
||||
}
|
||||
|
||||
private function entityDelta(string $tenantId, string $userId, array $data): mixed {
|
||||
if (!isset($data['targets'])) {
|
||||
throw new InvalidArgumentException(self::ERR_MISSING_TARGETS);
|
||||
}
|
||||
if (!is_array($data['targets'])) {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_TARGETS);
|
||||
}
|
||||
|
||||
$targets = ResourceIdentifiers::fromArray($data['targets']);
|
||||
foreach ($targets as $target) {
|
||||
if (!$target instanceof CollectionIdentifier && !$target instanceof EntityIdentifier) {
|
||||
throw new InvalidArgumentException('Invalid parameter: targets must contain provider:service:collection or provider:service:collection:signature identifiers');
|
||||
}
|
||||
}
|
||||
|
||||
return $this->manager->entityDelta($tenantId, $userId, $targets);
|
||||
}
|
||||
|
||||
private function entityCreate(string $tenantId, string $userId, array $data = []): mixed {
|
||||
if (!isset($data['target'])) {
|
||||
throw new InvalidArgumentException(self::ERR_MISSING_TARGET);
|
||||
}
|
||||
if (!is_string($data['target'])) {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_TARGET);
|
||||
}
|
||||
if (!isset($data['properties'])) {
|
||||
throw new InvalidArgumentException(self::ERR_MISSING_DATA);
|
||||
}
|
||||
if (!is_array($data['properties'])) {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_DATA);
|
||||
}
|
||||
|
||||
$target = ResourceIdentifier::fromString($data['target']);
|
||||
if (!$target instanceof CollectionIdentifier) {
|
||||
throw new InvalidArgumentException('Invalid parameter: target must be provider:service:collection');
|
||||
}
|
||||
|
||||
$options = $data['options'] ?? [];
|
||||
|
||||
return $this->manager->entityCreate($tenantId, $userId, $target, $data['properties'], $options);
|
||||
}
|
||||
|
||||
private function entityUpdate(string $tenantId, string $userId, array $data = []): mixed {
|
||||
if (!isset($data['target'])) {
|
||||
throw new InvalidArgumentException(self::ERR_MISSING_TARGET);
|
||||
}
|
||||
if (!is_string($data['target'])) {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_TARGET);
|
||||
}
|
||||
if (!isset($data['properties'])) {
|
||||
throw new InvalidArgumentException(self::ERR_MISSING_DATA);
|
||||
}
|
||||
if (!is_array($data['properties'])) {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_DATA);
|
||||
}
|
||||
|
||||
$target = ResourceIdentifier::fromString($data['target']);
|
||||
if (!$target instanceof EntityIdentifier) {
|
||||
throw new InvalidArgumentException('Invalid parameter: target must be provider:service:collection:entity');
|
||||
}
|
||||
|
||||
return $this->manager->entityModify($tenantId, $userId, $target, $data['properties']);
|
||||
}
|
||||
|
||||
private function entityDelete(string $tenantId, string $userId, array $data): mixed {
|
||||
if (!isset($data['targets'])) {
|
||||
throw new InvalidArgumentException(self::ERR_MISSING_TARGETS);
|
||||
}
|
||||
if (!is_array($data['targets'])) {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_TARGETS);
|
||||
}
|
||||
|
||||
$targets = ResourceIdentifiers::fromArray($data['targets']);
|
||||
foreach ($targets as $target) {
|
||||
if (!$target instanceof EntityIdentifier) {
|
||||
throw new InvalidArgumentException('Invalid parameter: targets must contain provider:service:collection:entity identifiers');
|
||||
}
|
||||
}
|
||||
|
||||
return $this->manager->entityDelete($tenantId, $userId, ...$targets->all());
|
||||
}
|
||||
|
||||
private function entityMove(string $tenantId, string $userId, array $data): mixed {
|
||||
if (!isset($data['target'])) {
|
||||
throw new InvalidArgumentException(self::ERR_MISSING_TARGET);
|
||||
}
|
||||
if (!is_string($data['target'])) {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_TARGET);
|
||||
}
|
||||
if (!isset($data['sources'])) {
|
||||
throw new InvalidArgumentException(self::ERR_MISSING_SOURCES);
|
||||
}
|
||||
@@ -612,10 +835,19 @@ class DefaultController extends ControllerAbstract {
|
||||
throw new InvalidArgumentException(self::ERR_INVALID_SOURCES);
|
||||
}
|
||||
|
||||
$sources = new SourceSelector();
|
||||
$sources->jsonDeserialize($data['sources']);
|
||||
$target = ResourceIdentifier::fromString($data['target']);
|
||||
if (!$target instanceof CollectionIdentifier) {
|
||||
throw new InvalidArgumentException('Invalid parameter: target must be provider:service:collection');
|
||||
}
|
||||
|
||||
return $this->manager->entityDelta($tenantId, $userId, $sources);
|
||||
$sources = ResourceIdentifiers::fromArray($data['sources']);
|
||||
foreach ($sources as $source) {
|
||||
if (!$source instanceof EntityIdentifier) {
|
||||
throw new InvalidArgumentException('Invalid parameter: sources must contain provider:service:collection:entity identifiers');
|
||||
}
|
||||
}
|
||||
|
||||
return $this->manager->entityMove($tenantId, $userId, $target, ...$sources->all());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,310 @@
|
||||
<?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)); }
|
||||
}
|
||||
@@ -0,0 +1,387 @@
|
||||
<?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'));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
<?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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<?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];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
<?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';
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?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 {
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
<?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,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
<?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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
<?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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+575
-413
File diff suppressed because it is too large
Load Diff
@@ -14,6 +14,15 @@ class Module extends ModuleInstanceAbstract implements ModuleBrowserInterface
|
||||
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
|
||||
{
|
||||
return 'chrono_manager';
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
<?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;
|
||||
}
|
||||
Generated
+1736
-783
File diff suppressed because it is too large
Load Diff
+14
-7
@@ -7,17 +7,24 @@
|
||||
"build": "vite build --mode production --config vite.config.ts",
|
||||
"dev": "vite build --mode development --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": {
|
||||
"pinia": "^2.3.0",
|
||||
"pinia": "^4.0.0",
|
||||
"vue": "^3.5.13"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tsconfig/node22": "^22.0.0",
|
||||
"@types/node": "^22.10.1",
|
||||
"@vue/tsconfig": "^0.8.0",
|
||||
"typescript": "~5.7.2",
|
||||
"vite": "^6.0.3"
|
||||
"@tsconfig/node24": "^24.0.0",
|
||||
"@types/node": "^24.0.0",
|
||||
"@vue/tsconfig": "^0.9.0",
|
||||
"typescript": "~6.0.0",
|
||||
"vite": "^8.0.0",
|
||||
"@vitest/coverage-v8": "^4.1.6",
|
||||
"jsdom": "^29.1.1",
|
||||
"vitest": "^4.1.6"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
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));
|
||||
}
|
||||
+52
-61
@@ -1,47 +1,52 @@
|
||||
/**
|
||||
* Class model for Collection Interface
|
||||
* Class models for Collection interfaces
|
||||
*/
|
||||
|
||||
import type { CollectionContentTypes, CollectionInterface, CollectionPropertiesInterface } from "@/types/collection";
|
||||
import type {
|
||||
CollectionContentTypes,
|
||||
CollectionInterface,
|
||||
CollectionModelInterface,
|
||||
CollectionPropertiesInterface,
|
||||
CollectionPropertiesModelInterface
|
||||
} from '@/types/collection';
|
||||
import type {
|
||||
CollectionIdentifier,
|
||||
ServiceIdentifier
|
||||
} from '@/types/common';
|
||||
import { clonePlain } from './clone-plain';
|
||||
|
||||
export class CollectionObject implements CollectionInterface {
|
||||
export class CollectionObject implements CollectionModelInterface {
|
||||
|
||||
_data!: CollectionInterface;
|
||||
private _data: CollectionInterface<CollectionPropertiesInterface>;
|
||||
private _properties: CollectionPropertiesObject | undefined = undefined;
|
||||
|
||||
constructor() {
|
||||
this._data = {
|
||||
'@type': 'people:collection',
|
||||
version: 1,
|
||||
provider: '',
|
||||
service: '',
|
||||
collection: null,
|
||||
identifier: '',
|
||||
signature: null,
|
||||
created: null,
|
||||
modified: null,
|
||||
properties: new CollectionPropertiesObject(),
|
||||
service: '' as ServiceIdentifier,
|
||||
collection: null as CollectionIdentifier | null,
|
||||
identifier: '' as CollectionIdentifier,
|
||||
properties: new CollectionPropertiesObject().toJson(),
|
||||
};
|
||||
}
|
||||
|
||||
fromJson(data: CollectionInterface): CollectionObject {
|
||||
this._data = data;
|
||||
if (data.properties) {
|
||||
this._data.properties = new CollectionPropertiesObject().fromJson(data.properties as CollectionPropertiesInterface);
|
||||
}
|
||||
this._data = clonePlain(data);
|
||||
this._properties = undefined;
|
||||
return this;
|
||||
}
|
||||
|
||||
toJson(): CollectionInterface {
|
||||
const json = { ...this._data };
|
||||
if (this._data.properties instanceof CollectionPropertiesObject) {
|
||||
json.properties = this._data.properties.toJson();
|
||||
}
|
||||
return json;
|
||||
const json = this._properties
|
||||
? { ...this._data, properties: this._properties.toJson() }
|
||||
: this._data;
|
||||
return clonePlain(json);
|
||||
}
|
||||
|
||||
clone(): CollectionObject {
|
||||
const cloned = new CollectionObject();
|
||||
cloned._data = { ...this._data };
|
||||
cloned._data.properties = this.properties.clone();
|
||||
return cloned;
|
||||
return new CollectionObject().fromJson(this.toJson());
|
||||
}
|
||||
|
||||
/** Immutable Properties */
|
||||
@@ -50,16 +55,16 @@ export class CollectionObject implements CollectionInterface {
|
||||
return this._data.provider;
|
||||
}
|
||||
|
||||
get service(): string | number {
|
||||
return this._data.service;
|
||||
get service(): ServiceIdentifier {
|
||||
return this._data.service as ServiceIdentifier;
|
||||
}
|
||||
|
||||
get collection(): string | number | null {
|
||||
return this._data.collection;
|
||||
get collection(): CollectionIdentifier | null {
|
||||
return this._data.collection as CollectionIdentifier | null;
|
||||
}
|
||||
|
||||
get identifier(): string | number {
|
||||
return this._data.identifier;
|
||||
get identifier(): CollectionIdentifier {
|
||||
return this._data.identifier as CollectionIdentifier;
|
||||
}
|
||||
|
||||
get signature(): string | null | undefined {
|
||||
@@ -74,37 +79,33 @@ export class CollectionObject implements CollectionInterface {
|
||||
return this._data.modified;
|
||||
}
|
||||
|
||||
get properties(): CollectionPropertiesObject {
|
||||
if (this._data.properties instanceof CollectionPropertiesObject) {
|
||||
return this._data.properties;
|
||||
}
|
||||
/** Mutable Properties */
|
||||
|
||||
if (this._data.properties) {
|
||||
const hydrated = new CollectionPropertiesObject().fromJson(this._data.properties as CollectionPropertiesInterface);
|
||||
this._data.properties = hydrated;
|
||||
return hydrated;
|
||||
get properties(): CollectionPropertiesObject {
|
||||
if (this._properties) {
|
||||
return this._properties;
|
||||
}
|
||||
else if (this._data.properties) {
|
||||
const properties = new CollectionPropertiesObject().fromJson(this._data.properties as CollectionPropertiesInterface);
|
||||
this._properties = properties;
|
||||
return properties;
|
||||
}
|
||||
|
||||
return new CollectionPropertiesObject();
|
||||
}
|
||||
|
||||
set properties(value: CollectionPropertiesObject) {
|
||||
if (value instanceof CollectionPropertiesObject) {
|
||||
this._data.properties = value as any;
|
||||
} else {
|
||||
this._data.properties = value;
|
||||
}
|
||||
this._properties = value;
|
||||
}
|
||||
}
|
||||
|
||||
export class CollectionPropertiesObject implements CollectionPropertiesInterface {
|
||||
export class CollectionPropertiesObject implements CollectionPropertiesModelInterface {
|
||||
|
||||
_data!: CollectionPropertiesInterface;
|
||||
private _data: CollectionPropertiesInterface;
|
||||
|
||||
constructor() {
|
||||
this._data = {
|
||||
'@type': 'chrono:collection',
|
||||
version: 1,
|
||||
'@type': 'chrono:calendar',
|
||||
content: [],
|
||||
label: '',
|
||||
description: null,
|
||||
@@ -115,32 +116,22 @@ export class CollectionPropertiesObject implements CollectionPropertiesInterface
|
||||
}
|
||||
|
||||
fromJson(data: CollectionPropertiesInterface): CollectionPropertiesObject {
|
||||
this._data = data;
|
||||
this._data = clonePlain(data);
|
||||
return this;
|
||||
}
|
||||
|
||||
toJson(): CollectionPropertiesInterface {
|
||||
return this._data;
|
||||
return clonePlain(this._data);
|
||||
}
|
||||
|
||||
clone(): CollectionPropertiesObject {
|
||||
const cloned = new CollectionPropertiesObject();
|
||||
cloned._data = { ...this._data };
|
||||
return cloned;
|
||||
return new CollectionPropertiesObject().fromJson(this.toJson());
|
||||
}
|
||||
|
||||
/** Immutable Properties */
|
||||
|
||||
get '@type'(): string {
|
||||
return this._data['@type'];
|
||||
}
|
||||
|
||||
get version(): number {
|
||||
return this._data.version;
|
||||
}
|
||||
|
||||
get content(): CollectionContentTypes[] {
|
||||
return this._data.content || [];
|
||||
return this._data.content ?? [];
|
||||
}
|
||||
|
||||
/** Mutable Properties */
|
||||
|
||||
+52
-56
@@ -1,106 +1,102 @@
|
||||
/**
|
||||
* 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";
|
||||
|
||||
export class EntityObject implements EntityInterface {
|
||||
import type { CollectionIdentifier, EntityIdentifier } from '@/types/common';
|
||||
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';
|
||||
|
||||
_data!: EntityInterface;
|
||||
export type EntityPropertiesObject = EventObject | TaskObject | JournalObject;
|
||||
|
||||
export class EntityObject implements EntityModelInterface {
|
||||
private _data: EntityInterface<EntityPropertiesInterface>;
|
||||
private _properties: EntityPropertiesObject | undefined;
|
||||
|
||||
constructor() {
|
||||
this._data = {
|
||||
'@type': 'chrono:entity',
|
||||
version: 1,
|
||||
provider: '',
|
||||
service: '',
|
||||
collection: '',
|
||||
identifier: '',
|
||||
collection: '' as CollectionIdentifier,
|
||||
identifier: '' as EntityIdentifier,
|
||||
signature: null,
|
||||
created: null,
|
||||
modified: null,
|
||||
properties: new EventObject(),
|
||||
properties: new EventObject().toJson(),
|
||||
};
|
||||
}
|
||||
|
||||
fromJson(data: EntityInterface): EntityObject {
|
||||
this._data = data
|
||||
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);
|
||||
}
|
||||
}
|
||||
this._data = clonePlain(data);
|
||||
this._properties = undefined;
|
||||
return this;
|
||||
}
|
||||
|
||||
toJson(): EntityInterface {
|
||||
const json = { ...this._data }
|
||||
if (this._data.properties instanceof EventObject ||
|
||||
this._data.properties instanceof TaskObject ||
|
||||
this._data.properties instanceof JournalObject) {
|
||||
json.properties = this._data.properties.toJson();
|
||||
}
|
||||
return json as EntityInterface
|
||||
const json = this._properties
|
||||
? { ...this._data, properties: this._properties.toJson() }
|
||||
: this._data;
|
||||
return clonePlain(json);
|
||||
}
|
||||
|
||||
clone(): EntityObject {
|
||||
const cloned = new EntityObject()
|
||||
cloned._data = { ...this._data }
|
||||
return cloned
|
||||
return new EntityObject().fromJson(this.toJson());
|
||||
}
|
||||
|
||||
/** Immutable Properties */
|
||||
/** Metadata Properties */
|
||||
|
||||
get provider(): string {
|
||||
return this._data.provider
|
||||
return this._data.provider;
|
||||
}
|
||||
|
||||
get service(): string {
|
||||
return this._data.service
|
||||
return this._data.service;
|
||||
}
|
||||
|
||||
get collection(): string | number {
|
||||
return this._data.collection
|
||||
get collection(): CollectionIdentifier {
|
||||
return this._data.collection;
|
||||
}
|
||||
|
||||
get identifier(): string | number {
|
||||
return this._data.identifier
|
||||
get identifier(): EntityIdentifier {
|
||||
return this._data.identifier;
|
||||
}
|
||||
|
||||
get signature(): string | null {
|
||||
return this._data.signature
|
||||
return this._data.signature;
|
||||
}
|
||||
|
||||
get created(): string | null {
|
||||
return this._data.created
|
||||
return this._data.created;
|
||||
}
|
||||
|
||||
get modified(): string | null {
|
||||
return this._data.modified
|
||||
return this._data.modified;
|
||||
}
|
||||
|
||||
get properties(): EventObject | TaskObject | JournalObject {
|
||||
if (this._data.properties instanceof EventObject ||
|
||||
this._data.properties instanceof TaskObject ||
|
||||
this._data.properties instanceof JournalObject) {
|
||||
return this._data.properties
|
||||
/** Entity Properties (individual | organization | group) */
|
||||
|
||||
get properties(): EntityPropertiesObject {
|
||||
if (this._properties) return this._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) {
|
||||
this._properties = value;
|
||||
}
|
||||
|
||||
set properties(value: EventObject | TaskObject | JournalObject) {
|
||||
this._data.properties = value
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+8
-1
@@ -114,8 +114,15 @@ export class EventObject implements 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 JSON.parse(JSON.stringify(this._data));
|
||||
return JSON.parse(JSON.stringify(data));
|
||||
}
|
||||
|
||||
clone(): EventObject {
|
||||
|
||||
+94
-166
@@ -1,196 +1,124 @@
|
||||
/**
|
||||
* Identity implementation classes for Mail Manager services
|
||||
* Identity models for Chrono Manager services
|
||||
*/
|
||||
|
||||
import type {
|
||||
ServiceIdentity,
|
||||
ServiceIdentityNone,
|
||||
ServiceIdentityBasic,
|
||||
ServiceIdentityToken,
|
||||
ServiceIdentityCertificate,
|
||||
ServiceIdentityNone,
|
||||
ServiceIdentityOAuth,
|
||||
ServiceIdentityCertificate
|
||||
ServiceIdentityToken
|
||||
} from '@/types/service';
|
||||
import { clonePlain } from './clone-plain';
|
||||
import { MutationProxy } from './mutation-proxy';
|
||||
|
||||
/**
|
||||
* Base Identity class
|
||||
*/
|
||||
export abstract class Identity {
|
||||
abstract toJson(): ServiceIdentity;
|
||||
export abstract class Identity<T extends ServiceIdentity = ServiceIdentity> {
|
||||
protected _original: T;
|
||||
protected _mutated: Partial<T>;
|
||||
protected _mutationProxy: MutationProxy<T>;
|
||||
protected _data: T;
|
||||
|
||||
protected constructor(initial: T) {
|
||||
this._original = clonePlain(initial);
|
||||
this._mutated = {};
|
||||
this._mutationProxy = new MutationProxy<T>(() => this._original, () => this._mutated);
|
||||
this._data = this._mutationProxy.create();
|
||||
}
|
||||
|
||||
protected load(data: T): this {
|
||||
this._original = clonePlain(data);
|
||||
this._mutated = {};
|
||||
this._data = this._mutationProxy.create();
|
||||
return this;
|
||||
}
|
||||
|
||||
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}`);
|
||||
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}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* No authentication
|
||||
*/
|
||||
export class IdentityNone extends Identity {
|
||||
readonly type = 'NA' as const;
|
||||
|
||||
static fromJson(_data: ServiceIdentityNone): IdentityNone {
|
||||
return new IdentityNone();
|
||||
export class IdentityNone extends Identity<ServiceIdentityNone> {
|
||||
constructor() { super({ type: 'NA' }); }
|
||||
static fromJson(_data: ServiceIdentityNone): IdentityNone { return new IdentityNone(); }
|
||||
clone(): IdentityNone { return IdentityNone.fromJson(this.toJson()); }
|
||||
get type(): 'NA' { return this._data.type; }
|
||||
}
|
||||
|
||||
toJson(): ServiceIdentityNone {
|
||||
return {
|
||||
type: this.type
|
||||
};
|
||||
}
|
||||
export class IdentityBasic extends Identity<ServiceIdentityBasic> {
|
||||
constructor(identity: string = '', secret: string = '') { super({ type: 'BA', identity, secret }); }
|
||||
static fromJson(data: ServiceIdentityBasic): IdentityBasic { return new IdentityBasic().load(data); }
|
||||
clone(): IdentityBasic { return IdentityBasic.fromJson(this.toJson()); }
|
||||
get type(): 'BA' { return this._data.type; }
|
||||
get identity(): string { return this._data.identity; }
|
||||
set identity(value: string) { this._data.identity = value; }
|
||||
get secret(): string { return this._data.secret; }
|
||||
set secret(value: string) { this._data.secret = value; }
|
||||
}
|
||||
|
||||
/**
|
||||
* Basic authentication (username/password)
|
||||
*/
|
||||
export class IdentityBasic extends Identity {
|
||||
readonly type = 'BA' as const;
|
||||
identity: string;
|
||||
secret: string;
|
||||
|
||||
constructor(identity: string = '', secret: string = '') {
|
||||
super();
|
||||
this.identity = identity;
|
||||
this.secret = secret;
|
||||
export class IdentityToken extends Identity<ServiceIdentityToken> {
|
||||
constructor(token: string = '') { super({ type: 'TA', token }); }
|
||||
static fromJson(data: ServiceIdentityToken): IdentityToken { return new IdentityToken().load(data); }
|
||||
clone(): IdentityToken { return IdentityToken.fromJson(this.toJson()); }
|
||||
get type(): 'TA' { return this._data.type; }
|
||||
get token(): string { return this._data.token; }
|
||||
set token(value: string) { this._data.token = value; }
|
||||
}
|
||||
|
||||
static fromJson(data: ServiceIdentityBasic): IdentityBasic {
|
||||
return new IdentityBasic(data.identity, data.secret);
|
||||
export class IdentityOAuth extends Identity<ServiceIdentityOAuth> {
|
||||
constructor(accessToken: string = '', accessScope?: string[], accessExpiry?: number, refreshToken?: string, refreshLocation?: string) {
|
||||
super({ type: 'OA', accessToken, accessScope, accessExpiry, refreshToken, refreshLocation });
|
||||
}
|
||||
|
||||
toJson(): ServiceIdentityBasic {
|
||||
return {
|
||||
type: this.type,
|
||||
identity: this.identity,
|
||||
secret: this.secret
|
||||
};
|
||||
}
|
||||
static fromJson(data: ServiceIdentityOAuth): IdentityOAuth { return new IdentityOAuth().load(data); }
|
||||
clone(): IdentityOAuth { return IdentityOAuth.fromJson(this.toJson()); }
|
||||
isExpired(): boolean { return this.accessExpiry ? Date.now() / 1000 >= this.accessExpiry : false; }
|
||||
expiresIn(): number { return this.accessExpiry ? Math.max(0, this.accessExpiry - Date.now() / 1000) : Infinity; }
|
||||
|
||||
get type(): 'OA' { return this._data.type; }
|
||||
get accessToken(): string { return this._data.accessToken; }
|
||||
set accessToken(value: string) { this._data.accessToken = value; }
|
||||
get accessScope(): string[] | undefined { return this._data.accessScope ? [...this._data.accessScope] : undefined; }
|
||||
set accessScope(value: string[] | undefined) { this._data.accessScope = value ? [...value] : undefined; }
|
||||
get accessExpiry(): number | undefined { return this._data.accessExpiry; }
|
||||
set accessExpiry(value: number | undefined) { this._data.accessExpiry = value; }
|
||||
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; }
|
||||
}
|
||||
|
||||
/**
|
||||
* Token authentication (API key, static token)
|
||||
*/
|
||||
export class IdentityToken extends Identity {
|
||||
readonly type = 'TA' as const;
|
||||
token: string;
|
||||
|
||||
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
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* OAuth authentication
|
||||
*/
|
||||
export class IdentityOAuth extends Identity {
|
||||
readonly type = 'OA' as const;
|
||||
accessToken: string;
|
||||
accessScope?: string[];
|
||||
accessExpiry?: number;
|
||||
refreshToken?: string;
|
||||
refreshLocation?: string;
|
||||
|
||||
constructor(
|
||||
accessToken: string = '',
|
||||
accessScope?: string[],
|
||||
accessExpiry?: number,
|
||||
refreshToken?: string,
|
||||
refreshLocation?: string
|
||||
) {
|
||||
super();
|
||||
this.accessToken = accessToken;
|
||||
this.accessScope = accessScope;
|
||||
this.accessExpiry = accessExpiry;
|
||||
this.refreshToken = refreshToken;
|
||||
this.refreshLocation = refreshLocation;
|
||||
}
|
||||
|
||||
static fromJson(data: ServiceIdentityOAuth): IdentityOAuth {
|
||||
return new IdentityOAuth(
|
||||
data.accessToken,
|
||||
data.accessScope,
|
||||
data.accessExpiry,
|
||||
data.refreshToken,
|
||||
data.refreshLocation
|
||||
);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Client certificate authentication (mTLS)
|
||||
*/
|
||||
export class IdentityCertificate extends Identity {
|
||||
readonly type = 'CC' as const;
|
||||
certificate: string;
|
||||
privateKey: string;
|
||||
passphrase?: string;
|
||||
|
||||
export class IdentityCertificate extends Identity<ServiceIdentityCertificate> {
|
||||
constructor(certificate: string = '', privateKey: string = '', passphrase?: string) {
|
||||
super();
|
||||
this.certificate = certificate;
|
||||
this.privateKey = privateKey;
|
||||
this.passphrase = passphrase;
|
||||
super({ type: 'CC', certificate, privateKey, passphrase });
|
||||
}
|
||||
|
||||
static fromJson(data: ServiceIdentityCertificate): IdentityCertificate {
|
||||
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 })
|
||||
};
|
||||
}
|
||||
static fromJson(data: ServiceIdentityCertificate): IdentityCertificate { return new IdentityCertificate().load(data); }
|
||||
clone(): IdentityCertificate { return IdentityCertificate.fromJson(this.toJson()); }
|
||||
get type(): 'CC' { return this._data.type; }
|
||||
get certificate(): string { return this._data.certificate; }
|
||||
set certificate(value: string) { this._data.certificate = value; }
|
||||
get privateKey(): string { return this._data.privateKey; }
|
||||
set privateKey(value: string) { this._data.privateKey = value; }
|
||||
get passphrase(): string | undefined { return this._data.passphrase; }
|
||||
set passphrase(value: string | undefined) { this._data.passphrase = value; }
|
||||
}
|
||||
|
||||
+2
-3
@@ -1,6 +1,6 @@
|
||||
export { ProviderObject } from './provider';
|
||||
export { ServiceObject } from './service';
|
||||
export { CollectionObject } from './collection';
|
||||
export { CollectionObject, CollectionPropertiesObject } from './collection';
|
||||
export { EntityObject } from './entity';
|
||||
export { EventObject } from './event';
|
||||
export { TaskObject } from './task';
|
||||
@@ -16,7 +16,6 @@ export {
|
||||
export {
|
||||
Location,
|
||||
LocationUri,
|
||||
LocationSocketSole,
|
||||
LocationSocketSplit,
|
||||
LocationFile
|
||||
} from './location';
|
||||
export { MutationProxy } from './mutation-proxy';
|
||||
|
||||
+66
-215
@@ -1,50 +1,55 @@
|
||||
/**
|
||||
* Location implementation classes for Mail Manager services
|
||||
* Location models for Chrono Manager services
|
||||
*/
|
||||
|
||||
import type {
|
||||
ServiceLocation,
|
||||
ServiceLocationUri,
|
||||
ServiceLocationSocketSole,
|
||||
ServiceLocationSocketSplit,
|
||||
ServiceLocationFile
|
||||
} from '@/types/service';
|
||||
import type { ServiceLocation, ServiceLocationFile, ServiceLocationUri } from '@/types/service';
|
||||
import { clonePlain } from './clone-plain';
|
||||
import { MutationProxy } from './mutation-proxy';
|
||||
|
||||
/**
|
||||
* Base Location class
|
||||
*/
|
||||
export abstract class Location {
|
||||
abstract toJson(): ServiceLocation;
|
||||
export abstract class Location<T extends ServiceLocation = ServiceLocation> {
|
||||
protected _original: T;
|
||||
protected _mutated: Partial<T>;
|
||||
protected _mutationProxy: MutationProxy<T>;
|
||||
protected _data: T;
|
||||
|
||||
protected constructor(initial: T) {
|
||||
this._original = clonePlain(initial);
|
||||
this._mutated = {};
|
||||
this._mutationProxy = new MutationProxy<T>(() => this._original, () => this._mutated);
|
||||
this._data = this._mutationProxy.create();
|
||||
}
|
||||
|
||||
protected load(data: T): this {
|
||||
this._original = clonePlain(data);
|
||||
this._mutated = {};
|
||||
this._data = this._mutationProxy.create();
|
||||
return this;
|
||||
}
|
||||
|
||||
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 'SOCKET_SOLE':
|
||||
return LocationSocketSole.fromJson(data);
|
||||
case 'SOCKET_SPLIT':
|
||||
return LocationSocketSplit.fromJson(data);
|
||||
case 'FILE':
|
||||
return LocationFile.fromJson(data);
|
||||
default:
|
||||
throw new Error(`Unknown location type: ${(data as any).type}`);
|
||||
case 'URI': return LocationUri.fromJson(data);
|
||||
case 'FILE': return LocationFile.fromJson(data);
|
||||
default: throw new Error(`Unknown location type: ${(data as any).type}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* URI-based service location for API and web services
|
||||
* Used by: JMAP, Gmail API, etc.
|
||||
*/
|
||||
export class LocationUri extends Location {
|
||||
readonly type = 'URI' as const;
|
||||
scheme: string;
|
||||
host: string;
|
||||
port: number;
|
||||
path?: string;
|
||||
verifyPeer: boolean;
|
||||
verifyHost: boolean;
|
||||
|
||||
export class LocationUri extends Location<ServiceLocationUri> {
|
||||
constructor(
|
||||
scheme: string = 'https',
|
||||
host: string = '',
|
||||
@@ -53,188 +58,34 @@ export class LocationUri extends Location {
|
||||
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;
|
||||
super({ type: 'URI', scheme, host, port, ...(path !== undefined && { path }), verifyPeer, verifyHost });
|
||||
}
|
||||
|
||||
static fromJson(data: ServiceLocationUri): LocationUri {
|
||||
return new LocationUri(
|
||||
data.scheme,
|
||||
data.host,
|
||||
data.port,
|
||||
data.path,
|
||||
data.verifyPeer ?? true,
|
||||
data.verifyHost ?? true
|
||||
);
|
||||
static fromJson(data: ServiceLocationUri): LocationUri { return new LocationUri().load(data); }
|
||||
clone(): LocationUri { return LocationUri.fromJson(this.toJson()); }
|
||||
getUrl(): string { return `${this.scheme}://${this.host}:${this.port}${this.path || ''}`; }
|
||||
|
||||
get type(): 'URI' { return this._data.type; }
|
||||
get scheme(): string { return this._data.scheme; }
|
||||
set scheme(value: string) { this._data.scheme = value; }
|
||||
get host(): string { return this._data.host; }
|
||||
set host(value: string) { this._data.host = value; }
|
||||
get port(): number { return this._data.port; }
|
||||
set port(value: number) { this._data.port = value; }
|
||||
get path(): string | undefined { return this._data.path; }
|
||||
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; }
|
||||
set verifyHost(value: boolean) { this._data.verifyHost = value; }
|
||||
}
|
||||
|
||||
toJson(): ServiceLocationUri {
|
||||
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 })
|
||||
};
|
||||
}
|
||||
export class LocationFile extends Location<ServiceLocationFile> {
|
||||
constructor(path: string = '') { super({ type: 'FILE', path }); }
|
||||
static fromJson(data: ServiceLocationFile): LocationFile { return new LocationFile().load(data); }
|
||||
clone(): LocationFile { return LocationFile.fromJson(this.toJson()); }
|
||||
|
||||
getUrl(): string {
|
||||
const path = this.path || '';
|
||||
return `${this.scheme}://${this.host}:${this.port}${path}`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Single socket-based service location
|
||||
* Used by: services using a single host/port combination
|
||||
*/
|
||||
export class LocationSocketSole extends Location {
|
||||
readonly type = 'SOCKET_SOLE' as const;
|
||||
host: string;
|
||||
port: number;
|
||||
encryption: 'none' | 'ssl' | 'tls' | 'starttls';
|
||||
verifyPeer: boolean;
|
||||
verifyHost: boolean;
|
||||
|
||||
constructor(
|
||||
host: string = '',
|
||||
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
|
||||
};
|
||||
}
|
||||
get type(): 'FILE' { return this._data.type; }
|
||||
get path(): string { return this._data.path; }
|
||||
set path(value: string) { this._data.path = value; }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
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 }),
|
||||
});
|
||||
}
|
||||
}
|
||||
+11
-9
@@ -4,10 +4,12 @@
|
||||
|
||||
import type {
|
||||
ProviderInterface,
|
||||
ProviderCapabilitiesInterface
|
||||
ProviderCapabilitiesInterface,
|
||||
ProviderModelInterface
|
||||
} from "@/types/provider";
|
||||
import { clonePlain } from './clone-plain';
|
||||
|
||||
export class ProviderObject implements ProviderInterface {
|
||||
export class ProviderObject implements ProviderModelInterface {
|
||||
|
||||
_data!: ProviderInterface;
|
||||
|
||||
@@ -21,12 +23,16 @@ export class ProviderObject implements ProviderInterface {
|
||||
}
|
||||
|
||||
fromJson(data: ProviderInterface): ProviderObject {
|
||||
this._data = data;
|
||||
this._data = clonePlain(data);
|
||||
return this;
|
||||
}
|
||||
|
||||
toJson(): ProviderInterface {
|
||||
return this._data;
|
||||
return clonePlain(this._data);
|
||||
}
|
||||
|
||||
clone(): ProviderObject {
|
||||
return new ProviderObject().fromJson(this.toJson());
|
||||
}
|
||||
|
||||
capable(capability: keyof ProviderCapabilitiesInterface): boolean {
|
||||
@@ -43,10 +49,6 @@ export class ProviderObject implements ProviderInterface {
|
||||
|
||||
/** Immutable Properties */
|
||||
|
||||
get '@type'(): string {
|
||||
return this._data['@type'];
|
||||
}
|
||||
|
||||
get identifier(): string {
|
||||
return this._data.identifier;
|
||||
}
|
||||
@@ -56,7 +58,7 @@ export class ProviderObject implements ProviderInterface {
|
||||
}
|
||||
|
||||
get capabilities(): ProviderCapabilitiesInterface {
|
||||
return this._data.capabilities;
|
||||
return clonePlain(this._data.capabilities);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+86
-81
@@ -5,18 +5,26 @@
|
||||
import type {
|
||||
ServiceInterface,
|
||||
ServiceCapabilitiesInterface,
|
||||
ServiceIdentity,
|
||||
ServiceLocation
|
||||
ServiceLocation,
|
||||
ServiceModelInterface
|
||||
} from "@/types/service";
|
||||
import { Identity } from './identity';
|
||||
import { Location } from './location';
|
||||
import { MutationProxy } from './mutation-proxy';
|
||||
import { clonePlain } from './clone-plain';
|
||||
|
||||
export class ServiceObject implements ServiceInterface {
|
||||
|
||||
export class ServiceObject implements ServiceModelInterface {
|
||||
private _original: ServiceInterface;
|
||||
private _mutated: Partial<ServiceInterface>;
|
||||
private _mutationProxy = new MutationProxy<ServiceInterface>(() => this._original, () => this._mutated);
|
||||
_data!: ServiceInterface;
|
||||
private _location: Location | null | undefined = undefined;
|
||||
private _identity: Identity | null | undefined = undefined;
|
||||
private _locationAssigned = false;
|
||||
private _identityAssigned = false;
|
||||
|
||||
constructor() {
|
||||
this._data = {
|
||||
this._original = {
|
||||
'@type': 'chrono:service',
|
||||
provider: '',
|
||||
identifier: null,
|
||||
@@ -24,15 +32,59 @@ export class ServiceObject implements ServiceInterface {
|
||||
enabled: false,
|
||||
capabilities: {}
|
||||
};
|
||||
this._mutated = {};
|
||||
this._data = this._mutationProxy.create();
|
||||
}
|
||||
|
||||
fromJson(data: ServiceInterface): ServiceObject {
|
||||
this._data = data;
|
||||
this._original = clonePlain(data);
|
||||
this._mutated = {};
|
||||
this._data = this._mutationProxy.create();
|
||||
this._location = undefined;
|
||||
this._identity = undefined;
|
||||
this._locationAssigned = false;
|
||||
this._identityAssigned = false;
|
||||
return this;
|
||||
}
|
||||
|
||||
toJson(): ServiceInterface {
|
||||
return this._data;
|
||||
toJson(): ServiceInterface;
|
||||
toJson(delta: true): Partial<ServiceInterface>;
|
||||
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 {
|
||||
@@ -41,88 +93,41 @@ export class ServiceObject implements ServiceInterface {
|
||||
}
|
||||
|
||||
capability(capability: keyof ServiceCapabilitiesInterface): any | null {
|
||||
if (this._data.capabilities) {
|
||||
return this._data.capabilities[capability];
|
||||
}
|
||||
return null;
|
||||
return this._data.capabilities?.[capability] ?? null;
|
||||
}
|
||||
|
||||
/** Immutable Properties */
|
||||
get provider(): string { return this._data.provider; }
|
||||
get identifier(): string | number | null { return this._data.identifier; }
|
||||
get capabilities(): ServiceCapabilitiesInterface { return this._data.capabilities ?? {}; }
|
||||
|
||||
get '@type'(): string {
|
||||
return this._data['@type'];
|
||||
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(): 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;
|
||||
}
|
||||
|
||||
get provider(): string {
|
||||
return this._data.provider;
|
||||
set location(value: Location | null) {
|
||||
this._location = value;
|
||||
this._locationAssigned = true;
|
||||
}
|
||||
|
||||
get identifier(): string | number | null {
|
||||
return this._data.identifier;
|
||||
get identity(): Identity | null {
|
||||
if (this._identity !== undefined) return this._identity;
|
||||
this._identity = this._data.identity ? Identity.fromJson(this._data.identity) : null;
|
||||
return this._identity;
|
||||
}
|
||||
|
||||
get capabilities(): ServiceCapabilitiesInterface | undefined {
|
||||
return this._data.capabilities;
|
||||
}
|
||||
|
||||
/** 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);
|
||||
set identity(value: Identity | null) {
|
||||
this._identity = value;
|
||||
this._identityAssigned = true;
|
||||
}
|
||||
|
||||
get auxiliary(): Record<string, any> { return this._data.auxiliary ?? {}; }
|
||||
set auxiliary(value: Record<string, any>) { this._data.auxiliary = value; }
|
||||
}
|
||||
|
||||
@@ -70,9 +70,15 @@ export const collectionService = {
|
||||
*
|
||||
* @returns Promise with collection object
|
||||
*/
|
||||
async fetch(request: CollectionFetchRequest): Promise<CollectionObject> {
|
||||
async fetch(request: CollectionFetchRequest): Promise<Record<string, CollectionObject>> {
|
||||
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;
|
||||
},
|
||||
|
||||
/**
|
||||
@@ -123,8 +129,14 @@ export const collectionService = {
|
||||
*
|
||||
* @returns Promise with deletion result
|
||||
*/
|
||||
async delete(request: CollectionDeleteRequest): Promise<CollectionDeleteResponse> {
|
||||
return await transceivePost<CollectionDeleteRequest, CollectionDeleteResponse>('collection.delete', request);
|
||||
async delete(request: CollectionDeleteRequest): Promise<boolean | CollectionObject> {
|
||||
const response = await transceivePost<CollectionDeleteRequest, CollectionDeleteResponse>('collection.delete', request);
|
||||
|
||||
if (response.disposition === 'moved' && response.mutation) {
|
||||
return createCollectionObject(response.mutation);
|
||||
}
|
||||
|
||||
return true;
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -2,10 +2,12 @@
|
||||
* Entity management service
|
||||
*/
|
||||
|
||||
import { transceivePost } from './transceive';
|
||||
import { transceivePost, transceiveStream } from './transceive';
|
||||
import type {
|
||||
EntityListRequest,
|
||||
EntityListResponse,
|
||||
EntityListBulkRequest,
|
||||
EntityListBulkResponse,
|
||||
EntityListStreamRequest,
|
||||
EntityListStreamResponse,
|
||||
EntityFetchRequest,
|
||||
EntityFetchResponse,
|
||||
EntityExtantRequest,
|
||||
@@ -18,6 +20,10 @@ import type {
|
||||
EntityDeleteResponse,
|
||||
EntityDeltaRequest,
|
||||
EntityDeltaResponse,
|
||||
EntityMoveRequest,
|
||||
EntityMoveResponse,
|
||||
EntityImportRequest,
|
||||
EntityImportResponse,
|
||||
EntityInterface,
|
||||
} from '../types/entity';
|
||||
import { useIntegrationStore } from '@KTXC/stores/integrationStore';
|
||||
@@ -39,16 +45,11 @@ function createEntityObject(data: EntityInterface): EntityObject {
|
||||
export const entityService = {
|
||||
|
||||
/**
|
||||
* 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
|
||||
* Retrieve list of entities, optionally filtered by source collection identifiers
|
||||
*/
|
||||
async list(request: EntityListRequest = {}): Promise<Record<string, Record<string, Record<string, Record<string, EntityObject>>>>> {
|
||||
const response = await transceivePost<EntityListRequest, EntityListResponse>('entity.list', request);
|
||||
async listBulk(request: EntityListBulkRequest = {}): Promise<Record<string, Record<string, Record<string, Record<string, EntityObject>>>>> {
|
||||
const response = await transceivePost<EntityListBulkRequest, EntityListBulkResponse>('entity.listBulk', request);
|
||||
|
||||
// Convert nested response to EntityObject instances
|
||||
const providerList: Record<string, Record<string, Record<string, Record<string, EntityObject>>>> = {};
|
||||
Object.entries(response).forEach(([providerId, providerServices]) => {
|
||||
const serviceList: Record<string, Record<string, Record<string, EntityObject>>> = {};
|
||||
@@ -70,30 +71,34 @@ export const entityService = {
|
||||
},
|
||||
|
||||
/**
|
||||
* Retrieve a specific entity by provider and identifier
|
||||
*
|
||||
* @param request - fetch request parameters
|
||||
*
|
||||
* @returns Promise with entity objects keyed by identifier
|
||||
* Stream entities as NDJSON, invoking onEntity for each entity as it arrives.
|
||||
*/
|
||||
async listStream(request: EntityListStreamRequest, onEntity: (entity: EntityObject) => void): Promise<{ total: number }> {
|
||||
return await transceiveStream<EntityListStreamRequest, EntityListStreamResponse>(
|
||||
'entity.listStream',
|
||||
request,
|
||||
(entity) => {
|
||||
onEntity(createEntityObject(entity));
|
||||
}
|
||||
);
|
||||
},
|
||||
|
||||
/**
|
||||
* Retrieve specific entities by their identifiers
|
||||
*/
|
||||
async fetch(request: EntityFetchRequest): Promise<Record<string, EntityObject>> {
|
||||
const response = await transceivePost<EntityFetchRequest, EntityFetchResponse>('entity.fetch', request);
|
||||
|
||||
// Convert response to EntityObject instances
|
||||
const list: Record<string, EntityObject> = {};
|
||||
Object.entries(response).forEach(([identifier, entityData]) => {
|
||||
list[identifier] = createEntityObject(entityData);
|
||||
Object.entries(response).forEach(([, entity]) => {
|
||||
list[entity.identifier] = createEntityObject(entity);
|
||||
});
|
||||
|
||||
return list;
|
||||
},
|
||||
|
||||
/**
|
||||
* Retrieve entity availability status for a given source selector
|
||||
*
|
||||
* @param request - extant request parameters
|
||||
*
|
||||
* @returns Promise with entity availability status
|
||||
* Retrieve entity availability status for a given set of entity identifiers
|
||||
*/
|
||||
async extant(request: EntityExtantRequest): Promise<EntityExtantResponse> {
|
||||
return await transceivePost<EntityExtantRequest, EntityExtantResponse>('entity.extant', request);
|
||||
@@ -101,10 +106,6 @@ export const entityService = {
|
||||
|
||||
/**
|
||||
* Create a new entity
|
||||
*
|
||||
* @param request - create request parameters
|
||||
*
|
||||
* @returns Promise with created entity object
|
||||
*/
|
||||
async create(request: EntityCreateRequest): Promise<EntityObject> {
|
||||
const response = await transceivePost<EntityCreateRequest, EntityCreateResponse>('entity.create', request);
|
||||
@@ -113,10 +114,6 @@ export const entityService = {
|
||||
|
||||
/**
|
||||
* Update an existing entity
|
||||
*
|
||||
* @param request - update request parameters
|
||||
*
|
||||
* @returns Promise with updated entity object
|
||||
*/
|
||||
async update(request: EntityUpdateRequest): Promise<EntityObject> {
|
||||
const response = await transceivePost<EntityUpdateRequest, EntityUpdateResponse>('entity.update', request);
|
||||
@@ -124,11 +121,7 @@ export const entityService = {
|
||||
},
|
||||
|
||||
/**
|
||||
* Delete an entity
|
||||
*
|
||||
* @param request - delete request parameters
|
||||
*
|
||||
* @returns Promise with deletion result
|
||||
* Delete entities by their identifiers
|
||||
*/
|
||||
async delete(request: EntityDeleteRequest): Promise<EntityDeleteResponse> {
|
||||
return await transceivePost<EntityDeleteRequest, EntityDeleteResponse>('entity.delete', request);
|
||||
@@ -136,15 +129,40 @@ export const entityService = {
|
||||
|
||||
/**
|
||||
* Retrieve delta changes for entities
|
||||
*
|
||||
* @param request - delta request parameters
|
||||
*
|
||||
* @returns Promise with delta changes (created, modified, deleted)
|
||||
*/
|
||||
async delta(request: EntityDeltaRequest): Promise<EntityDeltaResponse> {
|
||||
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;
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
*/
|
||||
|
||||
import { createFetchWrapper } from '@KTXC';
|
||||
import type { ApiRequest, ApiResponse } from '../types/common';
|
||||
import type { ApiRequest, ApiResponse, ApiStreamResponse } from '../types/common';
|
||||
|
||||
const fetchWrapper = createFetchWrapper();
|
||||
const API_URL = '/m/chrono_manager/v1';
|
||||
@@ -48,3 +48,82 @@ export async function transceivePost<TRequest, TResponse>(
|
||||
|
||||
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 };
|
||||
}
|
||||
|
||||
+61
-127
@@ -4,9 +4,14 @@
|
||||
|
||||
import { ref, computed, readonly } from 'vue'
|
||||
import { defineStore } from 'pinia'
|
||||
import {
|
||||
type ServiceIdentifier,
|
||||
type CollectionIdentifier,
|
||||
type ListFilter,
|
||||
type ListSort,
|
||||
} from '../types'
|
||||
import { collectionService } from '../services'
|
||||
import { CollectionObject, CollectionPropertiesObject } from '../models/collection'
|
||||
import type { SourceSelector, ListFilter, ListSort } from '../types'
|
||||
|
||||
export const useCollectionsStore = defineStore('chronoCollectionsStore', () => {
|
||||
// State
|
||||
@@ -36,10 +41,8 @@ export const useCollectionsStore = defineStore('chronoCollectionsStore', () => {
|
||||
|
||||
Object.values(_collections.value).forEach((collection) => {
|
||||
const serviceKey = `${collection.provider}:${collection.service}`
|
||||
if (!groups[serviceKey]) {
|
||||
groups[serviceKey] = []
|
||||
}
|
||||
groups[serviceKey].push(collection)
|
||||
const serviceCollections = (groups[serviceKey] ??= [])
|
||||
serviceCollections.push(collection)
|
||||
})
|
||||
|
||||
return groups
|
||||
@@ -47,87 +50,49 @@ export const useCollectionsStore = defineStore('chronoCollectionsStore', () => {
|
||||
|
||||
/**
|
||||
* 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(provider: string, service: string | number, identifier: string | number, retrieve: boolean = false): CollectionObject | null {
|
||||
const key = identifierKey(provider, service, identifier)
|
||||
if (retrieve === true && !_collections.value[key]) {
|
||||
console.debug(`[Chrono Manager][Store] - Force fetching collection "${key}"`)
|
||||
fetch(provider, service, identifier)
|
||||
function collection(target: CollectionIdentifier, retrieve: boolean = false): CollectionObject | null {
|
||||
if (retrieve === true && !_collections.value[target]) {
|
||||
console.debug(`[Chrono Manager][Store] - Force fetching collection "${target}"`)
|
||||
fetch([target])
|
||||
}
|
||||
|
||||
return _collections.value[key] || null
|
||||
return _collections.value[target] || null
|
||||
}
|
||||
|
||||
/**
|
||||
* 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[] {
|
||||
const serviceKeyPrefix = `${provider}:${service}:`
|
||||
const serviceCollections = Object.entries(_collections.value)
|
||||
.filter(([key]) => key.startsWith(serviceKeyPrefix))
|
||||
.map(([_, collection]) => collection)
|
||||
const serviceIdentifier = `${provider}:${service}` as ServiceIdentifier
|
||||
const serviceCollections = Object.values(_collections.value)
|
||||
.filter(collection => `${collection.provider}:${collection.service}` === serviceIdentifier)
|
||||
|
||||
if (retrieve === true && serviceCollections.length === 0) {
|
||||
console.debug(`[Chrono Manager][Store] - Force fetching collections for service "${provider}:${service}"`)
|
||||
const sources: SourceSelector = {
|
||||
[provider]: {
|
||||
[String(service)]: true
|
||||
}
|
||||
}
|
||||
list(sources)
|
||||
console.debug(`[Chrono Manager][Store] - Force fetching collections for service "${serviceIdentifier}"`)
|
||||
list([serviceIdentifier])
|
||||
}
|
||||
|
||||
return serviceCollections
|
||||
}
|
||||
|
||||
/**
|
||||
* Create unique key for a collection
|
||||
* Retrieve all or specific collections, optionally filtered by service/collection identifiers
|
||||
*/
|
||||
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>> {
|
||||
async function list(sources?: ServiceIdentifier[] | CollectionIdentifier[], filter?: ListFilter, sort?: ListSort): Promise<Record<string, CollectionObject>> {
|
||||
transceiving.value = true
|
||||
try {
|
||||
const response = await collectionService.list({ sources, filter, sort })
|
||||
|
||||
// Flatten nested structure: provider:service:collection -> "provider:service:collection": object
|
||||
const collections: Record<string, CollectionObject> = {}
|
||||
Object.entries(response).forEach(([_providerId, providerServices]) => {
|
||||
Object.entries(providerServices).forEach(([_serviceId, serviceCollections]) => {
|
||||
Object.entries(serviceCollections).forEach(([_collectionId, collectionObj]) => {
|
||||
const key = identifierKey(collectionObj.provider, collectionObj.service, collectionObj.identifier)
|
||||
collections[key] = collectionObj
|
||||
collections[collectionObj.identifier] = collectionObj
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
// Merge retrieved collections into state
|
||||
_collections.value = { ..._collections.value, ...collections }
|
||||
|
||||
console.debug('[Chrono Manager][Store] - Successfully retrieved', Object.keys(collections).length, 'collections')
|
||||
@@ -141,27 +106,21 @@ export const useCollectionsStore = defineStore('chronoCollectionsStore', () => {
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
* Retrieve specific collections by their identifiers
|
||||
*/
|
||||
async function fetch(provider: string, service: string | number, identifier: string | number): Promise<CollectionObject> {
|
||||
async function fetch(targets: CollectionIdentifier[]): Promise<Record<string, CollectionObject>> {
|
||||
transceiving.value = true
|
||||
try {
|
||||
const response = await collectionService.fetch({ provider, service, collection: identifier })
|
||||
const response = await collectionService.fetch({ targets })
|
||||
|
||||
// Merge fetched collection into state
|
||||
const key = identifierKey(response.provider, response.service, response.identifier)
|
||||
_collections.value[key] = response
|
||||
Object.values(response).forEach(collectionObj => {
|
||||
_collections.value[collectionObj.identifier] = collectionObj
|
||||
})
|
||||
|
||||
console.debug('[Chrono Manager][Store] - Successfully fetched collection:', key)
|
||||
console.debug('[Chrono Manager][Store] - Successfully fetched collections:', Object.keys(response).join(', '))
|
||||
return response
|
||||
} catch (error: any) {
|
||||
console.error('[Chrono Manager][Store] - Failed to fetch collection:', error)
|
||||
console.error('[Chrono Manager][Store] - Failed to fetch collections:', error)
|
||||
throw error
|
||||
} finally {
|
||||
transceiving.value = false
|
||||
@@ -169,18 +128,14 @@ export const useCollectionsStore = defineStore('chronoCollectionsStore', () => {
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve collection availability status for a given source selector
|
||||
*
|
||||
* @param sources - source selector to check availability for
|
||||
*
|
||||
* @returns Promise with collection availability status
|
||||
* Retrieve collection availability status for the given collection identifiers
|
||||
*/
|
||||
async function extant(sources: SourceSelector) {
|
||||
async function extant(targets: CollectionIdentifier[]): Promise<Record<string, Record<string, Record<string, boolean>>>> {
|
||||
transceiving.value = true
|
||||
try {
|
||||
const response = await collectionService.extant({ sources })
|
||||
const response = await collectionService.extant({ targets })
|
||||
|
||||
console.debug('[Chrono Manager][Store] - Successfully checked', sources ? Object.keys(sources).length : 0, 'collections')
|
||||
console.debug('[Chrono Manager][Store] - Successfully checked', targets ? targets.length : 0, 'collections')
|
||||
return response
|
||||
} catch (error: any) {
|
||||
console.error('[Chrono Manager][Store] - Failed to check collections:', error)
|
||||
@@ -191,30 +146,20 @@ export const useCollectionsStore = defineStore('chronoCollectionsStore', () => {
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
* Create a new collection with given provider, service, and properties
|
||||
*/
|
||||
async function create(provider: string, service: string | number, collection: string | number | null, data: CollectionPropertiesObject): Promise<CollectionObject> {
|
||||
async function create(provider: string, service: string | number, properties: CollectionPropertiesObject): Promise<CollectionObject> {
|
||||
transceiving.value = true
|
||||
try {
|
||||
const response = await collectionService.create({
|
||||
provider,
|
||||
service,
|
||||
collection,
|
||||
properties: data
|
||||
properties: properties.toJson(),
|
||||
})
|
||||
|
||||
// Merge created collection into state
|
||||
const key = identifierKey(response.provider, response.service, response.identifier)
|
||||
_collections.value[key] = response
|
||||
_collections.value[response.identifier] = response
|
||||
|
||||
console.debug('[Chrono Manager][Store] - Successfully created collection:', key)
|
||||
console.debug('[Chrono Manager][Store] - Successfully created collection:', response.identifier)
|
||||
return response
|
||||
} catch (error: any) {
|
||||
console.error('[Chrono Manager][Store] - Failed to create collection:', error)
|
||||
@@ -225,30 +170,19 @@ export const useCollectionsStore = defineStore('chronoCollectionsStore', () => {
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
* Update an existing collection with given target and properties
|
||||
*/
|
||||
async function update(provider: string, service: string | number, identifier: string | number, data: CollectionPropertiesObject): Promise<CollectionObject> {
|
||||
async function update(target: CollectionIdentifier, properties: CollectionPropertiesObject): Promise<CollectionObject> {
|
||||
transceiving.value = true
|
||||
try {
|
||||
const response = await collectionService.update({
|
||||
provider,
|
||||
service,
|
||||
identifier,
|
||||
properties: data
|
||||
target,
|
||||
properties: properties.toJson(),
|
||||
})
|
||||
|
||||
// Merge updated collection into state
|
||||
const key = identifierKey(response.provider, response.service, response.identifier)
|
||||
_collections.value[key] = response
|
||||
_collections.value[response.identifier] = response
|
||||
|
||||
console.debug('[Chrono Manager][Store] - Successfully updated collection:', key)
|
||||
console.debug('[Chrono Manager][Store] - Successfully updated collection:', response.identifier)
|
||||
return response
|
||||
} catch (error: any) {
|
||||
console.error('[Chrono Manager][Store] - Failed to update collection:', error)
|
||||
@@ -259,24 +193,28 @@ export const useCollectionsStore = defineStore('chronoCollectionsStore', () => {
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
* Delete a collection by identifier.
|
||||
*/
|
||||
async function remove(provider: string, service: string | number, identifier: string | number): Promise<any> {
|
||||
async function remove(target: CollectionIdentifier, force?: boolean): Promise<CollectionObject | boolean> {
|
||||
transceiving.value = true
|
||||
try {
|
||||
await collectionService.delete({ provider, service, identifier })
|
||||
const response = await collectionService.delete({ target, options: { force } })
|
||||
|
||||
// Remove deleted collection from state
|
||||
const key = identifierKey(provider, service, identifier)
|
||||
delete _collections.value[key]
|
||||
if (response !== true && !(response instanceof CollectionObject)) {
|
||||
console.warn('[Chrono Manager][Store] - Delete failed. Received unexpected response from delete operation:', response)
|
||||
return false
|
||||
}
|
||||
|
||||
console.debug('[Chrono Manager][Store] - Successfully deleted collection:', key)
|
||||
delete _collections.value[target]
|
||||
|
||||
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) {
|
||||
console.error('[Chrono Manager][Store] - Failed to delete collection:', error)
|
||||
throw error
|
||||
@@ -285,17 +223,13 @@ export const useCollectionsStore = defineStore('chronoCollectionsStore', () => {
|
||||
}
|
||||
}
|
||||
|
||||
// Return public API
|
||||
return {
|
||||
// State (readonly)
|
||||
transceiving: readonly(transceiving),
|
||||
// Getters
|
||||
count,
|
||||
has,
|
||||
collections,
|
||||
collectionsByService,
|
||||
collectionsForService,
|
||||
// Actions
|
||||
collection,
|
||||
list,
|
||||
fetch,
|
||||
|
||||
+184
-203
@@ -6,7 +6,14 @@ import { ref, computed, readonly } from 'vue'
|
||||
import { defineStore } from 'pinia'
|
||||
import { entityService } from '../services'
|
||||
import { EntityObject } from '../models'
|
||||
import type { SourceSelector, ListFilter, ListSort, ListRange } from '../types/common'
|
||||
import type {
|
||||
CollectionIdentifier,
|
||||
EntityIdentifier,
|
||||
ListFilter,
|
||||
ListRange,
|
||||
ListSort,
|
||||
} from '../types/common'
|
||||
import type { EntityPropertiesInterface } from '@/types/entity'
|
||||
|
||||
export const useEntitiesStore = defineStore('chronoEntitiesStore', () => {
|
||||
// State
|
||||
@@ -30,95 +37,44 @@ export const useEntitiesStore = defineStore('chronoEntitiesStore', () => {
|
||||
|
||||
/**
|
||||
* 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(provider: string, service: string | number, collection: string | number, identifier: string | number, retrieve: boolean = false): EntityObject | null {
|
||||
const key = identifierKey(provider, service, collection, identifier)
|
||||
if (retrieve === true && !_entities.value[key]) {
|
||||
console.debug(`[Chrono Manager][Store] - Force fetching entity "${key}"`)
|
||||
fetch(provider, service, collection, [identifier])
|
||||
function entity(target: EntityIdentifier, retrieve: boolean = false): EntityObject | null {
|
||||
if (retrieve === true && !_entities.value[target]) {
|
||||
console.debug(`[Chrono Manager][Store] - Force fetching entity "${target}"`)
|
||||
fetch([target])
|
||||
}
|
||||
|
||||
return _entities.value[key] || null
|
||||
return _entities.value[target] || null
|
||||
}
|
||||
|
||||
/**
|
||||
* 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(provider: string, service: string | number, collection: string | number, retrieve: boolean = false): EntityObject[] {
|
||||
const collectionKeyPrefix = `${provider}:${service}:${collection}:`
|
||||
function entitiesForCollection(target: CollectionIdentifier, retrieve: boolean = false): EntityObject[] {
|
||||
const collectionEntities = Object.entries(_entities.value)
|
||||
.filter(([key]) => key.startsWith(collectionKeyPrefix))
|
||||
.filter(([key]) => key.startsWith(`${target}:`))
|
||||
.map(([_, entity]) => entity)
|
||||
|
||||
if (retrieve === true && collectionEntities.length === 0) {
|
||||
console.debug(`[Chrono Manager][Store] - Force fetching entities for collection "${provider}:${service}:${collection}"`)
|
||||
const sources: SourceSelector = {
|
||||
[provider]: {
|
||||
[String(service)]: {
|
||||
[String(collection)]: true
|
||||
}
|
||||
}
|
||||
}
|
||||
list(sources)
|
||||
console.debug(`[Chrono Manager][Store] - Force fetching entities for collection "${target}"`)
|
||||
list([target])
|
||||
}
|
||||
|
||||
return collectionEntities
|
||||
}
|
||||
|
||||
/**
|
||||
* Create unique key for an entity
|
||||
* Retrieve all or specific entities, optionally filtered by source collection identifiers
|
||||
*/
|
||||
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>> {
|
||||
async function list(sources: CollectionIdentifier[], filter?: ListFilter, sort?: ListSort, range?: ListRange): Promise<Record<string, EntityObject>> {
|
||||
transceiving.value = true
|
||||
try {
|
||||
const response = await entityService.list({ sources, filter, sort, range })
|
||||
|
||||
// Flatten nested structure: provider:service:collection:entity -> "provider:service:collection:entity": object
|
||||
const entities: Record<string, EntityObject> = {}
|
||||
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 }
|
||||
await entityService.listStream({ sources, filter, sort, range }, (entity: EntityObject) => {
|
||||
_entities.value[entity.identifier] = entity
|
||||
entities[entity.identifier] = entity
|
||||
})
|
||||
|
||||
console.debug('[Chrono Manager][Store] - Successfully retrieved', Object.keys(entities).length, 'entities')
|
||||
return entities
|
||||
@@ -131,26 +87,17 @@ export const useEntitiesStore = defineStore('chronoEntitiesStore', () => {
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
* Retrieve specific entities by their identifiers
|
||||
*/
|
||||
async function fetch(provider: string, service: string | number, collection: string | number, identifiers: (string | number)[]): Promise<Record<string, EntityObject>> {
|
||||
async function fetch(targets: EntityIdentifier[]): Promise<Record<string, EntityObject>> {
|
||||
transceiving.value = true
|
||||
try {
|
||||
const response = await entityService.fetch({ provider, service, collection, identifiers })
|
||||
const response = await entityService.fetch({ targets })
|
||||
|
||||
// Merge fetched entities into state
|
||||
const entities: Record<string, EntityObject> = {}
|
||||
Object.entries(response).forEach(([identifier, entityData]) => {
|
||||
const key = identifierKey(provider, service, collection, identifier)
|
||||
entities[key] = entityData
|
||||
_entities.value[key] = entityData
|
||||
Object.entries(response).forEach(([identifier, entity]) => {
|
||||
entities[identifier] = entity
|
||||
_entities.value[identifier] = entity
|
||||
})
|
||||
|
||||
console.debug('[Chrono Manager][Store] - Successfully fetched', Object.keys(entities).length, 'entities')
|
||||
@@ -164,16 +111,12 @@ export const useEntitiesStore = defineStore('chronoEntitiesStore', () => {
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve entity availability status for a given source selector
|
||||
*
|
||||
* @param sources - source selector to check availability for
|
||||
*
|
||||
* @returns Promise with entity availability status
|
||||
* Retrieve entity availability status for a given set of entity identifiers
|
||||
*/
|
||||
async function extant(sources: SourceSelector) {
|
||||
async function extant(targets: EntityIdentifier[]) {
|
||||
transceiving.value = true
|
||||
try {
|
||||
const response = await entityService.extant({ sources })
|
||||
const response = await entityService.extant({ targets })
|
||||
console.debug('[Chrono Manager][Store] - Successfully checked entity availability')
|
||||
return response
|
||||
} catch (error: any) {
|
||||
@@ -184,132 +127,28 @@ export const useEntitiesStore = defineStore('chronoEntitiesStore', () => {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 create(provider: string, service: string | number, collection: string | number, data: any): Promise<EntityObject> {
|
||||
transceiving.value = true
|
||||
try {
|
||||
const response = await entityService.create({ provider, service, collection, properties: data })
|
||||
|
||||
// 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) {
|
||||
async function delta(targets: (CollectionIdentifier | EntityIdentifier)[]) {
|
||||
transceiving.value = true
|
||||
try {
|
||||
const response = await entityService.delta({ sources })
|
||||
const response = await entityService.delta({ targets })
|
||||
|
||||
// Process delta and update store
|
||||
Object.entries(response).forEach(([provider, providerData]) => {
|
||||
// Skip if no changes for provider
|
||||
Object.entries(response).forEach(([, providerData]) => {
|
||||
if (providerData === false) return
|
||||
|
||||
Object.entries(providerData).forEach(([service, serviceData]) => {
|
||||
// Skip if no changes for service
|
||||
Object.entries(providerData).forEach(([, serviceData]) => {
|
||||
if (serviceData === false) return
|
||||
|
||||
Object.entries(serviceData).forEach(([collection, collectionData]) => {
|
||||
// Skip if no changes for collection
|
||||
Object.entries(serviceData).forEach(([, collectionData]) => {
|
||||
if (collectionData === false) return
|
||||
|
||||
// Process deletions (remove from store)
|
||||
if (collectionData.deletions && collectionData.deletions.length > 0) {
|
||||
collectionData.deletions.forEach((identifier) => {
|
||||
const key = identifierKey(provider, service, collection, identifier)
|
||||
delete _entities.value[key]
|
||||
delete _entities.value[identifier]
|
||||
})
|
||||
}
|
||||
|
||||
// Note: additions and modifications contain only identifiers
|
||||
// The caller should fetch full entities using the fetch() method
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -324,16 +163,156 @@ 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 {
|
||||
// State (readonly)
|
||||
transceiving: readonly(transceiving),
|
||||
// Getters
|
||||
count,
|
||||
has,
|
||||
entities,
|
||||
entitiesForCollection,
|
||||
// Actions
|
||||
entity,
|
||||
list,
|
||||
fetch,
|
||||
@@ -342,5 +321,7 @@ export const useEntitiesStore = defineStore('chronoEntitiesStore', () => {
|
||||
update,
|
||||
delete: remove,
|
||||
delta,
|
||||
fresh,
|
||||
move,
|
||||
}
|
||||
})
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
/**
|
||||
* 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 }
|
||||
})
|
||||
@@ -2,3 +2,4 @@ export { useProvidersStore } from './providersStore';
|
||||
export { useServicesStore } from './servicesStore';
|
||||
export { useCollectionsStore } from './collectionsStore';
|
||||
export { useEntitiesStore } from './entitiesStore';
|
||||
export { useImportStore } from './importStore';
|
||||
|
||||
@@ -6,7 +6,7 @@ import { ref, computed, readonly } from 'vue'
|
||||
import { defineStore } from 'pinia'
|
||||
import { providerService } from '../services'
|
||||
import { ProviderObject } from '../models/provider'
|
||||
import type { SourceSelector } from '../types'
|
||||
import type { ProviderIdentifier } from '../types'
|
||||
|
||||
export const useProvidersStore = defineStore('chronoProvidersStore', () => {
|
||||
// State
|
||||
@@ -54,10 +54,10 @@ export const useProvidersStore = defineStore('chronoProvidersStore', () => {
|
||||
*
|
||||
* @returns Promise with provider object list keyed by provider identifier
|
||||
*/
|
||||
async function list(sources?: SourceSelector): Promise<Record<string, ProviderObject>> {
|
||||
async function list(targets?: ProviderIdentifier[]): Promise<Record<string, ProviderObject>> {
|
||||
transceiving.value = true
|
||||
try {
|
||||
const providers = await providerService.list({ sources })
|
||||
const providers = await providerService.list({ targets })
|
||||
|
||||
// Merge retrieved providers into state
|
||||
_providers.value = { ..._providers.value, ...providers }
|
||||
@@ -82,7 +82,7 @@ export const useProvidersStore = defineStore('chronoProvidersStore', () => {
|
||||
async function fetch(identifier: string): Promise<ProviderObject> {
|
||||
transceiving.value = true
|
||||
try {
|
||||
const provider = await providerService.fetch({ identifier })
|
||||
const provider = await providerService.fetch({ target: identifier })
|
||||
|
||||
// Merge fetched provider into state
|
||||
_providers.value[provider.identifier] = provider
|
||||
@@ -104,10 +104,10 @@ export const useProvidersStore = defineStore('chronoProvidersStore', () => {
|
||||
*
|
||||
* @returns Promise with provider availability status
|
||||
*/
|
||||
async function extant(sources: SourceSelector) {
|
||||
async function extant(targets: ProviderIdentifier[]) {
|
||||
transceiving.value = true
|
||||
try {
|
||||
const response = await providerService.extant({ sources })
|
||||
const response = await providerService.extant({ targets })
|
||||
|
||||
Object.entries(response).forEach(([providerId, providerStatus]) => {
|
||||
if (providerStatus === false) {
|
||||
@@ -115,7 +115,7 @@ export const useProvidersStore = defineStore('chronoProvidersStore', () => {
|
||||
}
|
||||
})
|
||||
|
||||
console.debug('[Chrono Manager][Store] - Successfully checked', sources ? Object.keys(sources).length : 0, 'providers')
|
||||
console.debug('[Chrono Manager][Store] - Successfully checked', targets ? targets.length : 0, 'providers')
|
||||
return response
|
||||
} catch (error: any) {
|
||||
console.error('[Chrono Manager][Store] - Failed to check providers:', error)
|
||||
|
||||
+31
-15
@@ -7,7 +7,8 @@ import { defineStore } from 'pinia'
|
||||
import { serviceService } from '../services'
|
||||
import { ServiceObject } from '../models/service'
|
||||
import type {
|
||||
SourceSelector,
|
||||
CollectionIdentifier,
|
||||
ServiceIdentifier,
|
||||
ServiceInterface,
|
||||
} from '../types'
|
||||
|
||||
@@ -55,20 +56,30 @@ export const useServicesStore = defineStore('chronoServicesStore', () => {
|
||||
* @returns Service object or null
|
||||
*/
|
||||
function service(provider: string, identifier: string | number, retrieve: boolean = false): ServiceObject | null {
|
||||
const key = identifierKey(provider, identifier)
|
||||
if (retrieve === true && !_services.value[key]) {
|
||||
console.debug(`[Chrono Manager][Store] - Force fetching service "${key}"`)
|
||||
fetch(provider, identifier)
|
||||
return serviceByIdentifier(identifierKey(provider, identifier), retrieve)
|
||||
}
|
||||
|
||||
return _services.value[key] || null
|
||||
/**
|
||||
* 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
|
||||
}
|
||||
|
||||
/**
|
||||
* Unique key for a service
|
||||
*/
|
||||
function identifierKey(provider: string, identifier: string | number | null): string {
|
||||
return `${provider}:${identifier ?? ''}`
|
||||
function identifierKey(provider: string, identifier: string | number | null): ServiceIdentifier {
|
||||
return `${provider}:${identifier ?? ''}` as ServiceIdentifier
|
||||
}
|
||||
|
||||
// Actions
|
||||
@@ -80,10 +91,10 @@ export const useServicesStore = defineStore('chronoServicesStore', () => {
|
||||
*
|
||||
* @returns Promise with service object list keyed by provider and service identifier
|
||||
*/
|
||||
async function list(sources?: SourceSelector): Promise<Record<string, ServiceObject>> {
|
||||
async function list(targets?: ServiceIdentifier[] | CollectionIdentifier[]): Promise<Record<string, ServiceObject>> {
|
||||
transceiving.value = true
|
||||
try {
|
||||
const response = await serviceService.list({ sources })
|
||||
const response = await serviceService.list({ targets })
|
||||
|
||||
// Flatten nested structure: provider-id: { service-id: object } -> "provider-id:service-id": object
|
||||
const services: Record<string, ServiceObject> = {}
|
||||
@@ -141,12 +152,12 @@ export const useServicesStore = defineStore('chronoServicesStore', () => {
|
||||
*
|
||||
* @returns Promise with service availability status
|
||||
*/
|
||||
async function extant(sources: SourceSelector) {
|
||||
async function extant(targets: ServiceIdentifier[]) {
|
||||
transceiving.value = true
|
||||
try {
|
||||
const response = await serviceService.extant({ sources })
|
||||
const response = await serviceService.extant({ targets })
|
||||
|
||||
console.debug('[Chrono Manager][Store] - Successfully checked', sources ? Object.keys(sources).length : 0, 'services')
|
||||
console.debug('[Chrono Manager][Store] - Successfully checked', targets?.length ?? 0, 'services')
|
||||
return response
|
||||
} catch (error: any) {
|
||||
console.error('[Chrono Manager][Store] - Failed to check services:', error)
|
||||
@@ -192,10 +203,14 @@ export const useServicesStore = defineStore('chronoServicesStore', () => {
|
||||
*
|
||||
* @returns Promise with updated service object
|
||||
*/
|
||||
async function update(provider: string, identifier: string | number, data: Partial<ServiceInterface>): Promise<ServiceObject> {
|
||||
async function update(provider: string, identifier: string | number, delta: boolean, data: ServiceObject | Partial<ServiceInterface>): Promise<ServiceObject> {
|
||||
transceiving.value = true
|
||||
try {
|
||||
const service = await serviceService.update({ provider, identifier, data })
|
||||
const payload: Partial<ServiceInterface> = data instanceof ServiceObject
|
||||
? (delta ? data.toJson(true) : data.toJson())
|
||||
: data
|
||||
|
||||
const service = await serviceService.update({ provider, identifier, delta, data: payload })
|
||||
|
||||
// Merge updated service into state
|
||||
const key = identifierKey(service.provider, service.identifier)
|
||||
@@ -249,6 +264,7 @@ export const useServicesStore = defineStore('chronoServicesStore', () => {
|
||||
|
||||
// Actions
|
||||
service,
|
||||
serviceByIdentifier,
|
||||
list,
|
||||
fetch,
|
||||
extant,
|
||||
|
||||
+28
-20
@@ -1,27 +1,37 @@
|
||||
/**
|
||||
* Collection type definitions
|
||||
*/
|
||||
import type { ListFilter, ListSort, SourceSelector } from './common';
|
||||
import type {
|
||||
ServiceIdentifier,
|
||||
CollectionIdentifier,
|
||||
ListFilter,
|
||||
ListSort
|
||||
} from './common';
|
||||
|
||||
/**
|
||||
* Collection information
|
||||
*/
|
||||
export interface CollectionInterface {
|
||||
export interface CollectionInterface<T = CollectionPropertiesInterface> {
|
||||
'@type': string;
|
||||
version: number;
|
||||
provider: string;
|
||||
service: string | number;
|
||||
collection: string | number | null;
|
||||
identifier: string | number;
|
||||
collection: CollectionIdentifier | null;
|
||||
identifier: CollectionIdentifier;
|
||||
signature?: string | null;
|
||||
created?: string | null;
|
||||
modified?: string | null;
|
||||
properties: CollectionPropertiesInterface;
|
||||
properties: T;
|
||||
}
|
||||
|
||||
export interface CollectionModelInterface extends Omit<CollectionInterface<CollectionPropertiesInterface>, '@type' | 'version' | 'properties'> {
|
||||
properties: CollectionPropertiesModelInterface;
|
||||
}
|
||||
|
||||
export type CollectionContentTypes = 'event' | 'task' | 'journal';
|
||||
|
||||
export interface CollectionBaseProperties {
|
||||
'@type': string;
|
||||
version: number;
|
||||
}
|
||||
|
||||
export interface CollectionImmutableProperties extends CollectionBaseProperties {
|
||||
@@ -38,11 +48,13 @@ export interface CollectionMutableProperties extends CollectionBaseProperties {
|
||||
|
||||
export interface CollectionPropertiesInterface extends CollectionMutableProperties, CollectionImmutableProperties {}
|
||||
|
||||
export interface CollectionPropertiesModelInterface extends Omit<CollectionPropertiesInterface, '@type'> {}
|
||||
|
||||
/**
|
||||
* Collection list
|
||||
*/
|
||||
export interface CollectionListRequest {
|
||||
sources?: SourceSelector;
|
||||
sources?: ServiceIdentifier[] | CollectionIdentifier[];
|
||||
filter?: ListFilter;
|
||||
sort?: ListSort;
|
||||
}
|
||||
@@ -59,18 +71,18 @@ export interface CollectionListResponse {
|
||||
* Collection fetch
|
||||
*/
|
||||
export interface CollectionFetchRequest {
|
||||
provider: string;
|
||||
service: string | number;
|
||||
collection: string | number;
|
||||
targets: CollectionIdentifier[];
|
||||
}
|
||||
|
||||
export interface CollectionFetchResponse extends CollectionInterface {}
|
||||
export interface CollectionFetchResponse {
|
||||
[identifier: CollectionIdentifier]: CollectionInterface;
|
||||
}
|
||||
|
||||
/**
|
||||
* Collection extant
|
||||
*/
|
||||
export interface CollectionExtantRequest {
|
||||
sources: SourceSelector;
|
||||
targets: CollectionIdentifier[];
|
||||
}
|
||||
|
||||
export interface CollectionExtantResponse {
|
||||
@@ -87,7 +99,6 @@ export interface CollectionExtantResponse {
|
||||
export interface CollectionCreateRequest {
|
||||
provider: string;
|
||||
service: string | number;
|
||||
collection?: string | number | null; // Parent Collection Identifier
|
||||
properties: CollectionMutableProperties;
|
||||
}
|
||||
|
||||
@@ -97,9 +108,7 @@ export interface CollectionCreateResponse extends CollectionInterface {}
|
||||
* Collection modify
|
||||
*/
|
||||
export interface CollectionUpdateRequest {
|
||||
provider: string;
|
||||
service: string | number;
|
||||
identifier: string | number;
|
||||
target: CollectionIdentifier;
|
||||
properties: CollectionMutableProperties;
|
||||
}
|
||||
|
||||
@@ -109,14 +118,13 @@ export interface CollectionUpdateResponse extends CollectionInterface {}
|
||||
* Collection delete
|
||||
*/
|
||||
export interface CollectionDeleteRequest {
|
||||
provider: string;
|
||||
service: string | number;
|
||||
identifier: string | number;
|
||||
target: CollectionIdentifier;
|
||||
options?: {
|
||||
force?: boolean; // Whether to force delete even if collection is not empty
|
||||
};
|
||||
}
|
||||
|
||||
export interface CollectionDeleteResponse {
|
||||
success: boolean;
|
||||
disposition: 'deleted' | 'moved';
|
||||
mutation?: CollectionInterface | null; // If moved, the new location of the collection
|
||||
}
|
||||
|
||||
+62
-25
@@ -44,34 +44,57 @@ export interface ApiErrorResponse {
|
||||
export type ApiResponse<T = any> = ApiSuccessResponse<T> | ApiErrorResponse;
|
||||
|
||||
/**
|
||||
* Selector for targeting specific providers, services, collections, or entities in list or extant operations.
|
||||
*
|
||||
* Example usage:
|
||||
* {
|
||||
* "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
|
||||
* }
|
||||
* }
|
||||
* }
|
||||
* Stream control start line.
|
||||
*/
|
||||
export type SourceSelector = {
|
||||
[provider: string]: boolean | ServiceSelector;
|
||||
};
|
||||
export interface ApiStreamStartResponse {
|
||||
type: 'control';
|
||||
status: 'start';
|
||||
version: number;
|
||||
transaction: string;
|
||||
total?: number;
|
||||
}
|
||||
|
||||
export type ServiceSelector = {
|
||||
[service: string]: boolean | CollectionSelector;
|
||||
};
|
||||
/**
|
||||
* Stream control end line
|
||||
*/
|
||||
export interface ApiStreamEndResponse {
|
||||
type: 'control';
|
||||
status: 'end';
|
||||
total: number;
|
||||
}
|
||||
|
||||
export type CollectionSelector = {
|
||||
[collection: string | number]: boolean | EntitySelector;
|
||||
};
|
||||
/**
|
||||
* Stream error line
|
||||
*/
|
||||
export interface ApiStreamErrorResponse {
|
||||
type: 'error';
|
||||
message: string;
|
||||
}
|
||||
|
||||
export type EntitySelector = (string | number)[];
|
||||
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.
|
||||
* ["caldav:account1:calendar", "caldav:account1:calendar:1001"].
|
||||
*/
|
||||
export type ProviderIdentifier = `${string}`;
|
||||
export type ServiceIdentifier = `${string}:${string}`;
|
||||
export type CollectionIdentifier = `${string}:${string}:${string | number}`;
|
||||
export type EntityIdentifier = `${string}:${string}:${string}:${string | number}`;
|
||||
|
||||
/**
|
||||
* Filter comparison for list operations
|
||||
@@ -142,15 +165,29 @@ export interface ListSort {
|
||||
}
|
||||
|
||||
/**
|
||||
* Range for list operations
|
||||
* Tally (pagination) range for list operations
|
||||
*
|
||||
* Values can be:
|
||||
* - relative based on item identifier
|
||||
* - absolute based on item count
|
||||
*/
|
||||
export interface ListRange {
|
||||
export interface ListRangeTally {
|
||||
type: 'tally';
|
||||
anchor: 'relative' | 'absolute';
|
||||
position: string | 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;
|
||||
+106
-55
@@ -1,64 +1,86 @@
|
||||
/**
|
||||
* Entity type definitions
|
||||
*/
|
||||
import type { ListFilter, ListRange, ListSort, SourceSelector } from './common';
|
||||
import type {
|
||||
CollectionIdentifier,
|
||||
EntityIdentifier,
|
||||
ListFilter,
|
||||
ListRange,
|
||||
ListSort,
|
||||
} from './common';
|
||||
import type { EventInterface } from './event';
|
||||
import type { TaskInterface } from './task';
|
||||
import type { JournalInterface } from './journal';
|
||||
import type { ImportDisposition, ImportFileOptions } from './import';
|
||||
|
||||
export type EntityPropertiesInterface = EventInterface | TaskInterface | JournalInterface;
|
||||
|
||||
/**
|
||||
* Entity definition
|
||||
*/
|
||||
export interface EntityInterface<T = EventInterface | TaskInterface | JournalInterface> {
|
||||
export interface EntityInterface<T = EntityPropertiesInterface> {
|
||||
'@type': string;
|
||||
version: number;
|
||||
provider: string;
|
||||
service: string;
|
||||
collection: string | number;
|
||||
identifier: string | number;
|
||||
collection: CollectionIdentifier;
|
||||
identifier: EntityIdentifier;
|
||||
signature: string | null;
|
||||
created: string | null;
|
||||
modified: string | null;
|
||||
properties: T;
|
||||
}
|
||||
|
||||
export interface EntityModelInterface extends Omit<EntityInterface<EntityPropertiesInterface>, '@type' | 'version'> {}
|
||||
|
||||
/**
|
||||
* Entity list
|
||||
* Entity list bulk
|
||||
*/
|
||||
export interface EntityListRequest {
|
||||
sources?: SourceSelector;
|
||||
export interface EntityListBulkRequest {
|
||||
sources?: CollectionIdentifier[];
|
||||
filter?: ListFilter;
|
||||
sort?: ListSort;
|
||||
range?: ListRange;
|
||||
}
|
||||
|
||||
export interface EntityListResponse {
|
||||
export interface EntityListBulkResponse {
|
||||
[providerId: string]: {
|
||||
[serviceId: string]: {
|
||||
[collectionId: string]: {
|
||||
[identifier: string]: EntityInterface<EventInterface | TaskInterface | JournalInterface>;
|
||||
[identifier: string]: EntityInterface;
|
||||
};
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Entity list stream
|
||||
*/
|
||||
export interface EntityListStreamRequest {
|
||||
sources?: CollectionIdentifier[];
|
||||
filter?: ListFilter;
|
||||
sort?: ListSort;
|
||||
range?: ListRange;
|
||||
}
|
||||
|
||||
export interface EntityListStreamResponse extends EntityInterface {}
|
||||
|
||||
/**
|
||||
* Entity fetch
|
||||
*/
|
||||
export interface EntityFetchRequest {
|
||||
provider: string;
|
||||
service: string | number;
|
||||
collection: string | number;
|
||||
identifiers: (string | number)[];
|
||||
targets: EntityIdentifier[];
|
||||
}
|
||||
|
||||
export interface EntityFetchResponse {
|
||||
[identifier: string]: EntityInterface<EventInterface | TaskInterface | JournalInterface>;
|
||||
[identifier: string]: EntityInterface;
|
||||
}
|
||||
|
||||
/**
|
||||
* Entity extant
|
||||
*/
|
||||
export interface EntityExtantRequest {
|
||||
sources: SourceSelector;
|
||||
targets: EntityIdentifier[];
|
||||
}
|
||||
|
||||
export interface EntityExtantResponse {
|
||||
@@ -71,50 +93,13 @@ 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
|
||||
*/
|
||||
export interface EntityDeltaRequest {
|
||||
sources: SourceSelector;
|
||||
// Each target is provider:service:collection, or provider:service:collection:signature
|
||||
// to request a delta relative to a known signature (the signature is the entity slot).
|
||||
targets: (CollectionIdentifier | EntityIdentifier)[];
|
||||
}
|
||||
|
||||
export interface EntityDeltaResponse {
|
||||
@@ -129,3 +114,69 @@ 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[];
|
||||
}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
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;
|
||||
}
|
||||
@@ -3,6 +3,7 @@ export type * from './common';
|
||||
export type * from './entity';
|
||||
export type * from './event';
|
||||
export type * from './journal';
|
||||
export type * from './import';
|
||||
export type * from './provider';
|
||||
export type * from './service';
|
||||
export type * from './task';
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* Provider type definitions
|
||||
*/
|
||||
import type { SourceSelector } from "./common";
|
||||
import type { ProviderIdentifier } from './common';
|
||||
|
||||
/**
|
||||
* Provider capabilities
|
||||
@@ -28,22 +28,24 @@ export interface ProviderInterface {
|
||||
capabilities: ProviderCapabilitiesInterface;
|
||||
}
|
||||
|
||||
export interface ProviderModelInterface extends Omit<ProviderInterface, '@type'> {}
|
||||
|
||||
/**
|
||||
* Provider list
|
||||
*/
|
||||
export interface ProviderListRequest {
|
||||
sources?: SourceSelector;
|
||||
targets?: ProviderIdentifier[];
|
||||
}
|
||||
|
||||
export interface ProviderListResponse {
|
||||
[identifier: string]: ProviderInterface;
|
||||
[identifier: ProviderIdentifier]: ProviderInterface;
|
||||
}
|
||||
|
||||
/**
|
||||
* Provider fetch
|
||||
*/
|
||||
export interface ProviderFetchRequest {
|
||||
identifier: string;
|
||||
target: ProviderIdentifier;
|
||||
}
|
||||
|
||||
export interface ProviderFetchResponse extends ProviderInterface {}
|
||||
@@ -52,9 +54,9 @@ export interface ProviderFetchResponse extends ProviderInterface {}
|
||||
* Provider extant
|
||||
*/
|
||||
export interface ProviderExtantRequest {
|
||||
sources: SourceSelector;
|
||||
targets: ProviderIdentifier[];
|
||||
}
|
||||
|
||||
export interface ProviderExtantResponse {
|
||||
[identifier: string]: boolean;
|
||||
[identifier: ProviderIdentifier]: boolean;
|
||||
}
|
||||
|
||||
+17
-3
@@ -1,7 +1,13 @@
|
||||
/**
|
||||
* Service type definitions
|
||||
*/
|
||||
import type { SourceSelector, ListFilterComparisonOperator } from './common';
|
||||
import type {
|
||||
ServiceIdentifier,
|
||||
CollectionIdentifier,
|
||||
ListFilterComparisonOperator,
|
||||
} from './common';
|
||||
import type { Identity } from '@/models/identity';
|
||||
import type { Location } from '@/models/location';
|
||||
|
||||
/**
|
||||
* Service capabilities
|
||||
@@ -47,11 +53,18 @@ export interface ServiceInterface {
|
||||
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
|
||||
*/
|
||||
export interface ServiceListRequest {
|
||||
sources?: SourceSelector;
|
||||
targets?: ServiceIdentifier[] | CollectionIdentifier[];
|
||||
}
|
||||
|
||||
export interface ServiceListResponse {
|
||||
@@ -74,7 +87,7 @@ export interface ServiceFetchResponse extends ServiceInterface {}
|
||||
* Service extant
|
||||
*/
|
||||
export interface ServiceExtantRequest {
|
||||
sources: SourceSelector;
|
||||
targets: ServiceIdentifier[];
|
||||
}
|
||||
|
||||
export interface ServiceExtantResponse {
|
||||
@@ -99,6 +112,7 @@ export interface ServiceCreateResponse extends ServiceInterface {}
|
||||
export interface ServiceUpdateRequest {
|
||||
provider: string;
|
||||
identifier: string | number;
|
||||
delta?: boolean;
|
||||
data: Partial<ServiceInterface>;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
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)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,31 @@
|
||||
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/**',
|
||||
],
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,29 @@
|
||||
<?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));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<?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));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
<?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);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<?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>
|
||||
Reference in New Issue
Block a user