70 Commits

Author SHA1 Message Date
Sebastian b3c74ffe38 chore(deps): update dependency phpunit/phpunit to v12.5.33
Build Test / test (pull_request) Successful in 32s
JS Unit Tests / test (pull_request) Successful in 42s
PHP Integration Tests / Integration Tests (pull_request) Failing after 1m19s
PHP Unit Tests / test (pull_request) Successful in 1m39s
2026-07-29 03:03:30 +00:00
Sebastian 1f4b627536 refactor: migrate to scoped execution contexts
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-07-27 00:50:43 -04:00
Sebastian 0b93f1a183 Merge pull request 'chore: implement js test suites' (#41) from chore/js-test-suites into main
Reviewed-on: #41
2026-07-24 04:27:28 +00:00
Sebastian 6a9a7d31e7 chore: implement js test suites
Build Test / test (pull_request) Successful in 48s
JS Unit Tests / test (pull_request) Successful in 47s
PHP Unit Tests / test (pull_request) Successful in 1m57s
PHP Integration Tests / Integration Tests (pull_request) Successful in 2m46s
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-07-24 00:13:45 -04:00
Sebastian b5759958a8 Merge pull request 'chore(deps): update mongo docker tag to v8' (#40) from renovate/mongo-8.x into main
Reviewed-on: #40
2026-07-24 03:25:58 +00:00
Sebastian 1b7bc18b42 chore(deps): update mongo docker tag to v8
PHP Integration Tests / Integration Tests (pull_request) Successful in 1m13s
PHP Unit Tests / test (pull_request) Successful in 1m17s
2026-07-24 03:14:16 +00:00
Sebastian b6d3610e32 Merge pull request 'chore(deps): update dependency pinia to v4.0.2' (#37) from renovate/pinia-4.x-lockfile into main
Reviewed-on: #37
2026-07-24 02:36:59 +00:00
Sebastian 5891e3a070 Merge pull request 'chore: implement php test suites' (#38) from chore/php83-test-suites into main
Reviewed-on: #38
2026-07-24 02:36:51 +00:00
Sebastian aed6b1bdad fix: install module dependencies before running integration tests
PHP Integration Tests / Integration Tests (pull_request) Successful in 1m5s
PHP Unit Tests / test (pull_request) Successful in 1m27s
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-07-23 22:32:07 -04:00
Sebastian 39fc49ab07 chore: implement php test suites
PHP Integration Tests / Integration Tests (pull_request) Failing after 1m2s
PHP Unit Tests / test (pull_request) Successful in 1m5s
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-07-23 22:20:36 -04:00
Sebastian a3d67da88a chore(deps): update dependency pinia to v4.0.2 2026-07-18 03:05:37 +00:00
Sebastian a80df9c580 Merge pull request 'chore(deps): update dependency vite to v8.1.5' (#33) from renovate/vite-8.x-lockfile into main
Reviewed-on: #33
2026-07-17 23:17:02 +00:00
Sebastian f1288c4cad Merge pull request 'fix(deps): update dependency sabre/vobject to v5' (#34) from renovate/sabre-vobject-5.x into main
Reviewed-on: #34
2026-07-17 23:16:56 +00:00
Sebastian 7614265ac3 Merge pull request 'fix(deps): update dependency pinia to v4' (#35) from renovate/pinia-4.x into main
Reviewed-on: #35
2026-07-17 23:16:46 +00:00
Sebastian a6e5098ed4 Merge pull request 'chore(deps): update dependency vue to v3.5.40' (#36) from renovate/vue-monorepo into main
Reviewed-on: #36
2026-07-17 23:16:40 +00:00
Sebastian 3d1a07e0ad feat: 2 way conversion and export
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-07-17 19:13:08 -04:00
Sebastian fa5165aa38 chore(deps): update dependency vue to v3.5.40 2026-07-17 03:08:50 +00:00
Sebastian c0f5867ff3 chore(deps): update dependency vite to v8.1.5 2026-07-17 03:08:47 +00:00
Sebastian 4da25b6924 fix(deps): update dependency pinia to v4 2026-07-15 03:08:18 +00:00
Sebastian cc0bc97d9a fix(deps): update dependency sabre/vobject to v5 2026-07-10 03:08:49 +00:00
Sebastian 44ca40cc6e fix(renovate): install renovate in runner temp
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-07-09 20:12:07 -04:00
Sebastian e04a23c1f4 Merge pull request 'chore(deps): update dependency sabre/vobject to v4.6.1' (#29) from renovate/sabre-vobject-4.x-lockfile into main
Reviewed-on: #29
2026-07-09 23:48:10 +00:00
Sebastian 34c5b3046c Merge pull request 'chore(deps): update dependency vite to v8.1.3' (#30) from renovate/vite-8.x-lockfile into main
Reviewed-on: #30
2026-07-09 23:48:02 +00:00
Sebastian f0171941a7 Merge pull request 'chore(deps): update dependency @types/node to v24.13.3' (#31) from renovate/node-24.x-lockfile into main
Reviewed-on: #31
2026-07-09 23:47:56 +00:00
Sebastian df110c83db Merge pull request 'chore(deps): update dependency typescript to v7' (#32) from renovate/typescript-7.x into main
Reviewed-on: #32
2026-07-09 23:47:50 +00:00
Sebastian c4e007a017 chore(deps): update dependency typescript to v7 2026-07-09 03:02:48 +00:00
Sebastian e3c7249186 chore(deps): update dependency @types/node to v24.13.3 2026-07-09 03:02:42 +00:00
Sebastian 92deabc880 chore(deps): update dependency vite to v8.1.3 2026-07-08 03:02:55 +00:00
Sebastian 5d1faf24ea chore(deps): update dependency sabre/vobject to v4.6.1 2026-07-08 03:02:50 +00:00
Sebastian 1adb039678 fix: data serialization
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-07-07 18:35:53 -04:00
Sebastian 17602f077a recator: range construction
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-07-03 21:40:42 -04:00
Sebastian db748efffd feat: add date range filter
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-07-03 21:09:56 -04:00
Sebastian b7e12621cd feat: import
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-06-28 18:06:12 -04:00
Sebastian 0880bba063 refactor: manager backend to unified design
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-06-28 14:54:35 -04:00
Sebastian 80a8dac2fd refactor: front end code to unified design
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-06-28 12:21:09 -04:00
Sebastian 08c1de9723 Merge pull request 'chore(deps): update dependency vue to v3.5.39' (#27) from renovate/vue-monorepo into main
Reviewed-on: #27
2026-06-28 14:38:36 +00:00
Sebastian c2fe90518f Merge pull request 'chore(deps): update dependency vite to v8.1.0' (#28) from renovate/vite-8.x-lockfile into main
Reviewed-on: #28
2026-06-28 14:38:31 +00:00
Sebastian ec9f277287 chore(deps): update dependency vite to v8.1.0 2026-06-27 03:02:35 +00:00
Sebastian 2f7c5b3b67 chore(deps): update dependency vue to v3.5.39 2026-06-27 03:02:29 +00:00
Sebastian 557f42a06c recator: use unified interaface type
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-06-25 23:36:13 -04:00
Sebastian 4a4c1df269 Merge pull request 'chore(deps): update dependency @types/node to v24.13.2' (#25) from renovate/node-24.x-lockfile into main
Reviewed-on: #25
2026-06-18 23:09:47 +00:00
Sebastian b1b657fe6c Merge pull request 'chore(deps): update vue monorepo to v3.5.38' (#26) from renovate/vue-monorepo into main
Reviewed-on: #26
2026-06-18 23:09:40 +00:00
Sebastian b6065c23fa chore(deps): update vue monorepo to v3.5.38 2026-06-18 03:03:08 +00:00
Sebastian 392a92c5ca chore(deps): update dependency @types/node to v24.13.2 2026-06-18 03:03:05 +00:00
Sebastian e5b2ab441b Merge pull request 'chore(deps): update dependency @types/node to v24.13.1' (#24) from renovate/node-24.x-lockfile into main
Reviewed-on: #24
2026-06-16 17:45:01 +00:00
Sebastian 2b556a4835 Merge pull request 'chore(deps): update dependency vite to v8.0.16' (#22) from renovate/vite-8.x-lockfile into main
Reviewed-on: #22
2026-06-16 17:44:54 +00:00
Sebastian cd61016c90 chore(deps): update dependency vite to v8.0.16 2026-06-10 03:03:14 +00:00
Sebastian d42dba12c4 chore(deps): update dependency @types/node to v24.13.1 2026-06-10 03:03:05 +00:00
Sebastian c97bbf7fc9 Merge pull request 'chore(deps): update dependency @types/node to v24.13.0' (#23) from renovate/node-24.x-lockfile into main
Renovate / renovate (push) Failing after 1m53s
Reviewed-on: #23
2026-06-06 04:08:57 +00:00
Sebastian a2e162d474 chore(deps): update dependency @types/node to v24.13.0 2026-06-05 03:04:40 +00:00
Sebastian 35172ef7ba Merge pull request 'chore(deps): update dependency vite to v8.0.14' (#20) from renovate/vite-8.x-lockfile into main
Renovate / renovate (push) Failing after 1h14m57s
Reviewed-on: #20
2026-05-29 03:09:29 +00:00
Sebastian 53f34e111e Merge pull request 'chore(deps): update dependency vue to v3.5.35' (#21) from renovate/vue-monorepo into main
Reviewed-on: #21
2026-05-29 03:09:20 +00:00
Sebastian 145e0ce0d4 chore(deps): update dependency vue to v3.5.35 2026-05-29 03:05:07 +00:00
Sebastian d258c4c084 chore(deps): update dependency vite to v8.0.14 2026-05-22 03:05:39 +00:00
Sebastian 551d80a484 Merge pull request 'chore(deps): update dependency vue to v3.5.34' (#13) from renovate/vue-monorepo into main
Renovate / renovate (push) Successful in 1m24s
Reviewed-on: #13
2026-05-15 13:18:00 +00:00
Sebastian cc4ced8e92 Merge pull request 'chore(deps): update dependency typescript to v6' (#17) from renovate/typescript-6.x into main
Reviewed-on: #17
2026-05-15 13:16:49 +00:00
Sebastian 672f49458e chore(deps): update dependency typescript to v6 2026-05-15 13:15:56 +00:00
Sebastian 99d7dab9c6 chore(deps): update dependency vue to v3.5.34 2026-05-15 13:15:55 +00:00
Sebastian e31f39c5f6 Merge pull request 'chore(deps): update dependency @vue/tsconfig to ^0.9.0' (#14) from renovate/vue-tsconfig-0.x into main
Reviewed-on: #14
2026-05-15 13:14:28 +00:00
Sebastian fe8316c748 chore(deps): update dependency @vue/tsconfig to ^0.9.0 2026-05-15 13:14:02 +00:00
Sebastian 59abed19d7 Merge pull request 'chore(deps): update dependency typescript to ~5.9.0' (#15) from renovate/typescript-5.x into main
Reviewed-on: #15
2026-05-15 13:13:13 +00:00
Sebastian 741f774b55 chore(deps): update dependency typescript to ~5.9.0 2026-05-15 12:53:59 +00:00
Sebastian dbb107c98f Merge pull request 'chore(deps): update dependency vite to v8' (#18) from renovate/vite-8.x into main
Reviewed-on: #18
2026-05-15 12:52:13 +00:00
Sebastian 1a1528c15f chore(deps): update dependency vite to v8 2026-05-15 12:51:34 +00:00
Sebastian 751353b637 Merge pull request 'chore(deps): update dependency @types/node to v24' (#16) from renovate/node-24.x into main
Reviewed-on: #16
2026-05-15 03:52:03 +00:00
Sebastian aa9295d752 Merge pull request 'fix(deps): update dependency pinia to v3' (#19) from renovate/pinia-3.x into main
Reviewed-on: #19
2026-05-15 03:51:46 +00:00
Sebastian 791225e64a fix(deps): update dependency pinia to v3 2026-05-15 03:43:15 +00:00
Sebastian 6c16dcd659 chore(deps): update dependency @types/node to v24 2026-05-15 03:43:07 +00:00
Sebastian 4ddcd9cdb6 Merge pull request 'chore(deps): replace dependency @tsconfig/node22 with @tsconfig/node24' (#9) from renovate/tsconfig-node22-replacement into main
Reviewed-on: #9
2026-05-15 03:31:51 +00:00
Sebastian 30de830ace chore(deps): replace dependency @tsconfig/node22 with @tsconfig/node24 2026-05-09 03:06:06 +00:00
55 changed files with 7552 additions and 2701 deletions
+42
View File
@@ -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
+42
View File
@@ -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
+42
View File
@@ -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
+8 -2
View File
@@ -25,11 +25,17 @@ jobs:
tools: composer:v2 tools: composer:v2
- name: Install Renovate - 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 - name: Run Renovate
env: env:
RENOVATE_TOKEN: ${{ secrets.RENOVATE_TOKEN }} RENOVATE_TOKEN: ${{ secrets.RENOVATE_TOKEN }}
RENOVATE_PLATFORM: gitea RENOVATE_PLATFORM: gitea
RENOVATE_ENDPOINT: https://git.ktrix.dev/api/v1 RENOVATE_ENDPOINT: https://git.ktrix.dev/api/v1
run: renovate ${{ gitea.repository }} run: |
"${{ runner.temp }}/renovate-npm/bin/renovate" ${{ gitea.repository }}
+1 -4
View File
@@ -14,10 +14,7 @@ node_modules/
# Backend development # Backend development
/lib/vendor/ /lib/vendor/
coverage/ coverage/
phpunit.xml.cache *.cache
.phpunit.result.cache
.php-cs-fixer.cache
.phpstan.cache
.phpactor/ .phpactor/
# Editors # Editors
+15 -2
View File
@@ -10,17 +10,30 @@
"config": { "config": {
"optimize-autoloader": true, "optimize-autoloader": true,
"platform": { "platform": {
"php": "8.2" "php": "8.3"
}, },
"autoloader-suffix": "ChronoManager", "autoloader-suffix": "ChronoManager",
"vendor-dir": "lib/vendor" "vendor-dir": "lib/vendor"
}, },
"require": { "require": {
"php": ">=8.2 <=8.5" "php": ">=8.3 <=8.5",
"sabre/vobject": "^5.0"
},
"require-dev": {
"phpunit/phpunit": "^12.0"
}, },
"autoload": { "autoload": {
"psr-4": { "psr-4": {
"KTXM\\ChronoManager\\": "lib/" "KTXM\\ChronoManager\\": "lib/"
} }
},
"autoload-dev": {
"psr-4": {
"KTXT\\ChronoManager\\Tests\\": "tests/php/"
}
},
"scripts": {
"test:unit": "phpunit --configuration tests/php/phpunit.xml --testsuite \"Unit Tests\" --colors=always --testdox",
"test:integration": "phpunit --configuration tests/php/phpunit.xml --testsuite \"Integration Tests\" --colors=always --testdox"
} }
} }
Generated
+1934 -8
View File
File diff suppressed because it is too large Load Diff
+503 -271
View File
@@ -11,40 +11,67 @@ namespace KTXM\ChronoManager\Controllers;
use InvalidArgumentException; use InvalidArgumentException;
use KTXC\Http\Response\JsonResponse; use KTXC\Http\Response\JsonResponse;
use KTXC\SessionIdentity; use KTXC\Http\Response\Response;
use KTXC\SessionTenant; use KTXC\Http\Response\StreamedNdJsonResponse;
use KTXC\Http\Response\StreamedResponse;
use KTXC\Context\IdentityContextInterface;
use KTXC\Context\TenantContextInterface;
use KTXF\Controller\ControllerAbstract; 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 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\Manager;
use KTXM\ChronoManager\Stream\ExpectedTotal;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use Throwable; use Throwable;
class DefaultController extends ControllerAbstract { class DefaultController extends ControllerAbstract {
private const ERR_MISSING_PROVIDER = 'Missing parameter: provider'; private const ERR_MISSING_PROVIDER = 'Missing parameter: provider';
private const ERR_MISSING_IDENTIFIER = 'Missing parameter: identifier'; private const ERR_MISSING_IDENTIFIER = 'Missing parameter: identifier';
private const ERR_MISSING_SERVICE = 'Missing parameter: service'; 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_DATA = 'Missing parameter: data';
private const ERR_MISSING_SOURCES = 'Missing parameter: sources'; 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_OPERATION = 'Invalid operation: ';
private const ERR_INVALID_PROVIDER = 'Invalid parameter: provider must be a string'; 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_SERVICE = 'Invalid parameter: service must be a string';
private const ERR_INVALID_IDENTIFIER = 'Invalid parameter: identifier 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_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'; private const ERR_INVALID_DATA = 'Invalid parameter: data must be an array';
public function __construct( public function __construct(
private readonly SessionTenant $tenantIdentity, private readonly TenantContextInterface $tenantContext,
private readonly SessionIdentity $userIdentity, private readonly IdentityContextInterface $identityContext,
private readonly Manager $manager, private readonly Manager $manager,
private readonly ImportService $importService,
private readonly ExportService $exportService,
private readonly LoggerInterface $logger, 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'])] #[AuthenticatedRoute('/v1', name: 'chrono.manager.v1', methods: ['POST'])]
public function index( public function index(
int $version, int $version,
@@ -52,16 +79,21 @@ class DefaultController extends ControllerAbstract {
string|null $operation = null, string|null $operation = null,
array|null $data = null, array|null $data = null,
string|null $user = null string|null $user = null
): JsonResponse { ): Response {
// authorize request // authorize request
$tenantId = $this->tenantIdentity->identifier(); $tenantId = $this->tenantContext->identifier();
$userId = $this->userIdentity->identifier(); $userId = $this->identityContext->identifier();
try { try {
if ($operation !== null) { 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([ return new JsonResponse([
'version' => $version, 'version' => $version,
'transaction' => $transaction, 'transaction' => $transaction,
@@ -88,10 +120,11 @@ class DefaultController extends ControllerAbstract {
} }
} }
/** /**
* Process a single operation * 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) { return match ($operation) {
// Provider operations // Provider operations
'provider.list' => $this->providerList($tenantId, $userId, $data), 'provider.list' => $this->providerList($tenantId, $userId, $data),
@@ -105,7 +138,7 @@ class DefaultController extends ControllerAbstract {
'service.create' => $this->serviceCreate($tenantId, $userId, $data), 'service.create' => $this->serviceCreate($tenantId, $userId, $data),
'service.update' => $this->serviceUpdate($tenantId, $userId, $data), 'service.update' => $this->serviceUpdate($tenantId, $userId, $data),
'service.delete' => $this->serviceDelete($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 operations
'collection.list' => $this->collectionList($tenantId, $userId, $data), 'collection.list' => $this->collectionList($tenantId, $userId, $data),
@@ -116,16 +149,18 @@ class DefaultController extends ControllerAbstract {
'collection.delete' => $this->collectionDelete($tenantId, $userId, $data), 'collection.delete' => $this->collectionDelete($tenantId, $userId, $data),
// Entity operations // 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.fetch' => $this->entityFetch($tenantId, $userId, $data),
'entity.extant' => $this->entityExtant($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.create' => $this->entityCreate($tenantId, $userId, $data),
'entity.update' => $this->entityUpdate($tenantId, $userId, $data), 'entity.update' => $this->entityUpdate($tenantId, $userId, $data),
'entity.delete' => $this->entityDelete($tenantId, $userId, $data), 'entity.delete' => $this->entityDelete($tenantId, $userId, $data),
'entity.delta' => $this->entityDelta($tenantId, $userId, $data), 'entity.move' => $this->entityMove($tenantId, $userId, $data),
'entity.move' => throw new InvalidArgumentException('Operation not implemented: ' . $operation), 'entity.import' => $this->entityImport($tenantId, $userId, $data, $version, $transaction),
'entity.copy' => throw new InvalidArgumentException('Operation not implemented: ' . $operation), 'entity.export' => $this->entityExport($tenantId, $userId, $data),
default => throw new InvalidArgumentException(self::ERR_INVALID_OPERATION . $operation) 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 { private function providerList(string $tenantId, string $userId, array $data): mixed {
$sources = null; if (isset($data['targets'])) {
if (isset($data['sources']) && is_array($data['sources'])) { if (!is_array($data['targets'])) {
$sources = new SourceSelector(); throw new InvalidArgumentException(self::ERR_INVALID_TARGETS);
$sources->jsonDeserialize($data['sources']); }
}
foreach ($data['targets'] as $target) {
if (!is_string($target)) {
throw new InvalidArgumentException(self::ERR_INVALID_TARGETS);
}
}
}
return $this->manager->providerList($tenantId, $userId, $sources); return $this->manager->providerList($tenantId, $userId, $data['targets'] ?? []);
} }
private function providerFetch(string $tenantId, string $userId, array $data): mixed { private function providerFetch(string $tenantId, string $userId, array $data): mixed {
if (!isset($data['identifier'])) { if (!isset($data['target'])) {
throw new InvalidArgumentException(self::ERR_MISSING_IDENTIFIER); throw new InvalidArgumentException(self::ERR_MISSING_TARGET);
} }
if (!is_string($data['identifier'])) { if (!is_string($data['target'])) {
throw new InvalidArgumentException(self::ERR_INVALID_IDENTIFIER); 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 { private function providerExtant(string $tenantId, string $userId, array $data): mixed {
if (!isset($data['sources'])) { if (!isset($data['targets'])) {
throw new InvalidArgumentException(self::ERR_MISSING_SOURCES); throw new InvalidArgumentException(self::ERR_MISSING_TARGETS);
} }
if (!is_array($data['sources'])) {
throw new InvalidArgumentException(self::ERR_INVALID_SOURCES); foreach ($data['targets'] as $target) {
} if (!is_string($target)) {
$sources = new SourceSelector(); throw new InvalidArgumentException(self::ERR_INVALID_TARGETS);
$sources->jsonDeserialize($data['sources']); }
}
return $this->manager->providerExtant($tenantId, $userId, $sources); 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 { private function serviceList(string $tenantId, string $userId, array $data): mixed {
$sources = null; $targets = null;
if (isset($data['sources']) && is_array($data['sources'])) { if (isset($data['targets']) && is_array($data['targets'])) {
$sources = new SourceSelector(); $targets = ResourceIdentifiers::fromArray($data['targets']);
$sources->jsonDeserialize($data['sources']); 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 { private function serviceExtant(string $tenantId, string $userId, array $data): mixed {
if (!isset($data['sources'])) { if (!isset($data['targets'])) {
throw new InvalidArgumentException(self::ERR_MISSING_SOURCES); throw new InvalidArgumentException(self::ERR_MISSING_TARGETS);
} }
if (!is_array($data['sources'])) { if (!is_array($data['targets'])) {
throw new InvalidArgumentException(self::ERR_INVALID_SOURCES); throw new InvalidArgumentException(self::ERR_INVALID_TARGETS);
} }
$sources = new SourceSelector(); $targets = ResourceIdentifiers::fromArray($data['targets']);
$sources->jsonDeserialize($data['sources']); foreach ($targets as $target) {
if (!$target instanceof ServiceIdentifier) {
return $this->manager->serviceExtant($tenantId, $userId, $sources); throw new InvalidArgumentException('Invalid parameter: targets must contain provider:service identifiers');
}
}
return $this->manager->serviceExtant($tenantId, $userId, $targets);
} }
private function serviceCreate(string $tenantId, string $userId, array $data): mixed { private function serviceCreate(string $tenantId, string $userId, array $data): mixed {
@@ -258,13 +309,17 @@ class DefaultController extends ControllerAbstract {
if (!is_array($data['data'])) { if (!is_array($data['data'])) {
throw new InvalidArgumentException(self::ERR_INVALID_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( return $this->manager->serviceUpdate(
$tenantId, $tenantId,
$userId, $userId,
$data['provider'], $data['provider'],
$data['identifier'], $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 ==================== // ==================== Collection Operations ====================
private function collectionList(string $tenantId, string $userId, array $data): mixed { private function collectionList(string $tenantId, string $userId, array $data): mixed {
$sources = null; $sources = null;
if (isset($data['sources']) && is_array($data['sources'])) { if (isset($data['sources']) && is_array($data['sources'])) {
$sources = new SourceSelector(); $sources = ResourceIdentifiers::fromArray($data['sources']);
$sources->jsonDeserialize($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; $filter = $data['filter'] ?? null;
@@ -328,47 +364,45 @@ class DefaultController extends ControllerAbstract {
return $this->manager->collectionList($tenantId, $userId, $sources, $filter, $sort); 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 { private function collectionFetch(string $tenantId, string $userId, array $data): mixed {
if (!isset($data['provider'])) { if (!isset($data['targets'])) {
throw new InvalidArgumentException(self::ERR_MISSING_PROVIDER); throw new InvalidArgumentException(self::ERR_MISSING_TARGETS);
} }
if (!is_string($data['provider'])) { if (!is_array($data['targets'])) {
throw new InvalidArgumentException(self::ERR_INVALID_PROVIDER); throw new InvalidArgumentException(self::ERR_INVALID_TARGETS);
} }
if (!isset($data['service'])) {
throw new InvalidArgumentException(self::ERR_MISSING_SERVICE); $targetIdentifiers = ResourceIdentifiers::fromArray($data['targets']);
foreach ($targetIdentifiers as $targetIdentifier) {
if (!$targetIdentifier instanceof CollectionIdentifier) {
throw new InvalidArgumentException('Invalid parameter: target must be provider:service:collection');
}
} }
if (!is_string($data['service'])) {
throw new InvalidArgumentException(self::ERR_INVALID_SERVICE); $list = $this->manager->collectionFetch(
}
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);
}
return $this->manager->collectionFetch(
$tenantId, $tenantId,
$userId, $userId,
$data['provider'], $targetIdentifier
$data['service'],
$data['identifier']
); );
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 { private function collectionCreate(string $tenantId, string $userId, array $data): mixed {
@@ -384,8 +418,8 @@ class DefaultController extends ControllerAbstract {
if (!is_string($data['service'])) { if (!is_string($data['service'])) {
throw new InvalidArgumentException(self::ERR_INVALID_SERVICE); throw new InvalidArgumentException(self::ERR_INVALID_SERVICE);
} }
if (isset($data['collection']) && !is_string($data['collection']) && !is_int($data['collection'])) { if (isset($data['target']) && !is_string($data['target']) && !is_int($data['target'])) {
throw new InvalidArgumentException(self::ERR_INVALID_COLLECTION); throw new InvalidArgumentException(self::ERR_INVALID_TARGET);
} }
if (!isset($data['properties'])) { if (!isset($data['properties'])) {
throw new InvalidArgumentException(self::ERR_MISSING_DATA); throw new InvalidArgumentException(self::ERR_MISSING_DATA);
@@ -393,35 +427,30 @@ class DefaultController extends ControllerAbstract {
if (!is_array($data['properties'])) { if (!is_array($data['properties'])) {
throw new InvalidArgumentException(self::ERR_INVALID_DATA); 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( return $this->manager->collectionCreate(
$tenantId, $tenantId,
$userId, $userId,
$data['provider'], $data['provider'],
$data['service'], $data['service'],
$data['collection'] ?? null, $targetIdentifier ?? null,
$data['properties'] $data['properties']
); );
} }
private function collectionUpdate(string $tenantId, string $userId, array $data): mixed { private function collectionUpdate(string $tenantId, string $userId, array $data): mixed {
if (!isset($data['provider'])) { if (!isset($data['target'])) {
throw new InvalidArgumentException(self::ERR_MISSING_PROVIDER); throw new InvalidArgumentException(self::ERR_MISSING_TARGET);
} }
if (!is_string($data['provider'])) { if (!is_string($data['target'])) {
throw new InvalidArgumentException(self::ERR_INVALID_PROVIDER); throw new InvalidArgumentException(self::ERR_INVALID_TARGET);
}
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 (!isset($data['properties'])) { if (!isset($data['properties'])) {
throw new InvalidArgumentException(self::ERR_MISSING_DATA); throw new InvalidArgumentException(self::ERR_MISSING_DATA);
@@ -429,182 +458,376 @@ class DefaultController extends ControllerAbstract {
if (!is_array($data['properties'])) { if (!is_array($data['properties'])) {
throw new InvalidArgumentException(self::ERR_INVALID_DATA); 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( return $this->manager->collectionUpdate(
$tenantId, $tenantId,
$userId, $userId,
$data['provider'], $targetIdentifier,
$data['service'],
$data['identifier'],
$data['properties'] $data['properties']
); );
} }
private function collectionDelete(string $tenantId, string $userId, array $data): mixed { private function collectionDelete(string $tenantId, string $userId, array $data): mixed {
if (!isset($data['provider'])) { if (!isset($data['target'])) {
throw new InvalidArgumentException(self::ERR_MISSING_PROVIDER); throw new InvalidArgumentException(self::ERR_MISSING_TARGET);
} }
if (!is_string($data['provider'])) { if (!is_string($data['target'])) {
throw new InvalidArgumentException(self::ERR_INVALID_PROVIDER); throw new InvalidArgumentException(self::ERR_INVALID_TARGET);
} }
if (!isset($data['service'])) {
throw new InvalidArgumentException(self::ERR_MISSING_SERVICE); $targetIdentifier = ResourceIdentifier::fromString($data['target']);
} if (!$targetIdentifier instanceof CollectionIdentifier) {
if (!is_string($data['service'])) { throw new InvalidArgumentException('Invalid parameter: target must be provider:service:collection');
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);
} }
return $this->manager->collectionDelete( $result = $this->manager->collectionDelete($tenantId, $userId, $targetIdentifier, $data['options'] ?? [] );
$tenantId,
$userId, if (is_bool($result)) {
$data['provider'], return [
$data['service'], 'disposition' => 'deleted'
$data['identifier'], ];
$data['options'] ?? [] }
);
if ($result instanceof JsonSerializable) {
return [
'disposition' => 'moved',
'mutation' => $result
];
}
return $result;
} }
// ==================== Entity Operations ==================== // ==================== Entity Operations ====================
private function entityList(string $tenantId, string $userId, array $data): mixed { private function entityListBulk(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(); if (isset($data['sources'])) {
$sources->jsonDeserialize($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; $filter = $data['filter'] ?? null;
$sort = $data['sort'] ?? null; $sort = $data['sort'] ?? null;
$range = $data['range'] ?? 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 { private function entityFetch(string $tenantId, string $userId, array $data): mixed {
if (!isset($data['provider'])) { if (!isset($data['targets'])) {
throw new InvalidArgumentException(self::ERR_MISSING_PROVIDER); throw new InvalidArgumentException(self::ERR_MISSING_TARGETS);
} }
if (!is_string($data['provider'])) { if (!is_array($data['targets'])) {
throw new InvalidArgumentException(self::ERR_INVALID_PROVIDER); throw new InvalidArgumentException(self::ERR_INVALID_TARGETS);
} }
if (!isset($data['service'])) {
throw new InvalidArgumentException(self::ERR_MISSING_SERVICE); $targets = ResourceIdentifiers::fromArray($data['targets']);
} foreach ($targets as $target) {
if (!is_string($data['service'])) { if (!$target instanceof EntityIdentifier) {
throw new InvalidArgumentException(self::ERR_INVALID_SERVICE); throw new InvalidArgumentException('Invalid parameter: targets must contain provider:service:collection:entity identifiers');
} }
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);
} }
return $this->manager->entityFetch( return $this->manager->entityFetchBulk(
$tenantId, $tenantId,
$userId, $userId,
$data['provider'], ...$targets->all()
$data['service'],
$data['collection'],
$data['identifiers']
); );
} }
private function entityExtant(string $tenantId, string $userId, array $data): mixed { private function entityExtant(string $tenantId, string $userId, array $data): mixed {
if (!isset($data['sources'])) { if (!isset($data['targets'])) {
throw new InvalidArgumentException(self::ERR_MISSING_SOURCES); throw new InvalidArgumentException(self::ERR_MISSING_TARGETS);
} }
if (!is_array($data['sources'])) { if (!is_array($data['targets'])) {
throw new InvalidArgumentException(self::ERR_INVALID_SOURCES); throw new InvalidArgumentException(self::ERR_INVALID_TARGETS);
} }
$sources = new SourceSelector(); $targets = ResourceIdentifiers::fromArray($data['targets']);
$sources->jsonDeserialize($data['sources']); foreach ($targets as $target) {
if (!$target instanceof CollectionIdentifier && !$target instanceof EntityIdentifier) {
return $this->manager->entityExtant($tenantId, $userId, $sources); throw new InvalidArgumentException('Invalid parameter: targets must contain provider:service:collection or provider:service:collection:entity identifiers');
}
}
return $this->manager->entityExtant($tenantId, $userId, $targets);
} }
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']);
}
private function entityDelta(string $tenantId, string $userId, array $data): mixed { 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'])) { if (!isset($data['sources'])) {
throw new InvalidArgumentException(self::ERR_MISSING_SOURCES); throw new InvalidArgumentException(self::ERR_MISSING_SOURCES);
} }
@@ -612,10 +835,19 @@ class DefaultController extends ControllerAbstract {
throw new InvalidArgumentException(self::ERR_INVALID_SOURCES); throw new InvalidArgumentException(self::ERR_INVALID_SOURCES);
} }
$sources = new SourceSelector(); $target = ResourceIdentifier::fromString($data['target']);
$sources->jsonDeserialize($data['sources']); 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());
} }
} }
+310
View File
@@ -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)); }
}
+387
View File
@@ -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'));
}
}
+93
View File
@@ -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;
}
}
}
+25
View File
@@ -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];
}
}
+17
View File
@@ -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';
}
+15
View File
@@ -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 {
}
+37
View File
@@ -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,
];
}
}
+66
View File
@@ -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;
}
}
+75
View File
@@ -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;
}
}
}
}
}
+625 -463
View File
File diff suppressed because it is too large Load Diff
+9
View File
@@ -14,6 +14,15 @@ class Module extends ModuleInstanceAbstract implements ModuleBrowserInterface
public function __construct() public function __construct()
{ } { }
public function boot(): void
{
// Load module-local vendored dependencies used by iCalendar import.
$vendorAutoload = __DIR__ . '/vendor/autoload.php';
if (file_exists($vendorAutoload)) {
require_once $vendorAutoload;
}
}
public function handle(): string public function handle(): string
{ {
return 'chrono_manager'; return 'chrono_manager';
+20
View File
@@ -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;
}
+1738 -785
View File
File diff suppressed because it is too large Load Diff
+14 -7
View File
@@ -7,17 +7,24 @@
"build": "vite build --mode production --config vite.config.ts", "build": "vite build --mode production --config vite.config.ts",
"dev": "vite build --mode development --config vite.config.ts", "dev": "vite build --mode development --config vite.config.ts",
"watch": "vite build --mode development --watch --config vite.config.ts", "watch": "vite build --mode development --watch --config vite.config.ts",
"typecheck": "vue-tsc --noEmit" "typecheck": "vue-tsc --noEmit",
"test": "vitest run --config tests/js/vitest.config.ts",
"test:unit": "vitest run --config tests/js/vitest.config.ts",
"test:watch": "vitest watch --config tests/js/vitest.config.ts",
"test:coverage": "vitest run --coverage --config tests/js/vitest.config.ts"
}, },
"dependencies": { "dependencies": {
"pinia": "^2.3.0", "pinia": "^4.0.0",
"vue": "^3.5.13" "vue": "^3.5.13"
}, },
"devDependencies": { "devDependencies": {
"@tsconfig/node22": "^22.0.0", "@tsconfig/node24": "^24.0.0",
"@types/node": "^22.10.1", "@types/node": "^24.0.0",
"@vue/tsconfig": "^0.8.0", "@vue/tsconfig": "^0.9.0",
"typescript": "~5.7.2", "typescript": "~6.0.0",
"vite": "^6.0.3" "vite": "^8.0.0",
"@vitest/coverage-v8": "^4.1.6",
"jsdom": "^29.1.1",
"vitest": "^4.1.6"
} }
} }
+27
View File
@@ -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));
}
+54 -63
View File
@@ -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() { constructor() {
this._data = { this._data = {
'@type': 'people:collection',
version: 1,
provider: '', provider: '',
service: '', service: '' as ServiceIdentifier,
collection: null, collection: null as CollectionIdentifier | null,
identifier: '', identifier: '' as CollectionIdentifier,
signature: null, properties: new CollectionPropertiesObject().toJson(),
created: null,
modified: null,
properties: new CollectionPropertiesObject(),
}; };
} }
fromJson(data: CollectionInterface): CollectionObject { fromJson(data: CollectionInterface): CollectionObject {
this._data = data; this._data = clonePlain(data);
if (data.properties) { this._properties = undefined;
this._data.properties = new CollectionPropertiesObject().fromJson(data.properties as CollectionPropertiesInterface);
}
return this; return this;
} }
toJson(): CollectionInterface { toJson(): CollectionInterface {
const json = { ...this._data }; const json = this._properties
if (this._data.properties instanceof CollectionPropertiesObject) { ? { ...this._data, properties: this._properties.toJson() }
json.properties = this._data.properties.toJson(); : this._data;
} return clonePlain(json);
return json;
} }
clone(): CollectionObject { clone(): CollectionObject {
const cloned = new CollectionObject(); return new CollectionObject().fromJson(this.toJson());
cloned._data = { ...this._data };
cloned._data.properties = this.properties.clone();
return cloned;
} }
/** Immutable Properties */ /** Immutable Properties */
@@ -50,16 +55,16 @@ export class CollectionObject implements CollectionInterface {
return this._data.provider; return this._data.provider;
} }
get service(): string | number { get service(): ServiceIdentifier {
return this._data.service; return this._data.service as ServiceIdentifier;
} }
get collection(): string | number | null { get collection(): CollectionIdentifier | null {
return this._data.collection; return this._data.collection as CollectionIdentifier | null;
} }
get identifier(): string | number { get identifier(): CollectionIdentifier {
return this._data.identifier; return this._data.identifier as CollectionIdentifier;
} }
get signature(): string | null | undefined { get signature(): string | null | undefined {
@@ -74,37 +79,33 @@ export class CollectionObject implements CollectionInterface {
return this._data.modified; return this._data.modified;
} }
/** Mutable Properties */
get properties(): CollectionPropertiesObject { get properties(): CollectionPropertiesObject {
if (this._data.properties instanceof CollectionPropertiesObject) { if (this._properties) {
return this._data.properties; return this._properties;
}
else if (this._data.properties) {
const properties = new CollectionPropertiesObject().fromJson(this._data.properties as CollectionPropertiesInterface);
this._properties = properties;
return properties;
} }
if (this._data.properties) {
const hydrated = new CollectionPropertiesObject().fromJson(this._data.properties as CollectionPropertiesInterface);
this._data.properties = hydrated;
return hydrated;
}
return new CollectionPropertiesObject(); return new CollectionPropertiesObject();
} }
set properties(value: CollectionPropertiesObject) { set properties(value: CollectionPropertiesObject) {
if (value instanceof CollectionPropertiesObject) { this._properties = value;
this._data.properties = value as any;
} else {
this._data.properties = value;
}
} }
} }
export class CollectionPropertiesObject implements CollectionPropertiesInterface { export class CollectionPropertiesObject implements CollectionPropertiesModelInterface {
_data!: CollectionPropertiesInterface; private _data: CollectionPropertiesInterface;
constructor() { constructor() {
this._data = { this._data = {
'@type': 'chrono:collection', '@type': 'chrono:calendar',
version: 1,
content: [], content: [],
label: '', label: '',
description: null, description: null,
@@ -115,32 +116,22 @@ export class CollectionPropertiesObject implements CollectionPropertiesInterface
} }
fromJson(data: CollectionPropertiesInterface): CollectionPropertiesObject { fromJson(data: CollectionPropertiesInterface): CollectionPropertiesObject {
this._data = data; this._data = clonePlain(data);
return this; return this;
} }
toJson(): CollectionPropertiesInterface { toJson(): CollectionPropertiesInterface {
return this._data; return clonePlain(this._data);
} }
clone(): CollectionPropertiesObject { clone(): CollectionPropertiesObject {
const cloned = new CollectionPropertiesObject(); return new CollectionPropertiesObject().fromJson(this.toJson());
cloned._data = { ...this._data };
return cloned;
} }
/** Immutable Properties */ /** Immutable Properties */
get '@type'(): string {
return this._data['@type'];
}
get version(): number {
return this._data.version;
}
get content(): CollectionContentTypes[] { get content(): CollectionContentTypes[] {
return this._data.content || []; return this._data.content ?? [];
} }
/** Mutable Properties */ /** Mutable Properties */
@@ -185,4 +176,4 @@ export class CollectionPropertiesObject implements CollectionPropertiesInterface
this._data.color = value; this._data.color = value;
} }
} }
+51 -55
View File
@@ -1,106 +1,102 @@
/** /**
* Class model for Entity Interface * Class model for Entity Interface
*/ */
import type { EntityInterface } from "@/types/entity";
import type { EventInterface } from "@/types/event";
import type { TaskInterface } from "@/types/task";
import type { JournalInterface } from "@/types/journal";
import { EventObject } from "./event";
import { TaskObject } from "./task";
import { JournalObject } from "./journal";
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() { constructor() {
this._data = { this._data = {
'@type': 'chrono:entity',
version: 1,
provider: '', provider: '',
service: '', service: '',
collection: '', collection: '' as CollectionIdentifier,
identifier: '', identifier: '' as EntityIdentifier,
signature: null, signature: null,
created: null, created: null,
modified: null, modified: null,
properties: new EventObject(), properties: new EventObject().toJson(),
}; };
} }
fromJson(data: EntityInterface): EntityObject { fromJson(data: EntityInterface): EntityObject {
this._data = data this._data = clonePlain(data);
if (data.properties) { this._properties = undefined;
const type = data.properties.type
if (type === 'task') {
this._data.properties = new TaskObject().fromJson(data.properties as TaskInterface);
} else if (type === 'journal') {
this._data.properties = new JournalObject().fromJson(data.properties as JournalInterface);
} else {
this._data.properties = new EventObject().fromJson(data.properties as EventInterface);
}
}
return this; return this;
} }
toJson(): EntityInterface { toJson(): EntityInterface {
const json = { ...this._data } const json = this._properties
if (this._data.properties instanceof EventObject || ? { ...this._data, properties: this._properties.toJson() }
this._data.properties instanceof TaskObject || : this._data;
this._data.properties instanceof JournalObject) { return clonePlain(json);
json.properties = this._data.properties.toJson();
}
return json as EntityInterface
} }
clone(): EntityObject { clone(): EntityObject {
const cloned = new EntityObject() return new EntityObject().fromJson(this.toJson());
cloned._data = { ...this._data }
return cloned
} }
/** Immutable Properties */ /** Metadata Properties */
get provider(): string { get provider(): string {
return this._data.provider return this._data.provider;
} }
get service(): string { get service(): string {
return this._data.service return this._data.service;
} }
get collection(): string | number { get collection(): CollectionIdentifier {
return this._data.collection return this._data.collection;
} }
get identifier(): string | number { get identifier(): EntityIdentifier {
return this._data.identifier return this._data.identifier;
} }
get signature(): string | null { get signature(): string | null {
return this._data.signature return this._data.signature;
} }
get created(): string | null { get created(): string | null {
return this._data.created return this._data.created;
} }
get modified(): string | null { get modified(): string | null {
return this._data.modified return this._data.modified;
} }
get properties(): EventObject | TaskObject | JournalObject { /** Entity Properties (individual | organization | group) */
if (this._data.properties instanceof EventObject ||
this._data.properties instanceof TaskObject || get properties(): EntityPropertiesObject {
this._data.properties instanceof JournalObject) { if (this._properties) return this._properties;
return this._data.properties
const raw = this._data.properties;
if (raw.type === 'task') {
this._properties = new TaskObject().fromJson(raw as TaskInterface);
} else if (raw.type === 'journal') {
this._properties = new JournalObject().fromJson(raw as JournalInterface);
} else {
this._properties = new EventObject().fromJson(raw as EventInterface);
} }
return this._properties;
const defaultProperties = new EventObject();
this._data.properties = defaultProperties;
return defaultProperties
} }
set properties(value: EventObject | TaskObject | JournalObject) { set properties(value: EntityPropertiesObject) {
this._data.properties = value this._properties = value;
} }
} }
+8 -1
View File
@@ -114,8 +114,15 @@ export class EventObject implements EventInterface {
} }
toJson(): EventInterface { toJson(): EventInterface {
const data = {
...this._data,
pattern: this._data.pattern instanceof EventOccurrenceObject
? this._data.pattern.toJson()
: this._data.pattern,
};
// Return a deep copy to avoid external modifications // Return a deep copy to avoid external modifications
return JSON.parse(JSON.stringify(this._data)); return JSON.parse(JSON.stringify(data));
} }
clone(): EventObject { clone(): EventObject {
+103 -175
View File
@@ -1,196 +1,124 @@
/** /**
* Identity implementation classes for Mail Manager services * Identity models for Chrono Manager services
*/ */
import type { import type {
ServiceIdentity, ServiceIdentity,
ServiceIdentityNone, ServiceIdentityBasic,
ServiceIdentityBasic, ServiceIdentityCertificate,
ServiceIdentityToken, ServiceIdentityNone,
ServiceIdentityOAuth, ServiceIdentityOAuth,
ServiceIdentityCertificate ServiceIdentityToken
} from '@/types/service'; } from '@/types/service';
import { clonePlain } from './clone-plain';
import { MutationProxy } from './mutation-proxy';
/** export abstract class Identity<T extends ServiceIdentity = ServiceIdentity> {
* Base Identity class protected _original: T;
*/ protected _mutated: Partial<T>;
export abstract class Identity { protected _mutationProxy: MutationProxy<T>;
abstract toJson(): ServiceIdentity; protected _data: T;
static fromJson(data: ServiceIdentity): Identity { protected constructor(initial: T) {
switch (data.type) { this._original = clonePlain(initial);
case 'NA': this._mutated = {};
return IdentityNone.fromJson(data); this._mutationProxy = new MutationProxy<T>(() => this._original, () => this._mutated);
case 'BA': this._data = this._mutationProxy.create();
return IdentityBasic.fromJson(data); }
case 'TA':
return IdentityToken.fromJson(data); protected load(data: T): this {
case 'OA': this._original = clonePlain(data);
return IdentityOAuth.fromJson(data); this._mutated = {};
case 'CC': this._data = this._mutationProxy.create();
return IdentityCertificate.fromJson(data); return this;
default: }
throw new Error(`Unknown identity type: ${(data as any).type}`);
toJSON(): ServiceIdentity { return this.toJson(); }
toJson(): T;
toJson(delta: true): Partial<T>;
toJson(delta?: boolean): T | Partial<T> {
return delta
? clonePlain(this._mutated)
: { ...clonePlain(this._original), ...clonePlain(this._mutated) };
}
abstract clone(): Identity;
mutated(): boolean { return Reflect.ownKeys(this._mutated).length > 0; }
static fromJson(data: ServiceIdentity): Identity {
switch (data.type) {
case 'NA': return IdentityNone.fromJson(data);
case 'BA': return IdentityBasic.fromJson(data);
case 'TA': return IdentityToken.fromJson(data);
case 'OA': return IdentityOAuth.fromJson(data);
case 'CC': return IdentityCertificate.fromJson(data);
default: throw new Error(`Unknown identity type: ${(data as any).type}`);
}
} }
}
} }
/** export class IdentityNone extends Identity<ServiceIdentityNone> {
* No authentication constructor() { super({ type: 'NA' }); }
*/ static fromJson(_data: ServiceIdentityNone): IdentityNone { return new IdentityNone(); }
export class IdentityNone extends Identity { clone(): IdentityNone { return IdentityNone.fromJson(this.toJson()); }
readonly type = 'NA' as const; get type(): 'NA' { return this._data.type; }
static fromJson(_data: ServiceIdentityNone): IdentityNone {
return new IdentityNone();
}
toJson(): ServiceIdentityNone {
return {
type: this.type
};
}
} }
/** export class IdentityBasic extends Identity<ServiceIdentityBasic> {
* Basic authentication (username/password) constructor(identity: string = '', secret: string = '') { super({ type: 'BA', identity, secret }); }
*/ static fromJson(data: ServiceIdentityBasic): IdentityBasic { return new IdentityBasic().load(data); }
export class IdentityBasic extends Identity { clone(): IdentityBasic { return IdentityBasic.fromJson(this.toJson()); }
readonly type = 'BA' as const; get type(): 'BA' { return this._data.type; }
identity: string; get identity(): string { return this._data.identity; }
secret: string; set identity(value: string) { this._data.identity = value; }
get secret(): string { return this._data.secret; }
constructor(identity: string = '', secret: string = '') { set secret(value: string) { this._data.secret = value; }
super();
this.identity = identity;
this.secret = secret;
}
static fromJson(data: ServiceIdentityBasic): IdentityBasic {
return new IdentityBasic(data.identity, data.secret);
}
toJson(): ServiceIdentityBasic {
return {
type: this.type,
identity: this.identity,
secret: this.secret
};
}
} }
/** export class IdentityToken extends Identity<ServiceIdentityToken> {
* Token authentication (API key, static token) constructor(token: string = '') { super({ type: 'TA', token }); }
*/ static fromJson(data: ServiceIdentityToken): IdentityToken { return new IdentityToken().load(data); }
export class IdentityToken extends Identity { clone(): IdentityToken { return IdentityToken.fromJson(this.toJson()); }
readonly type = 'TA' as const; get type(): 'TA' { return this._data.type; }
token: string; get token(): string { return this._data.token; }
set token(value: string) { this._data.token = value; }
constructor(token: string = '') {
super();
this.token = token;
}
static fromJson(data: ServiceIdentityToken): IdentityToken {
return new IdentityToken(data.token);
}
toJson(): ServiceIdentityToken {
return {
type: this.type,
token: this.token
};
}
} }
/** export class IdentityOAuth extends Identity<ServiceIdentityOAuth> {
* OAuth authentication constructor(accessToken: string = '', accessScope?: string[], accessExpiry?: number, refreshToken?: string, refreshLocation?: string) {
*/ super({ type: 'OA', accessToken, accessScope, accessExpiry, refreshToken, refreshLocation });
export class IdentityOAuth extends Identity { }
readonly type = 'OA' as const;
accessToken: string;
accessScope?: string[];
accessExpiry?: number;
refreshToken?: string;
refreshLocation?: string;
constructor( static fromJson(data: ServiceIdentityOAuth): IdentityOAuth { return new IdentityOAuth().load(data); }
accessToken: string = '', clone(): IdentityOAuth { return IdentityOAuth.fromJson(this.toJson()); }
accessScope?: string[], isExpired(): boolean { return this.accessExpiry ? Date.now() / 1000 >= this.accessExpiry : false; }
accessExpiry?: number, expiresIn(): number { return this.accessExpiry ? Math.max(0, this.accessExpiry - Date.now() / 1000) : Infinity; }
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 { get type(): 'OA' { return this._data.type; }
return new IdentityOAuth( get accessToken(): string { return this._data.accessToken; }
data.accessToken, set accessToken(value: string) { this._data.accessToken = value; }
data.accessScope, get accessScope(): string[] | undefined { return this._data.accessScope ? [...this._data.accessScope] : undefined; }
data.accessExpiry, set accessScope(value: string[] | undefined) { this._data.accessScope = value ? [...value] : undefined; }
data.refreshToken, get accessExpiry(): number | undefined { return this._data.accessExpiry; }
data.refreshLocation 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; }
toJson(): ServiceIdentityOAuth { set refreshLocation(value: string | undefined) { this._data.refreshLocation = value; }
return {
type: this.type,
accessToken: this.accessToken,
...(this.accessScope && { accessScope: this.accessScope }),
...(this.accessExpiry && { accessExpiry: this.accessExpiry }),
...(this.refreshToken && { refreshToken: this.refreshToken }),
...(this.refreshLocation && { refreshLocation: this.refreshLocation })
};
}
isExpired(): boolean {
if (!this.accessExpiry) return false;
return Date.now() / 1000 >= this.accessExpiry;
}
expiresIn(): number {
if (!this.accessExpiry) return Infinity;
return Math.max(0, this.accessExpiry - Date.now() / 1000);
}
} }
/** export class IdentityCertificate extends Identity<ServiceIdentityCertificate> {
* Client certificate authentication (mTLS) constructor(certificate: string = '', privateKey: string = '', passphrase?: string) {
*/ super({ type: 'CC', certificate, privateKey, passphrase });
export class IdentityCertificate extends Identity { }
readonly type = 'CC' as const;
certificate: string;
privateKey: string;
passphrase?: string;
constructor(certificate: string = '', privateKey: string = '', passphrase?: string) { static fromJson(data: ServiceIdentityCertificate): IdentityCertificate { return new IdentityCertificate().load(data); }
super(); clone(): IdentityCertificate { return IdentityCertificate.fromJson(this.toJson()); }
this.certificate = certificate; get type(): 'CC' { return this._data.type; }
this.privateKey = privateKey; get certificate(): string { return this._data.certificate; }
this.passphrase = passphrase; set certificate(value: string) { this._data.certificate = value; }
} get privateKey(): string { return this._data.privateKey; }
set privateKey(value: string) { this._data.privateKey = value; }
static fromJson(data: ServiceIdentityCertificate): IdentityCertificate { get passphrase(): string | undefined { return this._data.passphrase; }
return new IdentityCertificate( set passphrase(value: string | undefined) { this._data.passphrase = value; }
data.certificate,
data.privateKey,
data.passphrase
);
}
toJson(): ServiceIdentityCertificate {
return {
type: this.type,
certificate: this.certificate,
privateKey: this.privateKey,
...(this.passphrase && { passphrase: this.passphrase })
};
}
} }
+2 -3
View File
@@ -1,6 +1,6 @@
export { ProviderObject } from './provider'; export { ProviderObject } from './provider';
export { ServiceObject } from './service'; export { ServiceObject } from './service';
export { CollectionObject } from './collection'; export { CollectionObject, CollectionPropertiesObject } from './collection';
export { EntityObject } from './entity'; export { EntityObject } from './entity';
export { EventObject } from './event'; export { EventObject } from './event';
export { TaskObject } from './task'; export { TaskObject } from './task';
@@ -16,7 +16,6 @@ export {
export { export {
Location, Location,
LocationUri, LocationUri,
LocationSocketSole,
LocationSocketSplit,
LocationFile LocationFile
} from './location'; } from './location';
export { MutationProxy } from './mutation-proxy';
+78 -227
View File
@@ -1,240 +1,91 @@
/** /**
* Location implementation classes for Mail Manager services * Location models for Chrono Manager services
*/ */
import type { import type { ServiceLocation, ServiceLocationFile, ServiceLocationUri } from '@/types/service';
ServiceLocation, import { clonePlain } from './clone-plain';
ServiceLocationUri, import { MutationProxy } from './mutation-proxy';
ServiceLocationSocketSole,
ServiceLocationSocketSplit,
ServiceLocationFile
} from '@/types/service';
/** export abstract class Location<T extends ServiceLocation = ServiceLocation> {
* Base Location class protected _original: T;
*/ protected _mutated: Partial<T>;
export abstract class Location { protected _mutationProxy: MutationProxy<T>;
abstract toJson(): ServiceLocation; protected _data: T;
static fromJson(data: ServiceLocation): Location { protected constructor(initial: T) {
switch (data.type) { this._original = clonePlain(initial);
case 'URI': this._mutated = {};
return LocationUri.fromJson(data); this._mutationProxy = new MutationProxy<T>(() => this._original, () => this._mutated);
case 'SOCKET_SOLE': this._data = this._mutationProxy.create();
return LocationSocketSole.fromJson(data); }
case 'SOCKET_SPLIT':
return LocationSocketSplit.fromJson(data); protected load(data: T): this {
case 'FILE': this._original = clonePlain(data);
return LocationFile.fromJson(data); this._mutated = {};
default: this._data = this._mutationProxy.create();
throw new Error(`Unknown location type: ${(data as any).type}`); 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 'FILE': return LocationFile.fromJson(data);
default: throw new Error(`Unknown location type: ${(data as any).type}`);
}
} }
}
} }
/** export class LocationUri extends Location<ServiceLocationUri> {
* URI-based service location for API and web services constructor(
* Used by: JMAP, Gmail API, etc. scheme: string = 'https',
*/ host: string = '',
export class LocationUri extends Location { port: number = 443,
readonly type = 'URI' as const; path?: string,
scheme: string; verifyPeer: boolean = true,
host: string; verifyHost: boolean = true
port: number; ) {
path?: string; super({ type: 'URI', scheme, host, port, ...(path !== undefined && { path }), verifyPeer, verifyHost });
verifyPeer: boolean; }
verifyHost: boolean;
constructor( static fromJson(data: ServiceLocationUri): LocationUri { return new LocationUri().load(data); }
scheme: string = 'https', clone(): LocationUri { return LocationUri.fromJson(this.toJson()); }
host: string = '', getUrl(): string { return `${this.scheme}://${this.host}:${this.port}${this.path || ''}`; }
port: number = 443,
path?: string,
verifyPeer: boolean = true,
verifyHost: boolean = true
) {
super();
this.scheme = scheme;
this.host = host;
this.port = port;
this.path = path;
this.verifyPeer = verifyPeer;
this.verifyHost = verifyHost;
}
static fromJson(data: ServiceLocationUri): LocationUri { get type(): 'URI' { return this._data.type; }
return new LocationUri( get scheme(): string { return this._data.scheme; }
data.scheme, set scheme(value: string) { this._data.scheme = value; }
data.host, get host(): string { return this._data.host; }
data.port, set host(value: string) { this._data.host = value; }
data.path, get port(): number { return this._data.port; }
data.verifyPeer ?? true, set port(value: number) { this._data.port = value; }
data.verifyHost ?? true 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; }
toJson(): ServiceLocationUri { get verifyHost(): boolean { return this._data.verifyHost ?? true; }
return { set verifyHost(value: boolean) { this._data.verifyHost = value; }
type: this.type,
scheme: this.scheme,
host: this.host,
port: this.port,
...(this.path && { path: this.path }),
...(this.verifyPeer !== undefined && { verifyPeer: this.verifyPeer }),
...(this.verifyHost !== undefined && { verifyHost: this.verifyHost })
};
}
getUrl(): string {
const path = this.path || '';
return `${this.scheme}://${this.host}:${this.port}${path}`;
}
} }
/** export class LocationFile extends Location<ServiceLocationFile> {
* Single socket-based service location constructor(path: string = '') { super({ type: 'FILE', path }); }
* Used by: services using a single host/port combination static fromJson(data: ServiceLocationFile): LocationFile { return new LocationFile().load(data); }
*/ clone(): LocationFile { return LocationFile.fromJson(this.toJson()); }
export class LocationSocketSole extends Location {
readonly type = 'SOCKET_SOLE' as const;
host: string;
port: number;
encryption: 'none' | 'ssl' | 'tls' | 'starttls';
verifyPeer: boolean;
verifyHost: boolean;
constructor( get type(): 'FILE' { return this._data.type; }
host: string = '', get path(): string { return this._data.path; }
port: number = 993, set path(value: string) { this._data.path = value; }
encryption: 'none' | 'ssl' | 'tls' | 'starttls' = 'ssl',
verifyPeer: boolean = true,
verifyHost: boolean = true
) {
super();
this.host = host;
this.port = port;
this.encryption = encryption;
this.verifyPeer = verifyPeer;
this.verifyHost = verifyHost;
}
static fromJson(data: ServiceLocationSocketSole): LocationSocketSole {
return new LocationSocketSole(
data.host,
data.port,
data.encryption,
data.verifyPeer ?? true,
data.verifyHost ?? true
);
}
toJson(): ServiceLocationSocketSole {
return {
type: this.type,
host: this.host,
port: this.port,
encryption: this.encryption,
...(this.verifyPeer !== undefined && { verifyPeer: this.verifyPeer }),
...(this.verifyHost !== undefined && { verifyHost: this.verifyHost })
};
}
}
/**
* Split socket-based service location
* Used by: traditional IMAP/SMTP configurations
*/
export class LocationSocketSplit extends Location {
readonly type = 'SOCKET_SPLIT' as const;
inboundHost: string;
inboundPort: number;
inboundEncryption: 'none' | 'ssl' | 'tls' | 'starttls';
outboundHost: string;
outboundPort: number;
outboundEncryption: 'none' | 'ssl' | 'tls' | 'starttls';
inboundVerifyPeer: boolean;
inboundVerifyHost: boolean;
outboundVerifyPeer: boolean;
outboundVerifyHost: boolean;
constructor(
inboundHost: string = '',
inboundPort: number = 993,
inboundEncryption: 'none' | 'ssl' | 'tls' | 'starttls' = 'ssl',
outboundHost: string = '',
outboundPort: number = 465,
outboundEncryption: 'none' | 'ssl' | 'tls' | 'starttls' = 'ssl',
inboundVerifyPeer: boolean = true,
inboundVerifyHost: boolean = true,
outboundVerifyPeer: boolean = true,
outboundVerifyHost: boolean = true
) {
super();
this.inboundHost = inboundHost;
this.inboundPort = inboundPort;
this.inboundEncryption = inboundEncryption;
this.outboundHost = outboundHost;
this.outboundPort = outboundPort;
this.outboundEncryption = outboundEncryption;
this.inboundVerifyPeer = inboundVerifyPeer;
this.inboundVerifyHost = inboundVerifyHost;
this.outboundVerifyPeer = outboundVerifyPeer;
this.outboundVerifyHost = outboundVerifyHost;
}
static fromJson(data: ServiceLocationSocketSplit): LocationSocketSplit {
return new LocationSocketSplit(
data.inboundHost,
data.inboundPort,
data.inboundEncryption,
data.outboundHost,
data.outboundPort,
data.outboundEncryption,
data.inboundVerifyPeer ?? true,
data.inboundVerifyHost ?? true,
data.outboundVerifyPeer ?? true,
data.outboundVerifyHost ?? true
);
}
toJson(): ServiceLocationSocketSplit {
return {
type: this.type,
inboundHost: this.inboundHost,
inboundPort: this.inboundPort,
inboundEncryption: this.inboundEncryption,
outboundHost: this.outboundHost,
outboundPort: this.outboundPort,
outboundEncryption: this.outboundEncryption,
...(this.inboundVerifyPeer !== undefined && { inboundVerifyPeer: this.inboundVerifyPeer }),
...(this.inboundVerifyHost !== undefined && { inboundVerifyHost: this.inboundVerifyHost }),
...(this.outboundVerifyPeer !== undefined && { outboundVerifyPeer: this.outboundVerifyPeer }),
...(this.outboundVerifyHost !== undefined && { outboundVerifyHost: this.outboundVerifyHost })
};
}
}
/**
* File-based service location
* Used by: local file system providers
*/
export class LocationFile extends Location {
readonly type = 'FILE' as const;
path: string;
constructor(path: string = '') {
super();
this.path = path;
}
static fromJson(data: ServiceLocationFile): LocationFile {
return new LocationFile(data.path);
}
toJson(): ServiceLocationFile {
return {
type: this.type,
path: this.path
};
}
} }
+36
View File
@@ -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
View File
@@ -4,10 +4,12 @@
import type { import type {
ProviderInterface, ProviderInterface,
ProviderCapabilitiesInterface ProviderCapabilitiesInterface,
ProviderModelInterface
} from "@/types/provider"; } from "@/types/provider";
import { clonePlain } from './clone-plain';
export class ProviderObject implements ProviderInterface { export class ProviderObject implements ProviderModelInterface {
_data!: ProviderInterface; _data!: ProviderInterface;
@@ -21,12 +23,16 @@ export class ProviderObject implements ProviderInterface {
} }
fromJson(data: ProviderInterface): ProviderObject { fromJson(data: ProviderInterface): ProviderObject {
this._data = data; this._data = clonePlain(data);
return this; return this;
} }
toJson(): ProviderInterface { toJson(): ProviderInterface {
return this._data; return clonePlain(this._data);
}
clone(): ProviderObject {
return new ProviderObject().fromJson(this.toJson());
} }
capable(capability: keyof ProviderCapabilitiesInterface): boolean { capable(capability: keyof ProviderCapabilitiesInterface): boolean {
@@ -43,10 +49,6 @@ export class ProviderObject implements ProviderInterface {
/** Immutable Properties */ /** Immutable Properties */
get '@type'(): string {
return this._data['@type'];
}
get identifier(): string { get identifier(): string {
return this._data.identifier; return this._data.identifier;
} }
@@ -56,7 +58,7 @@ export class ProviderObject implements ProviderInterface {
} }
get capabilities(): ProviderCapabilitiesInterface { get capabilities(): ProviderCapabilitiesInterface {
return this._data.capabilities; return clonePlain(this._data.capabilities);
} }
} }
+86 -81
View File
@@ -5,18 +5,26 @@
import type { import type {
ServiceInterface, ServiceInterface,
ServiceCapabilitiesInterface, ServiceCapabilitiesInterface,
ServiceIdentity, ServiceLocation,
ServiceLocation ServiceModelInterface
} from "@/types/service"; } from "@/types/service";
import { Identity } from './identity'; import { Identity } from './identity';
import { Location } from './location'; import { Location } from './location';
import { MutationProxy } from './mutation-proxy';
import { clonePlain } from './clone-plain';
export class ServiceObject implements ServiceInterface { export class ServiceObject implements ServiceModelInterface {
private _original: ServiceInterface;
private _mutated: Partial<ServiceInterface>;
private _mutationProxy = new MutationProxy<ServiceInterface>(() => this._original, () => this._mutated);
_data!: ServiceInterface; _data!: ServiceInterface;
private _location: Location | null | undefined = undefined;
private _identity: Identity | null | undefined = undefined;
private _locationAssigned = false;
private _identityAssigned = false;
constructor() { constructor() {
this._data = { this._original = {
'@type': 'chrono:service', '@type': 'chrono:service',
provider: '', provider: '',
identifier: null, identifier: null,
@@ -24,15 +32,59 @@ export class ServiceObject implements ServiceInterface {
enabled: false, enabled: false,
capabilities: {} capabilities: {}
}; };
this._mutated = {};
this._data = this._mutationProxy.create();
} }
fromJson(data: ServiceInterface): ServiceObject { 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; return this;
} }
toJson(): ServiceInterface { toJson(): ServiceInterface;
return this._data; 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 { capable(capability: keyof ServiceCapabilitiesInterface): boolean {
@@ -41,88 +93,41 @@ export class ServiceObject implements ServiceInterface {
} }
capability(capability: keyof ServiceCapabilitiesInterface): any | null { capability(capability: keyof ServiceCapabilitiesInterface): any | null {
if (this._data.capabilities) { return this._data.capabilities?.[capability] ?? null;
return this._data.capabilities[capability];
}
return 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 { get label(): string | null { return this._data.label; }
return this._data['@type']; 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 { set location(value: Location | null) {
return this._data.provider; this._location = value;
this._locationAssigned = true;
} }
get identifier(): string | number | null { get identity(): Identity | null {
return this._data.identifier; 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 { set identity(value: Identity | null) {
return this._data.capabilities; this._identity = value;
} this._identityAssigned = true;
/** Mutable Properties */
get label(): string | null {
return this._data.label;
}
set label(value: string | null) {
this._data.label = value;
}
get enabled(): boolean {
return this._data.enabled;
}
set enabled(value: boolean) {
this._data.enabled = value;
}
get location(): ServiceLocation | null {
return this._data.location ?? null;
}
set location(value: ServiceLocation | null) {
this._data.location = value;
}
get identity(): ServiceIdentity | null {
return this._data.identity ?? null;
}
set identity(value: ServiceIdentity | null) {
this._data.identity = value;
}
get auxiliary(): Record<string, any> {
return this._data.auxiliary ?? {};
}
set auxiliary(value: Record<string, any>) {
this._data.auxiliary = value;
}
/** Helper Methods */
/**
* Get identity as a class instance for easier manipulation
*/
getIdentity(): Identity | null {
if (!this._data.identity) return null;
return Identity.fromJson(this._data.identity);
}
/**
* Get location as a class instance for easier manipulation
*/
getLocation(): Location | null {
if (!this._data.location) return null;
return Location.fromJson(this._data.location);
} }
get auxiliary(): Record<string, any> { return this._data.auxiliary ?? {}; }
set auxiliary(value: Record<string, any>) { this._data.auxiliary = value; }
} }
+16 -4
View File
@@ -70,9 +70,15 @@ export const collectionService = {
* *
* @returns Promise with collection object * @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); 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 * @returns Promise with deletion result
*/ */
async delete(request: CollectionDeleteRequest): Promise<CollectionDeleteResponse> { async delete(request: CollectionDeleteRequest): Promise<boolean | CollectionObject> {
return await transceivePost<CollectionDeleteRequest, CollectionDeleteResponse>('collection.delete', request); const response = await transceivePost<CollectionDeleteRequest, CollectionDeleteResponse>('collection.delete', request);
if (response.disposition === 'moved' && response.mutation) {
return createCollectionObject(response.mutation);
}
return true;
}, },
}; };
+64 -46
View File
@@ -2,10 +2,12 @@
* Entity management service * Entity management service
*/ */
import { transceivePost } from './transceive'; import { transceivePost, transceiveStream } from './transceive';
import type { import type {
EntityListRequest, EntityListBulkRequest,
EntityListResponse, EntityListBulkResponse,
EntityListStreamRequest,
EntityListStreamResponse,
EntityFetchRequest, EntityFetchRequest,
EntityFetchResponse, EntityFetchResponse,
EntityExtantRequest, EntityExtantRequest,
@@ -18,6 +20,10 @@ import type {
EntityDeleteResponse, EntityDeleteResponse,
EntityDeltaRequest, EntityDeltaRequest,
EntityDeltaResponse, EntityDeltaResponse,
EntityMoveRequest,
EntityMoveResponse,
EntityImportRequest,
EntityImportResponse,
EntityInterface, EntityInterface,
} from '../types/entity'; } from '../types/entity';
import { useIntegrationStore } from '@KTXC/stores/integrationStore'; import { useIntegrationStore } from '@KTXC/stores/integrationStore';
@@ -31,7 +37,7 @@ function createEntityObject(data: EntityInterface): EntityObject {
const integrationStore = useIntegrationStore(); const integrationStore = useIntegrationStore();
const factoryItem = integrationStore.getItemById('chrono_entity_factory', data.provider) as any; const factoryItem = integrationStore.getItemById('chrono_entity_factory', data.provider) as any;
const factory = factoryItem?.factory; const factory = factoryItem?.factory;
// Use provider factory if available, otherwise base class // Use provider factory if available, otherwise base class
return factory ? factory(data) : new EntityObject().fromJson(data); return factory ? factory(data) : new EntityObject().fromJson(data);
} }
@@ -39,16 +45,11 @@ function createEntityObject(data: EntityInterface): EntityObject {
export const entityService = { export const entityService = {
/** /**
* Retrieve list of entities, optionally filtered by source selector * Retrieve list of entities, optionally filtered by source collection identifiers
*
* @param request - list request parameters
*
* @returns Promise with entity object list grouped by provider, service, collection, and entity identifier
*/ */
async list(request: EntityListRequest = {}): Promise<Record<string, Record<string, Record<string, Record<string, EntityObject>>>>> { async listBulk(request: EntityListBulkRequest = {}): Promise<Record<string, Record<string, Record<string, Record<string, EntityObject>>>>> {
const response = await transceivePost<EntityListRequest, EntityListResponse>('entity.list', request); 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>>>> = {}; const providerList: Record<string, Record<string, Record<string, Record<string, EntityObject>>>> = {};
Object.entries(response).forEach(([providerId, providerServices]) => { Object.entries(response).forEach(([providerId, providerServices]) => {
const serviceList: Record<string, Record<string, Record<string, EntityObject>>> = {}; const serviceList: Record<string, Record<string, Record<string, EntityObject>>> = {};
@@ -65,35 +66,39 @@ export const entityService = {
}); });
providerList[providerId] = serviceList; providerList[providerId] = serviceList;
}); });
return providerList; return providerList;
}, },
/** /**
* Retrieve a specific entity by provider and identifier * Stream entities as NDJSON, invoking onEntity for each entity as it arrives.
* */
* @param request - fetch request parameters async listStream(request: EntityListStreamRequest, onEntity: (entity: EntityObject) => void): Promise<{ total: number }> {
* return await transceiveStream<EntityListStreamRequest, EntityListStreamResponse>(
* @returns Promise with entity objects keyed by identifier 'entity.listStream',
request,
(entity) => {
onEntity(createEntityObject(entity));
}
);
},
/**
* Retrieve specific entities by their identifiers
*/ */
async fetch(request: EntityFetchRequest): Promise<Record<string, EntityObject>> { async fetch(request: EntityFetchRequest): Promise<Record<string, EntityObject>> {
const response = await transceivePost<EntityFetchRequest, EntityFetchResponse>('entity.fetch', request); const response = await transceivePost<EntityFetchRequest, EntityFetchResponse>('entity.fetch', request);
// Convert response to EntityObject instances
const list: Record<string, EntityObject> = {}; const list: Record<string, EntityObject> = {};
Object.entries(response).forEach(([identifier, entityData]) => { Object.entries(response).forEach(([, entity]) => {
list[identifier] = createEntityObject(entityData); list[entity.identifier] = createEntityObject(entity);
}); });
return list; return list;
}, },
/** /**
* Retrieve entity availability status for a given source selector * Retrieve entity availability status for a given set of entity identifiers
*
* @param request - extant request parameters
*
* @returns Promise with entity availability status
*/ */
async extant(request: EntityExtantRequest): Promise<EntityExtantResponse> { async extant(request: EntityExtantRequest): Promise<EntityExtantResponse> {
return await transceivePost<EntityExtantRequest, EntityExtantResponse>('entity.extant', request); return await transceivePost<EntityExtantRequest, EntityExtantResponse>('entity.extant', request);
@@ -101,10 +106,6 @@ export const entityService = {
/** /**
* Create a new entity * Create a new entity
*
* @param request - create request parameters
*
* @returns Promise with created entity object
*/ */
async create(request: EntityCreateRequest): Promise<EntityObject> { async create(request: EntityCreateRequest): Promise<EntityObject> {
const response = await transceivePost<EntityCreateRequest, EntityCreateResponse>('entity.create', request); const response = await transceivePost<EntityCreateRequest, EntityCreateResponse>('entity.create', request);
@@ -113,10 +114,6 @@ export const entityService = {
/** /**
* Update an existing entity * Update an existing entity
*
* @param request - update request parameters
*
* @returns Promise with updated entity object
*/ */
async update(request: EntityUpdateRequest): Promise<EntityObject> { async update(request: EntityUpdateRequest): Promise<EntityObject> {
const response = await transceivePost<EntityUpdateRequest, EntityUpdateResponse>('entity.update', request); const response = await transceivePost<EntityUpdateRequest, EntityUpdateResponse>('entity.update', request);
@@ -124,11 +121,7 @@ export const entityService = {
}, },
/** /**
* Delete an entity * Delete entities by their identifiers
*
* @param request - delete request parameters
*
* @returns Promise with deletion result
*/ */
async delete(request: EntityDeleteRequest): Promise<EntityDeleteResponse> { async delete(request: EntityDeleteRequest): Promise<EntityDeleteResponse> {
return await transceivePost<EntityDeleteRequest, EntityDeleteResponse>('entity.delete', request); return await transceivePost<EntityDeleteRequest, EntityDeleteResponse>('entity.delete', request);
@@ -136,15 +129,40 @@ export const entityService = {
/** /**
* Retrieve delta changes for entities * Retrieve delta changes for entities
*
* @param request - delta request parameters
*
* @returns Promise with delta changes (created, modified, deleted)
*/ */
async delta(request: EntityDeltaRequest): Promise<EntityDeltaResponse> { async delta(request: EntityDeltaRequest): Promise<EntityDeltaResponse> {
return await transceivePost<EntityDeltaRequest, EntityDeltaResponse>('entity.delta', request); return await transceivePost<EntityDeltaRequest, EntityDeltaResponse>('entity.delta', request);
}, },
/**
* Move entities to a target collection
*/
async move(request: EntityMoveRequest): Promise<EntityMoveResponse> {
return await transceivePost<EntityMoveRequest, EntityMoveResponse>('entity.move', request);
},
/**
* Import vCards into a collection, streaming progress as it arrives.
*
* @param request - import request (target collection, raw data, options)
* @param onObject - called synchronously for each per-contact result frame
* @param onDiscovered - called once with the discovered total (progress denominator)
*
* @returns Promise resolving to { total } (objects processed) when the stream completes
*/
async import(
request: EntityImportRequest,
onObject: (object: EntityImportResponse) => void,
onDiscovered: (expected: number) => void,
): Promise<{ total: number }> {
return await transceiveStream<EntityImportRequest, EntityImportResponse>(
'entity.import',
request,
onObject,
{ onStart: (expected) => { if (expected !== undefined) onDiscovered(expected); } },
);
},
}; };
export default entityService; export default entityService;
+80 -1
View File
@@ -4,7 +4,7 @@
*/ */
import { createFetchWrapper } from '@KTXC'; import { createFetchWrapper } from '@KTXC';
import type { ApiRequest, ApiResponse } from '../types/common'; import type { ApiRequest, ApiResponse, ApiStreamResponse } from '../types/common';
const fetchWrapper = createFetchWrapper(); const fetchWrapper = createFetchWrapper();
const API_URL = '/m/chrono_manager/v1'; const API_URL = '/m/chrono_manager/v1';
@@ -48,3 +48,82 @@ export async function transceivePost<TRequest, TResponse>(
return response.data; return response.data;
} }
/**
* Stream an NDJSON API response, unwrapping data frames for the caller.
*
* @param operation - Operation name, e.g. 'entity.listStream'
* @param data - Operation-specific request data
* @param onData - Synchronous callback invoked for every unwrapped data payload.
* @param options - Optional `user` override and an `onStart` hook.
* @returns Promise resolving to the final stream total from the control/end frame
*/
export async function transceiveStream<TRequest, TData>(
operation: string,
data: TRequest,
onData: (data: TData) => void,
options?: { user?: string; onStart?: (expected?: number) => void }
): Promise<{ total: number }> {
const request: ApiRequest<TRequest> = {
version: API_VERSION,
transaction: generateTransactionId(),
operation,
data,
user: options?.user,
};
let total = 0;
const dispatch = (line: string): void => {
const message = JSON.parse(line) as ApiStreamResponse<TData>;
if (message.type === 'control') {
if (message.status === 'start') {
options?.onStart?.(message.total);
} else if (message.status === 'end') {
total = message.total;
}
return;
}
if (message.type === 'error') {
throw new Error(`[${operation}] ${message.message}`);
}
onData(message.data);
};
await fetchWrapper.post(API_URL, request, {
headers: { 'Accept': 'application/json' },
onStream: async (response: Response) => {
if (!response.body) {
throw new Error(`[${operation}] Response body is not readable`);
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop()!;
for (const line of lines) {
if (line.trim()) dispatch(line);
}
}
if (buffer.trim()) dispatch(buffer);
} finally {
reader.releaseLock();
}
},
});
return { total };
}
+78 -144
View File
@@ -4,9 +4,14 @@
import { ref, computed, readonly } from 'vue' import { ref, computed, readonly } from 'vue'
import { defineStore } from 'pinia' import { defineStore } from 'pinia'
import {
type ServiceIdentifier,
type CollectionIdentifier,
type ListFilter,
type ListSort,
} from '../types'
import { collectionService } from '../services' import { collectionService } from '../services'
import { CollectionObject, CollectionPropertiesObject } from '../models/collection' import { CollectionObject, CollectionPropertiesObject } from '../models/collection'
import type { SourceSelector, ListFilter, ListSort } from '../types'
export const useCollectionsStore = defineStore('chronoCollectionsStore', () => { export const useCollectionsStore = defineStore('chronoCollectionsStore', () => {
// State // State
@@ -33,101 +38,61 @@ export const useCollectionsStore = defineStore('chronoCollectionsStore', () => {
*/ */
const collectionsByService = computed(() => { const collectionsByService = computed(() => {
const groups: Record<string, CollectionObject[]> = {} const groups: Record<string, CollectionObject[]> = {}
Object.values(_collections.value).forEach((collection) => { Object.values(_collections.value).forEach((collection) => {
const serviceKey = `${collection.provider}:${collection.service}` const serviceKey = `${collection.provider}:${collection.service}`
if (!groups[serviceKey]) { const serviceCollections = (groups[serviceKey] ??= [])
groups[serviceKey] = [] serviceCollections.push(collection)
}
groups[serviceKey].push(collection)
}) })
return groups return groups
}) })
/** /**
* Get a specific collection from store, with optional retrieval * Get a specific collection from store, with optional retrieval
*
* @param provider - provider identifier
* @param service - service identifier
* @param identifier - collection identifier
* @param retrieve - Retrieve behavior: true = fetch if missing or refresh, false = cache only
*
* @returns Collection object or null
*/ */
function collection(provider: string, service: string | number, identifier: string | number, retrieve: boolean = false): CollectionObject | null { function collection(target: CollectionIdentifier, retrieve: boolean = false): CollectionObject | null {
const key = identifierKey(provider, service, identifier) if (retrieve === true && !_collections.value[target]) {
if (retrieve === true && !_collections.value[key]) { console.debug(`[Chrono Manager][Store] - Force fetching collection "${target}"`)
console.debug(`[Chrono Manager][Store] - Force fetching collection "${key}"`) fetch([target])
fetch(provider, service, identifier)
} }
return _collections.value[key] || null return _collections.value[target] || null
} }
/** /**
* Get all collections for a specific service * Get all collections for a specific service
*
* @param provider - provider identifier
* @param service - service identifier
* @param retrieve - Retrieve behavior: true = fetch if missing or refresh, false = cache only
*
* @returns Array of collection objects
*/ */
function collectionsForService(provider: string, service: string | number, retrieve: boolean = false): CollectionObject[] { function collectionsForService(provider: string, service: string | number, retrieve: boolean = false): CollectionObject[] {
const serviceKeyPrefix = `${provider}:${service}:` const serviceIdentifier = `${provider}:${service}` as ServiceIdentifier
const serviceCollections = Object.entries(_collections.value) const serviceCollections = Object.values(_collections.value)
.filter(([key]) => key.startsWith(serviceKeyPrefix)) .filter(collection => `${collection.provider}:${collection.service}` === serviceIdentifier)
.map(([_, collection]) => collection)
if (retrieve === true && serviceCollections.length === 0) { if (retrieve === true && serviceCollections.length === 0) {
console.debug(`[Chrono Manager][Store] - Force fetching collections for service "${provider}:${service}"`) console.debug(`[Chrono Manager][Store] - Force fetching collections for service "${serviceIdentifier}"`)
const sources: SourceSelector = { list([serviceIdentifier])
[provider]: {
[String(service)]: true
}
}
list(sources)
} }
return serviceCollections 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 { async function list(sources?: ServiceIdentifier[] | CollectionIdentifier[], filter?: ListFilter, sort?: ListSort): Promise<Record<string, CollectionObject>> {
return `${provider}:${service ?? ''}:${identifier ?? ''}`
}
// Actions
/**
* Retrieve all or specific collections, optionally filtered by source selector
*
* @param sources - optional source selector
* @param filter - optional list filter
* @param sort - optional list sort
*
* @returns Promise with collection object list keyed by provider, service, and collection identifier
*/
async function list(sources?: SourceSelector, filter?: ListFilter, sort?: ListSort): Promise<Record<string, CollectionObject>> {
transceiving.value = true transceiving.value = true
try { try {
const response = await collectionService.list({ sources, filter, sort }) const response = await collectionService.list({ sources, filter, sort })
// Flatten nested structure: provider:service:collection -> "provider:service:collection": object
const collections: Record<string, CollectionObject> = {} const collections: Record<string, CollectionObject> = {}
Object.entries(response).forEach(([_providerId, providerServices]) => { Object.entries(response).forEach(([_providerId, providerServices]) => {
Object.entries(providerServices).forEach(([_serviceId, serviceCollections]) => { Object.entries(providerServices).forEach(([_serviceId, serviceCollections]) => {
Object.entries(serviceCollections).forEach(([_collectionId, collectionObj]) => { Object.entries(serviceCollections).forEach(([_collectionId, collectionObj]) => {
const key = identifierKey(collectionObj.provider, collectionObj.service, collectionObj.identifier) collections[collectionObj.identifier] = collectionObj
collections[key] = collectionObj
}) })
}) })
}) })
// Merge retrieved collections into state
_collections.value = { ..._collections.value, ...collections } _collections.value = { ..._collections.value, ...collections }
console.debug('[Chrono Manager][Store] - Successfully retrieved', Object.keys(collections).length, 'collections') console.debug('[Chrono Manager][Store] - Successfully retrieved', Object.keys(collections).length, 'collections')
@@ -139,29 +104,23 @@ export const useCollectionsStore = defineStore('chronoCollectionsStore', () => {
transceiving.value = false transceiving.value = false
} }
} }
/** /**
* Retrieve a specific collection by provider, service, and identifier * Retrieve specific collections by their identifiers
*
* @param provider - provider identifier
* @param service - service identifier
* @param identifier - collection identifier
*
* @returns Promise with collection object
*/ */
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 transceiving.value = true
try { 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
console.debug('[Chrono Manager][Store] - Successfully fetched collection:', key) Object.values(response).forEach(collectionObj => {
_collections.value[collectionObj.identifier] = collectionObj
})
console.debug('[Chrono Manager][Store] - Successfully fetched collections:', Object.keys(response).join(', '))
return response return response
} catch (error: any) { } 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 throw error
} finally { } finally {
transceiving.value = false transceiving.value = false
@@ -169,18 +128,14 @@ export const useCollectionsStore = defineStore('chronoCollectionsStore', () => {
} }
/** /**
* Retrieve collection availability status for a given source selector * Retrieve collection availability status for the given collection identifiers
*
* @param sources - source selector to check availability for
*
* @returns Promise with collection availability status
*/ */
async function extant(sources: SourceSelector) { async function extant(targets: CollectionIdentifier[]): Promise<Record<string, Record<string, Record<string, boolean>>>> {
transceiving.value = true transceiving.value = true
try { 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 return response
} catch (error: any) { } catch (error: any) {
console.error('[Chrono Manager][Store] - Failed to check collections:', error) console.error('[Chrono Manager][Store] - Failed to check collections:', error)
@@ -191,30 +146,20 @@ export const useCollectionsStore = defineStore('chronoCollectionsStore', () => {
} }
/** /**
* Create a new collection with given provider, service, and data * Create a new collection with given provider, service, and properties
*
* @param provider - provider identifier for the new collection
* @param service - service identifier for the new collection
* @param collection - optional parent collection identifier
* @param data - collection properties for creation
*
* @returns Promise with created collection object
*/ */
async function create(provider: string, service: string | number, collection: string | number | null, data: CollectionPropertiesObject): Promise<CollectionObject> { async function create(provider: string, service: string | number, properties: CollectionPropertiesObject): Promise<CollectionObject> {
transceiving.value = true transceiving.value = true
try { try {
const response = await collectionService.create({ const response = await collectionService.create({
provider, provider,
service, service,
collection, properties: properties.toJson(),
properties: data
}) })
// Merge created collection into state _collections.value[response.identifier] = response
const key = identifierKey(response.provider, response.service, response.identifier)
_collections.value[key] = response console.debug('[Chrono Manager][Store] - Successfully created collection:', response.identifier)
console.debug('[Chrono Manager][Store] - Successfully created collection:', key)
return response return response
} catch (error: any) { } catch (error: any) {
console.error('[Chrono Manager][Store] - Failed to create collection:', error) console.error('[Chrono Manager][Store] - Failed to create collection:', error)
@@ -225,30 +170,19 @@ export const useCollectionsStore = defineStore('chronoCollectionsStore', () => {
} }
/** /**
* Update an existing collection with given provider, service, identifier, and data * Update an existing collection with given target and properties
*
* @param provider - provider identifier for the collection to update
* @param service - service identifier for the collection to update
* @param identifier - collection identifier for the collection to update
* @param data - collection properties for update
*
* @returns Promise with updated collection object
*/ */
async function update(provider: string, service: string | number, identifier: string | number, data: CollectionPropertiesObject): Promise<CollectionObject> { async function update(target: CollectionIdentifier, properties: CollectionPropertiesObject): Promise<CollectionObject> {
transceiving.value = true transceiving.value = true
try { try {
const response = await collectionService.update({ const response = await collectionService.update({
provider, target,
service, properties: properties.toJson(),
identifier,
properties: data
}) })
// Merge updated collection into state _collections.value[response.identifier] = response
const key = identifierKey(response.provider, response.service, response.identifier)
_collections.value[key] = response console.debug('[Chrono Manager][Store] - Successfully updated collection:', response.identifier)
console.debug('[Chrono Manager][Store] - Successfully updated collection:', key)
return response return response
} catch (error: any) { } catch (error: any) {
console.error('[Chrono Manager][Store] - Failed to update collection:', error) console.error('[Chrono Manager][Store] - Failed to update collection:', error)
@@ -259,24 +193,28 @@ export const useCollectionsStore = defineStore('chronoCollectionsStore', () => {
} }
/** /**
* Delete a collection by provider, service, and identifier * Delete a collection by identifier.
*
* @param provider - provider identifier for the collection to delete
* @param service - service identifier for the collection to delete
* @param identifier - collection identifier for the collection to delete
*
* @returns Promise with deletion result
*/ */
async function remove(provider: string, service: string | number, identifier: string | number): Promise<any> { async function remove(target: CollectionIdentifier, force?: boolean): Promise<CollectionObject | boolean> {
transceiving.value = true transceiving.value = true
try { 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]
console.debug('[Chrono Manager][Store] - Successfully deleted collection:', key) if (response !== true && !(response instanceof CollectionObject)) {
console.warn('[Chrono Manager][Store] - Delete failed. Received unexpected response from delete operation:', response)
return false
}
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) { } catch (error: any) {
console.error('[Chrono Manager][Store] - Failed to delete collection:', error) console.error('[Chrono Manager][Store] - Failed to delete collection:', error)
throw error throw error
@@ -285,17 +223,13 @@ export const useCollectionsStore = defineStore('chronoCollectionsStore', () => {
} }
} }
// Return public API
return { return {
// State (readonly)
transceiving: readonly(transceiving), transceiving: readonly(transceiving),
// Getters
count, count,
has, has,
collections, collections,
collectionsByService, collectionsByService,
collectionsForService, collectionsForService,
// Actions
collection, collection,
list, list,
fetch, fetch,
+193 -212
View File
@@ -6,7 +6,14 @@ import { ref, computed, readonly } from 'vue'
import { defineStore } from 'pinia' import { defineStore } from 'pinia'
import { entityService } from '../services' import { entityService } from '../services'
import { EntityObject } from '../models' import { EntityObject } from '../models'
import type { 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', () => { export const useEntitiesStore = defineStore('chronoEntitiesStore', () => {
// State // State
@@ -30,95 +37,44 @@ export const useEntitiesStore = defineStore('chronoEntitiesStore', () => {
/** /**
* Get a specific entity from store, with optional retrieval * Get a specific entity from store, with optional retrieval
*
* @param provider - provider identifier
* @param service - service identifier
* @param collection - collection identifier
* @param identifier - entity identifier
* @param retrieve - Retrieve behavior: true = fetch if missing or refresh, false = cache only
*
* @returns Entity object or null
*/ */
function entity(provider: string, service: string | number, collection: string | number, identifier: string | number, retrieve: boolean = false): EntityObject | null { function entity(target: EntityIdentifier, retrieve: boolean = false): EntityObject | null {
const key = identifierKey(provider, service, collection, identifier) if (retrieve === true && !_entities.value[target]) {
if (retrieve === true && !_entities.value[key]) { console.debug(`[Chrono Manager][Store] - Force fetching entity "${target}"`)
console.debug(`[Chrono Manager][Store] - Force fetching entity "${key}"`) fetch([target])
fetch(provider, service, collection, [identifier])
} }
return _entities.value[key] || null return _entities.value[target] || null
} }
/** /**
* Get all entities for a specific collection * Get all entities for a specific collection
*
* @param provider - provider identifier
* @param service - service identifier
* @param collection - collection identifier
* @param retrieve - Retrieve behavior: true = fetch if missing or refresh, false = cache only
*
* @returns Array of entity objects
*/ */
function entitiesForCollection(provider: string, service: string | number, collection: string | number, retrieve: boolean = false): EntityObject[] { function entitiesForCollection(target: CollectionIdentifier, retrieve: boolean = false): EntityObject[] {
const collectionKeyPrefix = `${provider}:${service}:${collection}:`
const collectionEntities = Object.entries(_entities.value) const collectionEntities = Object.entries(_entities.value)
.filter(([key]) => key.startsWith(collectionKeyPrefix)) .filter(([key]) => key.startsWith(`${target}:`))
.map(([_, entity]) => entity) .map(([_, entity]) => entity)
if (retrieve === true && collectionEntities.length === 0) { if (retrieve === true && collectionEntities.length === 0) {
console.debug(`[Chrono Manager][Store] - Force fetching entities for collection "${provider}:${service}:${collection}"`) console.debug(`[Chrono Manager][Store] - Force fetching entities for collection "${target}"`)
const sources: SourceSelector = { list([target])
[provider]: {
[String(service)]: {
[String(collection)]: true
}
}
}
list(sources)
} }
return collectionEntities 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 { async function list(sources: CollectionIdentifier[], filter?: ListFilter, sort?: ListSort, range?: ListRange): Promise<Record<string, EntityObject>> {
return `${provider}:${service}:${collection}:${identifier}`
}
// Actions
/**
* Retrieve all or specific entities, optionally filtered by source selector
*
* @param sources - optional source selector
* @param filter - optional list filter
* @param sort - optional list sort
* @param range - optional list range
*
* @returns Promise with entity object list keyed by identifier
*/
async function list(sources?: SourceSelector, filter?: ListFilter, sort?: ListSort, range?: ListRange): Promise<Record<string, EntityObject>> {
transceiving.value = true transceiving.value = true
try { try {
const 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> = {} 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 await entityService.listStream({ sources, filter, sort, range }, (entity: EntityObject) => {
_entities.value = { ..._entities.value, ...entities } _entities.value[entity.identifier] = entity
entities[entity.identifier] = entity
})
console.debug('[Chrono Manager][Store] - Successfully retrieved', Object.keys(entities).length, 'entities') console.debug('[Chrono Manager][Store] - Successfully retrieved', Object.keys(entities).length, 'entities')
return entities return entities
@@ -129,28 +85,19 @@ export const useEntitiesStore = defineStore('chronoEntitiesStore', () => {
transceiving.value = false transceiving.value = false
} }
} }
/** /**
* Retrieve specific entities by provider, service, collection, and identifiers * Retrieve specific entities by their identifiers
*
* @param provider - provider identifier
* @param service - service identifier
* @param collection - collection identifier
* @param identifiers - array of entity identifiers to fetch
*
* @returns Promise with entity objects keyed by identifier
*/ */
async function fetch(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 transceiving.value = true
try { 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> = {} const entities: Record<string, EntityObject> = {}
Object.entries(response).forEach(([identifier, entityData]) => { Object.entries(response).forEach(([identifier, entity]) => {
const key = identifierKey(provider, service, collection, identifier) entities[identifier] = entity
entities[key] = entityData _entities.value[identifier] = entity
_entities.value[key] = entityData
}) })
console.debug('[Chrono Manager][Store] - Successfully fetched', Object.keys(entities).length, 'entities') console.debug('[Chrono Manager][Store] - Successfully fetched', Object.keys(entities).length, 'entities')
@@ -164,16 +111,12 @@ export const useEntitiesStore = defineStore('chronoEntitiesStore', () => {
} }
/** /**
* Retrieve entity availability status for a given source selector * Retrieve entity availability status for a given set of entity identifiers
*
* @param sources - source selector to check availability for
*
* @returns Promise with entity availability status
*/ */
async function extant(sources: SourceSelector) { async function extant(targets: EntityIdentifier[]) {
transceiving.value = true transceiving.value = true
try { try {
const response = await entityService.extant({ sources }) const response = await entityService.extant({ targets })
console.debug('[Chrono Manager][Store] - Successfully checked entity availability') console.debug('[Chrono Manager][Store] - Successfully checked entity availability')
return response return response
} catch (error: any) { } catch (error: any) {
@@ -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 * 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 transceiving.value = true
try { try {
const response = await entityService.delta({ sources }) const response = await entityService.delta({ targets })
// Process delta and update store Object.entries(response).forEach(([, providerData]) => {
Object.entries(response).forEach(([provider, providerData]) => {
// Skip if no changes for provider
if (providerData === false) return if (providerData === false) return
Object.entries(providerData).forEach(([service, serviceData]) => { Object.entries(providerData).forEach(([, serviceData]) => {
// Skip if no changes for service
if (serviceData === false) return if (serviceData === false) return
Object.entries(serviceData).forEach(([collection, collectionData]) => { Object.entries(serviceData).forEach(([, collectionData]) => {
// Skip if no changes for collection
if (collectionData === false) return if (collectionData === false) return
// Process deletions (remove from store)
if (collectionData.deletions && collectionData.deletions.length > 0) { if (collectionData.deletions && collectionData.deletions.length > 0) {
collectionData.deletions.forEach((identifier) => { collectionData.deletions.forEach((identifier) => {
const key = identifierKey(provider, service, collection, identifier) delete _entities.value[identifier]
delete _entities.value[key]
}) })
} }
// 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 { return {
// State (readonly)
transceiving: readonly(transceiving), transceiving: readonly(transceiving),
// Getters
count, count,
has, has,
entities, entities,
entitiesForCollection, entitiesForCollection,
// Actions
entity, entity,
list, list,
fetch, fetch,
@@ -342,5 +321,7 @@ export const useEntitiesStore = defineStore('chronoEntitiesStore', () => {
update, update,
delete: remove, delete: remove,
delta, delta,
fresh,
move,
} }
}) })
+124
View File
@@ -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 }
})
+1
View File
@@ -2,3 +2,4 @@ export { useProvidersStore } from './providersStore';
export { useServicesStore } from './servicesStore'; export { useServicesStore } from './servicesStore';
export { useCollectionsStore } from './collectionsStore'; export { useCollectionsStore } from './collectionsStore';
export { useEntitiesStore } from './entitiesStore'; export { useEntitiesStore } from './entitiesStore';
export { useImportStore } from './importStore';
+7 -7
View File
@@ -6,7 +6,7 @@ import { ref, computed, readonly } from 'vue'
import { defineStore } from 'pinia' import { defineStore } from 'pinia'
import { providerService } from '../services' import { providerService } from '../services'
import { ProviderObject } from '../models/provider' import { ProviderObject } from '../models/provider'
import type { SourceSelector } from '../types' import type { ProviderIdentifier } from '../types'
export const useProvidersStore = defineStore('chronoProvidersStore', () => { export const useProvidersStore = defineStore('chronoProvidersStore', () => {
// State // State
@@ -54,10 +54,10 @@ export const useProvidersStore = defineStore('chronoProvidersStore', () => {
* *
* @returns Promise with provider object list keyed by provider identifier * @returns Promise with provider object list keyed by provider identifier
*/ */
async function list(sources?: SourceSelector): Promise<Record<string, ProviderObject>> { async function list(targets?: ProviderIdentifier[]): Promise<Record<string, ProviderObject>> {
transceiving.value = true transceiving.value = true
try { try {
const providers = await providerService.list({ sources }) const providers = await providerService.list({ targets })
// Merge retrieved providers into state // Merge retrieved providers into state
_providers.value = { ..._providers.value, ...providers } _providers.value = { ..._providers.value, ...providers }
@@ -82,7 +82,7 @@ export const useProvidersStore = defineStore('chronoProvidersStore', () => {
async function fetch(identifier: string): Promise<ProviderObject> { async function fetch(identifier: string): Promise<ProviderObject> {
transceiving.value = true transceiving.value = true
try { try {
const provider = await providerService.fetch({ identifier }) const provider = await providerService.fetch({ target: identifier })
// Merge fetched provider into state // Merge fetched provider into state
_providers.value[provider.identifier] = provider _providers.value[provider.identifier] = provider
@@ -104,10 +104,10 @@ export const useProvidersStore = defineStore('chronoProvidersStore', () => {
* *
* @returns Promise with provider availability status * @returns Promise with provider availability status
*/ */
async function extant(sources: SourceSelector) { async function extant(targets: ProviderIdentifier[]) {
transceiving.value = true transceiving.value = true
try { try {
const response = await providerService.extant({ sources }) const response = await providerService.extant({ targets })
Object.entries(response).forEach(([providerId, providerStatus]) => { Object.entries(response).forEach(([providerId, providerStatus]) => {
if (providerStatus === false) { if (providerStatus === false) {
@@ -115,7 +115,7 @@ export const useProvidersStore = defineStore('chronoProvidersStore', () => {
} }
}) })
console.debug('[Chrono Manager][Store] - Successfully checked', sources ? Object.keys(sources).length : 0, 'providers') console.debug('[Chrono Manager][Store] - Successfully checked', targets ? targets.length : 0, 'providers')
return response return response
} catch (error: any) { } catch (error: any) {
console.error('[Chrono Manager][Store] - Failed to check providers:', error) console.error('[Chrono Manager][Store] - Failed to check providers:', error)
+32 -16
View File
@@ -7,7 +7,8 @@ import { defineStore } from 'pinia'
import { serviceService } from '../services' import { serviceService } from '../services'
import { ServiceObject } from '../models/service' import { ServiceObject } from '../models/service'
import type { import type {
SourceSelector, CollectionIdentifier,
ServiceIdentifier,
ServiceInterface, ServiceInterface,
} from '../types' } from '../types'
@@ -55,20 +56,30 @@ export const useServicesStore = defineStore('chronoServicesStore', () => {
* @returns Service object or null * @returns Service object or null
*/ */
function service(provider: string, identifier: string | number, retrieve: boolean = false): ServiceObject | null { function service(provider: string, identifier: string | number, retrieve: boolean = false): ServiceObject | null {
const key = identifierKey(provider, identifier) return serviceByIdentifier(identifierKey(provider, identifier), retrieve)
if (retrieve === true && !_services.value[key]) { }
console.debug(`[Chrono Manager][Store] - Force fetching service "${key}"`)
fetch(provider, identifier) /**
* Get a service from store by its unique identifier, with optional retrieval
*/
function serviceByIdentifier(identifier: ServiceIdentifier, retrieve: boolean = false): ServiceObject | null {
if (retrieve === true && !_services.value[identifier]) {
console.debug(`[Chrono Manager][Store] - Force fetching service "${identifier}"`)
const separatorIndex = identifier.indexOf(':')
const provider = identifier.slice(0, separatorIndex)
const serviceIdentifier = identifier.slice(separatorIndex + 1)
void fetch(provider, serviceIdentifier)
} }
return _services.value[key] || null return _services.value[identifier] ?? null
} }
/** /**
* Unique key for a service * Unique key for a service
*/ */
function identifierKey(provider: string, identifier: string | number | null): string { function identifierKey(provider: string, identifier: string | number | null): ServiceIdentifier {
return `${provider}:${identifier ?? ''}` return `${provider}:${identifier ?? ''}` as ServiceIdentifier
} }
// Actions // Actions
@@ -80,10 +91,10 @@ export const useServicesStore = defineStore('chronoServicesStore', () => {
* *
* @returns Promise with service object list keyed by provider and service identifier * @returns Promise with service object list keyed by provider and service identifier
*/ */
async function list(sources?: SourceSelector): Promise<Record<string, ServiceObject>> { async function list(targets?: ServiceIdentifier[] | CollectionIdentifier[]): Promise<Record<string, ServiceObject>> {
transceiving.value = true transceiving.value = true
try { 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 // Flatten nested structure: provider-id: { service-id: object } -> "provider-id:service-id": object
const services: Record<string, ServiceObject> = {} const services: Record<string, ServiceObject> = {}
@@ -141,12 +152,12 @@ export const useServicesStore = defineStore('chronoServicesStore', () => {
* *
* @returns Promise with service availability status * @returns Promise with service availability status
*/ */
async function extant(sources: SourceSelector) { async function extant(targets: ServiceIdentifier[]) {
transceiving.value = true transceiving.value = true
try { 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 return response
} catch (error: any) { } catch (error: any) {
console.error('[Chrono Manager][Store] - Failed to check services:', error) console.error('[Chrono Manager][Store] - Failed to check services:', error)
@@ -192,10 +203,14 @@ export const useServicesStore = defineStore('chronoServicesStore', () => {
* *
* @returns Promise with updated service object * @returns Promise with updated service object
*/ */
async function update(provider: string, identifier: string | number, data: Partial<ServiceInterface>): Promise<ServiceObject> { async function update(provider: string, identifier: string | number, delta: boolean, data: ServiceObject | Partial<ServiceInterface>): Promise<ServiceObject> {
transceiving.value = true transceiving.value = true
try { 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 // Merge updated service into state
const key = identifierKey(service.provider, service.identifier) const key = identifierKey(service.provider, service.identifier)
@@ -249,6 +264,7 @@ export const useServicesStore = defineStore('chronoServicesStore', () => {
// Actions // Actions
service, service,
serviceByIdentifier,
list, list,
fetch, fetch,
extant, extant,
+28 -20
View File
@@ -1,27 +1,37 @@
/** /**
* Collection type definitions * Collection type definitions
*/ */
import type { ListFilter, ListSort, SourceSelector } from './common'; import type {
ServiceIdentifier,
CollectionIdentifier,
ListFilter,
ListSort
} from './common';
/** /**
* Collection information * Collection information
*/ */
export interface CollectionInterface { export interface CollectionInterface<T = CollectionPropertiesInterface> {
'@type': string;
version: number;
provider: string; provider: string;
service: string | number; service: string | number;
collection: string | number | null; collection: CollectionIdentifier | null;
identifier: string | number; identifier: CollectionIdentifier;
signature?: string | null; signature?: string | null;
created?: string | null; created?: string | null;
modified?: 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 type CollectionContentTypes = 'event' | 'task' | 'journal';
export interface CollectionBaseProperties { export interface CollectionBaseProperties {
'@type': string; '@type': string;
version: number;
} }
export interface CollectionImmutableProperties extends CollectionBaseProperties { export interface CollectionImmutableProperties extends CollectionBaseProperties {
@@ -38,11 +48,13 @@ export interface CollectionMutableProperties extends CollectionBaseProperties {
export interface CollectionPropertiesInterface extends CollectionMutableProperties, CollectionImmutableProperties {} export interface CollectionPropertiesInterface extends CollectionMutableProperties, CollectionImmutableProperties {}
export interface CollectionPropertiesModelInterface extends Omit<CollectionPropertiesInterface, '@type'> {}
/** /**
* Collection list * Collection list
*/ */
export interface CollectionListRequest { export interface CollectionListRequest {
sources?: SourceSelector; sources?: ServiceIdentifier[] | CollectionIdentifier[];
filter?: ListFilter; filter?: ListFilter;
sort?: ListSort; sort?: ListSort;
} }
@@ -59,18 +71,18 @@ export interface CollectionListResponse {
* Collection fetch * Collection fetch
*/ */
export interface CollectionFetchRequest { export interface CollectionFetchRequest {
provider: string; targets: CollectionIdentifier[];
service: string | number;
collection: string | number;
} }
export interface CollectionFetchResponse extends CollectionInterface {} export interface CollectionFetchResponse {
[identifier: CollectionIdentifier]: CollectionInterface;
}
/** /**
* Collection extant * Collection extant
*/ */
export interface CollectionExtantRequest { export interface CollectionExtantRequest {
sources: SourceSelector; targets: CollectionIdentifier[];
} }
export interface CollectionExtantResponse { export interface CollectionExtantResponse {
@@ -87,7 +99,6 @@ export interface CollectionExtantResponse {
export interface CollectionCreateRequest { export interface CollectionCreateRequest {
provider: string; provider: string;
service: string | number; service: string | number;
collection?: string | number | null; // Parent Collection Identifier
properties: CollectionMutableProperties; properties: CollectionMutableProperties;
} }
@@ -97,9 +108,7 @@ export interface CollectionCreateResponse extends CollectionInterface {}
* Collection modify * Collection modify
*/ */
export interface CollectionUpdateRequest { export interface CollectionUpdateRequest {
provider: string; target: CollectionIdentifier;
service: string | number;
identifier: string | number;
properties: CollectionMutableProperties; properties: CollectionMutableProperties;
} }
@@ -109,14 +118,13 @@ export interface CollectionUpdateResponse extends CollectionInterface {}
* Collection delete * Collection delete
*/ */
export interface CollectionDeleteRequest { export interface CollectionDeleteRequest {
provider: string; target: CollectionIdentifier;
service: string | number;
identifier: string | number;
options?: { options?: {
force?: boolean; // Whether to force delete even if collection is not empty force?: boolean; // Whether to force delete even if collection is not empty
}; };
} }
export interface CollectionDeleteResponse { export interface CollectionDeleteResponse {
success: boolean; disposition: 'deleted' | 'moved';
mutation?: CollectionInterface | null; // If moved, the new location of the collection
} }
+66 -29
View File
@@ -44,34 +44,57 @@ export interface ApiErrorResponse {
export type ApiResponse<T = any> = ApiSuccessResponse<T> | ApiErrorResponse; export type ApiResponse<T = any> = ApiSuccessResponse<T> | ApiErrorResponse;
/** /**
* Selector for targeting specific providers, services, collections, or entities in list or extant operations. * Stream control start line.
*
* 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
* }
* }
* }
*/ */
export type SourceSelector = { export interface ApiStreamStartResponse {
[provider: string]: boolean | ServiceSelector; 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 * 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: * Values can be:
* - relative based on item identifier * - relative based on item identifier
* - absolute based on item count * - absolute based on item count
*/ */
export interface ListRange { export interface ListRangeTally {
type: 'tally'; type: 'tally';
anchor: 'relative' | 'absolute'; anchor: 'relative' | 'absolute';
position: string | number; position: string | number;
tally: number; tally: number;
} }
/**
* Date (pagination) range for list operations
*/
export interface ListRangeDate {
type: 'date';
start: number;
end: number;
}
/**
* Range for list operations
*/
export type ListRange = ListRangeTally | ListRangeDate;
+107 -56
View File
@@ -1,64 +1,86 @@
/** /**
* Entity type definitions * 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 { EventInterface } from './event';
import type { TaskInterface } from './task'; import type { TaskInterface } from './task';
import type { JournalInterface } from './journal'; import type { JournalInterface } from './journal';
import type { ImportDisposition, ImportFileOptions } from './import';
export type EntityPropertiesInterface = EventInterface | TaskInterface | JournalInterface;
/** /**
* Entity definition * Entity definition
*/ */
export interface EntityInterface<T = EventInterface | TaskInterface | JournalInterface> { export interface EntityInterface<T = EntityPropertiesInterface> {
'@type': string;
version: number;
provider: string; provider: string;
service: string; service: string;
collection: string | number; collection: CollectionIdentifier;
identifier: string | number; identifier: EntityIdentifier;
signature: string | null; signature: string | null;
created: string | null; created: string | null;
modified: string | null; modified: string | null;
properties: T; properties: T;
} }
export interface EntityModelInterface extends Omit<EntityInterface<EntityPropertiesInterface>, '@type' | 'version'> {}
/** /**
* Entity list * Entity list bulk
*/ */
export interface EntityListRequest { export interface EntityListBulkRequest {
sources?: SourceSelector; sources?: CollectionIdentifier[];
filter?: ListFilter; filter?: ListFilter;
sort?: ListSort; sort?: ListSort;
range?: ListRange; range?: ListRange;
} }
export interface EntityListResponse { export interface EntityListBulkResponse {
[providerId: string]: { [providerId: string]: {
[serviceId: string]: { [serviceId: string]: {
[collectionId: 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 * Entity fetch
*/ */
export interface EntityFetchRequest { export interface EntityFetchRequest {
provider: string; targets: EntityIdentifier[];
service: string | number;
collection: string | number;
identifiers: (string | number)[];
} }
export interface EntityFetchResponse { export interface EntityFetchResponse {
[identifier: string]: EntityInterface<EventInterface | TaskInterface | JournalInterface>; [identifier: string]: EntityInterface;
} }
/** /**
* Entity extant * Entity extant
*/ */
export interface EntityExtantRequest { export interface EntityExtantRequest {
sources: SourceSelector; targets: EntityIdentifier[];
} }
export interface EntityExtantResponse { 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 * Entity delta
*/ */
export interface EntityDeltaRequest { 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 { export interface EntityDeltaResponse {
@@ -128,4 +113,70 @@ export interface EntityDeltaResponse {
}; };
}; };
}; };
} }
/**
* Entity create
*/
export interface EntityCreateRequest<T = EntityPropertiesInterface> {
target: CollectionIdentifier;
properties: T;
options?: Record<string, any>;
}
export interface EntityCreateResponse<T = EntityPropertiesInterface> extends EntityInterface<T> {}
/**
* Entity update
*/
export interface EntityUpdateRequest<T = EntityPropertiesInterface> {
target: EntityIdentifier;
properties: T;
}
export interface EntityUpdateResponse<T = EntityPropertiesInterface> extends EntityInterface<T> {}
/**
* Entity delete
*/
export interface EntityDeleteRequest {
targets: EntityIdentifier[];
}
export interface EntityDeleteResponse {
[targetIdentifier: EntityIdentifier]: {
disposition: 'deleted' | 'moved' | 'error';
destination: CollectionIdentifier | null;
mutation: EntityIdentifier | null;
error?: string;
};
}
/**
* Entity move
*/
export interface EntityMoveRequest {
target: CollectionIdentifier;
sources: EntityIdentifier[];
}
export interface EntityMoveResponse {
[sourceIdentifier: EntityIdentifier]: {
disposition: 'moved' | 'error';
destination: CollectionIdentifier | null;
mutation: EntityIdentifier | null;
error?: string;
};
}
export interface EntityImportRequest {
target: CollectionIdentifier;
data: string;
options: ImportFileOptions;
}
export interface EntityImportResponse {
identifier: string | null;
disposition: ImportDisposition;
errors: string[];
}
+19
View File
@@ -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;
}
+2 -1
View File
@@ -3,6 +3,7 @@ export type * from './common';
export type * from './entity'; export type * from './entity';
export type * from './event'; export type * from './event';
export type * from './journal'; export type * from './journal';
export type * from './import';
export type * from './provider'; export type * from './provider';
export type * from './service'; export type * from './service';
export type * from './task'; export type * from './task';
+8 -6
View File
@@ -1,7 +1,7 @@
/** /**
* Provider type definitions * Provider type definitions
*/ */
import type { SourceSelector } from "./common"; import type { ProviderIdentifier } from './common';
/** /**
* Provider capabilities * Provider capabilities
@@ -28,22 +28,24 @@ export interface ProviderInterface {
capabilities: ProviderCapabilitiesInterface; capabilities: ProviderCapabilitiesInterface;
} }
export interface ProviderModelInterface extends Omit<ProviderInterface, '@type'> {}
/** /**
* Provider list * Provider list
*/ */
export interface ProviderListRequest { export interface ProviderListRequest {
sources?: SourceSelector; targets?: ProviderIdentifier[];
} }
export interface ProviderListResponse { export interface ProviderListResponse {
[identifier: string]: ProviderInterface; [identifier: ProviderIdentifier]: ProviderInterface;
} }
/** /**
* Provider fetch * Provider fetch
*/ */
export interface ProviderFetchRequest { export interface ProviderFetchRequest {
identifier: string; target: ProviderIdentifier;
} }
export interface ProviderFetchResponse extends ProviderInterface {} export interface ProviderFetchResponse extends ProviderInterface {}
@@ -52,9 +54,9 @@ export interface ProviderFetchResponse extends ProviderInterface {}
* Provider extant * Provider extant
*/ */
export interface ProviderExtantRequest { export interface ProviderExtantRequest {
sources: SourceSelector; targets: ProviderIdentifier[];
} }
export interface ProviderExtantResponse { export interface ProviderExtantResponse {
[identifier: string]: boolean; [identifier: ProviderIdentifier]: boolean;
} }
+17 -3
View File
@@ -1,7 +1,13 @@
/** /**
* Service type definitions * 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 * Service capabilities
@@ -47,11 +53,18 @@ export interface ServiceInterface {
auxiliary?: Record<string, any>; // Provider-specific extension data auxiliary?: Record<string, any>; // Provider-specific extension data
} }
export interface ServiceModelInterface extends Omit<{
[K in keyof ServiceInterface]-?: Exclude<ServiceInterface[K], undefined>;
}, '@type' | 'location' | 'identity'> {
location: Location | null;
identity: Identity | null;
}
/** /**
* Service list * Service list
*/ */
export interface ServiceListRequest { export interface ServiceListRequest {
sources?: SourceSelector; targets?: ServiceIdentifier[] | CollectionIdentifier[];
} }
export interface ServiceListResponse { export interface ServiceListResponse {
@@ -74,7 +87,7 @@ export interface ServiceFetchResponse extends ServiceInterface {}
* Service extant * Service extant
*/ */
export interface ServiceExtantRequest { export interface ServiceExtantRequest {
sources: SourceSelector; targets: ServiceIdentifier[];
} }
export interface ServiceExtantResponse { export interface ServiceExtantResponse {
@@ -99,6 +112,7 @@ export interface ServiceCreateResponse extends ServiceInterface {}
export interface ServiceUpdateRequest { export interface ServiceUpdateRequest {
provider: string; provider: string;
identifier: string | number; identifier: string | number;
delta?: boolean;
data: Partial<ServiceInterface>; data: Partial<ServiceInterface>;
} }
+30
View File
@@ -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)
})
})
+31
View File
@@ -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/**',
],
},
},
})
+29
View File
@@ -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));
}
}
+29
View File
@@ -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));
}
}
+17
View File
@@ -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);
}
+41
View File
@@ -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>