Import ISA Project Format 1.1.0

This commit is contained in:
Peter Willemsen
2026-11-30 12:07:49 +00:00
commit 563d1992a2
32 changed files with 2308 additions and 0 deletions
+339
View File
@@ -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('');
}
+5
View File
@@ -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" />
+5
View File
@@ -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" />
+8
View File
@@ -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>
+3
View File
@@ -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';
+8
View File
@@ -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
View File
@@ -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'});}
+59
View File
@@ -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)}`);
}
+89
View File
@@ -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';
+3
View File
@@ -0,0 +1,3 @@
export * from './format.js';
export * from './client.js';
export * from './transfer.js';
+35
View File
@@ -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};
}
+4
View File
@@ -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
View File
@@ -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(); };
}
+17
View File
@@ -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;
}
+15
View File
@@ -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};
}>;
};
+52
View File
@@ -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);
}
};
}
+24
View File
@@ -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'};
}
+41
View File
@@ -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}}
`;
+18
View File
@@ -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
View File
@@ -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);
}
+49
View File
@@ -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;
}
+142
View File
@@ -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;
}