Import ISA Project Format 1.1.0
This commit is contained in:
@@ -0,0 +1,4 @@
|
|||||||
|
node_modules/
|
||||||
|
dist/
|
||||||
|
*.tgz
|
||||||
|
.DS_Store
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
# ISA Project format
|
||||||
|
|
||||||
|
Version 1 is a dashboard-backed `<name>.isap` folder containing `project.json`, `extensions/<extension-id>/` and `assets/`. The manifest contains `formatVersion: 1`, stable `id`, display `name`, and UTC `createdAt`/`updatedAt` timestamps. Canonical dashboard folder IDs are storage identities; names and paths do not grant access. Imports allocate a new identity and folder.
|
||||||
|
|
||||||
|
Extension namespaces organize data and are not permission boundaries. A project read-write grant permits supported edits across namespaces. Preserve unknown manifest fields, files and extension data. Each extension documents its canonical data; ISA Projects owns planning and detailed progress. Common summaries live in `extensions/<extension-id>/status.json` with `schemaVersion: 1`, `status` (`not-started`, `in-progress`, `blocked`, `complete`), `updatedAt`, and optional `completion` between 0 and 100. Summary data is editable project content and never grants publishing authority.
|
||||||
|
|
||||||
|
## Public APIs
|
||||||
|
|
||||||
|
The root export is framework-neutral ESM with TypeScript declarations. `@isa-warden/isa-project-format/dom` exports DOM mounting functions. `@isa-warden/isa-project-format/svelte` exports `ProjectWorkspace`, `ProjectHeader` and `ProjectPicker` components; Svelte is an optional peer for consumers of those components. Extension packages bundle these modules and the ZIP dependency at build time. No remote runtime imports are required.
|
||||||
|
|
||||||
|
```js
|
||||||
|
import { createProjectClient } from '@isa-warden/isa-project-format';
|
||||||
|
import { mountProjectWorkspace } from '@isa-warden/isa-project-format/dom';
|
||||||
|
|
||||||
|
const client = createProjectClient({
|
||||||
|
bridge,
|
||||||
|
extensionId: 'example',
|
||||||
|
projectCommands: appInfo.projects?.commands,
|
||||||
|
scope: { workspaceId, groupId }
|
||||||
|
});
|
||||||
|
const view = mountProjectWorkspace(target, { client, bridge, extensionName: 'Example', locale: 'en' });
|
||||||
|
// On extension teardown:
|
||||||
|
view.destroy();
|
||||||
|
await client.close();
|
||||||
|
```
|
||||||
|
|
||||||
|
The shared UI provides a searchable group project overview, recent activity, project creation, an active-project header, file/media browsing, transfer actions and a Tauri-compatible HTML confirmation for dirty project switches. English and Dutch labels are included. It inherits ISA extension theme tokens; detailed application workflows and planning remain in the extension. Components consume a captured client instance: remount with a new client when the launch context changes.
|
||||||
|
|
||||||
|
`client.activate(reference)` opens a listed or recent reference by reading its manifest through an existing grant. `client.create(name, operationId?)` uses host creation and retains its operation ID through uncertain retries in the current client. Callers with durable recovery journals should provide their persisted operation ID. Recent references are private, launch-scoped host preferences rather than canonical project state. Preference failures are observable on `session.preferenceError` and do not invalidate an already committed creation/switch.
|
||||||
|
|
||||||
|
Sessions capture their project path and abort signal. `readJson` returns an authoritative CAS base; `writeJson(relative, value, base, {operationId?})` requires that same file’s base and sends its revision/hash. `ensureDirectory(relative)` creates real parent directories in order; `openKv` does this for its parent before opening a store. `openKv`, `applyKv` and `subscribeKv` use the captured project destination. Use `extensionPath` for extension-owned paths, `publishStatus` for summaries and `readStatuses` for the overview. Subscriptions and registered cleanup callbacks close on switching; late results cannot use a retired session. Mark unsaved work with `session.markDirty()`. Without explicit confirmation, dirty sessions block switching. Mounting the shared UI supplies a confirmation; applications can provide `beforeSwitch` to integrate an existing save/discard workflow.
|
||||||
|
|
||||||
|
## Project start screen
|
||||||
|
|
||||||
|
Use the ISA Match layout for a project-based extension. Show recent activity on the left and **Projects** (**Projecten**) on the right. Place **+ Create project** at the top right of the Projects panel. Populate this list on launch with `await client.list()`, which returns active shared projects for the launch group, including ones this extension has never used. `client.recent()` supplies optional personal shortcuts. Use the project rows to open existing projects and the create button to launch the setup form.
|
||||||
|
|
||||||
|
Use the shared `ProjectWorkspace` or `mountProjectWorkspace` overview with the extension’s display name, locale and launch-scoped client. Pass `projectCommands: appInfo.projects?.commands` to the client. Custom overviews call `client.list()` and `client.openListed(row)`. Declare `projects_open_listed`, `projects_read` and `filesystem_read` for direct access. On older hosts the client reads the selected folder using its existing grant. If access is unavailable, the overview shows the error and keeps the project list available. Only explicit creation calls `client.create(name, operationId)`.
|
||||||
|
|
||||||
|
Every project extension initializes its own data when a writable project first opens. The client ensures the extension directory exists, and the extension opens its workspace with the stored data. For a JSON-backed workspace, call `await session.ensureExtensionJson('data/current.json', () => initialState(session.manifest.name))` using the extension’s canonical relative path and default schema. The result includes the saved JSON value and version. The helper creates missing parents, uses a create-only write, and reads the committed record even if another client created it. An absent record on a read-only or archived project returns `status: 'absent'`. Unavailable or malformed data raises an error.
|
||||||
|
|
||||||
|
For directory-backed collections, initialize the empty collection in the selected project. If the schema needs a default item, derive its UUID using `await defaultProjectRecordId(session.manifest.id, extensionId)` so simultaneous first opens use the same path. Users can add optional details or import content after the workspace opens.
|
||||||
|
|
||||||
|
## Specialist viewers for shared data
|
||||||
|
|
||||||
|
A supplier viewer and a price-book viewer can each open on their own dataset. ISA Match and other authorised extensions can display that same data. All readers use the existing file or KV store and its schema. The viewer’s extension ID does not determine ownership of the data.
|
||||||
|
|
||||||
|
Use `@isa-warden/isa-project-format/shared-folder` with a folder already authorised for the current launch. For data inside an open project, pass `scope: session.scope`, `folder: session.project` and `assertCurrent: session.assertCurrent`. For a separately shared register, use the host-authorised workspace folder and the immutable launch scope. Host grants are per package. Reopening a linked folder uses its valid grant. A new reader needs its own host authorisation for a folder outside the project.
|
||||||
|
|
||||||
|
```js
|
||||||
|
import { createSharedFolderReader } from '@isa-warden/isa-project-format/shared-folder';
|
||||||
|
|
||||||
|
const reader = createSharedFolderReader({ bridge, scope, folder, assertCurrent });
|
||||||
|
const index = await reader.readJson('isa-match-suppliers.json');
|
||||||
|
if (index.status === 'found') {
|
||||||
|
const register = index.value;
|
||||||
|
if (register.format !== 'isa-match-workspace-suppliers-v1' ||
|
||||||
|
register.workspaceId !== scope.workspaceId ||
|
||||||
|
typeof register.id !== 'string' || !register.id || !Array.isArray(register.suppliers)) {
|
||||||
|
throw new Error('Unexpected supplier register');
|
||||||
|
}
|
||||||
|
const id = encodeURIComponent(register.id);
|
||||||
|
// The supplier directory contains stable supplier IDs and public identities.
|
||||||
|
const suppliers = register.suppliers;
|
||||||
|
// The price-book viewer reads the published price rows from the same folder.
|
||||||
|
const snapshot = await reader.readKv('isa-match-prices-' + id + '.kv');
|
||||||
|
const prices = snapshot.entries.filter(entry => entry.key.startsWith('price/'));
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
For supplier details, read `isa-match-catalog-<encoded register ID>.kv` and the active generation in `catalog/meta`. Profiles use `catalog/<active>/supplier/<supplier ID>/profile`. Use the active generation to exclude retired and staged records. The prices KV contains the shared price book. The separate ISA Prijzenregister searches published records across the workspace. A viewer that only needs suppliers can skip the prices read entirely.
|
||||||
|
|
||||||
|
`listFiles()` lists the authorised directory. `readFile` and `readJson` distinguish authoritative absence from a failed read. `readKv` pages a consistent snapshot and checks store identity and revision across pages. These operations use the host’s filesystem or KV read access without creating files, modifying records or granting another extension access.
|
||||||
|
|
||||||
|
## ZIP transfer
|
||||||
|
|
||||||
|
`exportProject`, `importProject`, `exportProjectToDialog` and `importProjectFromDialog` use existing host file and KV transfer primitives. Exports include media and unknown files, and capture consistent live KV snapshots instead of stale checkpoint artifacts. A versioned `.isa-transfer.json` sidecar maps logical KV contents to their canonical paths; the KV files are rebuilt through host operations on import, retaining list item identities/order. Runtime grants, service approvals and credentials are not part of the transfer format. Imported audit fields are historical reference data; server-owned authorization remains outside the project.
|
||||||
|
|
||||||
|
Imports validate the whole ZIP and transfer metadata before creating a project. Validation rejects traversal, absolute/backslash paths, links, duplicate/case/Unicode path collisions, overlapping headers, malformed compression/CRC, unsupported versions and bounded decompression failures. Transfer limits may be lowered: default archive and total expanded data limits are 512 MiB, individual entries 256 MiB, and entry count 10,000. Media above 16 MiB uses the host’s authorized download link and a bounded streamed fetch, verifies the snapshot hash and size, then renews authorization before completing. Other host transport limits can still be lower; a failed read is an explicit transfer failure and is never silently omitted. Export checks file generations/inventory and live KV revisions again before producing an archive. Transfers fence cancellation with the captured session.
|
||||||
|
|
||||||
|
Run `npm run build` to check ESM syntax, compile-check Svelte components and execute the focused format, lifecycle and real ZIP regression suites. The shared UI and large-media transport still require native/browser integration validation as part of the complete extension release.
|
||||||
|
|
||||||
|
Before an export, supply `beforeExport(session)` to the transfer UI when an editor uses debounced saves. It must flush that captured session or reject; the library revalidates the session and dirty state before reading the archive. Late work must never target a replacement project session.
|
||||||
Generated
+235
@@ -0,0 +1,235 @@
|
|||||||
|
{
|
||||||
|
"name": "@isa-warden/isa-project-format",
|
||||||
|
"version": "1.1.0",
|
||||||
|
"lockfileVersion": 3,
|
||||||
|
"requires": true,
|
||||||
|
"packages": {
|
||||||
|
"": {
|
||||||
|
"name": "@isa-warden/isa-project-format",
|
||||||
|
"version": "1.1.0",
|
||||||
|
"dependencies": {
|
||||||
|
"fflate": "0.8.3"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"svelte": "5.57.3"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"svelte": "^5.0.0"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"svelte": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@jridgewell/gen-mapping": {
|
||||||
|
"version": "0.3.13",
|
||||||
|
"resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
|
||||||
|
"integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@jridgewell/sourcemap-codec": "^1.5.0",
|
||||||
|
"@jridgewell/trace-mapping": "^0.3.24"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@jridgewell/remapping": {
|
||||||
|
"version": "2.3.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz",
|
||||||
|
"integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@jridgewell/gen-mapping": "^0.3.5",
|
||||||
|
"@jridgewell/trace-mapping": "^0.3.24"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@jridgewell/resolve-uri": {
|
||||||
|
"version": "3.1.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",
|
||||||
|
"integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=6.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@jridgewell/sourcemap-codec": {
|
||||||
|
"version": "1.6.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz",
|
||||||
|
"integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/@jridgewell/trace-mapping": {
|
||||||
|
"version": "0.3.31",
|
||||||
|
"resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz",
|
||||||
|
"integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@jridgewell/resolve-uri": "^3.1.0",
|
||||||
|
"@jridgewell/sourcemap-codec": "^1.4.14"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@sveltejs/acorn-typescript": {
|
||||||
|
"version": "1.0.13",
|
||||||
|
"resolved": "https://registry.npmjs.org/@sveltejs/acorn-typescript/-/acorn-typescript-1.0.13.tgz",
|
||||||
|
"integrity": "sha512-wgKggnhZVL9Bfx1OaKKTrYY9BFRk6C8UAkQNUcIv1+llzYrIqy+RZm5HPKzn0NpEBvTVhTqB4kQyllZywsRBRQ==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"peerDependencies": {
|
||||||
|
"acorn": "^8.9.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@types/estree": {
|
||||||
|
"version": "1.0.10",
|
||||||
|
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.10.tgz",
|
||||||
|
"integrity": "sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/acorn": {
|
||||||
|
"version": "8.19.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.19.0.tgz",
|
||||||
|
"integrity": "sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"bin": {
|
||||||
|
"acorn": "bin/acorn"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=0.4.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/aria-query": {
|
||||||
|
"version": "5.3.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.1.tgz",
|
||||||
|
"integrity": "sha512-Z/ZeOgVl7bcSYZ/u/rh0fOpvEpq//LZmdbkXyc7syVzjPAhfOa9ebsdTSjEBDU4vs5nC98Kfduj1uFo0qyET3g==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/axobject-query": {
|
||||||
|
"version": "4.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-4.1.0.tgz",
|
||||||
|
"integrity": "sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/clsx": {
|
||||||
|
"version": "2.1.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz",
|
||||||
|
"integrity": "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=6"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/devalue": {
|
||||||
|
"version": "5.9.4",
|
||||||
|
"resolved": "https://registry.npmjs.org/devalue/-/devalue-5.9.4.tgz",
|
||||||
|
"integrity": "sha512-sPAT4pztbu6586/hrhOnMKS17IJrvg12mXiSPSS3W5qDeN2RGgvZ0diZCm31dBbnevfVmujNO3IM2wrS4Y2Rhg==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/esm-env": {
|
||||||
|
"version": "1.2.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/esm-env/-/esm-env-1.2.2.tgz",
|
||||||
|
"integrity": "sha512-Epxrv+Nr/CaL4ZcFGPJIYLWFom+YeV1DqMLHJoEd9SYRxNbaFruBwfEX/kkHUJf55j2+TUbmDcmuilbP1TmXHA==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/esrap": {
|
||||||
|
"version": "2.4.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/esrap/-/esrap-2.4.0.tgz",
|
||||||
|
"integrity": "sha512-CQPcneEHw/czj32uwQC52nYnax8H4SXt25FCM+LIwGZ49cMIxpOj3bP8wmzcI+Z0HIy5KkClaPhRLfCySzwHPA==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@jridgewell/sourcemap-codec": "^1.4.15"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"@typescript-eslint/types": "^8.2.0"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"@typescript-eslint/types": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/fflate": {
|
||||||
|
"version": "0.8.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.3.tgz",
|
||||||
|
"integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/is-reference": {
|
||||||
|
"version": "3.0.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/is-reference/-/is-reference-3.0.3.tgz",
|
||||||
|
"integrity": "sha512-ixkJoqQvAP88E6wLydLGGqCJsrFUnqoH6HnaczB8XmDH1oaWU+xxdptvikTgaEhtZ53Ky6YXiBuUI2WXLMCwjw==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@types/estree": "^1.0.6"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/locate-character": {
|
||||||
|
"version": "3.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/locate-character/-/locate-character-3.0.0.tgz",
|
||||||
|
"integrity": "sha512-SW13ws7BjaeJ6p7Q6CO2nchbYEc3X3J6WrmTTDto7yMPqVSZTUyY5Tjbid+Ab8gLnATtygYtiDIJGQRRn2ZOiA==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/magic-string": {
|
||||||
|
"version": "0.30.21",
|
||||||
|
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",
|
||||||
|
"integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@jridgewell/sourcemap-codec": "^1.5.5"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/svelte": {
|
||||||
|
"version": "5.57.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/svelte/-/svelte-5.57.3.tgz",
|
||||||
|
"integrity": "sha512-5mAftM3SoDV9X0zdF386F9p2pv8iKOwi/KfBS1XnBAkVCKFzVOLHUoa8iGWAt4buoicLmyWVRpuuD5wplXOQsg==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@jridgewell/remapping": "^2.3.5",
|
||||||
|
"@jridgewell/sourcemap-codec": "^1.6.0",
|
||||||
|
"@sveltejs/acorn-typescript": "^1.0.13",
|
||||||
|
"@types/estree": "^1.0.9",
|
||||||
|
"acorn": "^8.18.0",
|
||||||
|
"aria-query": "5.3.1",
|
||||||
|
"axobject-query": "^4.1.0",
|
||||||
|
"clsx": "^2.1.1",
|
||||||
|
"devalue": "^5.9.2",
|
||||||
|
"esm-env": "^1.2.1",
|
||||||
|
"esrap": "^2.3.6",
|
||||||
|
"is-reference": "^3.0.3",
|
||||||
|
"locate-character": "^3.0.0",
|
||||||
|
"magic-string": "^0.30.11",
|
||||||
|
"zimmerframe": "^1.1.2"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/zimmerframe": {
|
||||||
|
"version": "1.1.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/zimmerframe/-/zimmerframe-1.1.5.tgz",
|
||||||
|
"integrity": "sha512-msJxIvYDYcoNL+PJsu+7qmpDWsYmAxTY+2TNYXXF0hzBzBk0BMecOqDOG/EckUoKCuKwObfbugIl8QpqHDXeFA==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
{
|
||||||
|
"name": "@isa-warden/isa-project-format",
|
||||||
|
"version": "1.1.0",
|
||||||
|
"type": "module",
|
||||||
|
"exports": {
|
||||||
|
".": {
|
||||||
|
"types": "./src/index.d.ts",
|
||||||
|
"import": "./src/index.js"
|
||||||
|
},
|
||||||
|
"./shared-folder": {
|
||||||
|
"types": "./src/shared-folder.d.ts",
|
||||||
|
"import": "./src/shared-folder.js"
|
||||||
|
},
|
||||||
|
"./dom": {
|
||||||
|
"types": "./src/dom.d.ts",
|
||||||
|
"import": "./src/dom.js"
|
||||||
|
},
|
||||||
|
"./svelte": {
|
||||||
|
"import": "./src/components/index.js"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"files": [
|
||||||
|
"src",
|
||||||
|
"README.md"
|
||||||
|
],
|
||||||
|
"scripts": {
|
||||||
|
"test": "node --test",
|
||||||
|
"build": "node scripts/build.mjs && npm test"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"fflate": "0.8.3"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"svelte": "5.57.3"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"svelte": "^5.0.0"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"svelte": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
import {readdir,readFile} from 'node:fs/promises';
|
||||||
|
import {fileURLToPath} from 'node:url';
|
||||||
|
import {execFileSync} from 'node:child_process';
|
||||||
|
import {compile} from 'svelte/compiler';
|
||||||
|
const root=new URL('../',import.meta.url);
|
||||||
|
async function validate(directory) {
|
||||||
|
for(const entry of await readdir(directory,{withFileTypes:true})) {
|
||||||
|
const path=new URL(entry.name,directory);
|
||||||
|
if(entry.isDirectory()){await validate(new URL(`${entry.name}/`,directory));continue;}
|
||||||
|
if(entry.name.endsWith('.js')&&!fileURLToPath(path).includes('/components/index.js'))execFileSync(process.execPath,['--check',fileURLToPath(path)]);
|
||||||
|
if(entry.name.endsWith('.svelte'))compile(await readFile(path,'utf8'),{filename:fileURLToPath(path),generate:'client'});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await validate(new URL('src/',root));
|
||||||
|
console.log('ESM and Svelte components validated');
|
||||||
+339
@@ -0,0 +1,339 @@
|
|||||||
|
import { confirmedWrite } from './proofs.js';
|
||||||
|
import { ProjectUnavailableError, readAuthoritativeFile } from './shared-read.js';
|
||||||
|
export { ProjectUnavailableError } from './shared-read.js';
|
||||||
|
import { parseProjectManifest, extensionDataPath, validateArchivePath } from './format.js';
|
||||||
|
|
||||||
|
const RECENTS_KEY = 'isa-project-format.recents.v1';
|
||||||
|
const abortError = () => new DOMException('Project session changed', 'AbortError');
|
||||||
|
function reference(value) {
|
||||||
|
if (!value || typeof value !== 'object') throw new TypeError('Project reference required');
|
||||||
|
const id = value.folderId ?? value.id;
|
||||||
|
const path = value.path;
|
||||||
|
if (typeof id !== 'string' || !id || typeof path !== 'string' || !path.startsWith('/') || !path.endsWith('.isap')) throw new TypeError('Invalid project folder');
|
||||||
|
validateArchivePath(path.slice(1));
|
||||||
|
return { id, folderId: id, path, name: String(value.name ?? ''),
|
||||||
|
archived: Boolean(value.archived), updatedAt: value.updatedAt, canWrite: value.canWrite,
|
||||||
|
projectIdentity: String(value.projectIdentity ?? id), manifestPath: `${path}/project.json`, formatVersion: 1 };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createProjectClient({ bridge, extensionId, scope, projectCommands, beforeSwitch, isCurrent = () => true }) {
|
||||||
|
if (!bridge || typeof bridge.invoke !== 'function') throw new TypeError('Host bridge required');
|
||||||
|
if (!scope?.workspaceId || !scope?.groupId) throw new TypeError('Dashboard workspace and launch group required');
|
||||||
|
extensionDataPath(extensionId, 'validate.json');
|
||||||
|
const captured = Object.freeze({ workspaceId: scope.workspaceId, groupId: scope.groupId });
|
||||||
|
let active = null, recents = [], generation = 0, closed = false;
|
||||||
|
let preferenceWrites = Promise.resolve();
|
||||||
|
const listeners = new Set();
|
||||||
|
const confirmationHandlers = [];
|
||||||
|
const pendingCreations = new Map();
|
||||||
|
const sessions = new Set();
|
||||||
|
const staged = new Map();
|
||||||
|
const state = () => Object.freeze({ active, recents: structuredClone(recents) });
|
||||||
|
const notify = () => { for (const listener of listeners) listener(state()); };
|
||||||
|
const guard = () => { if (closed || !isCurrent()) throw abortError(); };
|
||||||
|
const invoke = async (command, args = {}) => {
|
||||||
|
guard();
|
||||||
|
const value = await bridge.invoke(command, { ...args, ...captured });
|
||||||
|
guard();
|
||||||
|
return value;
|
||||||
|
};
|
||||||
|
const loadRecents = async () => {
|
||||||
|
guard();
|
||||||
|
// Host private settings are already bound to the immutable account and launch scope.
|
||||||
|
const ticket = generation;
|
||||||
|
await preferenceWrites;
|
||||||
|
const saved = await bridge.invoke('localstorage_get', {key: RECENTS_KEY, sync: false});
|
||||||
|
guard();
|
||||||
|
if (ticket !== generation) throw abortError();
|
||||||
|
if (saved != null && !Array.isArray(saved)) throw new TypeError('Invalid recent project settings');
|
||||||
|
recents = (saved ?? []).slice(0, 20).map(reference);
|
||||||
|
notify();
|
||||||
|
return structuredClone(recents);
|
||||||
|
};
|
||||||
|
async function remember(project) {
|
||||||
|
recents = [reference(project), ...recents.filter(item => item.id !== project.id)].slice(0, 20);
|
||||||
|
notify();
|
||||||
|
const snapshot = structuredClone(recents);
|
||||||
|
preferenceWrites = preferenceWrites.catch(() => {}).then(() => bridge.invoke('localstorage_put', {key: RECENTS_KEY, value: snapshot, sync: false}));
|
||||||
|
await preferenceWrites;
|
||||||
|
guard();
|
||||||
|
}
|
||||||
|
const read = (path, sessionGuard = guard) => readAuthoritativeFile(invoke,path,sessionGuard);
|
||||||
|
async function loadProject(value, check) {
|
||||||
|
check();
|
||||||
|
const project = reference(value);
|
||||||
|
const snapshot = await read(project.manifestPath, check);
|
||||||
|
if (snapshot.status !== 'found' || typeof snapshot.text !== 'string') throw new ProjectUnavailableError('Project manifest missing');
|
||||||
|
const manifest = parseProjectManifest(JSON.parse(snapshot.text));
|
||||||
|
if (manifest.id !== project.projectIdentity) throw new Error('Project manifest identity differs from its host folder');
|
||||||
|
return {project, manifest, snapshot};
|
||||||
|
}
|
||||||
|
function checkTransition(ticket) {
|
||||||
|
guard();
|
||||||
|
if (ticket !== generation) throw abortError();
|
||||||
|
}
|
||||||
|
async function approveSwitch(session) {
|
||||||
|
const confirm = beforeSwitch ?? confirmationHandlers.at(-1);
|
||||||
|
if (session?.dirty && (!confirm || await confirm(session) !== true)) {
|
||||||
|
throw new Error('Unsaved project changes must be saved or explicitly discarded');
|
||||||
|
}
|
||||||
|
guard();
|
||||||
|
}
|
||||||
|
function beginTransition(keep) {
|
||||||
|
const ticket=++generation;
|
||||||
|
for(const session of [...staged.keys()])if(session!==keep)void session.close();
|
||||||
|
if(keep)staged.get(keep).ticket=ticket;
|
||||||
|
return ticket;
|
||||||
|
}
|
||||||
|
async function switchTo(acquire, approved, keep) {
|
||||||
|
guard();
|
||||||
|
const ticket = beginTransition(keep);
|
||||||
|
const previous = active;
|
||||||
|
const dirtyVersion = previous?.dirtyVersion;
|
||||||
|
if(!approved || approved.session!==previous || approved.version!==dirtyVersion)await approveSwitch(previous);
|
||||||
|
if (ticket !== generation) throw abortError();
|
||||||
|
const check = () => checkTransition(ticket);
|
||||||
|
const selected = await acquire(check);
|
||||||
|
check();
|
||||||
|
const {project, manifest, snapshot} = selected;
|
||||||
|
const next = makeSession(project, manifest, snapshot);
|
||||||
|
staged.set(next, {ticket});
|
||||||
|
try {
|
||||||
|
if (project.canWrite === true && !project.archived) {
|
||||||
|
const namespace = `extensions/${extensionId}`;
|
||||||
|
const folders = await next.listFiles('extensions', false);
|
||||||
|
if (!folders.some(row => row.kind === 'folder' && row.path === next.path(namespace))) {
|
||||||
|
await next.ensureDirectory(namespace);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
check();
|
||||||
|
if (active !== previous || previous?.dirtyVersion !== dirtyVersion) await approveSwitch(active);
|
||||||
|
check();
|
||||||
|
} catch (error) {
|
||||||
|
await next.close();
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
staged.delete(next);
|
||||||
|
const retiring = active;
|
||||||
|
active = null; notify();
|
||||||
|
await retiring?.close();
|
||||||
|
if (ticket !== generation) { await next.close(); throw abortError(); }
|
||||||
|
active = next;
|
||||||
|
notify();
|
||||||
|
// A preference write cannot invalidate a committed creation or switch.
|
||||||
|
try { await remember(project); } catch (error) { next.preferenceError = error; notify(); }
|
||||||
|
if (ticket !== generation) throw abortError();
|
||||||
|
return next;
|
||||||
|
}
|
||||||
|
function makeSession(project, manifest, manifestSnapshot) {
|
||||||
|
const controller = new AbortController();
|
||||||
|
const cleanups = new Set();
|
||||||
|
let sessionClosed = false, dirty = false, dirtyVersion = 0;
|
||||||
|
const sessionGuard = () => { guard(); if (sessionClosed || controller.signal.aborted || staged.has(session) && staged.get(session).ticket !== generation) throw abortError(); };
|
||||||
|
const path = relative => `${project.path}/${validateArchivePath(relative)}`;
|
||||||
|
async function call(command, args) {
|
||||||
|
sessionGuard();
|
||||||
|
const value = await invoke(command, args);
|
||||||
|
sessionGuard();
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
const session = {
|
||||||
|
scope: captured, project: Object.freeze({...project}), manifest: structuredClone(manifest), manifestSnapshot,
|
||||||
|
signal: controller.signal, preferenceError: null,
|
||||||
|
get dirty() { return dirty; }, get dirtyVersion() { return dirtyVersion; },
|
||||||
|
markDirty(value = true) { sessionGuard(); dirty = value; dirtyVersion++; notify(); },
|
||||||
|
path, extensionPath: relative => path(extensionDataPath(extensionId, relative)),
|
||||||
|
assertCurrent: sessionGuard,
|
||||||
|
track(cleanup) { sessionGuard(); cleanups.add(cleanup); return () => cleanups.delete(cleanup); },
|
||||||
|
async readFile(relative) { return read(path(relative), sessionGuard); },
|
||||||
|
async readJson(relative) {
|
||||||
|
const item = await read(path(relative), sessionGuard);
|
||||||
|
return item.status === 'absent' ? item : {...item, value: JSON.parse(item.text)};
|
||||||
|
},
|
||||||
|
async ensureExtensionJson(relative, makeDefault) {
|
||||||
|
const file = extensionDataPath(extensionId, relative);
|
||||||
|
const base = await session.readJson(file);
|
||||||
|
if (base.status === 'found' || project.canWrite === false || project.archived) return base;
|
||||||
|
const value = await makeDefault();
|
||||||
|
await session.ensureDirectory(file.slice(0, file.lastIndexOf('/')));
|
||||||
|
try {
|
||||||
|
await session.writeJson(file, value, base);
|
||||||
|
} catch (error) {
|
||||||
|
// A competing creator or a lost acknowledgement may have committed the file.
|
||||||
|
const current = await session.readJson(file);
|
||||||
|
if (current.status === 'found') return current;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
const current = await session.readJson(file);
|
||||||
|
if (current.status !== 'found') throw new ProjectUnavailableError('Created project file could not be read');
|
||||||
|
return current;
|
||||||
|
},
|
||||||
|
async writeJson(relative, value, base, options = {}) {
|
||||||
|
sessionGuard();
|
||||||
|
if (!base || base.path !== path(relative) || !['found','absent'].includes(base.status)) throw new TypeError('An authoritative read of this project file is required before writing');
|
||||||
|
if (base.status === 'found' && (!base.fileId || base.authoritative !== true || !Number.isSafeInteger(base.syncRevision) || base.syncRevision < 0)) throw new TypeError('Replacement requires authoritative file identity');
|
||||||
|
if(options.operationId !== undefined && (typeof options.operationId !== 'string' || !/^[0-9a-f]{64}$/.test(options.operationId)))throw new TypeError('Invalid project write operation identity');
|
||||||
|
const result = await call('filesystem_upload_files', {files:[{
|
||||||
|
path:path(relative),text:JSON.stringify(value),contentType:'application/json',replaceExisting:base.status === 'found',
|
||||||
|
...(base.status === 'found' ? {expectedSyncRevision:base.syncRevision,expectedContentHash:base.contentHash} : {}),
|
||||||
|
metadata:{projectId:project.projectIdentity,client_operation_id:options.operationId ?? await operationId()}
|
||||||
|
}]});
|
||||||
|
return confirmedWrite(result,path(relative));
|
||||||
|
},
|
||||||
|
async listFiles(relative = '', recursive = true) {
|
||||||
|
const result = await call('filesystem_list_dir', {path:relative ? path(relative) : project.path,recursive,cachePolicy:'dashboard-required'});
|
||||||
|
if (result?.authoritative !== true || !Array.isArray(result.files) || result.snapshotComplete === false || result.error) throw new ProjectUnavailableError('Project inventory unavailable');
|
||||||
|
return result.files;
|
||||||
|
},
|
||||||
|
async publishStatus(summary, base) {
|
||||||
|
if (!['not-started','in-progress','blocked','complete'].includes(summary?.status)) throw new TypeError('Invalid extension project status');
|
||||||
|
if (summary.completion !== undefined && (typeof summary.completion !== 'number' || !Number.isFinite(summary.completion) || summary.completion < 0 || summary.completion > 100)) throw new TypeError('Completion must be between 0 and 100');
|
||||||
|
const relative = extensionDataPath(extensionId, 'status.json');
|
||||||
|
base ??= await session.readJson(relative);
|
||||||
|
if (base.status === 'found' && base.value.schemaVersion !== 1) throw new Error('Unsupported extension status format');
|
||||||
|
const value = {...(base.value ?? {}),schemaVersion:1,status:summary.status,updatedAt:new Date().toISOString()};
|
||||||
|
if (summary.completion !== undefined) value.completion=summary.completion; else delete value.completion;
|
||||||
|
return session.writeJson(relative,value,base);
|
||||||
|
},
|
||||||
|
async readStatuses() {
|
||||||
|
const entries = (await session.listFiles('extensions',true)).filter(file => file.kind === 'file' && /^extensions\/[^/]+\/status\.json$/.test(file.path.slice(project.path.length+1)));
|
||||||
|
return Promise.all(entries.map(async file => {
|
||||||
|
const relative=file.path.slice(project.path.length+1);
|
||||||
|
const owner=relative.split('/')[1];
|
||||||
|
try {
|
||||||
|
const snapshot=await session.readJson(relative);
|
||||||
|
if(snapshot.status!=='found' || snapshot.value.schemaVersion!==1) throw new Error('Unsupported extension status format');
|
||||||
|
return {...snapshot.value,extensionId:owner};
|
||||||
|
} catch(error) {sessionGuard();return {extensionId:owner,unavailable:true,error:String(error.message ?? error)};}
|
||||||
|
}));
|
||||||
|
},
|
||||||
|
async ensureDirectory(relative) {
|
||||||
|
const parts=validateArchivePath(relative).split('/');
|
||||||
|
for(let depth=1;depth<=parts.length;depth++) {
|
||||||
|
const directory=path(parts.slice(0,depth).join('/'));
|
||||||
|
try {
|
||||||
|
const reply=await call('filesystem_create_folder',{path:directory});
|
||||||
|
if(reply?.status!=='ok'||reply.path!==directory||typeof reply.fileId!=='string'||!reply.fileId)throw new ProjectUnavailableError('Project directory creation was not confirmed');
|
||||||
|
} catch (error) {
|
||||||
|
sessionGuard();
|
||||||
|
const parent = parts.slice(0, depth - 1).join('/');
|
||||||
|
const siblings = await session.listFiles(parent, false);
|
||||||
|
if (!siblings.some(row => row.path === directory && row.kind === 'folder' && row.canWrite !== false && (row.fileId || row.id))) throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
async openKv(relative, options = {}) {
|
||||||
|
const canonical=validateArchivePath(relative);
|
||||||
|
const separator=canonical.lastIndexOf('/');
|
||||||
|
if(separator>=0)await session.ensureDirectory(canonical.slice(0,separator));
|
||||||
|
return call('kv_store_open', {...options,path:path(canonical)});
|
||||||
|
},
|
||||||
|
async applyKv(relative, mutation) {
|
||||||
|
sessionGuard();
|
||||||
|
if (typeof bridge.applyKv !== 'function') throw new Error('Host KV transfer helper unavailable');
|
||||||
|
const reply = await bridge.applyKv({...mutation,...captured,path:path(relative)});
|
||||||
|
sessionGuard(); return reply;
|
||||||
|
},
|
||||||
|
async subscribeKv(relative, args, onChange) {
|
||||||
|
sessionGuard();
|
||||||
|
if (typeof bridge.subscribeKv !== 'function') throw new Error('Host KV subscriptions unavailable');
|
||||||
|
const subscription = await bridge.subscribeKv({...args,...captured,path:path(relative)}, value => {
|
||||||
|
if (!closed && !sessionClosed && !controller.signal.aborted && isCurrent()) onChange(value);
|
||||||
|
});
|
||||||
|
if (closed || sessionClosed || controller.signal.aborted || !isCurrent()) { await subscription.unsubscribe(); throw abortError(); }
|
||||||
|
cleanups.add(subscription.unsubscribe);
|
||||||
|
return subscription;
|
||||||
|
},
|
||||||
|
async close() {
|
||||||
|
if (sessionClosed) return;
|
||||||
|
sessionClosed = true; controller.abort(); sessions.delete(session); staged.delete(session);
|
||||||
|
const tasks = [...cleanups]; cleanups.clear();
|
||||||
|
const results = await Promise.allSettled(tasks.map(cleanup => Promise.resolve().then(cleanup)));
|
||||||
|
const failures = results.filter(result => result.status === 'rejected');
|
||||||
|
if (failures.length) session.cleanupErrors = failures.map(result => result.reason);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
sessions.add(session);
|
||||||
|
return session;
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
scope: captured, extensionId,
|
||||||
|
supports(command) { return !projectCommands || projectCommands.includes(command); },
|
||||||
|
get active() { return active; }, get state() { return state(); },
|
||||||
|
provideSwitchConfirmation(handler) {
|
||||||
|
confirmationHandlers.push(handler);
|
||||||
|
return () => { const index=confirmationHandlers.indexOf(handler); if(index>=0)confirmationHandlers.splice(index,1); };
|
||||||
|
},
|
||||||
|
subscribe(listener) { listeners.add(listener); listener(state()); return () => listeners.delete(listener); },
|
||||||
|
recent: loadRecents,
|
||||||
|
async list(includeArchived = false) { const result = await invoke('projects_list', {includeArchived}); return result.projects.map(reference); },
|
||||||
|
async create(name, operationId) {
|
||||||
|
if(typeof name !== 'string' || !name.trim())throw new TypeError('Project name required');
|
||||||
|
name=name.trim();
|
||||||
|
operationId ??= pendingCreations.get(name) ?? crypto.randomUUID();
|
||||||
|
pendingCreations.set(name,operationId);
|
||||||
|
const session=await switchTo(async check => loadProject((await invoke('projects_create',{name,operationId})).project, check));
|
||||||
|
if(pendingCreations.get(name)===operationId)pendingCreations.delete(name);
|
||||||
|
return session;
|
||||||
|
},
|
||||||
|
async stageCreate(name, operationId) {
|
||||||
|
guard(); const ticket=beginTransition(); const previous=active; const version=previous?.dirtyVersion;
|
||||||
|
await approveSwitch(previous); if(ticket!==generation)throw abortError();
|
||||||
|
if(typeof name!=='string'||!name.trim())throw new TypeError('Project name required');name=name.trim();
|
||||||
|
operationId ??= pendingCreations.get(name) ?? crypto.randomUUID();pendingCreations.set(name,operationId);
|
||||||
|
const created = await invoke('projects_create',{name,operationId});
|
||||||
|
const {project, manifest, snapshot} = await loadProject(created.project, () => checkTransition(ticket));
|
||||||
|
const session=makeSession(project,manifest,snapshot);staged.set(session,{ticket,session:previous,version,name,operationId});
|
||||||
|
return session;
|
||||||
|
},
|
||||||
|
async adopt(session) {
|
||||||
|
guard(); const approval=staged.get(session);
|
||||||
|
if(!approval||approval.ticket!==generation)throw abortError();session.assertCurrent();
|
||||||
|
try {
|
||||||
|
const current=await switchTo(check=>loadProject(session.project,check),approval,session);
|
||||||
|
if(pendingCreations.get(approval.name)===approval.operationId)pendingCreations.delete(approval.name);
|
||||||
|
return current;
|
||||||
|
} finally {await session.close();}
|
||||||
|
},
|
||||||
|
openListed(value) {
|
||||||
|
const selected = reference(value);
|
||||||
|
return switchTo(async check => {
|
||||||
|
const commands = projectCommands ?? (await invoke('get_app_info')).projects?.commands;
|
||||||
|
check();
|
||||||
|
if (!commands?.includes('projects_open_listed')) return loadProject(selected, check);
|
||||||
|
const result = await bridge.invoke('projects_open_listed', {projectId: selected.id});
|
||||||
|
check();
|
||||||
|
if (result?.status !== 'ok' || result.project?.id !== selected.id) {
|
||||||
|
throw new ProjectUnavailableError('Selected project identity could not be confirmed');
|
||||||
|
}
|
||||||
|
const granted = reference(result.project);
|
||||||
|
if (granted.folderId !== selected.id || granted.projectIdentity !== selected.projectIdentity) {
|
||||||
|
throw new ProjectUnavailableError('Selected project identity could not be confirmed');
|
||||||
|
}
|
||||||
|
return loadProject(granted, check);
|
||||||
|
});
|
||||||
|
},
|
||||||
|
activate(project) { return switchTo(check => loadProject(project, check)); },
|
||||||
|
async share(targetGroupId, linked) {
|
||||||
|
if (!active) throw new Error('Select a project');
|
||||||
|
const capturedSession = active; capturedSession.assertCurrent();
|
||||||
|
const result = await invoke('projects_set_group_link',{projectId:capturedSession.project.id,targetGroupId,linked});
|
||||||
|
capturedSession.assertCurrent(); return result;
|
||||||
|
},
|
||||||
|
async leave() {
|
||||||
|
guard(); const ticket=beginTransition(); const previous=active;
|
||||||
|
await approveSwitch(previous);
|
||||||
|
if(ticket!==generation)throw abortError();
|
||||||
|
active=null; notify(); await previous?.close();
|
||||||
|
},
|
||||||
|
async close() {
|
||||||
|
if (closed) return; closed = true; generation++;
|
||||||
|
active = null; await Promise.allSettled([...sessions].map(session=>session.close())); notify(); listeners.clear(); confirmationHandlers.length=0;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function operationId() {
|
||||||
|
const hash = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(crypto.randomUUID()));
|
||||||
|
return Array.from(new Uint8Array(hash), byte => byte.toString(16).padStart(2,'0')).join('');
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
<script>
|
||||||
|
import ProjectWorkspace from './ProjectWorkspace.svelte';
|
||||||
|
let {client,bridge,extensionName,locale='en',beforeExport}=$props();
|
||||||
|
</script>
|
||||||
|
<ProjectWorkspace {client} {bridge} {extensionName} {locale} {beforeExport} mode="header" />
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
<script>
|
||||||
|
import ProjectWorkspace from './ProjectWorkspace.svelte';
|
||||||
|
let {client,bridge,extensionName,locale='en'}=$props();
|
||||||
|
</script>
|
||||||
|
<ProjectWorkspace {client} {bridge} {extensionName} {locale} mode="picker" />
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
<script>
|
||||||
|
import { onMount } from 'svelte';
|
||||||
|
import { mountProjectWorkspace } from '../dom.js';
|
||||||
|
let {client,bridge,extensionName,locale='en',beforeExport,mode='workspace'}=$props();
|
||||||
|
let target;
|
||||||
|
onMount(()=>{const view=mountProjectWorkspace(target,{client,bridge,extensionName,locale,mode,beforeExport});return()=>view.destroy();});
|
||||||
|
</script>
|
||||||
|
<div bind:this={target}></div>
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
export {default as ProjectWorkspace} from './ProjectWorkspace.svelte';
|
||||||
|
export {default as ProjectHeader} from './ProjectHeader.svelte';
|
||||||
|
export {default as ProjectPicker} from './ProjectPicker.svelte';
|
||||||
Vendored
+8
@@ -0,0 +1,8 @@
|
|||||||
|
import type { ProjectClient, ProjectBridge, ProjectSession } from './index.js';
|
||||||
|
export interface ProjectMountOptions {
|
||||||
|
extensionName?: string; client: ProjectClient; bridge?: ProjectBridge; locale?: 'en' | 'nl';
|
||||||
|
beforeExport?: (session: ProjectSession) => void | Promise<void>;
|
||||||
|
mode?: 'workspace' | 'picker' | 'header';
|
||||||
|
}
|
||||||
|
export function mountProjectWorkspace(target: HTMLElement, options: ProjectMountOptions): {destroy(): void};
|
||||||
|
export function mountProjectHeader(target: HTMLElement, options: ProjectMountOptions): {destroy(): void};
|
||||||
+126
@@ -0,0 +1,126 @@
|
|||||||
|
import { mountOverview } from './overview.js';
|
||||||
|
import { labels } from './labels.js';
|
||||||
|
import { exportProjectToDialog, importProjectFromDialog } from './transfer.js';
|
||||||
|
import { styles } from './styles.js';
|
||||||
|
|
||||||
|
export function mountProjectWorkspace(target, {client,bridge,locale='en',extensionName,mode='workspace',beforeExport} = {}) {
|
||||||
|
if (!target?.ownerDocument || !client) throw new TypeError('Mount target and project client required');
|
||||||
|
const document = target.ownerDocument;
|
||||||
|
const text = labels[locale] ?? labels.en;
|
||||||
|
const shell = document.createElement('section'); shell.className='isa-project-ui';
|
||||||
|
const style = document.createElement('style'); style.textContent=styles;
|
||||||
|
const content = document.createElement('div');
|
||||||
|
const preview = document.createElement('div'); preview.className='isa-project-preview';
|
||||||
|
shell.append(style,content,preview);target.append(shell);
|
||||||
|
let mounted=true,busy=false,error='',files=[],directory='',fileLoading=false,loadGeneration=0,shownSession=null;
|
||||||
|
let removeOverview;
|
||||||
|
const dialogs = new Set();
|
||||||
|
const make = (tag,textContent,className) => {
|
||||||
|
const element=document.createElement(tag);
|
||||||
|
if (textContent != null) element.textContent=textContent;
|
||||||
|
if (className) element.className=className;
|
||||||
|
return element;
|
||||||
|
};
|
||||||
|
function button(label,action) {
|
||||||
|
const element=make('button',label,'isa-extension-button');element.type='button';element.disabled=busy;
|
||||||
|
element.addEventListener('click',()=>perform(action));return element;
|
||||||
|
}
|
||||||
|
async function perform(action) {
|
||||||
|
if (busy || !mounted) return;
|
||||||
|
busy=true;error='';render();
|
||||||
|
try {await action();} catch(failure) {if (failure?.name!=='AbortError') error=String(failure.message ?? failure);}
|
||||||
|
finally {if(mounted){busy=false;render();}}
|
||||||
|
}
|
||||||
|
function confirmDiscard() {
|
||||||
|
return new Promise(resolve=>{
|
||||||
|
const dialog=make('dialog');
|
||||||
|
const question=make('p',text.dirty);question.id=`isa-project-confirm-${crypto.randomUUID()}`;
|
||||||
|
dialog.setAttribute('aria-labelledby',question.id);
|
||||||
|
const actions=make('div',null,'isa-project-toolbar');
|
||||||
|
const cancel=make('button',text.cancel);cancel.type='button';cancel.onclick=()=>dialog.close('cancel');
|
||||||
|
const discard=make('button',text.discard);discard.type='button';discard.onclick=()=>dialog.close('discard');
|
||||||
|
actions.append(cancel,discard);dialog.append(question,actions);shell.append(dialog);dialogs.add(dialog);
|
||||||
|
dialog.addEventListener('close',()=>{dialogs.delete(dialog);dialog.remove();resolve(dialog.returnValue==='discard');},{once:true});
|
||||||
|
dialog.showModal();cancel.focus();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const removeConfirmation = client.provideSwitchConfirmation(confirmDiscard);
|
||||||
|
async function loadFiles(session,relative='') {
|
||||||
|
const ticket=++loadGeneration;
|
||||||
|
directory=relative;files=[];fileLoading=true;render();
|
||||||
|
try {
|
||||||
|
const result=await session.listFiles(relative,false);
|
||||||
|
if (!mounted || ticket!==loadGeneration || client.active!==session) return;
|
||||||
|
files=result.filter(file=>file.path !== (relative?session.path(relative):session.project.path));
|
||||||
|
} catch(failure) {if(mounted&&ticket===loadGeneration&&failure?.name!=='AbortError') error=String(failure.message ?? failure);}
|
||||||
|
finally {if(mounted&&ticket===loadGeneration){fileLoading=false;render();}}
|
||||||
|
}
|
||||||
|
async function showFile(session,file) {
|
||||||
|
const relative=file.path.slice(session.project.path.length+1);
|
||||||
|
const mime=file.contentType ?? '';
|
||||||
|
let element;
|
||||||
|
if (/^(audio|video|image)\//.test(mime)) {
|
||||||
|
if(!bridge) throw new Error('Media bridge unavailable');
|
||||||
|
const reply=await bridge.invoke('filesystem_get_download_link_file',{...session.scope,path:session.path(relative)});
|
||||||
|
session.assertCurrent();
|
||||||
|
const url=new URL(reply.downloadUrl);
|
||||||
|
if(!['http:','https:'].includes(url.protocol)) throw new Error('Unsupported project media URL');
|
||||||
|
element=make(mime.startsWith('audio/')?'audio':mime.startsWith('video/')?'video':'img');
|
||||||
|
element.src=url.toString();
|
||||||
|
if(element.tagName==='IMG') element.alt=file.name; else element.controls=true;
|
||||||
|
} else {
|
||||||
|
const reply=await session.readFile(relative);
|
||||||
|
session.assertCurrent();
|
||||||
|
if(reply.status!=='found'||typeof reply.text!=='string') throw new Error('File preview unavailable');
|
||||||
|
element=make('pre',reply.text);
|
||||||
|
}
|
||||||
|
if(mounted&&client.active===session) {clearPreview();preview.append(element);}
|
||||||
|
}
|
||||||
|
function clearPreview() {
|
||||||
|
for(const media of preview.querySelectorAll('audio,video')) {media.pause();media.removeAttribute('src');media.load();}
|
||||||
|
preview.replaceChildren();
|
||||||
|
}
|
||||||
|
function render() {
|
||||||
|
if(!mounted)return;
|
||||||
|
const session=client.active;
|
||||||
|
if (!session) {
|
||||||
|
if (!removeOverview) {
|
||||||
|
content.replaceChildren();
|
||||||
|
removeOverview = mountOverview(content,{client,extensionName,text,locale,
|
||||||
|
onImport:bridge && (() => importProjectFromDialog(client,{bridge}))});
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
removeOverview?.(); removeOverview = null;
|
||||||
|
content.replaceChildren();shell.setAttribute('aria-busy',String(busy));
|
||||||
|
const toolbar=make('div',null,'isa-project-toolbar');
|
||||||
|
if(session) toolbar.append(make('h2',session.manifest.name,'isa-project-title'));
|
||||||
|
if(bridge)toolbar.append(button(text.import,()=>importProjectFromDialog(client,{bridge})));
|
||||||
|
if(bridge&&session)toolbar.append(button(text.export,()=>exportProjectToDialog(session,{bridge,beforeExport})));
|
||||||
|
if(session) toolbar.append(button(text.close,()=>client.leave()));
|
||||||
|
content.append(toolbar);
|
||||||
|
if(error){const notice=make('p',error);notice.setAttribute('role','alert');content.append(notice);}
|
||||||
|
if(session&&mode==='workspace') {
|
||||||
|
const navigation=make('div',null,'isa-project-toolbar');navigation.append(button(text.files,()=>loadFiles(session)));
|
||||||
|
if(directory)navigation.append(button(text.back,()=>loadFiles(session,directory.split('/').slice(0,-1).join('/'))));
|
||||||
|
content.append(navigation);
|
||||||
|
if(fileLoading){const status=make('p',text.loading);status.setAttribute('role','status');content.append(status);}
|
||||||
|
else if(files.length===0)content.append(make('p',text.empty));
|
||||||
|
const list=make('div',null,'isa-project-list');
|
||||||
|
for(const file of [...files].sort((a,b)=>Number(b.kind==='folder')-Number(a.kind==='folder')||a.name.localeCompare(b.name))) {
|
||||||
|
list.append(button(file.name,()=>file.kind==='folder'?loadFiles(session,file.path.slice(session.project.path.length+1)):showFile(session,file)));
|
||||||
|
}
|
||||||
|
content.append(list);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const unsubscribe=client.subscribe(({active})=>{
|
||||||
|
if(active!==shownSession){shownSession=active;directory='';files=[];clearPreview();loadGeneration++;if(active&&mode==='workspace')void loadFiles(active);}
|
||||||
|
render();
|
||||||
|
});
|
||||||
|
client.recent().catch(failure=>{if(mounted&&failure?.name!=='AbortError'){error=String(failure.message ?? failure);render();}});
|
||||||
|
return {
|
||||||
|
destroy(){if(!mounted)return;mounted=false;removeOverview?.();loadGeneration++;unsubscribe();removeConfirmation();for(const dialog of dialogs)dialog.close('cancel');clearPreview();shell.remove();}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mountProjectHeader(target,options) {return mountProjectWorkspace(target,{...options,mode:'header'});}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
export const PROJECT_FORMAT_VERSION = 1;
|
||||||
|
export const PROJECT_MANIFEST = 'project.json';
|
||||||
|
|
||||||
|
export function parseProjectManifest(value) {
|
||||||
|
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
||||||
|
throw new TypeError('Project manifest must be an object');
|
||||||
|
}
|
||||||
|
if (value.formatVersion !== PROJECT_FORMAT_VERSION) {
|
||||||
|
throw new TypeError('Unsupported project format version');
|
||||||
|
}
|
||||||
|
if (typeof value.id !== 'string' || !/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(value.id)) {
|
||||||
|
throw new TypeError('Invalid stable project identity');
|
||||||
|
}
|
||||||
|
if (typeof value.name !== 'string' || !value.name.trim() || value.name.length > 160) {
|
||||||
|
throw new TypeError('Invalid project name');
|
||||||
|
}
|
||||||
|
for (const key of ['createdAt', 'updatedAt']) {
|
||||||
|
if (typeof value[key] !== 'string' || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/.test(value[key]) || !Number.isFinite(Date.parse(value[key])) || new Date(value[key]).toISOString().slice(0, 19) !== value[key].slice(0, 19)) {
|
||||||
|
throw new TypeError(`Invalid project ${key}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Return a copy preserving fields belonging to newer consumers of this version.
|
||||||
|
return structuredClone(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createProjectManifest({ id, name, now = new Date().toISOString() }) {
|
||||||
|
return parseProjectManifest({ formatVersion: PROJECT_FORMAT_VERSION, id, name, createdAt: now, updatedAt: now });
|
||||||
|
}
|
||||||
|
|
||||||
|
/** UUIDv8 for the first record of an extension that stores a collection by UUID. */
|
||||||
|
export async function defaultProjectRecordId(projectId, extensionId) {
|
||||||
|
const key = JSON.stringify(['isap.default-record.v1', projectId, extensionId]);
|
||||||
|
const bytes = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(key)));
|
||||||
|
bytes[6] = (bytes[6] & 0x0f) | 0x80;
|
||||||
|
bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
||||||
|
const hex = Array.from(bytes.subarray(0, 16), byte => byte.toString(16).padStart(2, '0')).join('');
|
||||||
|
return [hex.slice(0, 8), hex.slice(8, 12), hex.slice(12, 16), hex.slice(16, 20), hex.slice(20)].join('-');
|
||||||
|
}
|
||||||
|
|
||||||
|
export function validateArchivePath(path) {
|
||||||
|
if (typeof path !== 'string' || !path || path.length > 4096 || /[\\\u0000-\u001f\u007f:]/.test(path) || path.startsWith('/')) {
|
||||||
|
throw new TypeError('Unsafe project archive path');
|
||||||
|
}
|
||||||
|
const segments = path.split('/');
|
||||||
|
if (segments.some(segment => !segment || segment === '.' || segment === '..' || /[. ]$/.test(segment))) {
|
||||||
|
throw new TypeError('Unsafe project archive path');
|
||||||
|
}
|
||||||
|
if (segments.some(segment => /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(segment))) {
|
||||||
|
throw new TypeError('Unsafe project archive path');
|
||||||
|
}
|
||||||
|
return path;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function extensionDataPath(extensionId, relativePath) {
|
||||||
|
if (typeof extensionId !== 'string' || !/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(extensionId)) {
|
||||||
|
throw new TypeError('Invalid extension identity');
|
||||||
|
}
|
||||||
|
return validateArchivePath(`extensions/${extensionId}/${validateArchivePath(relativePath)}`);
|
||||||
|
}
|
||||||
Vendored
+89
@@ -0,0 +1,89 @@
|
|||||||
|
export interface ProjectManifest {
|
||||||
|
formatVersion: 1;
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
createdAt: string;
|
||||||
|
updatedAt: string;
|
||||||
|
[key: string]: unknown;
|
||||||
|
}
|
||||||
|
export const PROJECT_FORMAT_VERSION: 1;
|
||||||
|
export const PROJECT_MANIFEST: 'project.json';
|
||||||
|
export function parseProjectManifest(value: unknown): ProjectManifest;
|
||||||
|
export function createProjectManifest(options: { id: string; name: string; now?: string }): ProjectManifest;
|
||||||
|
export function defaultProjectRecordId(projectId: string, extensionId: string): Promise<string>;
|
||||||
|
export function validateArchivePath(path: string): string;
|
||||||
|
export function extensionDataPath(extensionId: string, relativePath: string): string;
|
||||||
|
|
||||||
|
export interface ProjectReference {
|
||||||
|
id: string; folderId: string; path: string; name: string;
|
||||||
|
archived?: boolean; updatedAt?: string; canWrite?: boolean;
|
||||||
|
projectIdentity: string; manifestPath: string; formatVersion: 1;
|
||||||
|
}
|
||||||
|
export interface ProjectScope { workspaceId: string; groupId: string; }
|
||||||
|
export interface ProjectBridge {
|
||||||
|
invoke(command: string, args?: Record<string, unknown>): Promise<any>;
|
||||||
|
applyKv?(args: Record<string, unknown>): Promise<any>;
|
||||||
|
snapshotKv?(args: Record<string, unknown>): Promise<any>;
|
||||||
|
subscribeKv?(args: Record<string, unknown>, onChange?: (value: any) => void): Promise<{unsubscribe: () => Promise<unknown>; [key: string]: any}>;
|
||||||
|
}
|
||||||
|
export interface ProjectRead {
|
||||||
|
status: 'found' | 'absent'; path: string;
|
||||||
|
authoritative?: boolean; fileId?: string; syncRevision?: number;
|
||||||
|
contentHash?: string; text?: string; bytesBase64?: string; value?: any;
|
||||||
|
[key: string]: any;
|
||||||
|
}
|
||||||
|
export interface ProjectSession {
|
||||||
|
readonly scope: Readonly<ProjectScope>;
|
||||||
|
readonly project: Readonly<ProjectReference>;
|
||||||
|
readonly manifest: ProjectManifest;
|
||||||
|
readonly manifestSnapshot: ProjectRead;
|
||||||
|
readonly signal: AbortSignal;
|
||||||
|
readonly dirty: boolean;
|
||||||
|
readonly dirtyVersion: number;
|
||||||
|
preferenceError: unknown;
|
||||||
|
cleanupErrors?: unknown[];
|
||||||
|
markDirty(value?: boolean): void;
|
||||||
|
path(relative: string): string;
|
||||||
|
extensionPath(relative: string): string;
|
||||||
|
assertCurrent(): void;
|
||||||
|
track(cleanup: () => unknown | Promise<unknown>): () => void;
|
||||||
|
readFile(relative: string): Promise<ProjectRead>;
|
||||||
|
readJson(relative: string): Promise<ProjectRead>;
|
||||||
|
ensureExtensionJson(relative: string, makeDefault: () => unknown | Promise<unknown>): Promise<ProjectRead>;
|
||||||
|
writeJson(relative: string, value: unknown, base: ProjectRead, options?: {operationId?: string}): Promise<any>;
|
||||||
|
listFiles(relative?: string, recursive?: boolean): Promise<any[]>;
|
||||||
|
publishStatus(summary: {status: 'not-started'|'in-progress'|'blocked'|'complete'; completion?: number}, base?: ProjectRead): Promise<any>;
|
||||||
|
readStatuses(): Promise<Array<{extensionId: string; [key: string]: any}>>;
|
||||||
|
ensureDirectory(relative: string): Promise<void>;
|
||||||
|
openKv(relative: string, options?: Record<string, unknown>): Promise<any>;
|
||||||
|
applyKv(relative: string, mutation: Record<string, unknown>): Promise<any>;
|
||||||
|
subscribeKv(relative: string, args: Record<string, unknown>, onChange: (value: any) => void): Promise<{unsubscribe: () => Promise<unknown>; [key: string]: any}>;
|
||||||
|
close(): Promise<void>;
|
||||||
|
}
|
||||||
|
export interface ProjectClient {
|
||||||
|
readonly scope: Readonly<ProjectScope>;
|
||||||
|
readonly extensionId: string;
|
||||||
|
readonly active: ProjectSession | null;
|
||||||
|
readonly state: {readonly active: ProjectSession | null; readonly recents: ProjectReference[]};
|
||||||
|
provideSwitchConfirmation(handler: (session: ProjectSession) => Promise<boolean>): () => void;
|
||||||
|
subscribe(listener: (state: ProjectClient['state']) => void): () => void;
|
||||||
|
supports(command: string): boolean;
|
||||||
|
recent(): Promise<ProjectReference[]>;
|
||||||
|
list(includeArchived?: boolean): Promise<ProjectReference[]>;
|
||||||
|
create(name: string, operationId?: string): Promise<ProjectSession>;
|
||||||
|
stageCreate(name: string, operationId?: string): Promise<ProjectSession>;
|
||||||
|
adopt(session: ProjectSession): Promise<ProjectSession>;
|
||||||
|
openListed(project: ProjectReference): Promise<ProjectSession>;
|
||||||
|
activate(project: ProjectReference): Promise<ProjectSession>;
|
||||||
|
share(targetGroupId: string, linked: boolean): Promise<any>;
|
||||||
|
leave(): Promise<void>;
|
||||||
|
close(): Promise<void>;
|
||||||
|
}
|
||||||
|
export class ProjectUnavailableError extends Error {}
|
||||||
|
export function createProjectClient(options: {
|
||||||
|
bridge: ProjectBridge; extensionId: string; scope: ProjectScope;
|
||||||
|
projectCommands?: readonly string[];
|
||||||
|
beforeSwitch?: (session: ProjectSession) => boolean | Promise<boolean>;
|
||||||
|
isCurrent?: () => boolean;
|
||||||
|
}): ProjectClient;
|
||||||
|
export * from './transfer.js';
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
export * from './format.js';
|
||||||
|
export * from './client.js';
|
||||||
|
export * from './transfer.js';
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
const encoder = new TextEncoder();
|
||||||
|
|
||||||
|
export function validateEntries(entries) {
|
||||||
|
if(!Array.isArray(entries))throw new Error('Invalid KV snapshot entries');
|
||||||
|
const keys=new Set();
|
||||||
|
for(const entry of entries) {
|
||||||
|
if(!entry||typeof entry.key!=='string'||!entry.key||entry.key.includes('\0')||keys.has(entry.key)||entry.status!=='found'||!['value','list'].includes(entry.kind)||!Object.hasOwn(entry,'value'))throw new Error('Invalid or duplicate KV snapshot key');
|
||||||
|
keys.add(entry.key);
|
||||||
|
if(entry.kind==='list') {
|
||||||
|
if(!Array.isArray(entry.value)||!Array.isArray(entry.itemIds)||entry.itemIds.length!==entry.value.length)throw new Error('KV list identities missing');
|
||||||
|
const ids=new Set();
|
||||||
|
for(const id of entry.itemIds) {if(typeof id!=='string'||!id||id.includes('\0')||ids.has(id))throw new Error('Invalid KV list item identity');ids.add(id);}
|
||||||
|
} else if(Array.isArray(entry.value))throw new Error('Array KV values require list identities');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
export async function readKvSnapshot(bridge,scope,path,assertCurrent,maxBytes) {
|
||||||
|
if(typeof bridge.snapshotKv!=='function')throw new Error('Host consistent KV snapshots unavailable');
|
||||||
|
const entries=[],cursors=new Set();let cursor,anchor,fence;
|
||||||
|
do {
|
||||||
|
assertCurrent();
|
||||||
|
const page=await bridge.snapshotKv({...scope,path,limit:100,cursor});
|
||||||
|
assertCurrent();
|
||||||
|
const local=page?.local===true&&page.snapshotComplete===true&&page.nextCursor==null&&!cursor&&Number.isSafeInteger(page.localRevision);
|
||||||
|
if(!Number.isSafeInteger(page?.revision)||!Array.isArray(page.entries)||page.incomplete||page.stale||(!local&&(typeof page.snapshotId!=='string'||!page.snapshotId)))throw new Error('Invalid host KV snapshot');
|
||||||
|
const generation=JSON.stringify([page.snapshotId??'local-complete',page.revision,page.localRevision??null,page.storeId??null,page.incarnation??null]);
|
||||||
|
if(anchor&&anchor!==generation)throw new Error('KV snapshot generation changed');
|
||||||
|
anchor=generation;fence={revision:page.revision,localRevision:page.localRevision??null,storeId:page.storeId??null,incarnation:page.incarnation??null,local:page.local===true};entries.push(...page.entries);
|
||||||
|
if(maxBytes !== undefined && encoder.encode(JSON.stringify(entries)).length>maxBytes)throw new Error('KV snapshot exceeds transfer limit');
|
||||||
|
cursor=page.nextCursor;
|
||||||
|
if(cursor!=null&&(typeof cursor!=='string'||!cursor||cursors.has(cursor)))throw new Error('Invalid or repeated KV snapshot cursor');
|
||||||
|
if(cursor)cursors.add(cursor);
|
||||||
|
}while(cursor);
|
||||||
|
validateEntries(entries);
|
||||||
|
return {entries:entries.map(entry=>({key:entry.key,status:'found',kind:entry.kind,value:entry.value,...(entry.kind==='list'?{itemIds:entry.itemIds}:{})})),fence};
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
export const labels = {
|
||||||
|
en: {projects:'Projects',search:'Search projects',updated:'Last modified',sort:'Sort projects',activity:'Recent activity',noActivity:'No projects opened yet.',noProjects:'No projects yet.',noMatches:'No matching projects.',refresh:'Refresh',create:'Create project',name:'Project name',recent:'Recent projects',files:'Files',back:'Back',close:'Close project',empty:'No files',loading:'Loading…',cancel:'Cancel',discard:'Discard changes',dirty:'Discard unsaved project changes?',retry:'Retry',export:'Export project',import:'Import project'},
|
||||||
|
nl: {projects:'Projecten',search:'Zoek op projectnaam',updated:'Laatst gewijzigd',sort:'Projecten sorteren',activity:'Recente activiteit',noActivity:'Nog geen projecten geopend.',noProjects:'Nog geen projecten.',noMatches:'Geen overeenkomende projecten.',refresh:'Vernieuwen',create:'Project maken',name:'Projectnaam',recent:'Recente projecten',files:'Bestanden',back:'Terug',close:'Project sluiten',empty:'Geen bestanden',loading:'Laden…',cancel:'Annuleren',discard:'Wijzigingen weggooien',dirty:'Niet-opgeslagen projectwijzigingen weggooien?',retry:'Opnieuw proberen',export:'Project exporteren',import:'Project importeren'}
|
||||||
|
};
|
||||||
+131
@@ -0,0 +1,131 @@
|
|||||||
|
// A row always identifies a folder in the current group inventory. Private
|
||||||
|
// recents supply the activity order only, never the inventory or a grant.
|
||||||
|
export function mountOverview(target, {client, extensionName, text, locale, onImport}) {
|
||||||
|
const document = target.ownerDocument;
|
||||||
|
function element(tag, label, className) {
|
||||||
|
const node = document.createElement(tag);
|
||||||
|
if (label) node.textContent = label;
|
||||||
|
if (className) node.className = className;
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
function button(label, action) {
|
||||||
|
const node = element('button', label);
|
||||||
|
node.type = 'button';
|
||||||
|
node.onclick = action;
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
const root = element('section', '', 'isa-group-home');
|
||||||
|
const header = element('header');
|
||||||
|
header.append(element('h1', extensionName || text.projects));
|
||||||
|
const actions = element('div', '', 'isa-project-toolbar');
|
||||||
|
const refreshButton = button(text.refresh, refresh);
|
||||||
|
actions.append(refreshButton);
|
||||||
|
const importButton = button(text.import, () => run(onImport));
|
||||||
|
if (onImport && client.supports('projects_create')) actions.append(importButton);
|
||||||
|
header.append(actions);
|
||||||
|
const grid = element('div', '', 'isa-group-grid');
|
||||||
|
const activity = element('aside');
|
||||||
|
const recent = element('div');
|
||||||
|
activity.append(element('h2', text.activity), recent);
|
||||||
|
const panel = element('section', '', 'isa-group-projects');
|
||||||
|
const heading = element('header');
|
||||||
|
const create = button('+ ' + text.create, () => { name.value = ''; formError.textContent = ''; dialog.showModal(); name.focus(); });
|
||||||
|
create.className = 'isa-group-create';
|
||||||
|
const panelTitle = element('h2', text.projects);
|
||||||
|
panelTitle.id = 'isa-projects-' + crypto.randomUUID();
|
||||||
|
panel.setAttribute('aria-labelledby',panelTitle.id);
|
||||||
|
heading.append(panelTitle);
|
||||||
|
if (client.supports('projects_create')) heading.append(create);
|
||||||
|
const controls = element('div', '', 'isa-project-toolbar');
|
||||||
|
const search = element('input');
|
||||||
|
search.type = 'search';
|
||||||
|
search.placeholder = text.search;
|
||||||
|
search.setAttribute('aria-label',text.search);
|
||||||
|
const sort = element('select');
|
||||||
|
sort.setAttribute('aria-label',text.sort);
|
||||||
|
for (const [value,label] of [['updated',text.updated],['name',text.name]]) {
|
||||||
|
const option = element('option',label); option.value = value; sort.append(option);
|
||||||
|
}
|
||||||
|
controls.append(search,sort);
|
||||||
|
const alert = element('p');
|
||||||
|
alert.setAttribute('role','alert');
|
||||||
|
const list = element('div', '', 'isa-group-rows');
|
||||||
|
const status = element('p');
|
||||||
|
status.setAttribute('role','status');
|
||||||
|
panel.append(heading,controls,alert,status,list);
|
||||||
|
grid.append(activity,panel);
|
||||||
|
const dialog = element('dialog');
|
||||||
|
const title = element('h2', text.create);
|
||||||
|
title.id = 'project-create-' + crypto.randomUUID();
|
||||||
|
dialog.setAttribute('aria-labelledby',title.id);
|
||||||
|
const form = element('form');
|
||||||
|
const label = element('label', text.name);
|
||||||
|
const name = element('input');
|
||||||
|
name.required = true; name.maxLength = 160; label.append(name);
|
||||||
|
const formError = element('p'); formError.setAttribute('role','alert');
|
||||||
|
const cancel = button(text.cancel, () => dialog.close());
|
||||||
|
const submit = element('button',text.create); submit.type = 'submit';
|
||||||
|
const footer = element('div', '', 'isa-project-toolbar'); footer.append(cancel,submit);
|
||||||
|
form.append(label,formError,footer);
|
||||||
|
dialog.append(title,form);
|
||||||
|
root.append(header,grid,dialog);
|
||||||
|
target.append(root);
|
||||||
|
|
||||||
|
let projects = [], recents = [], loading = true, failed = false, busy = false, alive = true, generation = 0;
|
||||||
|
const date = new Intl.DateTimeFormat(locale,{dateStyle:'medium'});
|
||||||
|
function draw() {
|
||||||
|
const needle = search.value.trim().toLocaleLowerCase(locale);
|
||||||
|
const visible = projects.filter(p => p.name.toLocaleLowerCase(locale).includes(needle));
|
||||||
|
visible.sort((a,b) => (sort.value === 'updated' && (Date.parse(b.updatedAt) || 0) - (Date.parse(a.updatedAt) || 0)) || a.name.localeCompare(b.name,locale));
|
||||||
|
list.replaceChildren();
|
||||||
|
for (const project of visible) {
|
||||||
|
const row = button('', () => run(() => client.openListed(project)));
|
||||||
|
const info = element('span'); info.append(element('strong',project.name),element('small',project.path));
|
||||||
|
row.append(info);
|
||||||
|
if (Number.isFinite(Date.parse(project.updatedAt))) row.append(element('time',date.format(new Date(project.updatedAt))));
|
||||||
|
row.disabled = busy;
|
||||||
|
list.append(row);
|
||||||
|
}
|
||||||
|
status.textContent = loading ? text.loading : visible.length || failed ? '' : needle ? text.noMatches : text.noProjects;
|
||||||
|
recent.replaceChildren();
|
||||||
|
for (const item of recents) {
|
||||||
|
const project = projects.find(p => p.id === item.id);
|
||||||
|
if (project) {
|
||||||
|
const row = button(project.name, () => run(() => client.openListed(project)));
|
||||||
|
row.disabled = busy; recent.append(row);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!recent.childElementCount && !loading && !failed) recent.append(element('p',text.noActivity));
|
||||||
|
create.disabled = busy; importButton.disabled = busy; refreshButton.disabled = busy || loading;
|
||||||
|
}
|
||||||
|
async function refresh() {
|
||||||
|
const ticket = ++generation;
|
||||||
|
loading = true; failed = false; alert.textContent = ''; draw();
|
||||||
|
try {
|
||||||
|
const inventory = await client.list();
|
||||||
|
if (alive && ticket === generation) projects = inventory.filter(p => !p.archived);
|
||||||
|
} catch (error) {
|
||||||
|
if (alive && ticket === generation) { failed = true; alert.textContent = String(error.message ?? error); }
|
||||||
|
} finally {
|
||||||
|
if (alive && ticket === generation) { loading = false; draw(); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async function run(action, notice = alert) {
|
||||||
|
if (busy) return;
|
||||||
|
busy = true; notice.textContent = ''; form.inert = true; draw();
|
||||||
|
try { await action(); }
|
||||||
|
catch (error) { if (alive && error?.name !== 'AbortError') notice.textContent = String(error.message ?? error); }
|
||||||
|
finally { if (alive) { busy = false; form.inert = false; draw(); } }
|
||||||
|
}
|
||||||
|
dialog.oncancel = event => { if (busy) event.preventDefault(); };
|
||||||
|
form.onsubmit = event => {
|
||||||
|
event.preventDefault();
|
||||||
|
if (name.value.trim()) void run(() => client.create(name.value.trim()), formError);
|
||||||
|
};
|
||||||
|
search.oninput = sort.onchange = draw;
|
||||||
|
const unsubscribe = client.subscribe(state => { recents = state.recents; draw(); });
|
||||||
|
void refresh();
|
||||||
|
const onVisible = () => { if (!document.hidden && !busy) void refresh(); };
|
||||||
|
document.addEventListener('visibilitychange',onVisible);
|
||||||
|
return () => { alive = false; unsubscribe(); document.removeEventListener('visibilitychange',onVisible); root.remove(); };
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
export function uncertain(item) {
|
||||||
|
return item?.conflict === true || item?.pending === true || item?.pendingUpload === true
|
||||||
|
|| Boolean(item?.pendingState) || Boolean(item?.workspaceFileConflictId)
|
||||||
|
|| Number(item?.conflictCount ?? 0) > 0
|
||||||
|
|| ['pending','conflict'].includes(item?.workspaceFileOutcome)
|
||||||
|
|| ['pending','conflict','cached','cache','offline'].includes(item?.syncStatus)
|
||||||
|
|| ['cache','local','pending'].includes(item?.source);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function confirmedWrite(result, path) {
|
||||||
|
const item=result?.items?.length===1?result.items[0]:null;
|
||||||
|
if(item?.conflict===true||item?.workspaceFileOutcome==='conflict'||item?.workspaceFileConflictId) {
|
||||||
|
const error=new Error(item.error?.message??'Project write conflict');error.code='conflict';throw error;
|
||||||
|
}
|
||||||
|
if(!item||!['ok','accepted','uploaded'].includes(item.status)||item.isComplete!==true||item.path!==path||typeof item.fileId!=='string'||!item.fileId||uncertain(item))throw new Error(item?.error?.message??'Project write was not confirmed');
|
||||||
|
return item;
|
||||||
|
}
|
||||||
Vendored
+15
@@ -0,0 +1,15 @@
|
|||||||
|
import type { ProjectBridge, ProjectScope, ProjectRead } from './index.js';
|
||||||
|
export function createSharedFolderReader(options: {
|
||||||
|
bridge: ProjectBridge;
|
||||||
|
scope: ProjectScope;
|
||||||
|
folder: {path: string; workspaceId?: string; groupId?: string};
|
||||||
|
assertCurrent?: () => void;
|
||||||
|
}): {
|
||||||
|
listFiles(relative?: string, recursive?: boolean): Promise<Array<{path:string;kind:string;[key:string]:unknown}>>;
|
||||||
|
readFile(relative: string): Promise<ProjectRead>;
|
||||||
|
readJson(relative: string): Promise<ProjectRead>;
|
||||||
|
readKv(relative: string): Promise<{
|
||||||
|
entries: Array<{key:string;status:'found';kind:'value'|'list';value:unknown;itemIds?:string[]}>;
|
||||||
|
fence: {storeId:string|null;incarnation:string|null;revision:number;local:boolean;localRevision:number|null};
|
||||||
|
}>;
|
||||||
|
};
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
import { validateArchivePath } from './format.js';
|
||||||
|
import { readAuthoritativeFile } from './shared-read.js';
|
||||||
|
import { readKvSnapshot } from './kv-snapshot.js';
|
||||||
|
|
||||||
|
/** Reads through the calling extension's own host grant. The folder can also
|
||||||
|
* be the root of an open project session. No source is opened for writing. */
|
||||||
|
export function createSharedFolderReader({bridge,scope,folder,assertCurrent = () => {}}) {
|
||||||
|
if (typeof bridge?.invoke !== 'function' || !scope?.workspaceId || !scope?.groupId) {
|
||||||
|
throw new TypeError('Host bridge and launch scope required');
|
||||||
|
}
|
||||||
|
if (typeof folder?.path !== 'string' || !folder.path.startsWith('/') ||
|
||||||
|
(folder.workspaceId && folder.workspaceId !== scope.workspaceId) ||
|
||||||
|
(folder.groupId && folder.groupId !== scope.groupId)) {
|
||||||
|
throw new TypeError('Invalid shared folder for this launch');
|
||||||
|
}
|
||||||
|
const root = '/' + validateArchivePath(folder.path.slice(1).replace(/\/$/, ''));
|
||||||
|
const launch = Object.freeze({workspaceId:scope.workspaceId,groupId:scope.groupId});
|
||||||
|
const path = relative => root + '/' + validateArchivePath(relative);
|
||||||
|
async function invoke(command,args) {
|
||||||
|
assertCurrent();
|
||||||
|
const result = await bridge.invoke(command,{...args,...launch});
|
||||||
|
assertCurrent();
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
const readFile = relative => readAuthoritativeFile(invoke,path(relative),assertCurrent);
|
||||||
|
return {
|
||||||
|
async listFiles(relative = '', recursive = false) {
|
||||||
|
const directory = relative ? path(relative) : root;
|
||||||
|
const inventory = await invoke('filesystem_list_dir',{path:directory,recursive,cachePolicy:'dashboard-required'});
|
||||||
|
if (inventory?.authoritative !== true || !Array.isArray(inventory.files) ||
|
||||||
|
inventory.files.some(file => file?.path !== directory && !file?.path?.startsWith(directory + '/'))) {
|
||||||
|
throw new Error('Shared folder inventory unavailable');
|
||||||
|
}
|
||||||
|
return inventory.files.filter(file => file.path !== directory);
|
||||||
|
},
|
||||||
|
readFile,
|
||||||
|
async readJson(relative) {
|
||||||
|
const file = await readFile(relative);
|
||||||
|
if (file.status === 'absent') return file;
|
||||||
|
let text = file.text;
|
||||||
|
if (typeof text !== 'string') {
|
||||||
|
if (typeof file.bytesBase64 !== 'string') throw new Error('Shared JSON file content unavailable');
|
||||||
|
const bytes = Uint8Array.from(atob(file.bytesBase64), character => character.charCodeAt(0));
|
||||||
|
text = new TextDecoder('utf-8',{fatal:true}).decode(bytes);
|
||||||
|
}
|
||||||
|
return {...file,value:JSON.parse(text)};
|
||||||
|
},
|
||||||
|
async readKv(relative) {
|
||||||
|
return readKvSnapshot(bridge,launch,path(relative),assertCurrent);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import { uncertain } from './proofs.js';
|
||||||
|
|
||||||
|
export class ProjectUnavailableError extends Error {
|
||||||
|
constructor(message = 'Project data is unavailable') { super(message); this.name = 'ProjectUnavailableError'; }
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function readAuthoritativeFile(invoke, path, sessionGuard) {
|
||||||
|
sessionGuard();
|
||||||
|
const result = await invoke('filesystem_get_files', {files:[{path, cachePolicy:'dashboard-required'}]});
|
||||||
|
sessionGuard();
|
||||||
|
const item = result?.items?.length === 1 ? result.items[0] : null;
|
||||||
|
if (!item || item.path !== path) throw new ProjectUnavailableError();
|
||||||
|
if (item.source !== 'dashboard' || item.authoritative !== true || uncertain(item) || item.status === 'unavailable') {
|
||||||
|
const detail = item.reason || (typeof item.error === 'string' ? item.error : item.error?.message);
|
||||||
|
throw new ProjectUnavailableError(detail);
|
||||||
|
}
|
||||||
|
if (item.status === 'absent') {
|
||||||
|
if (item.found === true || item.error || item.fileId) throw new ProjectUnavailableError('Conflicting project file metadata');
|
||||||
|
return {status:'absent',path};
|
||||||
|
}
|
||||||
|
if (!['ok','found'].includes(item.status)) throw new Error(item.error?.message ?? `Cannot read ${path}`);
|
||||||
|
if (typeof item.fileId !== 'string' || !item.fileId || !Number.isSafeInteger(item.syncRevision) || item.syncRevision < 0) throw new ProjectUnavailableError('Project file identity unavailable');
|
||||||
|
return {...item,status:'found'};
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
export const styles = `
|
||||||
|
.isa-project-ui {color:var(--isa-extension-panel-text,CanvasText);font-family:var(--isa-extension-font-family,system-ui);display:flex;flex-direction:column;gap:var(--isa-extension-space-3,.75rem)}
|
||||||
|
.isa-project-ui .isa-project-toolbar,.isa-project-ui form {display:flex;align-items:center;gap:var(--isa-extension-space-2,.5rem);flex-wrap:wrap}
|
||||||
|
.isa-project-ui .isa-project-title {margin:0 auto 0 0;font-size:1.125rem;font-weight:600;overflow-wrap:anywhere}
|
||||||
|
.isa-project-ui .isa-project-list {display:flex;flex-direction:column;gap:var(--isa-extension-space-1,.25rem);margin-block:var(--isa-extension-space-2,.5rem)}
|
||||||
|
.isa-project-ui button,.isa-project-ui input {font:inherit;min-height:36px;box-sizing:border-box;border:1px solid var(--isa-extension-border,ButtonBorder);border-radius:var(--isa-extension-radius-sm,.375rem);padding:.375rem .75rem;color:inherit;background:var(--isa-extension-control-bg,Canvas)}
|
||||||
|
.isa-project-ui input {flex:1;min-width:8rem}
|
||||||
|
.isa-project-ui button {cursor:pointer;text-align:start}
|
||||||
|
.isa-project-ui button:hover:not(:disabled) {background:var(--isa-extension-card-hover-bg,ButtonFace)}
|
||||||
|
.isa-project-ui button:focus-visible,.isa-project-ui input:focus-visible {outline:2px solid var(--isa-extension-focus-ring,Highlight);outline-offset:2px}
|
||||||
|
.isa-project-ui button:disabled {opacity:.55;cursor:default}
|
||||||
|
.isa-project-ui [role=alert] {color:var(--isa-extension-danger-text,CanvasText);overflow-wrap:anywhere}
|
||||||
|
.isa-project-ui .isa-project-heading {font-size:1rem;font-weight:600;margin:.75rem 0 .375rem}
|
||||||
|
.isa-project-ui .isa-project-preview audio,.isa-project-ui .isa-project-preview video,.isa-project-ui .isa-project-preview img {display:block;max-width:100%}
|
||||||
|
.isa-project-ui .isa-project-preview pre {white-space:pre-wrap;overflow-wrap:anywhere}
|
||||||
|
.isa-project-ui dialog {color:inherit;background:var(--isa-extension-panel-bg,Canvas);border:1px solid var(--isa-extension-border,ButtonBorder);border-radius:var(--isa-extension-radius-sm,.375rem);max-width:28rem;padding:1rem}
|
||||||
|
.isa-project-ui dialog::backdrop {background:rgb(0 0 0/.4)}
|
||||||
|
|
||||||
|
.isa-group-home {display:grid;gap:9px;padding:10px;min-height:75vh;grid-template-rows:auto 1fr;background:var(--isa-extension-app-bg,var(--isa-extension-panel-bg,Canvas))}
|
||||||
|
.isa-group-home > header,.isa-group-projects {background:var(--isa-extension-card-bg,Canvas);border:1px solid var(--isa-extension-border-subtle,GrayText);border-radius:14px;padding:14px 18px}
|
||||||
|
.isa-group-home header {display:flex;gap:12px;align-items:center;justify-content:space-between;flex-wrap:wrap}
|
||||||
|
.isa-group-home h1,.isa-group-home h2,.isa-group-home p {margin:0}
|
||||||
|
.isa-group-home h1 {font-size:1.15rem}
|
||||||
|
.isa-group-home h2 {font-size:.86rem}
|
||||||
|
.isa-group-grid {display:grid;grid-template-columns:minmax(140px, .42fr) minmax(0,1fr);gap:10px}
|
||||||
|
.isa-group-grid aside {padding:16px;color:var(--isa-extension-panel-muted,GrayText)}
|
||||||
|
.isa-group-grid aside div {display:grid;gap:4px;margin-top:10px}
|
||||||
|
.isa-group-grid aside button {border:0;background:transparent;padding-inline:0}
|
||||||
|
.isa-group-projects {display:flex;flex-direction:column;gap:14px;min-width:0}
|
||||||
|
.isa-group-projects h2 {text-transform:uppercase;letter-spacing:.08em}
|
||||||
|
.isa-group-projects select {font:inherit;color:inherit;background:var(--isa-extension-control-bg,Canvas);border:1px solid var(--isa-extension-border-subtle,GrayText);border-radius:.5rem;padding:.5rem;max-width:100%}
|
||||||
|
.isa-project-ui .isa-group-create {background:var(--isa-extension-primary,Highlight);color:var(--isa-extension-primary-text,HighlightText);border-color:transparent;font-weight:600}
|
||||||
|
.isa-group-rows {display:grid;gap:8px}
|
||||||
|
.isa-group-rows button {display:flex;justify-content:space-between;align-items:center;gap:10px;width:100%;padding:12px;border-radius:10px;border-color:var(--isa-extension-border-subtle,GrayText);background:var(--isa-extension-card-bg,Canvas)}
|
||||||
|
.isa-group-rows strong,.isa-group-rows small {display:block;overflow-wrap:anywhere}
|
||||||
|
.isa-group-rows small,.isa-group-rows time {color:var(--isa-extension-panel-muted,GrayText);font-size:.8em}
|
||||||
|
.isa-group-home p:empty {display:none}
|
||||||
|
.isa-group-home dialog form,.isa-group-home dialog label {display:grid;gap:10px}
|
||||||
|
.isa-group-home dialog h2 {margin-bottom:14px}
|
||||||
|
@media(max-width:640px){.isa-group-grid {grid-template-columns:minmax(0,1fr)}.isa-group-projects {grid-row:1}.isa-group-home {min-height:0}.isa-group-home header {gap:8px}}
|
||||||
|
`;
|
||||||
Vendored
+18
@@ -0,0 +1,18 @@
|
|||||||
|
export const TRANSFER_MANIFEST: '.isa-transfer.json';
|
||||||
|
export const TRANSFER_VERSION: 1;
|
||||||
|
export interface ProjectTransferOptions {
|
||||||
|
bridge: ProjectBridge;
|
||||||
|
scope?: ProjectScope;
|
||||||
|
beforeExport?: (session: ProjectSession) => void | Promise<void>;
|
||||||
|
name?: string;
|
||||||
|
fileName?: string;
|
||||||
|
maxArchiveBytes?: number;
|
||||||
|
maxFileBytes?: number;
|
||||||
|
maxTotalBytes?: number;
|
||||||
|
maxEntries?: number;
|
||||||
|
}
|
||||||
|
export function exportProject(session: ProjectSession, options: ProjectTransferOptions): Promise<Uint8Array>;
|
||||||
|
export function importProject(client: ProjectClient, bytes: Uint8Array | ArrayBuffer, options: ProjectTransferOptions): Promise<ProjectSession>;
|
||||||
|
export function exportProjectToDialog(session: ProjectSession, options: ProjectTransferOptions): Promise<unknown>;
|
||||||
|
export function importProjectFromDialog(client: ProjectClient, options: ProjectTransferOptions): Promise<ProjectSession | null>;
|
||||||
|
import type { ProjectBridge, ProjectClient, ProjectSession, ProjectScope } from './index.js';
|
||||||
+207
@@ -0,0 +1,207 @@
|
|||||||
|
import {readKvSnapshot,validateEntries} from './kv-snapshot.js';
|
||||||
|
import { readExportFile } from './transfer/files.js';
|
||||||
|
import { confirmedWrite } from './proofs.js';
|
||||||
|
import { parseProjectManifest, validateArchivePath } from './format.js';
|
||||||
|
import { packZip, unpackZip, limits, validatePaths } from './transfer/zip.js';
|
||||||
|
|
||||||
|
export const TRANSFER_MANIFEST = '.isa-transfer.json';
|
||||||
|
export const TRANSFER_VERSION = 1;
|
||||||
|
const KV_TYPE = 'application/vnd.isa.kv-store';
|
||||||
|
const encoder = new TextEncoder();
|
||||||
|
const decoder = new TextDecoder('utf-8', {fatal:true});
|
||||||
|
const jsonBytes = value => encoder.encode(JSON.stringify(value));
|
||||||
|
const json = bytes => JSON.parse(decoder.decode(bytes));
|
||||||
|
const reserved = ['credentials','secrets','publishingPermissions','hostGrants','runtimeGrants','serviceApprovals'];
|
||||||
|
function portableManifest(manifest) {
|
||||||
|
const value = parseProjectManifest(manifest);
|
||||||
|
for (const key of reserved) delete value[key];
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
function base64(bytes) {
|
||||||
|
let text=''; for(let offset=0;offset<bytes.length;offset+=8192)text+=String.fromCharCode(...bytes.subarray(offset,offset+8192));
|
||||||
|
return btoa(text);
|
||||||
|
}
|
||||||
|
function decodeBase64(value) {
|
||||||
|
if(typeof value!=='string'||value.length%4||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value))throw new Error('Invalid host file encoding');
|
||||||
|
return Uint8Array.from(atob(value),character=>character.charCodeAt(0));
|
||||||
|
}
|
||||||
|
function bridgeFor(options) {
|
||||||
|
if(!options.bridge||typeof options.bridge.invoke!=='function')throw new TypeError('Host bridge required for project transfer');
|
||||||
|
return options.bridge;
|
||||||
|
}
|
||||||
|
function scoped(session, options) {
|
||||||
|
if(session.scope&&options.scope&&(session.scope.workspaceId!==options.scope.workspaceId||session.scope.groupId!==options.scope.groupId))throw new Error('Transfer scope differs from captured project scope');
|
||||||
|
const scope=session.scope??options.scope;
|
||||||
|
if(!scope?.workspaceId||!scope?.groupId)throw new TypeError('Captured project scope required');
|
||||||
|
return scope;
|
||||||
|
}
|
||||||
|
function relative(session,path) {
|
||||||
|
const prefix=`${session.project.path}/`;
|
||||||
|
if(typeof path!=='string'||!path.startsWith(prefix))throw new Error('Host inventory escaped the project');
|
||||||
|
return validateArchivePath(path.slice(prefix.length));
|
||||||
|
}
|
||||||
|
function identity(row) {
|
||||||
|
const id=row.fileId??row.id;
|
||||||
|
if(typeof id!=='string'||!id||!Number.isSafeInteger(row.syncRevision)||row.syncRevision<0)throw new Error('Project inventory lacks canonical identity');
|
||||||
|
return {id,revision:row.syncRevision,hash:row.contentHash??null,kind:row.kind,size:row.fileSize??null,contentType:row.contentType??null,updatedAt:row.timestampUpdated??null};
|
||||||
|
}
|
||||||
|
function inventorySignature(rows) {
|
||||||
|
return JSON.stringify(rows.map(row=>({path:row.path,...identity(row)})).sort((a,b)=>a.path.localeCompare(b.path)));
|
||||||
|
}
|
||||||
|
function assertLive(session) {session.assertCurrent();if(session.signal?.aborted)throw new DOMException('Project transfer cancelled','AbortError');}
|
||||||
|
export async function exportProject(session, options={}) {
|
||||||
|
const bridge=bridgeFor(options),scope=scoped(session,options),bound=limits(options);
|
||||||
|
assertLive(session);
|
||||||
|
if(options.beforeExport) {await options.beforeExport(session);assertLive(session);}
|
||||||
|
if(session.dirty)throw new Error('Save project changes before exporting');
|
||||||
|
const rows=await session.listFiles('',true);assertLive(session);
|
||||||
|
if(!Array.isArray(rows)||rows.length>bound.maxEntries)throw new Error('Invalid or oversized project inventory');
|
||||||
|
const inventory=rows.filter(row=>row.path!==session.project.path);
|
||||||
|
const signature=inventorySignature(inventory);
|
||||||
|
validatePaths(inventory.map(row=>({path:relative(session,row.path),directory:row.kind==='folder'})));
|
||||||
|
const files=new Map(),metadata=[],stores=[],directories=[];
|
||||||
|
for(const row of inventory) {
|
||||||
|
assertLive(session);
|
||||||
|
if(row.kind==='folder'){directories.push(relative(session,row.path));continue;}
|
||||||
|
if(row.kind!=='file')throw new Error('Unsupported project resource kind');
|
||||||
|
const path=relative(session,row.path);
|
||||||
|
if(path===TRANSFER_MANIFEST)throw new Error('Project uses reserved transfer manifest path');
|
||||||
|
if(row.contentType===KV_TYPE) {
|
||||||
|
const captured=await readKvSnapshot(bridge,scope,row.path,() => assertLive(session),bound.maxFileBytes);
|
||||||
|
stores.push({path,revision:captured.fence.revision,entries:captured.entries,fence:captured.fence});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const expected=identity(row);
|
||||||
|
const bytes=await readExportFile(session,bridge,scope,row,expected,bound.maxFileBytes);
|
||||||
|
if(path==='project.json') {
|
||||||
|
const manifest=portableManifest(json(bytes));
|
||||||
|
if(manifest.id!==session.project.projectIdentity)throw new Error('Project manifest identity changed');
|
||||||
|
files.set(path,jsonBytes(manifest));
|
||||||
|
} else files.set(path,bytes);
|
||||||
|
metadata.push({path,contentType:typeof row.contentType==='string'?row.contentType:'application/octet-stream'});
|
||||||
|
}
|
||||||
|
if(!files.has('project.json'))throw new Error('Project manifest missing from export inventory');
|
||||||
|
for(const store of stores) {
|
||||||
|
const current=await bridge.snapshotKv({...scope,path:session.path(store.path),limit:1});assertLive(session);
|
||||||
|
const fence={revision:current.revision,localRevision:current.localRevision??null,storeId:current.storeId??null,incarnation:current.incarnation??null,local:current.local===true};
|
||||||
|
if(JSON.stringify(fence)!==JSON.stringify(store.fence))throw new Error('KV changed during project export');
|
||||||
|
}
|
||||||
|
const current=await session.listFiles('',true);assertLive(session);
|
||||||
|
if(inventorySignature(current.filter(row=>row.path!==session.project.path))!==signature)throw new Error('Project inventory changed during export');
|
||||||
|
files.set(TRANSFER_MANIFEST,jsonBytes({formatVersion:TRANSFER_VERSION,files:metadata,directories,kvStores:stores.map(({fence,...store})=>store),auditAuthority:'historical-only'}));
|
||||||
|
const bytes=packZip(files,bound,directories);assertLive(session);return bytes;
|
||||||
|
}
|
||||||
|
|
||||||
|
function inspectArchive(bytes,options) {
|
||||||
|
const files=unpackZip(bytes,options),raw=files.get('project.json');
|
||||||
|
if(!raw)throw new Error('Project archive requires project.json');
|
||||||
|
const manifest=portableManifest(json(raw));
|
||||||
|
const sidecar=files.has(TRANSFER_MANIFEST)?json(files.get(TRANSFER_MANIFEST)): {formatVersion:1,files:[...files.keys()].map(path=>({path,contentType:'application/octet-stream'})),kvStores:[]};
|
||||||
|
if(sidecar.formatVersion!==TRANSFER_VERSION||!Array.isArray(sidecar.files)||!Array.isArray(sidecar.kvStores))throw new Error('Unsupported project transfer metadata');
|
||||||
|
if(sidecar.directories!==undefined&&!Array.isArray(sidecar.directories))throw new Error('Invalid project directory inventory');
|
||||||
|
const declaredDirectories=sidecar.directories??[];
|
||||||
|
validatePaths(declaredDirectories.map(path=>({path,directory:true})));
|
||||||
|
const directories=new Set([...declaredDirectories,...(files.directories??[])]);
|
||||||
|
const paths=[],types=new Map();
|
||||||
|
for(const file of sidecar.files) {
|
||||||
|
if(!file||file.path===TRANSFER_MANIFEST||typeof file.contentType!=='string'||file.contentType.length>256||file.contentType===KV_TYPE||!files.has(file.path))throw new Error('Invalid project file metadata');
|
||||||
|
paths.push({path:file.path});types.set(file.path,file.contentType);
|
||||||
|
}
|
||||||
|
for(const store of sidecar.kvStores) {
|
||||||
|
if(!store||files.has(store.path))throw new Error('KV snapshot collides with archived file');
|
||||||
|
paths.push({path:store.path});validateEntries(store.entries);
|
||||||
|
}
|
||||||
|
validatePaths([...paths,...[...directories].map(path=>({path,directory:true}))]);
|
||||||
|
for(const path of files.keys())if(path!==TRANSFER_MANIFEST&&!types.has(path))throw new Error('Undeclared project archive file');
|
||||||
|
if(!types.has('project.json'))throw new Error('Project manifest metadata missing');
|
||||||
|
for(const path of [...paths.map(file=>file.path),...directories]) {
|
||||||
|
const parts=path.split('/');parts.pop();
|
||||||
|
while(parts.length){directories.add(parts.join('/'));parts.pop();}
|
||||||
|
}
|
||||||
|
if(paths.length+directories.size>limits(options).maxEntries)throw new Error('Too many logical project files');
|
||||||
|
return {files,manifest,types,stores:sidecar.kvStores,directories:[...directories]};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function importName(client,name) {
|
||||||
|
const projects=await client.list(true);
|
||||||
|
if(!Array.isArray(projects))throw new Error('Project inventory unavailable before import');
|
||||||
|
const names=new Set(projects.map(project=>String(project.name).normalize('NFC').toLowerCase()));
|
||||||
|
for(let index=1;index<=projects.length+2;index++) {
|
||||||
|
const suffix=index===1?' (import)':` (import ${index})`;
|
||||||
|
let prefix=name.trim().slice(0,160-suffix.length);
|
||||||
|
if(/[\ud800-\udbff]$/.test(prefix))prefix=prefix.slice(0,-1);
|
||||||
|
const candidate=`${prefix.trimEnd()}${suffix}`;
|
||||||
|
if(!names.has(candidate.normalize('NFC').toLowerCase()))return candidate;
|
||||||
|
}
|
||||||
|
throw new Error('No available import name');
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function importProject(client,bytes,options={}) {
|
||||||
|
const bridge=bridgeFor(options);
|
||||||
|
const archive=inspectArchive(bytes,options);
|
||||||
|
scoped(client,options);
|
||||||
|
if(typeof client.stageCreate!=='function'||typeof client.adopt!=='function')throw new Error('Project import requires staged project creation');
|
||||||
|
if(archive.stores.length&&typeof bridge.applyKv!=='function')throw new Error('Host KV transfer helper unavailable');
|
||||||
|
const name=options.name??await importName(client,archive.manifest.name);
|
||||||
|
const session=await client.stageCreate(name);
|
||||||
|
if(!session)throw new Error('Project creation cancelled');
|
||||||
|
const scope=scoped(session,options);
|
||||||
|
try {
|
||||||
|
const existing=await session.listFiles('',true);assertLive(session);
|
||||||
|
const known=new Map(existing.filter(file=>file.path!==session.project.path).map(file=>[relative(session,file.path),file]));
|
||||||
|
for(const path of archive.directories.sort((a,b)=>a.split('/').length-b.split('/').length||a.localeCompare(b))) {
|
||||||
|
assertLive(session);
|
||||||
|
if(known.has(path)) {if(known.get(path).kind!=='folder')throw new Error('Import directory collides with a file');continue;}
|
||||||
|
const reply=await bridge.invoke('filesystem_create_folder',{...scope,path:session.path(path)});assertLive(session);
|
||||||
|
if(reply?.status!=='ok'||reply.path!==session.path(path)||typeof reply.fileId!=='string'||!reply.fileId)throw new Error('Imported project directory was not persisted');
|
||||||
|
}
|
||||||
|
for(const [path,content] of archive.files) {
|
||||||
|
if(path===TRANSFER_MANIFEST||path==='project.json')continue;
|
||||||
|
assertLive(session);
|
||||||
|
const reply=await bridge.invoke('filesystem_upload_files',{...scope,files:[{path:session.path(path),bytesBase64:base64(content),contentType:archive.types.get(path),replaceExisting:false}]});
|
||||||
|
assertLive(session);
|
||||||
|
confirmedWrite(reply,session.path(path));
|
||||||
|
}
|
||||||
|
for(const store of archive.stores) {
|
||||||
|
assertLive(session);
|
||||||
|
const opened=await session.openKv(store.path,{syncable:true});assertLive(session);
|
||||||
|
if(!opened||opened.error||['error','failed','unavailable'].includes(opened.status))throw new Error('Imported KV store could not be opened');
|
||||||
|
let batch=[],batchBytes=0;
|
||||||
|
const flush=async()=> {
|
||||||
|
if(!batch.length)return;
|
||||||
|
assertLive(session);
|
||||||
|
const result=await session.applyKv(store.path,{operations:batch});assertLive(session);
|
||||||
|
if(!result||result.error||['error','failed','unavailable'].includes(result.status))throw new Error('Imported KV mutation was not accepted');
|
||||||
|
batch=[];batchBytes=0;
|
||||||
|
};
|
||||||
|
const append=async operation=> {
|
||||||
|
const length=jsonBytes(operation).length;
|
||||||
|
if(batch.length&&(batch.length>=128||batchBytes+length>192*1024))await flush();
|
||||||
|
batch.push(operation);batchBytes+=length;
|
||||||
|
};
|
||||||
|
for(const entry of store.entries) {
|
||||||
|
await append({kind:'set',key:entry.key,value:entry.kind==='list'?[]:entry.value});
|
||||||
|
if(entry.kind==='list')for(let index=0;index<entry.value.length;index++)await append({kind:'list_append',key:entry.key,id:entry.itemIds[index],value:entry.value[index]});
|
||||||
|
}
|
||||||
|
await flush();
|
||||||
|
}
|
||||||
|
const base=await session.readFile('project.json');assertLive(session);
|
||||||
|
if(base.status!=='found')throw new Error('New project manifest unavailable');
|
||||||
|
const host=parseProjectManifest(JSON.parse(base.text));
|
||||||
|
const imported={...archive.manifest,id:host.id,name:host.name,createdAt:host.createdAt,updatedAt:new Date().toISOString(),importedFrom:{id:archive.manifest.id,importedAt:new Date().toISOString()},auditAuthority:'historical-only'};
|
||||||
|
await session.writeJson('project.json',imported,base);assertLive(session);
|
||||||
|
return await client.adopt(session);
|
||||||
|
}catch(error){await session.close();const failure=error instanceof Error?error:new Error(String(error));failure.project=session.project;throw failure;}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function exportProjectToDialog(session,options={}) {
|
||||||
|
const bytes=await exportProject(session,options);assertLive(session);
|
||||||
|
const result=await bridgeFor(options).invoke('save_file_dialog',{fileName:options.fileName??`${session.project.name||'project'}.isap.zip`,bytesBase64:base64(bytes),filterName:'ISA Project',extensions:['zip']});
|
||||||
|
assertLive(session);return result;
|
||||||
|
}
|
||||||
|
export async function importProjectFromDialog(client,options={}) {
|
||||||
|
const reply=await bridgeFor(options).invoke('select_files',{multiple:false,accessPolicy:'read-only',filters:['.zip']});
|
||||||
|
if(reply?.canceled||reply?.cancelled||!reply?.selections?.length)return null;
|
||||||
|
if(reply.selections.length!==1)throw new Error('Select one project ZIP');
|
||||||
|
return importProject(client,decodeBase64(reply.selections[0].bytesBase64),options);
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import { uncertain } from '../proofs.js';
|
||||||
|
|
||||||
|
function assertSnapshot(item,path,expected) {
|
||||||
|
if(!item||!['ok','found'].includes(item.status)||item.path!==path||item.source!=='dashboard'||item.authoritative!==true||uncertain(item))throw new Error('Project file became unavailable during export');
|
||||||
|
if((item.fileId??item.id)!==expected.id||item.syncRevision!==expected.revision||(expected.hash&&item.contentHash!==expected.hash))throw new Error('Project file changed during export');
|
||||||
|
}
|
||||||
|
function decode(value) {
|
||||||
|
if(typeof value!=='string'||value.length%4||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value))throw new Error('Invalid host file encoding');
|
||||||
|
return Uint8Array.from(atob(value),character=>character.charCodeAt(0));
|
||||||
|
}
|
||||||
|
export async function readExportFile(session,bridge,scope,row,expected,maxBytes) {
|
||||||
|
session.assertCurrent();
|
||||||
|
if(expected.size!==null&&(!Number.isSafeInteger(expected.size)||expected.size<0||expected.size>maxBytes))throw new Error('Project file exceeds transfer limit');
|
||||||
|
const request={...scope,path:row.path,cachePolicy:'dashboard-required',expectedSyncRevision:expected.revision,...(expected.hash?{expectedContentHash:expected.hash}:{})};
|
||||||
|
if(expected.size!==null&&expected.size>16*1024*1024) {
|
||||||
|
const link=await bridge.invoke('filesystem_get_download_link_file',request);session.assertCurrent();
|
||||||
|
assertSnapshot(link,row.path,expected);
|
||||||
|
if(!Number.isSafeInteger(link.fileSize)||link.fileSize!==expected.size||link.fileSize>maxBytes||typeof link.contentHash!=='string'||!/^[a-f0-9]{64}$/i.test(link.contentHash))throw new Error('Large project file lacks a bounded verified snapshot');
|
||||||
|
const url=new URL(link.downloadUrl,globalThis.location?.href);
|
||||||
|
if(!['http:','https:'].includes(url.protocol))throw new Error('Unsupported project download URL');
|
||||||
|
const response=await fetch(url,{signal:session.signal,credentials:'omit',redirect:'error'});session.assertCurrent();
|
||||||
|
if(!response.ok||!response.body)throw new Error('Project media download failed');
|
||||||
|
const reader=response.body.getReader();const chunks=[];let length=0;
|
||||||
|
try {
|
||||||
|
while(true) {
|
||||||
|
const next=await reader.read();session.assertCurrent();if(next.done)break;
|
||||||
|
length+=next.value.byteLength;
|
||||||
|
if(length>link.fileSize||length>maxBytes)throw new Error('Project media exceeds its declared size');
|
||||||
|
chunks.push(next.value);
|
||||||
|
}
|
||||||
|
} finally {await reader.cancel().catch(()=>{});reader.releaseLock();}
|
||||||
|
if(length!==link.fileSize)throw new Error('Project media download was incomplete');
|
||||||
|
const bytes=new Uint8Array(length);let offset=0;for(const chunk of chunks){bytes.set(chunk,offset);offset+=chunk.length;}
|
||||||
|
const digest=await crypto.subtle.digest('SHA-256',bytes);session.assertCurrent();
|
||||||
|
const hash=Array.from(new Uint8Array(digest),byte=>byte.toString(16).padStart(2,'0')).join('');
|
||||||
|
if(hash!==link.contentHash.toLowerCase())throw new Error('Project media content hash mismatch');
|
||||||
|
// A renewed ticket rechecks current authority and generation after streaming.
|
||||||
|
const current=await bridge.invoke('filesystem_get_download_link_file',request);session.assertCurrent();
|
||||||
|
assertSnapshot(current,row.path,expected);
|
||||||
|
if(current.contentHash!==link.contentHash||current.fileSize!==link.fileSize)throw new Error('Project media changed during export');
|
||||||
|
return bytes;
|
||||||
|
}
|
||||||
|
const result=await bridge.invoke('filesystem_get_files',{...scope,files:[request]});session.assertCurrent();
|
||||||
|
const item=result?.items?.length===1?result.items[0]:null;assertSnapshot(item,row.path,expected);
|
||||||
|
const bytes=typeof item.bytesBase64==='string'?decode(item.bytesBase64):typeof item.text==='string'?new TextEncoder().encode(item.text):null;
|
||||||
|
if(!bytes)throw new Error('Host project file content unavailable');
|
||||||
|
if(bytes.length>maxBytes)throw new Error('Project file exceeds transfer limit');
|
||||||
|
return bytes;
|
||||||
|
}
|
||||||
@@ -0,0 +1,142 @@
|
|||||||
|
import { Inflate, Zip, ZipDeflate, ZipPassThrough } from 'fflate';
|
||||||
|
import { validateArchivePath } from '../format.js';
|
||||||
|
|
||||||
|
export const DEFAULT_LIMITS = Object.freeze({ maxArchiveBytes: 512 * 1024 * 1024, maxFileBytes: 256 * 1024 * 1024, maxTotalBytes: 512 * 1024 * 1024, maxEntries: 10000 });
|
||||||
|
export function limits(options = {}) {
|
||||||
|
const result = {};
|
||||||
|
for (const [key, fallback] of Object.entries(DEFAULT_LIMITS)) {
|
||||||
|
const value = options[key] ?? fallback;
|
||||||
|
if (!Number.isSafeInteger(value) || value <= 0 || value > fallback) throw new TypeError(`Invalid transfer limit ${key}`);
|
||||||
|
result[key] = value;
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
const text = new TextDecoder('utf-8', { fatal: true });
|
||||||
|
const table = Uint32Array.from({length:256}, (_, index) => {
|
||||||
|
let value = index;
|
||||||
|
for (let bit = 0; bit < 8; bit++) value = (value >>> 1) ^ ((value & 1) ? 0xedb88320 : 0);
|
||||||
|
return value >>> 0;
|
||||||
|
});
|
||||||
|
function crc32(bytes) {
|
||||||
|
let value = 0xffffffff;
|
||||||
|
for (const byte of bytes) value = table[(value ^ byte) & 255] ^ (value >>> 8);
|
||||||
|
return (value ^ 0xffffffff) >>> 0;
|
||||||
|
}
|
||||||
|
const collisionKey = path => path.normalize('NFC').toLowerCase();
|
||||||
|
|
||||||
|
export function validatePaths(records) {
|
||||||
|
const paths = new Map();
|
||||||
|
const spellings = new Map();
|
||||||
|
for (const record of records) {
|
||||||
|
validateArchivePath(record.path);
|
||||||
|
const parts=record.path.split('/');
|
||||||
|
if(parts.some(part=>part!==part.trim()))throw new Error('Archive filename would be normalized by the host');
|
||||||
|
for(let length=1;length<=parts.length;length++) {
|
||||||
|
const prefix=parts.slice(0,length).join('/'), folded=collisionKey(prefix);
|
||||||
|
if(spellings.has(folded)&&spellings.get(folded)!==prefix)throw new Error('Archive path spelling collision');
|
||||||
|
spellings.set(folded,prefix);
|
||||||
|
if(spellings.size>DEFAULT_LIMITS.maxEntries)throw new Error('Too many archive paths');
|
||||||
|
}
|
||||||
|
const key = collisionKey(record.path);
|
||||||
|
if (paths.has(key)) throw new Error(`Duplicate or colliding archive path: ${record.path}`);
|
||||||
|
paths.set(key, record);
|
||||||
|
}
|
||||||
|
for (const record of records) {
|
||||||
|
const parts = record.path.split('/');
|
||||||
|
parts.pop();
|
||||||
|
while (parts.length) {
|
||||||
|
const parent = paths.get(collisionKey(parts.join('/')));
|
||||||
|
if (parent && !parent.directory) throw new Error('Archive file shadows a directory');
|
||||||
|
parts.pop();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function unpackZip(input, options) {
|
||||||
|
const bound = limits(options);
|
||||||
|
const bytes = input instanceof Uint8Array ? input : input instanceof ArrayBuffer ? new Uint8Array(input) : null;
|
||||||
|
if (!bytes || bytes.length < 22 || bytes.length > bound.maxArchiveBytes) throw new Error('Invalid or oversized project ZIP');
|
||||||
|
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
||||||
|
let end = -1;
|
||||||
|
for (let position = bytes.length - 22; position >= Math.max(0, bytes.length - 65557); position--) {
|
||||||
|
if (view.getUint32(position,true) === 0x06054b50 && position + 22 + view.getUint16(position+20,true) === bytes.length) { end = position; break; }
|
||||||
|
}
|
||||||
|
if (end < 0) throw new Error('ZIP central directory missing');
|
||||||
|
const count = view.getUint16(end+10,true), size = view.getUint32(end+12,true), offset = view.getUint32(end+16,true);
|
||||||
|
if (view.getUint16(end+4,true) || view.getUint16(end+6,true) || view.getUint16(end+8,true) !== count || count === 65535 || offset === 0xffffffff || size === 0xffffffff || count > bound.maxEntries || offset + size !== end) throw new Error('Unsupported or oversized ZIP directory');
|
||||||
|
const records = [];
|
||||||
|
let position = offset, total = 0;
|
||||||
|
for (let index = 0; index < count; index++) {
|
||||||
|
if (position + 46 > end || view.getUint32(position,true) !== 0x02014b50) throw new Error('Invalid ZIP directory entry');
|
||||||
|
const flags = view.getUint16(position+8,true), method = view.getUint16(position+10,true);
|
||||||
|
const crc = view.getUint32(position+16,true), compressed = view.getUint32(position+20,true), length = view.getUint32(position+24,true);
|
||||||
|
const nameLength = view.getUint16(position+28,true), extraLength = view.getUint16(position+30,true), commentLength = view.getUint16(position+32,true);
|
||||||
|
const attributes = view.getUint32(position+38,true), local = view.getUint32(position+42,true);
|
||||||
|
const unixKind = (attributes >>> 16) & 0xf000;
|
||||||
|
if ((flags & ~0x80e) || (flags & 1) || ![0,8].includes(method) || !nameLength || compressed === 0xffffffff || length === 0xffffffff || local === 0xffffffff || view.getUint16(position+34,true)) throw new Error('Unsupported ZIP entry');
|
||||||
|
const next = position + 46 + nameLength + extraLength + commentLength;
|
||||||
|
if (next > end) throw new Error('Truncated ZIP name');
|
||||||
|
const nameBytes = bytes.subarray(position+46,position+46+nameLength);
|
||||||
|
if (!(flags & 0x800) && nameBytes.some(byte=>byte>127)) throw new Error('Ambiguous ZIP filename encoding');
|
||||||
|
const name = text.decode(nameBytes), directory = name.endsWith('/');
|
||||||
|
const path = directory ? name.slice(0,-1) : name;
|
||||||
|
if ((unixKind && unixKind !== (directory ? 0x4000 : 0x8000)) || (directory && length !== 0) || (attributes & 0x10) && !directory) throw new Error('ZIP links or special entries are forbidden');
|
||||||
|
if (length > bound.maxFileBytes || (total += length) > bound.maxTotalBytes) throw new Error('ZIP decompression limits exceeded');
|
||||||
|
if (local + 30 > offset || view.getUint32(local,true) !== 0x04034b50 || view.getUint16(local+6,true) !== flags || view.getUint16(local+8,true) !== method) throw new Error('Invalid ZIP local header');
|
||||||
|
const localName = view.getUint16(local+26,true), localExtra = view.getUint16(local+28,true);
|
||||||
|
const start = local + 30 + localName + localExtra;
|
||||||
|
if (localName !== nameLength || start + compressed > offset || !nameBytes.every((byte,index)=>byte===bytes[local+30+index])) throw new Error('ZIP local filename or bounds differ');
|
||||||
|
if (!(flags & 8) && (view.getUint32(local+14,true)!==crc || view.getUint32(local+18,true)!==compressed || view.getUint32(local+22,true)!==length)) throw new Error('ZIP local sizes differ');
|
||||||
|
records.push({path,directory,method,crc,length,local,start,end:start+compressed});
|
||||||
|
position = next;
|
||||||
|
}
|
||||||
|
if (position !== end) throw new Error('Unexpected ZIP directory data');
|
||||||
|
validatePaths(records);
|
||||||
|
const ordered = [...records].sort((a,b)=>a.local-b.local);
|
||||||
|
for (let index=1;index<ordered.length;index++) if (ordered[index].local < ordered[index-1].end) throw new Error('Overlapping ZIP entries');
|
||||||
|
const files = new Map();
|
||||||
|
for (const record of records) {
|
||||||
|
if (record.directory) continue;
|
||||||
|
const chunks = []; let written = 0;
|
||||||
|
const accept = chunk => {
|
||||||
|
written += chunk.length;
|
||||||
|
if (written > record.length || written > bound.maxFileBytes) throw new Error('ZIP expanded beyond declared bounds');
|
||||||
|
chunks.push(chunk.slice());
|
||||||
|
};
|
||||||
|
if (record.method === 0) accept(bytes.subarray(record.start,record.end));
|
||||||
|
else {
|
||||||
|
const inflater = new Inflate(accept);
|
||||||
|
if (record.start === record.end) throw new Error('Invalid empty DEFLATE stream');
|
||||||
|
for (let part=record.start;part<record.end;part+=4096) inflater.push(bytes.subarray(part,Math.min(part+4096,record.end)),part+4096>=record.end);
|
||||||
|
}
|
||||||
|
if (written !== record.length) throw new Error('ZIP expanded size differs');
|
||||||
|
const content = new Uint8Array(written); let cursor=0;
|
||||||
|
for (const chunk of chunks) {content.set(chunk,cursor);cursor+=chunk.length;}
|
||||||
|
if (crc32(content)!==record.crc) throw new Error('ZIP checksum differs');
|
||||||
|
files.set(record.path,content);
|
||||||
|
}
|
||||||
|
Object.defineProperty(files,'directories',{value:records.filter(record=>record.directory).map(record=>record.path)});
|
||||||
|
return files;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function packZip(files, options, directories=[]) {
|
||||||
|
const bound=limits(options), records=[...files.keys()].map(path=>({path,directory:false})).concat(directories.map(path=>({path,directory:true})));
|
||||||
|
validatePaths(records);
|
||||||
|
if(records.length>bound.maxEntries)throw new Error('Too many project files');
|
||||||
|
let total=0,archiveBytes=0; const chunks=[];
|
||||||
|
const archive=new Zip((error,chunk)=> {
|
||||||
|
if(error)throw error;
|
||||||
|
archiveBytes+=chunk.length;
|
||||||
|
if(archiveBytes>bound.maxArchiveBytes)throw new Error('Project ZIP exceeds archive limit');
|
||||||
|
chunks.push(chunk);
|
||||||
|
});
|
||||||
|
for(const [path,bytes] of files) {
|
||||||
|
if(bytes.length>bound.maxFileBytes||(total+=bytes.length)>bound.maxTotalBytes)throw new Error('Project transfer limits exceeded');
|
||||||
|
const file=new ZipDeflate(path,{level:6});archive.add(file);file.push(bytes,true);
|
||||||
|
}
|
||||||
|
for(const path of directories){const directory=new ZipPassThrough(`${path}/`);archive.add(directory);directory.push(new Uint8Array(),true);}
|
||||||
|
archive.end();
|
||||||
|
const result=new Uint8Array(archiveBytes);let offset=0;
|
||||||
|
for(const chunk of chunks){result.set(chunk,offset);offset+=chunk.length;}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
@@ -0,0 +1,217 @@
|
|||||||
|
import test from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { createProjectClient } from '../src/client.js';
|
||||||
|
|
||||||
|
const project = id => ({id,folderId:id,name:id,path:`/projects/${id}.isap`,projectIdentity:id,formatVersion:1});
|
||||||
|
function fixture(options = {}) {
|
||||||
|
const writes = [];
|
||||||
|
const files = new Map(['one','two','three'].map(id => [`${project(id).path}/project.json`,{
|
||||||
|
formatVersion:1,id,name:id,createdAt:'2026-11-03T12:00:00Z',updatedAt:'2026-11-03T12:00:00Z',unknown:{kept:true}
|
||||||
|
}]));
|
||||||
|
let saved = null;
|
||||||
|
const bridge = {
|
||||||
|
async invoke(command,args) {
|
||||||
|
if (options.invoke) { const result = options.invoke(command,args); if (result !== undefined) return result; }
|
||||||
|
if (command === 'filesystem_get_files') {
|
||||||
|
const path = args.files[0].path;
|
||||||
|
return {items:[files.has(path) ? {status:'ok',path,source:'dashboard',authoritative:true,text:JSON.stringify(files.get(path)),fileId:path,syncRevision:4,contentHash:'a'.repeat(64)} : {status:'absent',path,source:'dashboard',authoritative:true}]};
|
||||||
|
}
|
||||||
|
if (command === 'localstorage_get') return saved;
|
||||||
|
if (command === 'localstorage_put') { saved=args.value;return {ok:true}; }
|
||||||
|
if (command === 'filesystem_upload_files') { writes.push(args); return {items:[{status:'ok',isComplete:true,path:args.files[0].path,fileId:args.files[0].path}]}; }
|
||||||
|
throw new Error(`Unexpected command ${command}`);
|
||||||
|
},
|
||||||
|
subscribeKv: options.subscribeKv
|
||||||
|
};
|
||||||
|
const client = createProjectClient({bridge,extensionId:'contracts',scope:{workspaceId:'workspace',groupId:'group'},beforeSwitch:options.beforeSwitch});
|
||||||
|
return {client,writes,bridge,files};
|
||||||
|
}
|
||||||
|
|
||||||
|
test('captured sessions fence old writes and close late subscriptions during switching', async () => {
|
||||||
|
let finishSubscription;
|
||||||
|
let stopped = 0;
|
||||||
|
const {client,writes} = fixture({subscribeKv:() => new Promise(resolve=>{finishSubscription=resolve;})});
|
||||||
|
const first = await client.activate(project('one'));
|
||||||
|
const subscription = first.subscribeKv('extensions/contracts/state.kv',{},()=>assert.fail('Old subscription event'));
|
||||||
|
await client.activate(project('two'));
|
||||||
|
finishSubscription({unsubscribe:async()=>{stopped++;}});
|
||||||
|
await assert.rejects(subscription,{name:'AbortError'});
|
||||||
|
await assert.rejects(first.writeJson('extensions/contracts/state.json',{}, {status:'absent',path:first.path('extensions/contracts/state.json')}),{name:'AbortError'});
|
||||||
|
assert.equal(stopped,1);
|
||||||
|
assert.equal(writes.length,0);
|
||||||
|
await client.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('JSON writes require captured authoritative CAS base and preserve caller data', async () => {
|
||||||
|
const {client,writes,files} = fixture();
|
||||||
|
const session = await client.activate(project('one'));
|
||||||
|
files.set(session.path('extensions/contracts/state.json'),{unknown:{retained:1},value:2});
|
||||||
|
const base = await session.readJson('extensions/contracts/state.json');
|
||||||
|
await session.writeJson('extensions/contracts/state.json',{...base.value,value:3},base);
|
||||||
|
const uploaded = writes[0].files[0];
|
||||||
|
assert.equal(uploaded.expectedSyncRevision,4);
|
||||||
|
assert.equal(uploaded.expectedContentHash,'a'.repeat(64));
|
||||||
|
assert.equal(uploaded.replaceExisting,true);
|
||||||
|
assert.deepEqual(JSON.parse(uploaded.text),{unknown:{retained:1},value:3});
|
||||||
|
assert.equal(writes[0].workspaceId,'workspace');
|
||||||
|
assert.equal(writes[0].groupId,'group');
|
||||||
|
await assert.rejects(session.writeJson('elsewhere.json',{},base),/authoritative read/);
|
||||||
|
assert.throws(()=>session.path('../escape.json'),/Unsafe/);
|
||||||
|
await client.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('dirty state blocks switching and unavailable reads never become absence', async () => {
|
||||||
|
let missing = false;
|
||||||
|
const {client} = fixture({invoke:(command)=>missing && command==='filesystem_get_files' ? {items:[{status:'unavailable',authoritative:false}]} : undefined});
|
||||||
|
const first = await client.activate(project('one'));
|
||||||
|
first.markDirty();
|
||||||
|
await assert.rejects(client.activate(project('two')),/Unsaved/);
|
||||||
|
assert.equal(client.active,first);
|
||||||
|
first.markDirty(false);
|
||||||
|
missing=true;
|
||||||
|
await assert.rejects(first.readJson('state.json'),{name:'ProjectUnavailableError'});
|
||||||
|
assert.equal(client.active,first);
|
||||||
|
await client.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('uncertain create retries retain operation identity through manifest recovery', async () => {
|
||||||
|
const ids=[];
|
||||||
|
const {client}=fixture({invoke:(command,args)=>{
|
||||||
|
if(command!=='projects_create')return;
|
||||||
|
ids.push(args.operationId);
|
||||||
|
if(ids.length===1)throw new Error('Commit outcome unavailable');
|
||||||
|
return {project:project('one')};
|
||||||
|
}});
|
||||||
|
await assert.rejects(client.create('Example'),/unavailable/);
|
||||||
|
const created=await client.create('Example');
|
||||||
|
assert.equal(created.project.id,'one');
|
||||||
|
assert.equal(ids[0],ids[1]);
|
||||||
|
await client.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('authoritative reads reject another path, cached drafts and ambiguous identities', async () => {
|
||||||
|
let reply;
|
||||||
|
const {client}=fixture({invoke:command=>command==='filesystem_get_files'?reply:undefined});
|
||||||
|
const session=await client.activate(project('one'));
|
||||||
|
const path=session.path('state.json');
|
||||||
|
const valid={status:'ok',path,source:'dashboard',authoritative:true,fileId:'file',syncRevision:1,text:'{}'};
|
||||||
|
for(const change of [{path:path+'wrong'},{source:'cache'},{pendingUpload:true},{syncRevision:null},{workspaceFileOutcome:'conflict'},{status:'absent',path:path+'wrong'}]) {
|
||||||
|
reply={items:[{...valid,...change}]};
|
||||||
|
await assert.rejects(session.readJson('state.json'),{name:'ProjectUnavailableError'});
|
||||||
|
}
|
||||||
|
reply={items:[valid,valid]};
|
||||||
|
await assert.rejects(session.readJson('state.json'),{name:'ProjectUnavailableError'});
|
||||||
|
await client.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('successful transport cannot confirm pending or conflicted project writes', async () => {
|
||||||
|
let reply;
|
||||||
|
const {client}=fixture({invoke:command=>command==='filesystem_upload_files'?reply:undefined});
|
||||||
|
const session=await client.activate(project('one'));
|
||||||
|
const base=await session.readJson('state.json');
|
||||||
|
const valid={status:'ok',isComplete:true,path:base.path,fileId:'file'};
|
||||||
|
for(const change of [{isComplete:false},{path:base.path+'wrong'},{fileId:''},{pendingUpload:true},{pendingState:'queued'},{conflict:true},{workspaceFileOutcome:'conflict'},{workspaceFileOutcome:'pending'},{source:'cache'}]) {
|
||||||
|
reply={items:[{...valid,...change}]};
|
||||||
|
await assert.rejects(session.writeJson('state.json',{},base),/not confirmed|conflict/);
|
||||||
|
}
|
||||||
|
reply={items:[valid]};
|
||||||
|
assert.equal((await session.writeJson('state.json',{},base)).fileId,'file');
|
||||||
|
await client.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a listed group project opens by folder ID on its first use, without a second picker or project creation', async () => {
|
||||||
|
let reply = project('two');
|
||||||
|
const commands = [];
|
||||||
|
const {client} = fixture({invoke(command,args) {
|
||||||
|
commands.push(command);
|
||||||
|
if (command === 'get_app_info') return {projects:{commands:['projects_open_listed']}};
|
||||||
|
if (command === 'projects_list') return {projects:[{...reply, canWrite:false, updatedAt:'2026-09-01'}]};
|
||||||
|
if (command === 'projects_open_listed') {
|
||||||
|
assert.deepEqual(args,{projectId:'two'});
|
||||||
|
return {status:'ok',project:reply};
|
||||||
|
}
|
||||||
|
}});
|
||||||
|
const [listed] = await client.list();
|
||||||
|
assert.equal(listed.canWrite,false);
|
||||||
|
assert.equal(listed.updatedAt,'2026-09-01');
|
||||||
|
const selected = await client.openListed(listed);
|
||||||
|
assert.equal(selected.project.id,'two');
|
||||||
|
reply = project('one');
|
||||||
|
await assert.rejects(client.openListed(listed),/identity/);
|
||||||
|
assert.equal(client.active,selected);
|
||||||
|
assert.ok(!commands.some(command => ['projects_open','projects_create','filesystem_upload_files'].includes(command)));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('older hosts reopen an existing grant and report a denied row without reopening the picker', async () => {
|
||||||
|
const {client,files} = fixture({invoke(command, args) {
|
||||||
|
if (command === 'get_app_info') return {projects:{commands:['projects_open']}};
|
||||||
|
if (command === 'filesystem_get_files' && args.files[0].path === project('three').path + '/project.json') {
|
||||||
|
return {items:[{path:args.files[0].path, status:'error', authoritative:false, error:'extension filesystem permission is required'}]};
|
||||||
|
}
|
||||||
|
if (command === 'projects_open') assert.fail('Unexpected second project picker');
|
||||||
|
}});
|
||||||
|
const selected = await client.openListed(project('one'));
|
||||||
|
files.delete(project('two').path+'/project.json');
|
||||||
|
await assert.rejects(client.openListed(project('two')), /manifest missing/);
|
||||||
|
await assert.rejects(client.openListed(project('three')), /extension filesystem permission is required/);
|
||||||
|
assert.equal(client.active,selected);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a direct grant initializes the extension directory on first writable access', async () => {
|
||||||
|
const selected = {...project('two'), canWrite:true};
|
||||||
|
const directories = [];
|
||||||
|
const {client} = fixture({invoke(command, args) {
|
||||||
|
if (command === 'get_app_info') return {projects:{commands:['projects_open_listed']}};
|
||||||
|
if (command === 'projects_open_listed') return {status:'ok', project:selected};
|
||||||
|
if (command === 'filesystem_list_dir') return {authoritative:true, files:[]};
|
||||||
|
if (command === 'filesystem_create_folder') {
|
||||||
|
directories.push(args.path);
|
||||||
|
return {status:'ok', path:args.path, fileId:args.path};
|
||||||
|
}
|
||||||
|
}});
|
||||||
|
assert.equal((await client.openListed(selected)).project.id, selected.id);
|
||||||
|
assert.deepEqual(directories, [selected.path + '/extensions', selected.path + '/extensions/contracts']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('first-open initialization reads the winning record after a folder race and an uncertain create', async () => {
|
||||||
|
let uploads = 0;
|
||||||
|
const {client, files} = fixture({invoke(command, args) {
|
||||||
|
if (command === 'filesystem_create_folder') throw new Error('Already exists');
|
||||||
|
if (command === 'filesystem_list_dir') {
|
||||||
|
return {authoritative:true, files:['extensions','contracts','data'].map(name => ({path:args.path + '/' + name, kind:'folder', id:name}))};
|
||||||
|
}
|
||||||
|
if (command === 'filesystem_upload_files') {
|
||||||
|
const file = args.files[0];
|
||||||
|
assert.equal(file.replaceExisting, false);
|
||||||
|
assert.equal(file.path, project('one').path + '/extensions/contracts/data/current.json');
|
||||||
|
files.set(file.path, {from:'other session'});
|
||||||
|
uploads++;
|
||||||
|
throw new Error('Create outcome unknown');
|
||||||
|
}
|
||||||
|
}});
|
||||||
|
const session = await client.activate({...project('one'), canWrite:true});
|
||||||
|
const created = await session.ensureExtensionJson('data/current.json', () => ({from:'this session'}));
|
||||||
|
assert.deepEqual(created.value, {from:'other session'});
|
||||||
|
const reopened = await session.ensureExtensionJson('data/current.json', () => assert.fail('Record already exists'));
|
||||||
|
assert.deepEqual(reopened.value, created.value);
|
||||||
|
assert.equal(uploads, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('read-only, archived and uncertain reads cannot seed extension records', async () => {
|
||||||
|
let answer;
|
||||||
|
const {client, writes} = fixture({invoke(command, args) {
|
||||||
|
if (command === 'filesystem_get_files' && answer && !args.files[0].path.endsWith('/project.json')) {
|
||||||
|
return {items:[{path:args.files[0].path, ...answer}]};
|
||||||
|
}
|
||||||
|
}});
|
||||||
|
const fail = () => assert.fail('Unexpected default');
|
||||||
|
for (const access of [{canWrite:false}, {archived:true, canWrite:true}]) {
|
||||||
|
const session = await client.activate({...project('one'), ...access});
|
||||||
|
assert.equal((await session.ensureExtensionJson('state.json', fail)).status, 'absent');
|
||||||
|
}
|
||||||
|
const session = await client.activate(project('two'));
|
||||||
|
for (answer of [{status:'unavailable'}, {status:'absent',source:'dashboard',authoritative:true,found:true}]) {
|
||||||
|
await assert.rejects(session.ensureExtensionJson('state.json', fail), {name:'ProjectUnavailableError'});
|
||||||
|
}
|
||||||
|
assert.equal(writes.length, 0);
|
||||||
|
});
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import test from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { createProjectManifest, parseProjectManifest, validateArchivePath, extensionDataPath } from '../src/index.js';
|
||||||
|
|
||||||
|
test('reject archive traversal and cross-platform unsafe paths before storage', () => {
|
||||||
|
for (const path of ['../project.json', '/project.json', 'a/../../b', 'a\\..\\b', 'C:/x', 'a//b', './x', 'a/./b', 'a\0b', 'a\nb', 'a/NUL.txt', 'a/file.', 'a/file ']) {
|
||||||
|
assert.throws(() => validateArchivePath(path), { name: 'TypeError' }, path);
|
||||||
|
}
|
||||||
|
assert.equal(validateArchivePath('assets/meeting audio.ogg'), 'assets/meeting audio.ogg');
|
||||||
|
assert.equal(extensionDataPath('isa-quote', 'state/current.json'), 'extensions/isa-quote/state/current.json');
|
||||||
|
assert.throws(() => extensionDataPath('../quote', 'x'));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('preserve unknown manifest data without sharing mutable references', () => {
|
||||||
|
const manifest = { ...createProjectManifest({ id: 'project-1', name: 'Example' }), future: { value: 1 } };
|
||||||
|
const parsed = parseProjectManifest(manifest);
|
||||||
|
parsed.future.value = 2;
|
||||||
|
assert.equal(manifest.future.value, 1);
|
||||||
|
assert.throws(() => parseProjectManifest({ ...manifest, formatVersion: 2 }));
|
||||||
|
assert.throws(() => parseProjectManifest({ ...manifest, createdAt: 'yesterday' }));
|
||||||
|
assert.throws(() => parseProjectManifest({ ...manifest, createdAt: '2026-02-30T00:00:00Z' }));
|
||||||
|
});
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import test from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { readExportFile } from '../src/transfer/files.js';
|
||||||
|
|
||||||
|
test('large media uses bounded streaming with hash verification and renewed authority', async () => {
|
||||||
|
const bytes=new Uint8Array(16*1024*1024+1);bytes[bytes.length-1]=42;
|
||||||
|
const hash=Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',bytes)),v=>v.toString(16).padStart(2,'0')).join('');
|
||||||
|
const path='/project.isap/assets/recording.wav';
|
||||||
|
const expected={id:'recording',revision:2,hash,size:bytes.length};
|
||||||
|
const link={status:'ok',source:'dashboard',authoritative:true,path,fileId:expected.id,syncRevision:2,contentHash:hash,fileSize:bytes.length,downloadUrl:'https://downloads.example/one-use'};
|
||||||
|
const controller=new AbortController();
|
||||||
|
const session={signal:controller.signal,assertCurrent(){this.signal.throwIfAborted();}};
|
||||||
|
const original=globalThis.fetch;let requests=0,mode='ok';
|
||||||
|
const bridge={async invoke(command,args){assert.equal(command,'filesystem_get_download_link_file');assert.equal(args.path,path);requests++;return mode==='revoked'&&requests===2?{status:'unavailable',authoritative:false}:link;}};
|
||||||
|
globalThis.fetch=async(url,options)=> {
|
||||||
|
assert.equal(url.href,link.downloadUrl);assert.equal(options.signal,session.signal);assert.equal(options.credentials,'omit');
|
||||||
|
return new Response(new ReadableStream({start(stream){stream.enqueue(mode==='corrupt'?new Uint8Array(bytes.length):bytes);stream.close();}}));
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
assert.deepEqual(await readExportFile(session,bridge,{workspaceId:'workspace',groupId:'group'},{path},expected,bytes.length),bytes);
|
||||||
|
assert.equal(requests,2);
|
||||||
|
mode='corrupt';requests=0;
|
||||||
|
await assert.rejects(readExportFile(session,bridge,{}, {path},expected,bytes.length),/hash mismatch/);
|
||||||
|
assert.equal(requests,1);
|
||||||
|
mode='revoked';requests=0;
|
||||||
|
await assert.rejects(readExportFile(session,bridge,{}, {path},expected,bytes.length),/unavailable/);
|
||||||
|
await assert.rejects(readExportFile(session,bridge,{}, {path},expected,bytes.length-1),/transfer limit/);
|
||||||
|
} finally {globalThis.fetch=original;}
|
||||||
|
});
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
import test from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import {createSharedFolderReader} from '../src/shared-folder.js';
|
||||||
|
|
||||||
|
test('specialist and other viewers read the same existing supplier register and price book', async () => {
|
||||||
|
const root='/Shared/Registers';
|
||||||
|
const scope={workspaceId:'w',groupId:'g'};
|
||||||
|
const folder={path:root,...scope};
|
||||||
|
const register={format:'isa-match-workspace-suppliers-v1',workspaceId:'w',id:'abc',suppliers:[{id:'supplier-1',name:'Voorbeeld',administration:'',number:''}]};
|
||||||
|
const row={supplier:'Voorbeeld',unit:'m²',unitPrice:42,currency:'EUR'};
|
||||||
|
const commands=[];
|
||||||
|
function viewer(extension) {
|
||||||
|
return createSharedFolderReader({folder,scope,bridge:{
|
||||||
|
async invoke(command,args) {
|
||||||
|
commands.push([extension,command]);
|
||||||
|
if (command === 'filesystem_list_dir') {
|
||||||
|
assert.equal(args.path,root);
|
||||||
|
return {authoritative:true,files:[{kind:'file',path:root+'/isa-match-suppliers.json'}]};
|
||||||
|
}
|
||||||
|
assert.equal(command,'filesystem_get_files');
|
||||||
|
assert.equal(args.groupId,'g');
|
||||||
|
const [{path,cachePolicy}]=args.files;
|
||||||
|
assert.equal(path,root+'/isa-match-suppliers.json');
|
||||||
|
assert.equal(cachePolicy,'dashboard-required');
|
||||||
|
return {items:[{path,source:'dashboard',authoritative:true,status:'ok',fileId:'index',syncRevision:1,...(extension==='other-viewer'?{bytesBase64:Buffer.from(JSON.stringify(register)).toString('base64')}:{text:JSON.stringify(register)})}]};
|
||||||
|
},
|
||||||
|
async snapshotKv(args) {
|
||||||
|
commands.push([extension,'snapshot']);
|
||||||
|
assert.equal(args.path,root+'/isa-match-prices-abc.kv');
|
||||||
|
return {revision:2,snapshotId:'snapshot',storeId:'store',incarnation:'1',entries:[{status:'found',kind:'value',key:'price/g/1',value:row}]};
|
||||||
|
}
|
||||||
|
}});
|
||||||
|
}
|
||||||
|
for(const reader of [viewer('supplier-viewer'),viewer('other-viewer')]) {
|
||||||
|
assert.equal((await reader.listFiles()).length,1);
|
||||||
|
const index=await reader.readJson('isa-match-suppliers.json');
|
||||||
|
assert.deepEqual(index.value,register);
|
||||||
|
const result=await reader.readKv('isa-match-prices-'+index.value.id+'.kv');
|
||||||
|
assert.deepEqual(result.entries[0].value,row);
|
||||||
|
await assert.rejects(reader.readKv('../other.kv'),/Unsafe/);
|
||||||
|
}
|
||||||
|
assert.equal(commands.length,6);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('revocation and mismatched launch scopes never resolve to empty or initialized data',async () => {
|
||||||
|
const scope={workspaceId:'w',groupId:'g'};
|
||||||
|
const bridge={invoke:async()=>{throw new Error('Access revoked');}};
|
||||||
|
assert.throws(()=>createSharedFolderReader({scope,bridge,folder:{path:'/Shared',groupId:'other'}}),/Invalid shared folder/);
|
||||||
|
const reader=createSharedFolderReader({scope,bridge,folder:{path:'/Shared'}});
|
||||||
|
await assert.rejects(reader.readJson('isa-match-suppliers.json'),/Access revoked/);
|
||||||
|
});
|
||||||
@@ -0,0 +1,229 @@
|
|||||||
|
import test from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import {zipSync,unzipSync,strToU8,strFromU8} from 'fflate';
|
||||||
|
import {createProjectClient} from '../src/client.js';
|
||||||
|
import {exportProject,importProject,exportProjectToDialog,importProjectFromDialog,TRANSFER_MANIFEST} from '../src/transfer.js';
|
||||||
|
import {packZip,unpackZip} from '../src/transfer/zip.js';
|
||||||
|
|
||||||
|
const scope={workspaceId:'workspace',groupId:'group'};
|
||||||
|
const KV_TYPE='application/vnd.isa.kv-store';
|
||||||
|
const manifest=id=>({formatVersion:1,id,name:'Example',createdAt:'2026-11-03T12:00:00Z',updatedAt:'2026-11-03T12:00:00Z',unknown:{keep:true}});
|
||||||
|
const project=id=>({id,folderId:id,name:'Example',path:`/projects/${id}.isap`,projectIdentity:id});
|
||||||
|
function fixture() {
|
||||||
|
const files=new Map(),stores=new Map(),snapshots=new Map(),calls=[],projects=new Map();
|
||||||
|
let creates=0,snapshotSequence=0;
|
||||||
|
function add(path,bytes,type='application/octet-stream') {files.set(path,{bytes:bytes instanceof Uint8Array?bytes:strToU8(bytes),contentType:type,revision:1,id:path});}
|
||||||
|
function folder(path){files.set(path,{kind:'folder',bytes:new Uint8Array(),revision:0,id:path});}
|
||||||
|
function putProject(id,name='Example') {const value={...project(id),name};projects.set(id,value);folder(value.path);folder(`${value.path}/extensions`);folder(`${value.path}/assets`);add(`${value.path}/project.json`,JSON.stringify({...manifest(id),name}),'application/json');return value;}
|
||||||
|
const original=putProject('original');
|
||||||
|
const media=new Uint8Array([0,255,17,48,0,99]);
|
||||||
|
add(`${original.path}/assets/audio.bin`,media,'audio/wav');
|
||||||
|
add(`${original.path}/extensions/unknown/future.json`,'{"future":true}','application/json');
|
||||||
|
add(`${original.path}/extensions/unknown/opaque.kv`,'ordinary unknown bytes','application/octet-stream');
|
||||||
|
add(`${original.path}/__proto__`,'unknown root file','application/octet-stream');
|
||||||
|
folder(`${original.path}/extensions/unknown`);folder(`${original.path}/extensions/unknown/empty`);folder(`${original.path}/extensions/unknown/empty/deep`);folder(`${original.path}/extensions/quote`);
|
||||||
|
const kvPath=`${original.path}/extensions/quote/state.kv`;
|
||||||
|
add(kvPath,'STALE CHECKPOINT',KV_TYPE);
|
||||||
|
stores.set(kvPath,{revision:9,entries:[{key:'empty',status:'found',kind:'list',itemIds:[],value:[]},{key:'rows',status:'found',kind:'list',itemIds:['stable-b','stable-a'],value:[{name:'Latest'},{name:'Second'}]},{key:'value',status:'found',kind:'value',value:{updated:true}}]});
|
||||||
|
const bridge={
|
||||||
|
async invoke(command,args) {
|
||||||
|
calls.push({command,args});
|
||||||
|
if(command==='localstorage_get')return [];
|
||||||
|
if(command==='localstorage_put')return {status:'ok'};
|
||||||
|
if(command==='projects_list')return {projects:[...projects.values()]};
|
||||||
|
if(command==='projects_create')return {created:true,project:putProject(`imported-${++creates}`,args.name)};
|
||||||
|
if(command==='filesystem_list_dir')return {authoritative:true,files:[...files].filter(([path])=>path.startsWith(`${args.path}/`)).map(([path,row])=>({path,id:row.id,kind:row.kind??'file',contentType:row.contentType,syncRevision:row.revision,fileSize:row.bytes.length}))};
|
||||||
|
if(command==='filesystem_create_folder') {assert.equal(files.get(args.path.slice(0,args.path.lastIndexOf('/')))?.kind,'folder');folder(args.path);return {status:'ok',path:args.path,fileId:files.get(args.path).id};}
|
||||||
|
if(command==='filesystem_get_files')return {items:args.files.map(request=>{
|
||||||
|
const row=files.get(request.path);
|
||||||
|
if(!row)return {status:'absent',path:request.path,source:'dashboard',authoritative:true};
|
||||||
|
if(request.expectedSyncRevision!==undefined)assert.equal(request.expectedSyncRevision,row.revision);
|
||||||
|
return {status:'ok',source:'dashboard',authoritative:true,path:request.path,fileId:row.id,syncRevision:row.revision,bytesBase64:Buffer.from(row.bytes).toString('base64'),...(row.contentType==='application/json'?{text:strFromU8(row.bytes)}:{})};
|
||||||
|
})};
|
||||||
|
if(command==='filesystem_upload_files') {
|
||||||
|
for(const item of args.files) {
|
||||||
|
const previous=files.get(item.path);
|
||||||
|
assert.equal(item.replaceExisting,Boolean(previous));
|
||||||
|
if(previous)assert.equal(item.expectedSyncRevision,previous.revision);
|
||||||
|
add(item.path,item.text??new Uint8Array(Buffer.from(item.bytesBase64,'base64')),item.contentType);
|
||||||
|
if(previous)files.get(item.path).revision=previous.revision+1;
|
||||||
|
}
|
||||||
|
return {items:args.files.map(item=>({status:'ok',isComplete:true,path:item.path,fileId:files.get(item.path).id}))};
|
||||||
|
}
|
||||||
|
if(command==='kv_store_open') {add(args.path,'NEW CHECKPOINT',KV_TYPE);stores.set(args.path,{revision:0,entries:[]});return {status:'ok'};}
|
||||||
|
if(command==='save_file_dialog')return {status:'ok',saved:true};
|
||||||
|
if(command==='select_files')return bridge.selection??{canceled:true,selections:[]};
|
||||||
|
throw new Error(`Unexpected ${command}`);
|
||||||
|
},
|
||||||
|
async snapshotKv(args) {
|
||||||
|
calls.push({command:'snapshotKv',args});
|
||||||
|
let id,index;
|
||||||
|
if(args.cursor){[id,index]=args.cursor.split(':');index=Number(index);}
|
||||||
|
else {id=`snapshot-${++snapshotSequence}`;index=0;snapshots.set(id,structuredClone(stores.get(args.path)));}
|
||||||
|
const store=snapshots.get(id),limit=Math.min(args.limit??1,2),entries=store.entries.slice(index,index+limit);
|
||||||
|
return {snapshotId:id,revision:store.revision,storeId:args.path,incarnation:'incarnation',entries,nextCursor:index+limit<store.entries.length?`${id}:${index+limit}`:null};
|
||||||
|
},
|
||||||
|
async applyKv(args) {
|
||||||
|
calls.push({command:'applyKv',args});
|
||||||
|
const store=stores.get(args.path);
|
||||||
|
for(const operation of args.operations) {
|
||||||
|
let entry=store.entries.find(entry=>entry.key===operation.key);
|
||||||
|
if(operation.kind==='set') {
|
||||||
|
entry={key:operation.key,status:'found',kind:Array.isArray(operation.value)?'list':'value',value:structuredClone(operation.value),...(Array.isArray(operation.value)?{itemIds:[]}:{})};
|
||||||
|
store.entries=store.entries.filter(other=>other.key!==entry.key);store.entries.push(entry);
|
||||||
|
}else if(operation.kind==='list_append') {entry.itemIds.push(operation.id);entry.value.push(structuredClone(operation.value));}
|
||||||
|
else assert.fail(`Unexpected operation ${operation.kind}`);
|
||||||
|
}
|
||||||
|
store.revision++;return {status:'ok'};
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const client=createProjectClient({bridge,extensionId:'contracts',scope});
|
||||||
|
return {bridge,client,files,stores,calls,original,media,kvPath,get creates(){return creates;}};
|
||||||
|
}
|
||||||
|
|
||||||
|
test('whole project ZIP roundtrip preserves unknown files, media, live KV list IDs and a new identity',async()=>{
|
||||||
|
const f=fixture(),source=await f.client.activate(f.original);
|
||||||
|
source.permission={grantId:'DO-NOT-EXPORT'};
|
||||||
|
const originalManifest=manifest('original');originalManifest.credentials={token:'DO-NOT-EXPORT'};
|
||||||
|
f.files.get(`${f.original.path}/project.json`).bytes=strToU8(JSON.stringify(originalManifest));
|
||||||
|
const bytes=await exportProject(source,{bridge:f.bridge});
|
||||||
|
assert.equal(new DataView(bytes.buffer,bytes.byteOffset).getUint32(0,true),0x04034b50);
|
||||||
|
const decoded=unzipSync(bytes),sidecar=JSON.parse(strFromU8(decoded[TRANSFER_MANIFEST]));
|
||||||
|
assert.ok(!decoded['extensions/quote/state.kv']);
|
||||||
|
assert.ok(!JSON.stringify(sidecar).includes('STALE CHECKPOINT'));
|
||||||
|
assert.ok(!Object.values(decoded).some(value=>strFromU8(value).includes('DO-NOT-EXPORT')));
|
||||||
|
assert.deepEqual(sidecar.kvStores[0].entries[1].itemIds,['stable-b','stable-a']);
|
||||||
|
assert.ok(f.calls.some(call=>call.command==='snapshotKv'&&call.args.cursor));
|
||||||
|
const imported=await importProject(f.client,bytes,{bridge:f.bridge});
|
||||||
|
assert.notEqual(imported.project.id,source.project.id);
|
||||||
|
const saved=JSON.parse(strFromU8(f.files.get(imported.path('project.json')).bytes));
|
||||||
|
assert.equal(saved.id,imported.project.projectIdentity);assert.deepEqual(saved.unknown,{keep:true});
|
||||||
|
assert.equal(saved.importedFrom.id,'original');assert.equal(saved.auditAuthority,'historical-only');
|
||||||
|
assert.deepEqual(f.files.get(imported.path('assets/audio.bin')).bytes,f.media);
|
||||||
|
assert.equal(strFromU8(f.files.get(imported.path('extensions/unknown/future.json')).bytes),'{"future":true}');
|
||||||
|
assert.equal(strFromU8(f.files.get(imported.path('extensions/unknown/opaque.kv')).bytes),'ordinary unknown bytes');
|
||||||
|
assert.equal(strFromU8(f.files.get(imported.path('__proto__')).bytes),'unknown root file');
|
||||||
|
assert.equal(f.files.get(imported.path('extensions/unknown/empty/deep')).kind,'folder');
|
||||||
|
assert.ok(decoded['extensions/unknown/empty/deep/']);
|
||||||
|
assert.deepEqual(f.stores.get(imported.path('extensions/quote/state.kv')).entries,sidecar.kvStores[0].entries);
|
||||||
|
});
|
||||||
|
|
||||||
|
function zipped(extra={}) {return zipSync({'project.json':strToU8(JSON.stringify(manifest('old'))),...extra});}
|
||||||
|
function central(bytes){const view=new DataView(bytes.buffer,bytes.byteOffset,bytes.byteLength);for(let index=0;index<bytes.length-4;index++)if(view.getUint32(index,true)===0x02014b50)return index;throw new Error('Missing central');}
|
||||||
|
test('unsafe ZIP paths, collisions, links, corruption and decompression bounds fail before host creation',async()=>{
|
||||||
|
const duplicate=zipped({a:strToU8('a'),b:strToU8('b')});
|
||||||
|
for(let i=0;i<duplicate.length-4;i++) {
|
||||||
|
const view=new DataView(duplicate.buffer),signature=view.getUint32(i,true);
|
||||||
|
const length=signature===0x04034b50?view.getUint16(i+26,true):signature===0x02014b50?view.getUint16(i+28,true):0;
|
||||||
|
const name=i+(signature===0x04034b50?30:46);
|
||||||
|
if(length===1&&duplicate[name]===98)duplicate[name]=97;
|
||||||
|
}
|
||||||
|
const link=zipped();new DataView(link.buffer).setUint32(central(link)+38,0xa1ff0000,true);
|
||||||
|
const corrupt=zipped();new DataView(corrupt.buffer).setUint32(central(corrupt)+16,1,true);
|
||||||
|
const liar=zipped({bomb:strToU8('x'.repeat(20000))});
|
||||||
|
const liarView=new DataView(liar.buffer);let position=central(liar);
|
||||||
|
while(strFromU8(liar.subarray(position+46,position+46+liarView.getUint16(position+28,true)))!=='bomb')position+=46+liarView.getUint16(position+28,true)+liarView.getUint16(position+30,true)+liarView.getUint16(position+32,true);
|
||||||
|
const local=liarView.getUint32(position+42,true);liarView.setUint32(position+24,0,true);liarView.setUint32(local+22,0,true);
|
||||||
|
for(const bytes of [zipped({'../escape':strToU8('x')}),zipped({'/absolute':strToU8('x')}),zipped({'C:/drive':strToU8('x')}),zipped({' padded/name':strToU8('x')}),zipped({'folder/name\u00a0':strToU8('x')}),zipped({'same/a':strToU8('x'),'Same/b':strToU8('x')}),zipped({parent:strToU8('x'),'parent/child':strToU8('x')}),duplicate,link,corrupt,liar]) {
|
||||||
|
const f=fixture();await assert.rejects(importProject(f.client,bytes,{bridge:f.bridge}));assert.equal(f.creates,0);
|
||||||
|
}
|
||||||
|
const f=fixture();await assert.rejects(importProject(f.client,zipped({large:strToU8('a'.repeat(4096))}),{bridge:f.bridge,maxFileBytes:2048}));assert.equal(f.creates,0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('inconsistent KV pages, concurrent files and retired sessions cannot produce an export',async()=>{
|
||||||
|
const f=fixture(),session=await f.client.activate(f.original),normal=f.bridge.snapshotKv.bind(f.bridge);
|
||||||
|
f.bridge.snapshotKv=async args=>{const value=await normal(args);if(args.cursor)value.snapshotId='different';return value;};
|
||||||
|
await assert.rejects(exportProject(session,{bridge:f.bridge}),/generation/);
|
||||||
|
f.bridge.snapshotKv=normal;
|
||||||
|
const invoke=f.bridge.invoke.bind(f.bridge);
|
||||||
|
f.bridge.invoke=async(command,args)=>{const value=await invoke(command,args);if(command==='filesystem_get_files')f.files.get(`${f.original.path}/assets/audio.bin`).revision++;return value;};
|
||||||
|
await assert.rejects(exportProject(session,{bridge:f.bridge}),/changed|equal/);
|
||||||
|
await session.close();await assert.rejects(exportProject(session,{bridge:f.bridge}),{name:'AbortError'});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('host save/select dialogs transfer real ZIP bytes with cancellation and validation',async()=>{
|
||||||
|
const f=fixture(),session=await f.client.activate(f.original);
|
||||||
|
await exportProjectToDialog(session,{bridge:f.bridge});
|
||||||
|
const saved=f.calls.find(call=>call.command==='save_file_dialog');
|
||||||
|
assert.ok(saved.args.fileName.endsWith('.isap.zip'));
|
||||||
|
assert.equal(await importProjectFromDialog(f.client,{bridge:f.bridge}),null);
|
||||||
|
assert.deepEqual(f.calls.find(call=>call.command==='select_files').args,{multiple:false,accessPolicy:'read-only',filters:['.zip']});
|
||||||
|
f.bridge.selection={selections:[{filename:'project.zip',bytesBase64:saved.args.bytesBase64}]};
|
||||||
|
assert.ok(await importProjectFromDialog(f.client,{bridge:f.bridge}));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('complete local KV snapshots retain unsent values and reject a changed local revision',async()=>{
|
||||||
|
const f=fixture(),session=await f.client.activate(f.original);
|
||||||
|
let localRevision=20;
|
||||||
|
f.bridge.snapshotKv=async()=>({local:true,snapshotComplete:true,revision:9,localRevision,storeId:'old-store',incarnation:'old-incarnation',pending:true,entries:structuredClone(f.stores.get(f.kvPath).entries),nextCursor:null});
|
||||||
|
const bytes=await exportProject(session,{bridge:f.bridge});
|
||||||
|
const sidecar=JSON.parse(strFromU8(unzipSync(bytes)[TRANSFER_MANIFEST]));
|
||||||
|
assert.equal(sidecar.kvStores[0].entries[1].value[0].name,'Latest');
|
||||||
|
assert.ok(!JSON.stringify(sidecar).includes('old-store'));
|
||||||
|
let calls=0;const snapshot=f.bridge.snapshotKv;
|
||||||
|
f.bridge.snapshotKv=async args=>{if(++calls>1)localRevision++;return snapshot(args);};
|
||||||
|
await assert.rejects(exportProject(session,{bridge:f.bridge}),/KV changed/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('malformed logical KV snapshots and unsupported transfer versions fail before creation',async()=>{
|
||||||
|
for(const change of [sidecar=>{sidecar.formatVersion=2;},sidecar=>{sidecar.kvStores[0].entries[0].itemIds=['duplicate','duplicate'];},sidecar=>{sidecar.kvStores[0].path='../escape.kv';},sidecar=>{sidecar.kvStores.push(structuredClone(sidecar.kvStores[0]));}]) {
|
||||||
|
const f=fixture(),session=await f.client.activate(f.original),files=unpackZip(await exportProject(session,{bridge:f.bridge}));
|
||||||
|
const sidecar=JSON.parse(strFromU8(files.get(TRANSFER_MANIFEST)));change(sidecar);files.set(TRANSFER_MANIFEST,strToU8(JSON.stringify(sidecar)));
|
||||||
|
await assert.rejects(importProject(f.client,packZip(files,{},files.directories),{bridge:f.bridge}));assert.equal(f.creates,0);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('large lists replay in bounded ordered batches and switching stops subsequent mutations',async()=>{
|
||||||
|
const f=fixture(),session=await f.client.activate(f.original);
|
||||||
|
const entry={key:'large',status:'found',kind:'list',itemIds:Array.from({length:350},(_,i)=>`id-${350-i}`),value:Array.from({length:350},(_,i)=>({position:i}))};
|
||||||
|
f.stores.get(f.kvPath).entries=[entry];
|
||||||
|
const bytes=await exportProject(session,{bridge:f.bridge});
|
||||||
|
const imported=await importProject(f.client,bytes,{bridge:f.bridge});
|
||||||
|
const mutations=f.calls.filter(call=>call.command==='applyKv');
|
||||||
|
assert.equal(mutations.length,3);assert.ok(mutations.every(call=>call.args.operations.length<=128));
|
||||||
|
assert.deepEqual(f.stores.get(imported.path('extensions/quote/state.kv')).entries,[entry]);
|
||||||
|
const normal=f.bridge.applyKv.bind(f.bridge);let applied=0;
|
||||||
|
f.bridge.applyKv=async args=>{const result=await normal(args);if(++applied===1)await f.client.close();return result;};
|
||||||
|
await assert.rejects(importProject(f.client,bytes,{bridge:f.bridge}),{name:'AbortError'});
|
||||||
|
assert.equal(applied,1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('import activates only complete staged projects and picks unique UTF-16-safe names',async()=>{
|
||||||
|
const f=fixture(),source=await f.client.activate(f.original),bytes=await exportProject(source,{bridge:f.bridge});
|
||||||
|
let release,started;
|
||||||
|
const blocked=new Promise(resolve=>{started=resolve;}),normal=f.bridge.invoke.bind(f.bridge);
|
||||||
|
f.bridge.invoke=async(command,args)=>{if(command==='filesystem_upload_files'&&!release){await new Promise(resolve=>{release=resolve;started();});}return normal(command,args);};
|
||||||
|
const events=[];f.client.subscribe(({active})=>{if(active&&active!==source)events.push(JSON.parse(strFromU8(f.files.get(active.path('project.json')).bytes)));});
|
||||||
|
const pending=importProject(f.client,bytes,{bridge:f.bridge});await blocked;
|
||||||
|
assert.equal(f.client.active,source);assert.deepEqual(events,[]);release();
|
||||||
|
const imported=await pending;assert.equal(f.client.active,imported);assert.ok(events.length&&events.every(value=>value.importedFrom?.id==='original'));
|
||||||
|
assert.equal(imported.project.name,'Example (import)');
|
||||||
|
const second=await importProject(f.client,bytes,{bridge:f.bridge});assert.equal(second.project.name,'Example (import 2)');
|
||||||
|
const long={...manifest('old'),name:'😀'.repeat(80)};
|
||||||
|
const third=await importProject(f.client,zipSync({'project.json':strToU8(JSON.stringify(long))}),{bridge:f.bridge});
|
||||||
|
assert.ok(third.project.name.length<=160);assert.ok(!/[\ud800-\udbff]$/.test(third.project.name.slice(0,-' (import)'.length)));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('failed import retires its staged session while preserving the previously active project',async()=>{
|
||||||
|
const f=fixture(),source=await f.client.activate(f.original),bytes=await exportProject(source,{bridge:f.bridge});
|
||||||
|
const normal=f.bridge.invoke.bind(f.bridge);f.bridge.invoke=(command,args)=>command==='filesystem_create_folder'?Promise.reject(new Error('Folder write failed')):normal(command,args);
|
||||||
|
let staged;const stage=f.client.stageCreate.bind(f.client);f.client.stageCreate=async(...args)=>(staged=await stage(...args));
|
||||||
|
await assert.rejects(importProject(f.client,bytes,{bridge:f.bridge}),error=>error.message==='Folder write failed'&&Boolean(error.project));
|
||||||
|
assert.equal(f.client.active,source);assert.equal(staged.signal.aborted,true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('export preparation flushes the captured session before snapshot and fences a closed session',async()=>{
|
||||||
|
const f=fixture(),session=await f.client.activate(f.original);
|
||||||
|
session.markDirty();
|
||||||
|
const bytes=await exportProject(session,{bridge:f.bridge,beforeExport:async captured=>{
|
||||||
|
assert.equal(captured,session);
|
||||||
|
f.stores.get(f.kvPath).entries[2].value={flushed:true};
|
||||||
|
f.stores.get(f.kvPath).revision++;
|
||||||
|
captured.markDirty(false);
|
||||||
|
}});
|
||||||
|
const sidecar=JSON.parse(strFromU8(unpackZip(bytes).get(TRANSFER_MANIFEST)));
|
||||||
|
assert.deepEqual(sidecar.kvStores[0].entries[2].value,{flushed:true});
|
||||||
|
const before=f.calls.filter(call=>call.command==='filesystem_list_dir').length;
|
||||||
|
await assert.rejects(exportProject(session,{bridge:f.bridge,beforeExport:()=>session.close()}),{name:'AbortError'});
|
||||||
|
assert.equal(f.calls.filter(call=>call.command==='filesystem_list_dir').length,before);
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user