Project format updates
This commit is contained in:
@@ -1,8 +1,8 @@
|
|||||||
# ISA Project format
|
# 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.
|
Version 1 is an ordinary workspace `<name>.isap` folder containing `project.json`, `extensions/<extension-id>/` and `assets/`. The manifest contains `formatVersion: 1`, stable `id`, display `name`, UTC `createdAt`/`updatedAt` timestamps, and optional `archived` state. 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.
|
Extension namespaces organize data and are not permission boundaries. An ordinary writable folder 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
|
## Public APIs
|
||||||
|
|
||||||
@@ -15,7 +15,7 @@ import { mountProjectWorkspace } from '@isa-warden/isa-project-format/dom';
|
|||||||
const client = createProjectClient({
|
const client = createProjectClient({
|
||||||
bridge,
|
bridge,
|
||||||
extensionId: 'example',
|
extensionId: 'example',
|
||||||
projectCommands: appInfo.projects?.commands,
|
filesystemCommands: appInfo.filesystem?.commands,
|
||||||
scope: { workspaceId, groupId }
|
scope: { workspaceId, groupId }
|
||||||
});
|
});
|
||||||
const view = mountProjectWorkspace(target, { client, bridge, extensionName: 'Example', locale: 'en' });
|
const view = mountProjectWorkspace(target, { client, bridge, extensionName: 'Example', locale: 'en' });
|
||||||
@@ -24,17 +24,17 @@ view.destroy();
|
|||||||
await client.close();
|
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.
|
The shared UI provides a searchable 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.
|
`client.activate(reference)` opens a listed or recent reference by reading its manifest through an existing grant. `client.create(name, operationId?)` creates an ordinary folder and publishes its manifest after the standard subdirectories exist. It retains the same operation ID and folder 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.
|
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. A requested synchronized store uses offline storage when the granted parent is synchronized. Otherwise, new stores use the ordinary online filesystem contract. `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
|
## 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 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 projects discovered in the folders selected by the user. `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)`.
|
Use the shared `ProjectWorkspace` or `mountProjectWorkspace` with the extension display name, locale and launch-scoped client. Custom overviews call `client.pickFolder()` from a user action and refresh `client.list()` after a selection. The picker can select a container such as `/shared` or a single existing `.isap` folder. The extension remembers selected paths for the launch scope and reads only through its ordinary filesystem grants. Use `client.openListed(row)` to reopen a project, `client.create(name, operationId)` to create it in an editable container, and `client.setArchived(row, archived)` to update the manifest. Extensions need the host permissions for filesystem reads, optional writes, and private preferences.
|
||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
|
|||||||
+72
-54
@@ -1,7 +1,8 @@
|
|||||||
import { confirmedWrite } from './proofs.js';
|
import { confirmedWrite } from './proofs.js';
|
||||||
import { ProjectUnavailableError, readAuthoritativeFile } from './shared-read.js';
|
import { ProjectUnavailableError, readAuthoritativeFile } from './shared-read.js';
|
||||||
export { ProjectUnavailableError } from './shared-read.js';
|
export { ProjectUnavailableError } from './shared-read.js';
|
||||||
import { parseProjectManifest, extensionDataPath, validateArchivePath } from './format.js';
|
import { extensionDataPath, validateArchivePath } from './format.js';
|
||||||
|
import { createProjectFilesystem, manifestFromSnapshot } from './project-filesystem.js';
|
||||||
|
|
||||||
const RECENTS_KEY = 'isa-project-format.recents.v1';
|
const RECENTS_KEY = 'isa-project-format.recents.v1';
|
||||||
const abortError = () => new DOMException('Project session changed', 'AbortError');
|
const abortError = () => new DOMException('Project session changed', 'AbortError');
|
||||||
@@ -16,11 +17,13 @@ function reference(value) {
|
|||||||
projectIdentity: String(value.projectIdentity ?? id), manifestPath: `${path}/project.json`, formatVersion: 1 };
|
projectIdentity: String(value.projectIdentity ?? id), manifestPath: `${path}/project.json`, formatVersion: 1 };
|
||||||
}
|
}
|
||||||
|
|
||||||
export function createProjectClient({ bridge, extensionId, scope, projectCommands, beforeSwitch, isCurrent = () => true }) {
|
export function createProjectClient({ bridge, extensionId, scope, filesystemCommands, beforeSwitch, isCurrent = () => true }) {
|
||||||
if (!bridge || typeof bridge.invoke !== 'function') throw new TypeError('Host bridge required');
|
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');
|
if (!scope?.workspaceId || !scope?.groupId) throw new TypeError('Dashboard workspace and launch group required');
|
||||||
extensionDataPath(extensionId, 'validate.json');
|
extensionDataPath(extensionId, 'validate.json');
|
||||||
const captured = Object.freeze({ workspaceId: scope.workspaceId, groupId: scope.groupId });
|
const captured = Object.freeze({ workspaceId: scope.workspaceId, groupId: scope.groupId });
|
||||||
|
const supportsFilesystem = command => !filesystemCommands || filesystemCommands.includes(command);
|
||||||
|
const canWrite = supportsFilesystem('filesystem_upload_files');
|
||||||
let active = null, recents = [], generation = 0, closed = false;
|
let active = null, recents = [], generation = 0, closed = false;
|
||||||
let preferenceWrites = Promise.resolve();
|
let preferenceWrites = Promise.resolve();
|
||||||
const listeners = new Set();
|
const listeners = new Set();
|
||||||
@@ -31,12 +34,13 @@ export function createProjectClient({ bridge, extensionId, scope, projectCommand
|
|||||||
const state = () => Object.freeze({ active, recents: structuredClone(recents) });
|
const state = () => Object.freeze({ active, recents: structuredClone(recents) });
|
||||||
const notify = () => { for (const listener of listeners) listener(state()); };
|
const notify = () => { for (const listener of listeners) listener(state()); };
|
||||||
const guard = () => { if (closed || !isCurrent()) throw abortError(); };
|
const guard = () => { if (closed || !isCurrent()) throw abortError(); };
|
||||||
const invoke = async (command, args = {}) => {
|
const invokeCurrent = async (command, args) => {
|
||||||
guard();
|
guard();
|
||||||
const value = await bridge.invoke(command, { ...args, ...captured });
|
const value = await bridge.invoke(command, args);
|
||||||
guard();
|
guard();
|
||||||
return value;
|
return value;
|
||||||
};
|
};
|
||||||
|
const invoke = (command, args = {}) => invokeCurrent(command, { ...args, ...captured });
|
||||||
const loadRecents = async () => {
|
const loadRecents = async () => {
|
||||||
guard();
|
guard();
|
||||||
// Host private settings are already bound to the immutable account and launch scope.
|
// Host private settings are already bound to the immutable account and launch scope.
|
||||||
@@ -59,14 +63,16 @@ export function createProjectClient({ bridge, extensionId, scope, projectCommand
|
|||||||
guard();
|
guard();
|
||||||
}
|
}
|
||||||
const read = (path, sessionGuard = guard) => readAuthoritativeFile(invoke,path,sessionGuard);
|
const read = (path, sessionGuard = guard) => readAuthoritativeFile(invoke,path,sessionGuard);
|
||||||
|
const filesystem = createProjectFilesystem({ invoke, invokePrivateStorage: invokeCurrent, read, canWrite });
|
||||||
async function loadProject(value, check) {
|
async function loadProject(value, check) {
|
||||||
check();
|
check();
|
||||||
const project = reference(value);
|
const project = reference(value);
|
||||||
const snapshot = await read(project.manifestPath, check);
|
const snapshot = await read(project.manifestPath, check);
|
||||||
if (snapshot.status !== 'found' || typeof snapshot.text !== 'string') throw new ProjectUnavailableError('Project manifest missing');
|
if (snapshot.status !== 'found') throw new ProjectUnavailableError('Project manifest missing');
|
||||||
const manifest = parseProjectManifest(JSON.parse(snapshot.text));
|
const manifest = manifestFromSnapshot(snapshot);
|
||||||
if (manifest.id !== project.projectIdentity) throw new Error('Project manifest identity differs from its host folder');
|
if (manifest.id !== project.projectIdentity) throw new Error('Project manifest identity changed');
|
||||||
return {project, manifest, snapshot};
|
return { project: { ...project, name: manifest.name, updatedAt: manifest.updatedAt,
|
||||||
|
archived: manifest.archived ?? project.archived, canWrite: canWrite && project.canWrite }, manifest, snapshot };
|
||||||
}
|
}
|
||||||
function checkTransition(ticket) {
|
function checkTransition(ticket) {
|
||||||
guard();
|
guard();
|
||||||
@@ -224,9 +230,16 @@ export function createProjectClient({ bridge, extensionId, scope, projectCommand
|
|||||||
},
|
},
|
||||||
async openKv(relative, options = {}) {
|
async openKv(relative, options = {}) {
|
||||||
const canonical=validateArchivePath(relative);
|
const canonical=validateArchivePath(relative);
|
||||||
const separator=canonical.lastIndexOf('/');
|
const separator = canonical.lastIndexOf('/');
|
||||||
if(separator>=0)await session.ensureDirectory(canonical.slice(0,separator));
|
const parent = separator < 0 ? '' : canonical.slice(0,separator);
|
||||||
return call('kv_store_open', {...options,path:path(canonical)});
|
if (parent) await session.ensureDirectory(parent);
|
||||||
|
if (options.syncable === true) {
|
||||||
|
const parentPath = parent ? path(parent) : project.path;
|
||||||
|
const inventory = await session.listFiles(parent, true);
|
||||||
|
options = { ...options, syncable: inventory.some(row =>
|
||||||
|
row.path === parentPath && row.kind === 'folder' && row.synced === true) };
|
||||||
|
}
|
||||||
|
return call('kv_store_open', { ...options, path: path(canonical) });
|
||||||
},
|
},
|
||||||
async applyKv(relative, mutation) {
|
async applyKv(relative, mutation) {
|
||||||
sessionGuard();
|
sessionGuard();
|
||||||
@@ -256,9 +269,22 @@ export function createProjectClient({ bridge, extensionId, scope, projectCommand
|
|||||||
sessions.add(session);
|
sessions.add(session);
|
||||||
return session;
|
return session;
|
||||||
}
|
}
|
||||||
|
function prepareCreation(name, id) {
|
||||||
|
if (typeof name !== 'string' || !name.trim()) throw new TypeError('Project name required');
|
||||||
|
name = name.trim();
|
||||||
|
const pending = pendingCreations.get(name);
|
||||||
|
if (pending && (id === undefined || pending.id === id)) return pending;
|
||||||
|
const creation = { name, id: id ?? crypto.randomUUID(), root: null };
|
||||||
|
pendingCreations.set(name, creation);
|
||||||
|
return creation;
|
||||||
|
}
|
||||||
return {
|
return {
|
||||||
scope: captured, extensionId,
|
scope: captured, extensionId,
|
||||||
supports(command) { return !projectCommands || projectCommands.includes(command); },
|
supports(action) {
|
||||||
|
if (action === 'create') return canWrite && supportsFilesystem('filesystem_create_folder');
|
||||||
|
if (action === 'archive') return canWrite;
|
||||||
|
return action === 'pickFolder' && supportsFilesystem('open_workspace_folder');
|
||||||
|
},
|
||||||
get active() { return active; }, get state() { return state(); },
|
get active() { return active; }, get state() { return state(); },
|
||||||
provideSwitchConfirmation(handler) {
|
provideSwitchConfirmation(handler) {
|
||||||
confirmationHandlers.push(handler);
|
confirmationHandlers.push(handler);
|
||||||
@@ -266,59 +292,51 @@ export function createProjectClient({ bridge, extensionId, scope, projectCommand
|
|||||||
},
|
},
|
||||||
subscribe(listener) { listeners.add(listener); listener(state()); return () => listeners.delete(listener); },
|
subscribe(listener) { listeners.add(listener); listener(state()); return () => listeners.delete(listener); },
|
||||||
recent: loadRecents,
|
recent: loadRecents,
|
||||||
async list(includeArchived = false) { const result = await invoke('projects_list', {includeArchived}); return result.projects.map(reference); },
|
async list(includeArchived = false) {
|
||||||
|
return (await filesystem.list(includeArchived)).map(reference);
|
||||||
|
},
|
||||||
|
pickFolder: () => filesystem.pickFolder(),
|
||||||
async create(name, operationId) {
|
async create(name, operationId) {
|
||||||
if(typeof name !== 'string' || !name.trim())throw new TypeError('Project name required');
|
const creation = prepareCreation(name, operationId);
|
||||||
name=name.trim();
|
const session = await switchTo(async check => {
|
||||||
operationId ??= pendingCreations.get(name) ?? crypto.randomUUID();
|
const project = await filesystem.create(creation.name, creation, check);
|
||||||
pendingCreations.set(name,operationId);
|
return loadProject(project, check);
|
||||||
const session=await switchTo(async check => loadProject((await invoke('projects_create',{name,operationId})).project, check));
|
});
|
||||||
if(pendingCreations.get(name)===operationId)pendingCreations.delete(name);
|
if (pendingCreations.get(creation.name) === creation) pendingCreations.delete(creation.name);
|
||||||
return session;
|
return session;
|
||||||
},
|
},
|
||||||
async stageCreate(name, operationId) {
|
async stageCreate(name, operationId) {
|
||||||
guard(); const ticket=beginTransition(); const previous=active; const version=previous?.dirtyVersion;
|
guard();
|
||||||
await approveSwitch(previous); if(ticket!==generation)throw abortError();
|
const ticket = beginTransition();
|
||||||
if(typeof name!=='string'||!name.trim())throw new TypeError('Project name required');name=name.trim();
|
const previous = active;
|
||||||
operationId ??= pendingCreations.get(name) ?? crypto.randomUUID();pendingCreations.set(name,operationId);
|
const version = previous?.dirtyVersion;
|
||||||
const created = await invoke('projects_create',{name,operationId});
|
await approveSwitch(previous);
|
||||||
const {project, manifest, snapshot} = await loadProject(created.project, () => checkTransition(ticket));
|
const check = () => checkTransition(ticket);
|
||||||
const session=makeSession(project,manifest,snapshot);staged.set(session,{ticket,session:previous,version,name,operationId});
|
check();
|
||||||
|
const creation = prepareCreation(name, operationId);
|
||||||
|
const created = await filesystem.create(creation.name, creation, check);
|
||||||
|
const { project, manifest, snapshot } = await loadProject(created, check);
|
||||||
|
const session = makeSession(project, manifest, snapshot);
|
||||||
|
staged.set(session, { ticket, session: previous, version, creation });
|
||||||
return session;
|
return session;
|
||||||
},
|
},
|
||||||
async adopt(session) {
|
async adopt(session) {
|
||||||
guard(); const approval=staged.get(session);
|
guard();
|
||||||
if(!approval||approval.ticket!==generation)throw abortError();session.assertCurrent();
|
const approval = staged.get(session);
|
||||||
|
if (!approval || approval.ticket !== generation) throw abortError();
|
||||||
|
session.assertCurrent();
|
||||||
try {
|
try {
|
||||||
const current=await switchTo(check=>loadProject(session.project,check),approval,session);
|
const current = await switchTo(check => loadProject(session.project, check), approval, session);
|
||||||
if(pendingCreations.get(approval.name)===approval.operationId)pendingCreations.delete(approval.name);
|
if (pendingCreations.get(approval.creation.name) === approval.creation) pendingCreations.delete(approval.creation.name);
|
||||||
return current;
|
return current;
|
||||||
} finally {await session.close();}
|
} 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);
|
|
||||||
});
|
|
||||||
},
|
},
|
||||||
|
openListed(project) { return switchTo(check => loadProject(project, check)); },
|
||||||
activate(project) { return switchTo(check => loadProject(project, check)); },
|
activate(project) { return switchTo(check => loadProject(project, check)); },
|
||||||
async share(targetGroupId, linked) {
|
async setArchived(project, archived) {
|
||||||
if (!active) throw new Error('Select a project');
|
if (typeof archived !== 'boolean') throw new TypeError('Archive state must be a boolean');
|
||||||
const capturedSession = active; capturedSession.assertCurrent();
|
const loaded = await loadProject(project, guard);
|
||||||
const result = await invoke('projects_set_group_link',{projectId:capturedSession.project.id,targetGroupId,linked});
|
await filesystem.setArchived(loaded.project, loaded.snapshot, loaded.manifest, archived);
|
||||||
capturedSession.assertCurrent(); return result;
|
|
||||||
},
|
},
|
||||||
async leave() {
|
async leave() {
|
||||||
guard(); const ticket=beginTransition(); const previous=active;
|
guard(); const ticket=beginTransition(); const previous=active;
|
||||||
|
|||||||
+1
-1
@@ -95,7 +95,7 @@ export function mountProjectWorkspace(target, {client,bridge,locale='en',extensi
|
|||||||
content.replaceChildren();shell.setAttribute('aria-busy',String(busy));
|
content.replaceChildren();shell.setAttribute('aria-busy',String(busy));
|
||||||
const toolbar=make('div',null,'isa-project-toolbar');
|
const toolbar=make('div',null,'isa-project-toolbar');
|
||||||
if(session) toolbar.append(make('h2',session.manifest.name,'isa-project-title'));
|
if(session) toolbar.append(make('h2',session.manifest.name,'isa-project-title'));
|
||||||
if(bridge)toolbar.append(button(text.import,()=>importProjectFromDialog(client,{bridge})));
|
if(bridge && client.supports('create'))toolbar.append(button(text.import,()=>importProjectFromDialog(client,{bridge})));
|
||||||
if(bridge&&session)toolbar.append(button(text.export,()=>exportProjectToDialog(session,{bridge,beforeExport})));
|
if(bridge&&session)toolbar.append(button(text.export,()=>exportProjectToDialog(session,{bridge,beforeExport})));
|
||||||
if(session) toolbar.append(button(text.close,()=>client.leave()));
|
if(session) toolbar.append(button(text.close,()=>client.leave()));
|
||||||
content.append(toolbar);
|
content.append(toolbar);
|
||||||
|
|||||||
@@ -19,6 +19,9 @@ export function parseProjectManifest(value) {
|
|||||||
throw new TypeError(`Invalid project ${key}`);
|
throw new TypeError(`Invalid project ${key}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (value.archived !== undefined && typeof value.archived !== 'boolean') {
|
||||||
|
throw new TypeError('Invalid project archive state');
|
||||||
|
}
|
||||||
// Return a copy preserving fields belonging to newer consumers of this version.
|
// Return a copy preserving fields belonging to newer consumers of this version.
|
||||||
return structuredClone(value);
|
return structuredClone(value);
|
||||||
}
|
}
|
||||||
|
|||||||
Vendored
+5
-3
@@ -4,6 +4,7 @@ export interface ProjectManifest {
|
|||||||
name: string;
|
name: string;
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
updatedAt: string;
|
updatedAt: string;
|
||||||
|
archived?: boolean;
|
||||||
[key: string]: unknown;
|
[key: string]: unknown;
|
||||||
}
|
}
|
||||||
export const PROJECT_FORMAT_VERSION: 1;
|
export const PROJECT_FORMAT_VERSION: 1;
|
||||||
@@ -67,22 +68,23 @@ export interface ProjectClient {
|
|||||||
readonly state: {readonly active: ProjectSession | null; readonly recents: ProjectReference[]};
|
readonly state: {readonly active: ProjectSession | null; readonly recents: ProjectReference[]};
|
||||||
provideSwitchConfirmation(handler: (session: ProjectSession) => Promise<boolean>): () => void;
|
provideSwitchConfirmation(handler: (session: ProjectSession) => Promise<boolean>): () => void;
|
||||||
subscribe(listener: (state: ProjectClient['state']) => void): () => void;
|
subscribe(listener: (state: ProjectClient['state']) => void): () => void;
|
||||||
supports(command: string): boolean;
|
supports(action: 'create' | 'archive' | 'pickFolder'): boolean;
|
||||||
recent(): Promise<ProjectReference[]>;
|
recent(): Promise<ProjectReference[]>;
|
||||||
list(includeArchived?: boolean): Promise<ProjectReference[]>;
|
list(includeArchived?: boolean): Promise<ProjectReference[]>;
|
||||||
|
pickFolder(): Promise<{path: string; fileId: string; canWrite: boolean} | null>;
|
||||||
create(name: string, operationId?: string): Promise<ProjectSession>;
|
create(name: string, operationId?: string): Promise<ProjectSession>;
|
||||||
stageCreate(name: string, operationId?: string): Promise<ProjectSession>;
|
stageCreate(name: string, operationId?: string): Promise<ProjectSession>;
|
||||||
adopt(session: ProjectSession): Promise<ProjectSession>;
|
adopt(session: ProjectSession): Promise<ProjectSession>;
|
||||||
openListed(project: ProjectReference): Promise<ProjectSession>;
|
openListed(project: ProjectReference): Promise<ProjectSession>;
|
||||||
activate(project: ProjectReference): Promise<ProjectSession>;
|
activate(project: ProjectReference): Promise<ProjectSession>;
|
||||||
share(targetGroupId: string, linked: boolean): Promise<any>;
|
setArchived(project: ProjectReference, archived: boolean): Promise<void>;
|
||||||
leave(): Promise<void>;
|
leave(): Promise<void>;
|
||||||
close(): Promise<void>;
|
close(): Promise<void>;
|
||||||
}
|
}
|
||||||
export class ProjectUnavailableError extends Error {}
|
export class ProjectUnavailableError extends Error {}
|
||||||
export function createProjectClient(options: {
|
export function createProjectClient(options: {
|
||||||
bridge: ProjectBridge; extensionId: string; scope: ProjectScope;
|
bridge: ProjectBridge; extensionId: string; scope: ProjectScope;
|
||||||
projectCommands?: readonly string[];
|
filesystemCommands?: readonly string[];
|
||||||
beforeSwitch?: (session: ProjectSession) => boolean | Promise<boolean>;
|
beforeSwitch?: (session: ProjectSession) => boolean | Promise<boolean>;
|
||||||
isCurrent?: () => boolean;
|
isCurrent?: () => boolean;
|
||||||
}): ProjectClient;
|
}): ProjectClient;
|
||||||
|
|||||||
+2
-2
@@ -1,4 +1,4 @@
|
|||||||
export const labels = {
|
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'},
|
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',pickFolder:'Add project folder',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'}
|
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',pickFolder:'Projectmap toevoegen',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'}
|
||||||
};
|
};
|
||||||
|
|||||||
+8
-4
@@ -1,4 +1,4 @@
|
|||||||
// A row always identifies a folder in the current group inventory. Private
|
// A row identifies a folder accessible through the current launch's grants. Private
|
||||||
// recents supply the activity order only, never the inventory or a grant.
|
// recents supply the activity order only, never the inventory or a grant.
|
||||||
export function mountOverview(target, {client, extensionName, text, locale, onImport}) {
|
export function mountOverview(target, {client, extensionName, text, locale, onImport}) {
|
||||||
const document = target.ownerDocument;
|
const document = target.ownerDocument;
|
||||||
@@ -20,8 +20,12 @@ export function mountOverview(target, {client, extensionName, text, locale, onIm
|
|||||||
const actions = element('div', '', 'isa-project-toolbar');
|
const actions = element('div', '', 'isa-project-toolbar');
|
||||||
const refreshButton = button(text.refresh, refresh);
|
const refreshButton = button(text.refresh, refresh);
|
||||||
actions.append(refreshButton);
|
actions.append(refreshButton);
|
||||||
|
const pickFolder = button(text.pickFolder, () => run(async () => {
|
||||||
|
if (await client.pickFolder()) await refresh();
|
||||||
|
}));
|
||||||
|
if (client.supports('pickFolder')) actions.append(pickFolder);
|
||||||
const importButton = button(text.import, () => run(onImport));
|
const importButton = button(text.import, () => run(onImport));
|
||||||
if (onImport && client.supports('projects_create')) actions.append(importButton);
|
if (onImport && client.supports('create')) actions.append(importButton);
|
||||||
header.append(actions);
|
header.append(actions);
|
||||||
const grid = element('div', '', 'isa-group-grid');
|
const grid = element('div', '', 'isa-group-grid');
|
||||||
const activity = element('aside');
|
const activity = element('aside');
|
||||||
@@ -35,7 +39,7 @@ export function mountOverview(target, {client, extensionName, text, locale, onIm
|
|||||||
panelTitle.id = 'isa-projects-' + crypto.randomUUID();
|
panelTitle.id = 'isa-projects-' + crypto.randomUUID();
|
||||||
panel.setAttribute('aria-labelledby',panelTitle.id);
|
panel.setAttribute('aria-labelledby',panelTitle.id);
|
||||||
heading.append(panelTitle);
|
heading.append(panelTitle);
|
||||||
if (client.supports('projects_create')) heading.append(create);
|
if (client.supports('create')) heading.append(create);
|
||||||
const controls = element('div', '', 'isa-project-toolbar');
|
const controls = element('div', '', 'isa-project-toolbar');
|
||||||
const search = element('input');
|
const search = element('input');
|
||||||
search.type = 'search';
|
search.type = 'search';
|
||||||
@@ -96,7 +100,7 @@ export function mountOverview(target, {client, extensionName, text, locale, onIm
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (!recent.childElementCount && !loading && !failed) recent.append(element('p',text.noActivity));
|
if (!recent.childElementCount && !loading && !failed) recent.append(element('p',text.noActivity));
|
||||||
create.disabled = busy; importButton.disabled = busy; refreshButton.disabled = busy || loading;
|
pickFolder.disabled = busy; create.disabled = busy; importButton.disabled = busy; refreshButton.disabled = busy || loading;
|
||||||
}
|
}
|
||||||
async function refresh() {
|
async function refresh() {
|
||||||
const ticket = ++generation;
|
const ticket = ++generation;
|
||||||
|
|||||||
@@ -0,0 +1,227 @@
|
|||||||
|
import { createProjectManifest, parseProjectManifest, validateArchivePath } from './format.js';
|
||||||
|
import { confirmedWrite } from './proofs.js';
|
||||||
|
import { ProjectUnavailableError } from './shared-read.js';
|
||||||
|
|
||||||
|
const ROOTS_KEY = 'isa-project-format.folders.v1';
|
||||||
|
const folderKey = id => String(id).replace(/^workspace_file:/, '');
|
||||||
|
|
||||||
|
function unavailableGrant(error) {
|
||||||
|
const message = String(error?.message ?? error).toLowerCase();
|
||||||
|
return message.includes('extension filesystem permission is required')
|
||||||
|
|| message.includes('filesystem path requires a current extension root or picker grant');
|
||||||
|
}
|
||||||
|
|
||||||
|
function folderReference(value) {
|
||||||
|
const { path, fileId = value.id, access, canWrite, archivedAt } = value;
|
||||||
|
if (typeof fileId !== 'string' || !fileId || typeof path !== 'string' || !path.startsWith('/')) {
|
||||||
|
throw new ProjectUnavailableError('Invalid project folder reference');
|
||||||
|
}
|
||||||
|
validateArchivePath(path.slice(1));
|
||||||
|
return { path, fileId, canWrite: access ? access === 'read_write' : canWrite === true, archivedAt };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function manifestFromSnapshot(snapshot) {
|
||||||
|
let text = snapshot.text;
|
||||||
|
if (typeof text !== 'string' && typeof snapshot.bytesBase64 === 'string') {
|
||||||
|
text = new TextDecoder('utf-8', { fatal: true }).decode(
|
||||||
|
Uint8Array.from(atob(snapshot.bytesBase64), character => character.charCodeAt(0))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return parseProjectManifest(JSON.parse(text));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createProjectFilesystem({ invoke, invokePrivateStorage, read, canWrite }) {
|
||||||
|
let selecting;
|
||||||
|
|
||||||
|
async function roots() {
|
||||||
|
const saved = await invokePrivateStorage('localstorage_get', { key: ROOTS_KEY, sync: false });
|
||||||
|
if (saved == null) return [];
|
||||||
|
if (!Array.isArray(saved)) throw new ProjectUnavailableError('Invalid project folder settings');
|
||||||
|
return saved.map(folderReference);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function pickFolder(editable = canWrite) {
|
||||||
|
if (selecting) return selecting;
|
||||||
|
selecting = (async () => {
|
||||||
|
const result = await invoke('open_workspace_folder', {
|
||||||
|
accessPolicy: editable ? 'editable' : 'read-only',
|
||||||
|
allowSharing: false
|
||||||
|
});
|
||||||
|
if (result?.canceled) return null;
|
||||||
|
if (result?.file?.kind !== 'folder') throw new ProjectUnavailableError('The selected folder was not granted');
|
||||||
|
const folder = folderReference(result.file);
|
||||||
|
const previous = await roots();
|
||||||
|
await invokePrivateStorage('localstorage_put', {
|
||||||
|
key: ROOTS_KEY, sync: false,
|
||||||
|
value: [...previous.filter(item => item.path !== folder.path), folder]
|
||||||
|
});
|
||||||
|
return folder;
|
||||||
|
})();
|
||||||
|
try {
|
||||||
|
return await selecting;
|
||||||
|
} finally {
|
||||||
|
selecting = undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function files(path, recursive) {
|
||||||
|
const inventory = await invoke('filesystem_list_dir', { path, recursive, cachePolicy: 'dashboard-required' });
|
||||||
|
if (inventory?.authoritative !== true || inventory.snapshotComplete === false || inventory.error ||
|
||||||
|
!Array.isArray(inventory.files) || inventory.files.some(file =>
|
||||||
|
file?.path !== path && !file?.path?.startsWith(path + '/'))) {
|
||||||
|
throw new ProjectUnavailableError('Project folder inventory unavailable');
|
||||||
|
}
|
||||||
|
return inventory.files;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function resolveRoot(root, recursive) {
|
||||||
|
let inventory;
|
||||||
|
try {
|
||||||
|
inventory = await files(root.path, recursive);
|
||||||
|
} catch (error) {
|
||||||
|
if (unavailableGrant(error)) return null;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
const current = inventory.find(entry => entry.path === root.path && entry.kind === 'folder');
|
||||||
|
if (!current || folderKey(current.fileId ?? current.id) !== folderKey(root.fileId)) return null;
|
||||||
|
return { inventory, current, writable: root.canWrite && current.canWrite !== false };
|
||||||
|
}
|
||||||
|
|
||||||
|
function projectFrom(folder, manifest) {
|
||||||
|
return {
|
||||||
|
id: folder.fileId, folderId: folder.fileId, path: folder.path,
|
||||||
|
name: manifest.name, projectIdentity: manifest.id,
|
||||||
|
canWrite: canWrite && folder.canWrite, updatedAt: manifest.updatedAt,
|
||||||
|
archived: manifest.archived ?? Boolean(folder.archivedAt)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function list(includeArchived) {
|
||||||
|
const folders = new Map();
|
||||||
|
for (const root of await roots()) {
|
||||||
|
const resolved = await resolveRoot(root, true);
|
||||||
|
if (!resolved) continue;
|
||||||
|
const { inventory, current, writable } = resolved;
|
||||||
|
if (root.path.endsWith('.isap')) {
|
||||||
|
folders.set(root.path, { ...root, fileId: current.fileId ?? current.id,
|
||||||
|
archivedAt: current.archivedAt ?? root.archivedAt, canWrite: writable });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for (const entry of inventory) {
|
||||||
|
if (entry.kind !== 'folder' || !entry.path.endsWith('.isap') || entry.canRead === false) continue;
|
||||||
|
const relativeParts = entry.path.slice(root.path.length + 1).split('/');
|
||||||
|
if (relativeParts.slice(0, -1).some(part => part.endsWith('.isap'))) continue;
|
||||||
|
const folder = folderReference({ ...entry, canWrite: writable && entry.canWrite !== false });
|
||||||
|
const previous = folders.get(folder.path);
|
||||||
|
if (!previous || folder.canWrite) folders.set(folder.path, folder);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const projects = [];
|
||||||
|
const candidates = [...folders.values()];
|
||||||
|
// Bound concurrent manifest reads independently of the size of the container.
|
||||||
|
for (let start = 0; start < candidates.length; start += 12) {
|
||||||
|
const batch = await Promise.all(candidates.slice(start, start + 12).map(async folder => {
|
||||||
|
let snapshot;
|
||||||
|
try {
|
||||||
|
snapshot = await read(folder.path + '/project.json');
|
||||||
|
} catch (error) {
|
||||||
|
if (unavailableGrant(error)) return null;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
if (snapshot.status === 'absent') return null;
|
||||||
|
try {
|
||||||
|
return projectFrom(folder, manifestFromSnapshot(snapshot));
|
||||||
|
} catch {
|
||||||
|
// A folder with the suffix can contain an unrelated or unsupported manifest.
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
projects.push(...batch.filter(project => project && (includeArchived || !project.archived)));
|
||||||
|
}
|
||||||
|
return projects.sort((a, b) => Date.parse(b.updatedAt) - Date.parse(a.updatedAt)
|
||||||
|
|| a.name.localeCompare(b.name) || a.id.localeCompare(b.id));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function ensureFolder(path) {
|
||||||
|
try {
|
||||||
|
const result = await invoke('filesystem_create_folder', { path });
|
||||||
|
if (result?.status === 'ok' && result.path === path && result.fileId) {
|
||||||
|
return folderReference({ ...result, canWrite: true });
|
||||||
|
}
|
||||||
|
throw new ProjectUnavailableError('Project directory creation was not confirmed');
|
||||||
|
} catch (error) {
|
||||||
|
const parent = path.slice(0, path.lastIndexOf('/'));
|
||||||
|
const existing = (await files(parent, false)).find(row => row.path === path && row.kind === 'folder');
|
||||||
|
if (!existing || existing.canWrite === false) throw error;
|
||||||
|
return folderReference({ ...existing, canWrite: true });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function create(name, creation, check) {
|
||||||
|
if (!canWrite) throw new ProjectUnavailableError('Project folder is read-only');
|
||||||
|
const manifest = createProjectManifest({ id: creation.id, name });
|
||||||
|
if (!creation.root) {
|
||||||
|
const candidates = (await roots()).filter(root => root.canWrite && !root.path.endsWith('.isap'));
|
||||||
|
const shared = candidates.findIndex(root => root.path === '/shared');
|
||||||
|
if (shared > 0) candidates.unshift(...candidates.splice(shared, 1));
|
||||||
|
// Recursive filesystem listings include the directory row needed to verify its ID.
|
||||||
|
for (const candidate of candidates) {
|
||||||
|
const resolved = await resolveRoot(candidate, true);
|
||||||
|
check();
|
||||||
|
if (resolved?.writable) {
|
||||||
|
creation.root = candidate;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
creation.root ??= await pickFolder(true);
|
||||||
|
check();
|
||||||
|
}
|
||||||
|
if (!creation.root) throw new DOMException('Project folder selection canceled', 'AbortError');
|
||||||
|
if (!creation.root.canWrite || creation.root.path.endsWith('.isap')) {
|
||||||
|
creation.root = null;
|
||||||
|
throw new ProjectUnavailableError('Choose an editable folder to store projects');
|
||||||
|
}
|
||||||
|
const prefix = name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 70);
|
||||||
|
const path = `${creation.root.path}/${prefix || 'project'}-${manifest.id}.isap`;
|
||||||
|
const folder = await ensureFolder(path);
|
||||||
|
check();
|
||||||
|
const manifestPath = path + '/project.json';
|
||||||
|
const existing = await read(manifestPath, check);
|
||||||
|
if (existing.status === 'found') {
|
||||||
|
const saved = manifestFromSnapshot(existing);
|
||||||
|
if (saved.id !== manifest.id || saved.name !== manifest.name) {
|
||||||
|
throw new ProjectUnavailableError('Project folder is already in use');
|
||||||
|
}
|
||||||
|
return projectFrom(folder, saved);
|
||||||
|
}
|
||||||
|
await ensureFolder(path + '/extensions');
|
||||||
|
check();
|
||||||
|
await ensureFolder(path + '/assets');
|
||||||
|
check();
|
||||||
|
try {
|
||||||
|
confirmedWrite(await invoke('filesystem_upload_files', { files: [{
|
||||||
|
path: manifestPath, text: JSON.stringify(manifest), contentType: 'application/json',
|
||||||
|
replaceExisting: false
|
||||||
|
}] }), manifestPath);
|
||||||
|
} catch (error) {
|
||||||
|
const current = await read(manifestPath, check);
|
||||||
|
if (current.status === 'absent') throw error;
|
||||||
|
const saved = manifestFromSnapshot(current);
|
||||||
|
if (saved.id !== manifest.id || saved.name !== manifest.name) throw error;
|
||||||
|
}
|
||||||
|
return projectFrom(folder, manifest);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function setArchived(project, snapshot, manifest, archived) {
|
||||||
|
if (!canWrite || project.canWrite !== true) throw new ProjectUnavailableError('Project folder is read-only');
|
||||||
|
if (project.archived === archived) return;
|
||||||
|
const value = { ...manifest, archived, updatedAt: new Date().toISOString() };
|
||||||
|
confirmedWrite(await invoke('filesystem_upload_files', { files: [{
|
||||||
|
path: project.manifestPath, text: JSON.stringify(value), contentType: 'application/json',
|
||||||
|
replaceExisting: true, expectedSyncRevision: snapshot.syncRevision, expectedContentHash: snapshot.contentHash
|
||||||
|
}] }), project.manifestPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
return { list, pickFolder, create, setArchived };
|
||||||
|
}
|
||||||
+1
-1
@@ -188,7 +188,7 @@ export async function importProject(client,bytes,options={}) {
|
|||||||
const base=await session.readFile('project.json');assertLive(session);
|
const base=await session.readFile('project.json');assertLive(session);
|
||||||
if(base.status!=='found')throw new Error('New project manifest unavailable');
|
if(base.status!=='found')throw new Error('New project manifest unavailable');
|
||||||
const host=parseProjectManifest(JSON.parse(base.text));
|
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'};
|
const imported={...archive.manifest,archived:false,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);
|
await session.writeJson('project.json',imported,base);assertLive(session);
|
||||||
return await client.adopt(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;}
|
}catch(error){await session.close();const failure=error instanceof Error?error:new Error(String(error));failure.project=session.project;throw failure;}
|
||||||
|
|||||||
+91
-30
@@ -8,17 +8,35 @@ function fixture(options = {}) {
|
|||||||
const files = new Map(['one','two','three'].map(id => [`${project(id).path}/project.json`,{
|
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}
|
formatVersion:1,id,name:id,createdAt:'2026-11-03T12:00:00Z',updatedAt:'2026-11-03T12:00:00Z',unknown:{kept:true}
|
||||||
}]));
|
}]));
|
||||||
let saved = null;
|
const saved = new Map();
|
||||||
|
const directories = new Set(['/projects']);
|
||||||
const bridge = {
|
const bridge = {
|
||||||
async invoke(command,args) {
|
async invoke(command,args) {
|
||||||
|
if (command.startsWith('localstorage_')) {
|
||||||
|
assert.equal(Object.hasOwn(args, 'workspaceId'), false, 'Private storage scope is set by the host');
|
||||||
|
assert.equal(Object.hasOwn(args, 'groupId'), false, 'Private storage scope is set by the host');
|
||||||
|
}
|
||||||
if (options.invoke) { const result = options.invoke(command,args); if (result !== undefined) return result; }
|
if (options.invoke) { const result = options.invoke(command,args); if (result !== undefined) return result; }
|
||||||
if (command === 'filesystem_get_files') {
|
if (command === 'filesystem_get_files') {
|
||||||
const path = args.files[0].path;
|
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}]};
|
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_get') return saved.get(args.key) ?? null;
|
||||||
if (command === 'localstorage_put') { saved=args.value;return {ok:true}; }
|
if (command === 'localstorage_put') { saved.set(args.key,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}]}; }
|
if (command === 'open_workspace_folder') return {file:{path:'/projects',id:'parent',kind:'folder',access:'read_write'}};
|
||||||
|
if (command === 'filesystem_list_dir') return {authoritative:true,files:[...directories]
|
||||||
|
.filter(path => path === args.path || path.startsWith(args.path + '/'))
|
||||||
|
.map(path => ({kind:'folder',path,id:path === '/projects' ? 'parent' : path,canWrite:true}))};
|
||||||
|
if (command === 'filesystem_create_folder') {
|
||||||
|
directories.add(args.path);
|
||||||
|
return {status:'ok',path:args.path,fileId:args.path};
|
||||||
|
}
|
||||||
|
if (command === 'filesystem_upload_files') {
|
||||||
|
writes.push(args);
|
||||||
|
const {path,text}=args.files[0];
|
||||||
|
files.set(path,JSON.parse(text));
|
||||||
|
return {items:[{status:'ok',isComplete:true,path,fileId:path}]};
|
||||||
|
}
|
||||||
throw new Error(`Unexpected command ${command}`);
|
throw new Error(`Unexpected command ${command}`);
|
||||||
},
|
},
|
||||||
subscribeKv: options.subscribeKv
|
subscribeKv: options.subscribeKv
|
||||||
@@ -74,18 +92,18 @@ test('dirty state blocks switching and unavailable reads never become absence',
|
|||||||
await client.close();
|
await client.close();
|
||||||
});
|
});
|
||||||
|
|
||||||
test('uncertain create retries retain operation identity through manifest recovery', async () => {
|
test('uncertain create retains the same folder and manifest identity on retry', async () => {
|
||||||
const ids=[];
|
const paths=[];
|
||||||
const {client}=fixture({invoke:(command,args)=>{
|
const {client}=fixture({invoke:(command,args)=>{
|
||||||
if(command!=='projects_create')return;
|
if(command!=='filesystem_upload_files'||!args.files[0].path.endsWith('/project.json'))return;
|
||||||
ids.push(args.operationId);
|
paths.push(args.files[0].path);
|
||||||
if(ids.length===1)throw new Error('Commit outcome unavailable');
|
if(paths.length===1)throw new Error('Commit outcome unavailable');
|
||||||
return {project:project('one')};
|
|
||||||
}});
|
}});
|
||||||
await assert.rejects(client.create('Example'),/unavailable/);
|
await assert.rejects(client.create('Example'),/unavailable/);
|
||||||
const created=await client.create('Example');
|
const created=await client.create('Example');
|
||||||
assert.equal(created.project.id,'one');
|
assert.equal(paths[0],paths[1]);
|
||||||
assert.equal(ids[0],ids[1]);
|
assert.equal(created.manifest.name,'Example');
|
||||||
|
assert.equal(created.project.projectIdentity,created.manifest.id);
|
||||||
await client.close();
|
await client.close();
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -119,36 +137,39 @@ test('successful transport cannot confirm pending or conflicted project writes',
|
|||||||
await client.close();
|
await client.close();
|
||||||
});
|
});
|
||||||
|
|
||||||
test('a listed group project opens by folder ID on its first use, without a second picker or project creation', async () => {
|
test('a selected container lists valid project manifests and opens them through its existing grant', async () => {
|
||||||
let reply = project('two');
|
let picks = 0;
|
||||||
const commands = [];
|
const {client,files} = fixture({invoke(command, args) {
|
||||||
const {client} = fixture({invoke(command,args) {
|
if (command === 'open_workspace_folder') { picks++; return; }
|
||||||
commands.push(command);
|
if (command === 'filesystem_list_dir' && args.path === '/projects') {
|
||||||
if (command === 'get_app_info') return {projects:{commands:['projects_open_listed']}};
|
return {authoritative:true,files:[
|
||||||
if (command === 'projects_list') return {projects:[{...reply, canWrite:false, updatedAt:'2026-09-01'}]};
|
{path:'/projects',kind:'folder',fileId:'parent'},
|
||||||
if (command === 'projects_open_listed') {
|
{path:project('two').path,kind:'folder',fileId:'two',canWrite:false},
|
||||||
assert.deepEqual(args,{projectId:'two'});
|
{path:project('missing').path,kind:'folder',fileId:'incomplete'},
|
||||||
return {status:'ok',project:reply};
|
{path:'/projects/not-a-folder.isap',kind:'file',fileId:'file'}
|
||||||
|
]};
|
||||||
}
|
}
|
||||||
}});
|
}});
|
||||||
|
assert.deepEqual(await client.list(),[]);
|
||||||
|
await client.pickFolder();
|
||||||
const [listed] = await client.list();
|
const [listed] = await client.list();
|
||||||
assert.equal(listed.canWrite,false);
|
assert.equal(listed.canWrite,false);
|
||||||
assert.equal(listed.updatedAt,'2026-09-01');
|
assert.equal(listed.updatedAt,'2026-11-03T12:00:00Z');
|
||||||
const selected = await client.openListed(listed);
|
const selected = await client.openListed(listed);
|
||||||
assert.equal(selected.project.id,'two');
|
assert.equal(selected.project.id,'two');
|
||||||
reply = project('one');
|
const manifest = files.get(listed.manifestPath);
|
||||||
|
files.set(listed.manifestPath,{...manifest,id:'one'});
|
||||||
await assert.rejects(client.openListed(listed),/identity/);
|
await assert.rejects(client.openListed(listed),/identity/);
|
||||||
assert.equal(client.active,selected);
|
assert.equal(client.active,selected);
|
||||||
assert.ok(!commands.some(command => ['projects_open','projects_create','filesystem_upload_files'].includes(command)));
|
assert.equal(picks,1);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('older hosts reopen an existing grant and report a denied row without reopening the picker', async () => {
|
test('opening from an existing grant reports a denied row without reopening the picker', async () => {
|
||||||
const {client,files} = fixture({invoke(command, args) {
|
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') {
|
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'}]};
|
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');
|
if (command === 'open_workspace_folder') assert.fail('Unexpected second project picker');
|
||||||
}});
|
}});
|
||||||
const selected = await client.openListed(project('one'));
|
const selected = await client.openListed(project('one'));
|
||||||
files.delete(project('two').path+'/project.json');
|
files.delete(project('two').path+'/project.json');
|
||||||
@@ -161,8 +182,6 @@ test('a direct grant initializes the extension directory on first writable acces
|
|||||||
const selected = {...project('two'), canWrite:true};
|
const selected = {...project('two'), canWrite:true};
|
||||||
const directories = [];
|
const directories = [];
|
||||||
const {client} = fixture({invoke(command, args) {
|
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_list_dir') return {authoritative:true, files:[]};
|
||||||
if (command === 'filesystem_create_folder') {
|
if (command === 'filesystem_create_folder') {
|
||||||
directories.push(args.path);
|
directories.push(args.path);
|
||||||
@@ -215,3 +234,45 @@ test('read-only, archived and uncertain reads cannot seed extension records', as
|
|||||||
}
|
}
|
||||||
assert.equal(writes.length, 0);
|
assert.equal(writes.length, 0);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('an archived legacy folder stays in the archive until the manifest explicitly restores it', async () => {
|
||||||
|
const {client} = fixture({invoke(command,args) {
|
||||||
|
if (command === 'open_workspace_folder') {
|
||||||
|
return {file:{path:project('two').path,id:'two',kind:'folder',access:'read_write'}};
|
||||||
|
}
|
||||||
|
if (command === 'filesystem_list_dir' && args.path === project('two').path) {
|
||||||
|
return {authoritative:true,files:[{path:args.path,fileId:'two',kind:'folder',archivedAt:100}]};
|
||||||
|
}
|
||||||
|
}});
|
||||||
|
await client.pickFolder();
|
||||||
|
assert.deepEqual(await client.list(), []);
|
||||||
|
const [archived] = await client.list(true);
|
||||||
|
assert.equal(archived.archived,true);
|
||||||
|
await client.setArchived(archived,false);
|
||||||
|
assert.equal((await client.list())[0].archived,false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('replaced and revoked roots do not hide accessible projects or conceal dashboard outages', async () => {
|
||||||
|
let offline = false;
|
||||||
|
const {client} = fixture({invoke(command,args) {
|
||||||
|
if (command === 'localstorage_get' && args.key.endsWith('folders.v1')) return [
|
||||||
|
{path:'/revoked',id:'revoked'},
|
||||||
|
{path:'/replaced',id:'old'},
|
||||||
|
{path:'/projects',id:'parent'}
|
||||||
|
];
|
||||||
|
if (command !== 'filesystem_list_dir') return;
|
||||||
|
if (args.path === '/revoked') throw new Error('Filesystem path requires a current extension root or picker grant');
|
||||||
|
if (args.path === '/replaced') return {authoritative:true,files:[
|
||||||
|
{kind:'folder',path:'/replaced',fileId:'new'},
|
||||||
|
{kind:'folder',path:'/replaced/other.isap',fileId:'other'}
|
||||||
|
]};
|
||||||
|
if (offline) throw new Error('Dashboard unavailable');
|
||||||
|
return {authoritative:true,files:[
|
||||||
|
{kind:'folder',path:'/projects',fileId:'workspace_file:parent'},
|
||||||
|
{kind:'folder',path:project('two').path,fileId:'two'}
|
||||||
|
]};
|
||||||
|
}});
|
||||||
|
assert.deepEqual((await client.list()).map(item => item.id), ['two']);
|
||||||
|
offline = true;
|
||||||
|
await assert.rejects(client.list(),/Dashboard unavailable/);
|
||||||
|
});
|
||||||
|
|||||||
@@ -10,11 +10,12 @@ 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 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});
|
const project=id=>({id,folderId:id,name:'Example',path:`/projects/${id}.isap`,projectIdentity:id});
|
||||||
function fixture() {
|
function fixture() {
|
||||||
const files=new Map(),stores=new Map(),snapshots=new Map(),calls=[],projects=new Map();
|
const files=new Map(),stores=new Map(),snapshots=new Map(),calls=[];
|
||||||
let creates=0,snapshotSequence=0;
|
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 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 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;}
|
function putProject(id,name='Example') {const value={...project(id),name};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;}
|
||||||
|
folder('/projects');
|
||||||
const original=putProject('original');
|
const original=putProject('original');
|
||||||
const media=new Uint8Array([0,255,17,48,0,99]);
|
const media=new Uint8Array([0,255,17,48,0,99]);
|
||||||
add(`${original.path}/assets/audio.bin`,media,'audio/wav');
|
add(`${original.path}/assets/audio.bin`,media,'audio/wav');
|
||||||
@@ -28,12 +29,10 @@ function fixture() {
|
|||||||
const bridge={
|
const bridge={
|
||||||
async invoke(command,args) {
|
async invoke(command,args) {
|
||||||
calls.push({command,args});
|
calls.push({command,args});
|
||||||
if(command==='localstorage_get')return [];
|
if(command==='localstorage_get')return args.key==='isa-project-format.folders.v1' ? [{path:'/projects',id:'/projects',canWrite:true}] : [];
|
||||||
if(command==='localstorage_put')return {status:'ok'};
|
if(command==='localstorage_put')return {status:'ok'};
|
||||||
if(command==='projects_list')return {projects:[...projects.values()]};
|
if(command==='filesystem_list_dir')return {authoritative:true,files:[...files].filter(([path])=>path===args.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==='projects_create')return {created:true,project:putProject(`imported-${++creates}`,args.name)};
|
if(command==='filesystem_create_folder') {if(args.path.endsWith('.isap'))creates++;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_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=>{
|
if(command==='filesystem_get_files')return {items:args.files.map(request=>{
|
||||||
const row=files.get(request.path);
|
const row=files.get(request.path);
|
||||||
if(!row)return {status:'absent',path:request.path,source:'dashboard',authoritative:true};
|
if(!row)return {status:'absent',path:request.path,source:'dashboard',authoritative:true};
|
||||||
@@ -206,7 +205,7 @@ test('import activates only complete staged projects and picks unique UTF-16-saf
|
|||||||
|
|
||||||
test('failed import retires its staged session while preserving the previously active project',async()=>{
|
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 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);
|
const normal=f.bridge.invoke.bind(f.bridge);f.bridge.invoke=(command,args)=>command==='filesystem_create_folder'&&args.path.endsWith('/extensions/unknown')?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));
|
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));
|
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);
|
assert.equal(f.client.active,source);assert.equal(staged.signal.aborted,true);
|
||||||
|
|||||||
Reference in New Issue
Block a user