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
+217
View File
@@ -0,0 +1,217 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createProjectClient } from '../src/client.js';
const project = id => ({id,folderId:id,name:id,path:`/projects/${id}.isap`,projectIdentity:id,formatVersion:1});
function fixture(options = {}) {
const writes = [];
const files = new Map(['one','two','three'].map(id => [`${project(id).path}/project.json`,{
formatVersion:1,id,name:id,createdAt:'2026-11-03T12:00:00Z',updatedAt:'2026-11-03T12:00:00Z',unknown:{kept:true}
}]));
let saved = null;
const bridge = {
async invoke(command,args) {
if (options.invoke) { const result = options.invoke(command,args); if (result !== undefined) return result; }
if (command === 'filesystem_get_files') {
const path = args.files[0].path;
return {items:[files.has(path) ? {status:'ok',path,source:'dashboard',authoritative:true,text:JSON.stringify(files.get(path)),fileId:path,syncRevision:4,contentHash:'a'.repeat(64)} : {status:'absent',path,source:'dashboard',authoritative:true}]};
}
if (command === 'localstorage_get') return saved;
if (command === 'localstorage_put') { saved=args.value;return {ok:true}; }
if (command === 'filesystem_upload_files') { writes.push(args); return {items:[{status:'ok',isComplete:true,path:args.files[0].path,fileId:args.files[0].path}]}; }
throw new Error(`Unexpected command ${command}`);
},
subscribeKv: options.subscribeKv
};
const client = createProjectClient({bridge,extensionId:'contracts',scope:{workspaceId:'workspace',groupId:'group'},beforeSwitch:options.beforeSwitch});
return {client,writes,bridge,files};
}
test('captured sessions fence old writes and close late subscriptions during switching', async () => {
let finishSubscription;
let stopped = 0;
const {client,writes} = fixture({subscribeKv:() => new Promise(resolve=>{finishSubscription=resolve;})});
const first = await client.activate(project('one'));
const subscription = first.subscribeKv('extensions/contracts/state.kv',{},()=>assert.fail('Old subscription event'));
await client.activate(project('two'));
finishSubscription({unsubscribe:async()=>{stopped++;}});
await assert.rejects(subscription,{name:'AbortError'});
await assert.rejects(first.writeJson('extensions/contracts/state.json',{}, {status:'absent',path:first.path('extensions/contracts/state.json')}),{name:'AbortError'});
assert.equal(stopped,1);
assert.equal(writes.length,0);
await client.close();
});
test('JSON writes require captured authoritative CAS base and preserve caller data', async () => {
const {client,writes,files} = fixture();
const session = await client.activate(project('one'));
files.set(session.path('extensions/contracts/state.json'),{unknown:{retained:1},value:2});
const base = await session.readJson('extensions/contracts/state.json');
await session.writeJson('extensions/contracts/state.json',{...base.value,value:3},base);
const uploaded = writes[0].files[0];
assert.equal(uploaded.expectedSyncRevision,4);
assert.equal(uploaded.expectedContentHash,'a'.repeat(64));
assert.equal(uploaded.replaceExisting,true);
assert.deepEqual(JSON.parse(uploaded.text),{unknown:{retained:1},value:3});
assert.equal(writes[0].workspaceId,'workspace');
assert.equal(writes[0].groupId,'group');
await assert.rejects(session.writeJson('elsewhere.json',{},base),/authoritative read/);
assert.throws(()=>session.path('../escape.json'),/Unsafe/);
await client.close();
});
test('dirty state blocks switching and unavailable reads never become absence', async () => {
let missing = false;
const {client} = fixture({invoke:(command)=>missing && command==='filesystem_get_files' ? {items:[{status:'unavailable',authoritative:false}]} : undefined});
const first = await client.activate(project('one'));
first.markDirty();
await assert.rejects(client.activate(project('two')),/Unsaved/);
assert.equal(client.active,first);
first.markDirty(false);
missing=true;
await assert.rejects(first.readJson('state.json'),{name:'ProjectUnavailableError'});
assert.equal(client.active,first);
await client.close();
});
test('uncertain create retries retain operation identity through manifest recovery', async () => {
const ids=[];
const {client}=fixture({invoke:(command,args)=>{
if(command!=='projects_create')return;
ids.push(args.operationId);
if(ids.length===1)throw new Error('Commit outcome unavailable');
return {project:project('one')};
}});
await assert.rejects(client.create('Example'),/unavailable/);
const created=await client.create('Example');
assert.equal(created.project.id,'one');
assert.equal(ids[0],ids[1]);
await client.close();
});
test('authoritative reads reject another path, cached drafts and ambiguous identities', async () => {
let reply;
const {client}=fixture({invoke:command=>command==='filesystem_get_files'?reply:undefined});
const session=await client.activate(project('one'));
const path=session.path('state.json');
const valid={status:'ok',path,source:'dashboard',authoritative:true,fileId:'file',syncRevision:1,text:'{}'};
for(const change of [{path:path+'wrong'},{source:'cache'},{pendingUpload:true},{syncRevision:null},{workspaceFileOutcome:'conflict'},{status:'absent',path:path+'wrong'}]) {
reply={items:[{...valid,...change}]};
await assert.rejects(session.readJson('state.json'),{name:'ProjectUnavailableError'});
}
reply={items:[valid,valid]};
await assert.rejects(session.readJson('state.json'),{name:'ProjectUnavailableError'});
await client.close();
});
test('successful transport cannot confirm pending or conflicted project writes', async () => {
let reply;
const {client}=fixture({invoke:command=>command==='filesystem_upload_files'?reply:undefined});
const session=await client.activate(project('one'));
const base=await session.readJson('state.json');
const valid={status:'ok',isComplete:true,path:base.path,fileId:'file'};
for(const change of [{isComplete:false},{path:base.path+'wrong'},{fileId:''},{pendingUpload:true},{pendingState:'queued'},{conflict:true},{workspaceFileOutcome:'conflict'},{workspaceFileOutcome:'pending'},{source:'cache'}]) {
reply={items:[{...valid,...change}]};
await assert.rejects(session.writeJson('state.json',{},base),/not confirmed|conflict/);
}
reply={items:[valid]};
assert.equal((await session.writeJson('state.json',{},base)).fileId,'file');
await client.close();
});
test('a listed group project opens by folder ID on its first use, without a second picker or project creation', async () => {
let reply = project('two');
const commands = [];
const {client} = fixture({invoke(command,args) {
commands.push(command);
if (command === 'get_app_info') return {projects:{commands:['projects_open_listed']}};
if (command === 'projects_list') return {projects:[{...reply, canWrite:false, updatedAt:'2026-09-01'}]};
if (command === 'projects_open_listed') {
assert.deepEqual(args,{projectId:'two'});
return {status:'ok',project:reply};
}
}});
const [listed] = await client.list();
assert.equal(listed.canWrite,false);
assert.equal(listed.updatedAt,'2026-09-01');
const selected = await client.openListed(listed);
assert.equal(selected.project.id,'two');
reply = project('one');
await assert.rejects(client.openListed(listed),/identity/);
assert.equal(client.active,selected);
assert.ok(!commands.some(command => ['projects_open','projects_create','filesystem_upload_files'].includes(command)));
});
test('older hosts reopen an existing grant and report a denied row without reopening the picker', async () => {
const {client,files} = fixture({invoke(command, args) {
if (command === 'get_app_info') return {projects:{commands:['projects_open']}};
if (command === 'filesystem_get_files' && args.files[0].path === project('three').path + '/project.json') {
return {items:[{path:args.files[0].path, status:'error', authoritative:false, error:'extension filesystem permission is required'}]};
}
if (command === 'projects_open') assert.fail('Unexpected second project picker');
}});
const selected = await client.openListed(project('one'));
files.delete(project('two').path+'/project.json');
await assert.rejects(client.openListed(project('two')), /manifest missing/);
await assert.rejects(client.openListed(project('three')), /extension filesystem permission is required/);
assert.equal(client.active,selected);
});
test('a direct grant initializes the extension directory on first writable access', async () => {
const selected = {...project('two'), canWrite:true};
const directories = [];
const {client} = fixture({invoke(command, args) {
if (command === 'get_app_info') return {projects:{commands:['projects_open_listed']}};
if (command === 'projects_open_listed') return {status:'ok', project:selected};
if (command === 'filesystem_list_dir') return {authoritative:true, files:[]};
if (command === 'filesystem_create_folder') {
directories.push(args.path);
return {status:'ok', path:args.path, fileId:args.path};
}
}});
assert.equal((await client.openListed(selected)).project.id, selected.id);
assert.deepEqual(directories, [selected.path + '/extensions', selected.path + '/extensions/contracts']);
});
test('first-open initialization reads the winning record after a folder race and an uncertain create', async () => {
let uploads = 0;
const {client, files} = fixture({invoke(command, args) {
if (command === 'filesystem_create_folder') throw new Error('Already exists');
if (command === 'filesystem_list_dir') {
return {authoritative:true, files:['extensions','contracts','data'].map(name => ({path:args.path + '/' + name, kind:'folder', id:name}))};
}
if (command === 'filesystem_upload_files') {
const file = args.files[0];
assert.equal(file.replaceExisting, false);
assert.equal(file.path, project('one').path + '/extensions/contracts/data/current.json');
files.set(file.path, {from:'other session'});
uploads++;
throw new Error('Create outcome unknown');
}
}});
const session = await client.activate({...project('one'), canWrite:true});
const created = await session.ensureExtensionJson('data/current.json', () => ({from:'this session'}));
assert.deepEqual(created.value, {from:'other session'});
const reopened = await session.ensureExtensionJson('data/current.json', () => assert.fail('Record already exists'));
assert.deepEqual(reopened.value, created.value);
assert.equal(uploads, 1);
});
test('read-only, archived and uncertain reads cannot seed extension records', async () => {
let answer;
const {client, writes} = fixture({invoke(command, args) {
if (command === 'filesystem_get_files' && answer && !args.files[0].path.endsWith('/project.json')) {
return {items:[{path:args.files[0].path, ...answer}]};
}
}});
const fail = () => assert.fail('Unexpected default');
for (const access of [{canWrite:false}, {archived:true, canWrite:true}]) {
const session = await client.activate({...project('one'), ...access});
assert.equal((await session.ensureExtensionJson('state.json', fail)).status, 'absent');
}
const session = await client.activate(project('two'));
for (answer of [{status:'unavailable'}, {status:'absent',source:'dashboard',authoritative:true,found:true}]) {
await assert.rejects(session.ensureExtensionJson('state.json', fail), {name:'ProjectUnavailableError'});
}
assert.equal(writes.length, 0);
});
+22
View File
@@ -0,0 +1,22 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createProjectManifest, parseProjectManifest, validateArchivePath, extensionDataPath } from '../src/index.js';
test('reject archive traversal and cross-platform unsafe paths before storage', () => {
for (const path of ['../project.json', '/project.json', 'a/../../b', 'a\\..\\b', 'C:/x', 'a//b', './x', 'a/./b', 'a\0b', 'a\nb', 'a/NUL.txt', 'a/file.', 'a/file ']) {
assert.throws(() => validateArchivePath(path), { name: 'TypeError' }, path);
}
assert.equal(validateArchivePath('assets/meeting audio.ogg'), 'assets/meeting audio.ogg');
assert.equal(extensionDataPath('isa-quote', 'state/current.json'), 'extensions/isa-quote/state/current.json');
assert.throws(() => extensionDataPath('../quote', 'x'));
});
test('preserve unknown manifest data without sharing mutable references', () => {
const manifest = { ...createProjectManifest({ id: 'project-1', name: 'Example' }), future: { value: 1 } };
const parsed = parseProjectManifest(manifest);
parsed.future.value = 2;
assert.equal(manifest.future.value, 1);
assert.throws(() => parseProjectManifest({ ...manifest, formatVersion: 2 }));
assert.throws(() => parseProjectManifest({ ...manifest, createdAt: 'yesterday' }));
assert.throws(() => parseProjectManifest({ ...manifest, createdAt: '2026-02-30T00:00:00Z' }));
});
+29
View File
@@ -0,0 +1,29 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readExportFile } from '../src/transfer/files.js';
test('large media uses bounded streaming with hash verification and renewed authority', async () => {
const bytes=new Uint8Array(16*1024*1024+1);bytes[bytes.length-1]=42;
const hash=Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',bytes)),v=>v.toString(16).padStart(2,'0')).join('');
const path='/project.isap/assets/recording.wav';
const expected={id:'recording',revision:2,hash,size:bytes.length};
const link={status:'ok',source:'dashboard',authoritative:true,path,fileId:expected.id,syncRevision:2,contentHash:hash,fileSize:bytes.length,downloadUrl:'https://downloads.example/one-use'};
const controller=new AbortController();
const session={signal:controller.signal,assertCurrent(){this.signal.throwIfAborted();}};
const original=globalThis.fetch;let requests=0,mode='ok';
const bridge={async invoke(command,args){assert.equal(command,'filesystem_get_download_link_file');assert.equal(args.path,path);requests++;return mode==='revoked'&&requests===2?{status:'unavailable',authoritative:false}:link;}};
globalThis.fetch=async(url,options)=> {
assert.equal(url.href,link.downloadUrl);assert.equal(options.signal,session.signal);assert.equal(options.credentials,'omit');
return new Response(new ReadableStream({start(stream){stream.enqueue(mode==='corrupt'?new Uint8Array(bytes.length):bytes);stream.close();}}));
};
try {
assert.deepEqual(await readExportFile(session,bridge,{workspaceId:'workspace',groupId:'group'},{path},expected,bytes.length),bytes);
assert.equal(requests,2);
mode='corrupt';requests=0;
await assert.rejects(readExportFile(session,bridge,{}, {path},expected,bytes.length),/hash mismatch/);
assert.equal(requests,1);
mode='revoked';requests=0;
await assert.rejects(readExportFile(session,bridge,{}, {path},expected,bytes.length),/unavailable/);
await assert.rejects(readExportFile(session,bridge,{}, {path},expected,bytes.length-1),/transfer limit/);
} finally {globalThis.fetch=original;}
});
+51
View File
@@ -0,0 +1,51 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {createSharedFolderReader} from '../src/shared-folder.js';
test('specialist and other viewers read the same existing supplier register and price book', async () => {
const root='/Shared/Registers';
const scope={workspaceId:'w',groupId:'g'};
const folder={path:root,...scope};
const register={format:'isa-match-workspace-suppliers-v1',workspaceId:'w',id:'abc',suppliers:[{id:'supplier-1',name:'Voorbeeld',administration:'',number:''}]};
const row={supplier:'Voorbeeld',unit:'m²',unitPrice:42,currency:'EUR'};
const commands=[];
function viewer(extension) {
return createSharedFolderReader({folder,scope,bridge:{
async invoke(command,args) {
commands.push([extension,command]);
if (command === 'filesystem_list_dir') {
assert.equal(args.path,root);
return {authoritative:true,files:[{kind:'file',path:root+'/isa-match-suppliers.json'}]};
}
assert.equal(command,'filesystem_get_files');
assert.equal(args.groupId,'g');
const [{path,cachePolicy}]=args.files;
assert.equal(path,root+'/isa-match-suppliers.json');
assert.equal(cachePolicy,'dashboard-required');
return {items:[{path,source:'dashboard',authoritative:true,status:'ok',fileId:'index',syncRevision:1,...(extension==='other-viewer'?{bytesBase64:Buffer.from(JSON.stringify(register)).toString('base64')}:{text:JSON.stringify(register)})}]};
},
async snapshotKv(args) {
commands.push([extension,'snapshot']);
assert.equal(args.path,root+'/isa-match-prices-abc.kv');
return {revision:2,snapshotId:'snapshot',storeId:'store',incarnation:'1',entries:[{status:'found',kind:'value',key:'price/g/1',value:row}]};
}
}});
}
for(const reader of [viewer('supplier-viewer'),viewer('other-viewer')]) {
assert.equal((await reader.listFiles()).length,1);
const index=await reader.readJson('isa-match-suppliers.json');
assert.deepEqual(index.value,register);
const result=await reader.readKv('isa-match-prices-'+index.value.id+'.kv');
assert.deepEqual(result.entries[0].value,row);
await assert.rejects(reader.readKv('../other.kv'),/Unsafe/);
}
assert.equal(commands.length,6);
});
test('revocation and mismatched launch scopes never resolve to empty or initialized data',async () => {
const scope={workspaceId:'w',groupId:'g'};
const bridge={invoke:async()=>{throw new Error('Access revoked');}};
assert.throws(()=>createSharedFolderReader({scope,bridge,folder:{path:'/Shared',groupId:'other'}}),/Invalid shared folder/);
const reader=createSharedFolderReader({scope,bridge,folder:{path:'/Shared'}});
await assert.rejects(reader.readJson('isa-match-suppliers.json'),/Access revoked/);
});
+229
View File
@@ -0,0 +1,229 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {zipSync,unzipSync,strToU8,strFromU8} from 'fflate';
import {createProjectClient} from '../src/client.js';
import {exportProject,importProject,exportProjectToDialog,importProjectFromDialog,TRANSFER_MANIFEST} from '../src/transfer.js';
import {packZip,unpackZip} from '../src/transfer/zip.js';
const scope={workspaceId:'workspace',groupId:'group'};
const KV_TYPE='application/vnd.isa.kv-store';
const manifest=id=>({formatVersion:1,id,name:'Example',createdAt:'2026-11-03T12:00:00Z',updatedAt:'2026-11-03T12:00:00Z',unknown:{keep:true}});
const project=id=>({id,folderId:id,name:'Example',path:`/projects/${id}.isap`,projectIdentity:id});
function fixture() {
const files=new Map(),stores=new Map(),snapshots=new Map(),calls=[],projects=new Map();
let creates=0,snapshotSequence=0;
function add(path,bytes,type='application/octet-stream') {files.set(path,{bytes:bytes instanceof Uint8Array?bytes:strToU8(bytes),contentType:type,revision:1,id:path});}
function folder(path){files.set(path,{kind:'folder',bytes:new Uint8Array(),revision:0,id:path});}
function putProject(id,name='Example') {const value={...project(id),name};projects.set(id,value);folder(value.path);folder(`${value.path}/extensions`);folder(`${value.path}/assets`);add(`${value.path}/project.json`,JSON.stringify({...manifest(id),name}),'application/json');return value;}
const original=putProject('original');
const media=new Uint8Array([0,255,17,48,0,99]);
add(`${original.path}/assets/audio.bin`,media,'audio/wav');
add(`${original.path}/extensions/unknown/future.json`,'{"future":true}','application/json');
add(`${original.path}/extensions/unknown/opaque.kv`,'ordinary unknown bytes','application/octet-stream');
add(`${original.path}/__proto__`,'unknown root file','application/octet-stream');
folder(`${original.path}/extensions/unknown`);folder(`${original.path}/extensions/unknown/empty`);folder(`${original.path}/extensions/unknown/empty/deep`);folder(`${original.path}/extensions/quote`);
const kvPath=`${original.path}/extensions/quote/state.kv`;
add(kvPath,'STALE CHECKPOINT',KV_TYPE);
stores.set(kvPath,{revision:9,entries:[{key:'empty',status:'found',kind:'list',itemIds:[],value:[]},{key:'rows',status:'found',kind:'list',itemIds:['stable-b','stable-a'],value:[{name:'Latest'},{name:'Second'}]},{key:'value',status:'found',kind:'value',value:{updated:true}}]});
const bridge={
async invoke(command,args) {
calls.push({command,args});
if(command==='localstorage_get')return [];
if(command==='localstorage_put')return {status:'ok'};
if(command==='projects_list')return {projects:[...projects.values()]};
if(command==='projects_create')return {created:true,project:putProject(`imported-${++creates}`,args.name)};
if(command==='filesystem_list_dir')return {authoritative:true,files:[...files].filter(([path])=>path.startsWith(`${args.path}/`)).map(([path,row])=>({path,id:row.id,kind:row.kind??'file',contentType:row.contentType,syncRevision:row.revision,fileSize:row.bytes.length}))};
if(command==='filesystem_create_folder') {assert.equal(files.get(args.path.slice(0,args.path.lastIndexOf('/')))?.kind,'folder');folder(args.path);return {status:'ok',path:args.path,fileId:files.get(args.path).id};}
if(command==='filesystem_get_files')return {items:args.files.map(request=>{
const row=files.get(request.path);
if(!row)return {status:'absent',path:request.path,source:'dashboard',authoritative:true};
if(request.expectedSyncRevision!==undefined)assert.equal(request.expectedSyncRevision,row.revision);
return {status:'ok',source:'dashboard',authoritative:true,path:request.path,fileId:row.id,syncRevision:row.revision,bytesBase64:Buffer.from(row.bytes).toString('base64'),...(row.contentType==='application/json'?{text:strFromU8(row.bytes)}:{})};
})};
if(command==='filesystem_upload_files') {
for(const item of args.files) {
const previous=files.get(item.path);
assert.equal(item.replaceExisting,Boolean(previous));
if(previous)assert.equal(item.expectedSyncRevision,previous.revision);
add(item.path,item.text??new Uint8Array(Buffer.from(item.bytesBase64,'base64')),item.contentType);
if(previous)files.get(item.path).revision=previous.revision+1;
}
return {items:args.files.map(item=>({status:'ok',isComplete:true,path:item.path,fileId:files.get(item.path).id}))};
}
if(command==='kv_store_open') {add(args.path,'NEW CHECKPOINT',KV_TYPE);stores.set(args.path,{revision:0,entries:[]});return {status:'ok'};}
if(command==='save_file_dialog')return {status:'ok',saved:true};
if(command==='select_files')return bridge.selection??{canceled:true,selections:[]};
throw new Error(`Unexpected ${command}`);
},
async snapshotKv(args) {
calls.push({command:'snapshotKv',args});
let id,index;
if(args.cursor){[id,index]=args.cursor.split(':');index=Number(index);}
else {id=`snapshot-${++snapshotSequence}`;index=0;snapshots.set(id,structuredClone(stores.get(args.path)));}
const store=snapshots.get(id),limit=Math.min(args.limit??1,2),entries=store.entries.slice(index,index+limit);
return {snapshotId:id,revision:store.revision,storeId:args.path,incarnation:'incarnation',entries,nextCursor:index+limit<store.entries.length?`${id}:${index+limit}`:null};
},
async applyKv(args) {
calls.push({command:'applyKv',args});
const store=stores.get(args.path);
for(const operation of args.operations) {
let entry=store.entries.find(entry=>entry.key===operation.key);
if(operation.kind==='set') {
entry={key:operation.key,status:'found',kind:Array.isArray(operation.value)?'list':'value',value:structuredClone(operation.value),...(Array.isArray(operation.value)?{itemIds:[]}:{})};
store.entries=store.entries.filter(other=>other.key!==entry.key);store.entries.push(entry);
}else if(operation.kind==='list_append') {entry.itemIds.push(operation.id);entry.value.push(structuredClone(operation.value));}
else assert.fail(`Unexpected operation ${operation.kind}`);
}
store.revision++;return {status:'ok'};
}
};
const client=createProjectClient({bridge,extensionId:'contracts',scope});
return {bridge,client,files,stores,calls,original,media,kvPath,get creates(){return creates;}};
}
test('whole project ZIP roundtrip preserves unknown files, media, live KV list IDs and a new identity',async()=>{
const f=fixture(),source=await f.client.activate(f.original);
source.permission={grantId:'DO-NOT-EXPORT'};
const originalManifest=manifest('original');originalManifest.credentials={token:'DO-NOT-EXPORT'};
f.files.get(`${f.original.path}/project.json`).bytes=strToU8(JSON.stringify(originalManifest));
const bytes=await exportProject(source,{bridge:f.bridge});
assert.equal(new DataView(bytes.buffer,bytes.byteOffset).getUint32(0,true),0x04034b50);
const decoded=unzipSync(bytes),sidecar=JSON.parse(strFromU8(decoded[TRANSFER_MANIFEST]));
assert.ok(!decoded['extensions/quote/state.kv']);
assert.ok(!JSON.stringify(sidecar).includes('STALE CHECKPOINT'));
assert.ok(!Object.values(decoded).some(value=>strFromU8(value).includes('DO-NOT-EXPORT')));
assert.deepEqual(sidecar.kvStores[0].entries[1].itemIds,['stable-b','stable-a']);
assert.ok(f.calls.some(call=>call.command==='snapshotKv'&&call.args.cursor));
const imported=await importProject(f.client,bytes,{bridge:f.bridge});
assert.notEqual(imported.project.id,source.project.id);
const saved=JSON.parse(strFromU8(f.files.get(imported.path('project.json')).bytes));
assert.equal(saved.id,imported.project.projectIdentity);assert.deepEqual(saved.unknown,{keep:true});
assert.equal(saved.importedFrom.id,'original');assert.equal(saved.auditAuthority,'historical-only');
assert.deepEqual(f.files.get(imported.path('assets/audio.bin')).bytes,f.media);
assert.equal(strFromU8(f.files.get(imported.path('extensions/unknown/future.json')).bytes),'{"future":true}');
assert.equal(strFromU8(f.files.get(imported.path('extensions/unknown/opaque.kv')).bytes),'ordinary unknown bytes');
assert.equal(strFromU8(f.files.get(imported.path('__proto__')).bytes),'unknown root file');
assert.equal(f.files.get(imported.path('extensions/unknown/empty/deep')).kind,'folder');
assert.ok(decoded['extensions/unknown/empty/deep/']);
assert.deepEqual(f.stores.get(imported.path('extensions/quote/state.kv')).entries,sidecar.kvStores[0].entries);
});
function zipped(extra={}) {return zipSync({'project.json':strToU8(JSON.stringify(manifest('old'))),...extra});}
function central(bytes){const view=new DataView(bytes.buffer,bytes.byteOffset,bytes.byteLength);for(let index=0;index<bytes.length-4;index++)if(view.getUint32(index,true)===0x02014b50)return index;throw new Error('Missing central');}
test('unsafe ZIP paths, collisions, links, corruption and decompression bounds fail before host creation',async()=>{
const duplicate=zipped({a:strToU8('a'),b:strToU8('b')});
for(let i=0;i<duplicate.length-4;i++) {
const view=new DataView(duplicate.buffer),signature=view.getUint32(i,true);
const length=signature===0x04034b50?view.getUint16(i+26,true):signature===0x02014b50?view.getUint16(i+28,true):0;
const name=i+(signature===0x04034b50?30:46);
if(length===1&&duplicate[name]===98)duplicate[name]=97;
}
const link=zipped();new DataView(link.buffer).setUint32(central(link)+38,0xa1ff0000,true);
const corrupt=zipped();new DataView(corrupt.buffer).setUint32(central(corrupt)+16,1,true);
const liar=zipped({bomb:strToU8('x'.repeat(20000))});
const liarView=new DataView(liar.buffer);let position=central(liar);
while(strFromU8(liar.subarray(position+46,position+46+liarView.getUint16(position+28,true)))!=='bomb')position+=46+liarView.getUint16(position+28,true)+liarView.getUint16(position+30,true)+liarView.getUint16(position+32,true);
const local=liarView.getUint32(position+42,true);liarView.setUint32(position+24,0,true);liarView.setUint32(local+22,0,true);
for(const bytes of [zipped({'../escape':strToU8('x')}),zipped({'/absolute':strToU8('x')}),zipped({'C:/drive':strToU8('x')}),zipped({' padded/name':strToU8('x')}),zipped({'folder/name\u00a0':strToU8('x')}),zipped({'same/a':strToU8('x'),'Same/b':strToU8('x')}),zipped({parent:strToU8('x'),'parent/child':strToU8('x')}),duplicate,link,corrupt,liar]) {
const f=fixture();await assert.rejects(importProject(f.client,bytes,{bridge:f.bridge}));assert.equal(f.creates,0);
}
const f=fixture();await assert.rejects(importProject(f.client,zipped({large:strToU8('a'.repeat(4096))}),{bridge:f.bridge,maxFileBytes:2048}));assert.equal(f.creates,0);
});
test('inconsistent KV pages, concurrent files and retired sessions cannot produce an export',async()=>{
const f=fixture(),session=await f.client.activate(f.original),normal=f.bridge.snapshotKv.bind(f.bridge);
f.bridge.snapshotKv=async args=>{const value=await normal(args);if(args.cursor)value.snapshotId='different';return value;};
await assert.rejects(exportProject(session,{bridge:f.bridge}),/generation/);
f.bridge.snapshotKv=normal;
const invoke=f.bridge.invoke.bind(f.bridge);
f.bridge.invoke=async(command,args)=>{const value=await invoke(command,args);if(command==='filesystem_get_files')f.files.get(`${f.original.path}/assets/audio.bin`).revision++;return value;};
await assert.rejects(exportProject(session,{bridge:f.bridge}),/changed|equal/);
await session.close();await assert.rejects(exportProject(session,{bridge:f.bridge}),{name:'AbortError'});
});
test('host save/select dialogs transfer real ZIP bytes with cancellation and validation',async()=>{
const f=fixture(),session=await f.client.activate(f.original);
await exportProjectToDialog(session,{bridge:f.bridge});
const saved=f.calls.find(call=>call.command==='save_file_dialog');
assert.ok(saved.args.fileName.endsWith('.isap.zip'));
assert.equal(await importProjectFromDialog(f.client,{bridge:f.bridge}),null);
assert.deepEqual(f.calls.find(call=>call.command==='select_files').args,{multiple:false,accessPolicy:'read-only',filters:['.zip']});
f.bridge.selection={selections:[{filename:'project.zip',bytesBase64:saved.args.bytesBase64}]};
assert.ok(await importProjectFromDialog(f.client,{bridge:f.bridge}));
});
test('complete local KV snapshots retain unsent values and reject a changed local revision',async()=>{
const f=fixture(),session=await f.client.activate(f.original);
let localRevision=20;
f.bridge.snapshotKv=async()=>({local:true,snapshotComplete:true,revision:9,localRevision,storeId:'old-store',incarnation:'old-incarnation',pending:true,entries:structuredClone(f.stores.get(f.kvPath).entries),nextCursor:null});
const bytes=await exportProject(session,{bridge:f.bridge});
const sidecar=JSON.parse(strFromU8(unzipSync(bytes)[TRANSFER_MANIFEST]));
assert.equal(sidecar.kvStores[0].entries[1].value[0].name,'Latest');
assert.ok(!JSON.stringify(sidecar).includes('old-store'));
let calls=0;const snapshot=f.bridge.snapshotKv;
f.bridge.snapshotKv=async args=>{if(++calls>1)localRevision++;return snapshot(args);};
await assert.rejects(exportProject(session,{bridge:f.bridge}),/KV changed/);
});
test('malformed logical KV snapshots and unsupported transfer versions fail before creation',async()=>{
for(const change of [sidecar=>{sidecar.formatVersion=2;},sidecar=>{sidecar.kvStores[0].entries[0].itemIds=['duplicate','duplicate'];},sidecar=>{sidecar.kvStores[0].path='../escape.kv';},sidecar=>{sidecar.kvStores.push(structuredClone(sidecar.kvStores[0]));}]) {
const f=fixture(),session=await f.client.activate(f.original),files=unpackZip(await exportProject(session,{bridge:f.bridge}));
const sidecar=JSON.parse(strFromU8(files.get(TRANSFER_MANIFEST)));change(sidecar);files.set(TRANSFER_MANIFEST,strToU8(JSON.stringify(sidecar)));
await assert.rejects(importProject(f.client,packZip(files,{},files.directories),{bridge:f.bridge}));assert.equal(f.creates,0);
}
});
test('large lists replay in bounded ordered batches and switching stops subsequent mutations',async()=>{
const f=fixture(),session=await f.client.activate(f.original);
const entry={key:'large',status:'found',kind:'list',itemIds:Array.from({length:350},(_,i)=>`id-${350-i}`),value:Array.from({length:350},(_,i)=>({position:i}))};
f.stores.get(f.kvPath).entries=[entry];
const bytes=await exportProject(session,{bridge:f.bridge});
const imported=await importProject(f.client,bytes,{bridge:f.bridge});
const mutations=f.calls.filter(call=>call.command==='applyKv');
assert.equal(mutations.length,3);assert.ok(mutations.every(call=>call.args.operations.length<=128));
assert.deepEqual(f.stores.get(imported.path('extensions/quote/state.kv')).entries,[entry]);
const normal=f.bridge.applyKv.bind(f.bridge);let applied=0;
f.bridge.applyKv=async args=>{const result=await normal(args);if(++applied===1)await f.client.close();return result;};
await assert.rejects(importProject(f.client,bytes,{bridge:f.bridge}),{name:'AbortError'});
assert.equal(applied,1);
});
test('import activates only complete staged projects and picks unique UTF-16-safe names',async()=>{
const f=fixture(),source=await f.client.activate(f.original),bytes=await exportProject(source,{bridge:f.bridge});
let release,started;
const blocked=new Promise(resolve=>{started=resolve;}),normal=f.bridge.invoke.bind(f.bridge);
f.bridge.invoke=async(command,args)=>{if(command==='filesystem_upload_files'&&!release){await new Promise(resolve=>{release=resolve;started();});}return normal(command,args);};
const events=[];f.client.subscribe(({active})=>{if(active&&active!==source)events.push(JSON.parse(strFromU8(f.files.get(active.path('project.json')).bytes)));});
const pending=importProject(f.client,bytes,{bridge:f.bridge});await blocked;
assert.equal(f.client.active,source);assert.deepEqual(events,[]);release();
const imported=await pending;assert.equal(f.client.active,imported);assert.ok(events.length&&events.every(value=>value.importedFrom?.id==='original'));
assert.equal(imported.project.name,'Example (import)');
const second=await importProject(f.client,bytes,{bridge:f.bridge});assert.equal(second.project.name,'Example (import 2)');
const long={...manifest('old'),name:'😀'.repeat(80)};
const third=await importProject(f.client,zipSync({'project.json':strToU8(JSON.stringify(long))}),{bridge:f.bridge});
assert.ok(third.project.name.length<=160);assert.ok(!/[\ud800-\udbff]$/.test(third.project.name.slice(0,-' (import)'.length)));
});
test('failed import retires its staged session while preserving the previously active project',async()=>{
const f=fixture(),source=await f.client.activate(f.original),bytes=await exportProject(source,{bridge:f.bridge});
const normal=f.bridge.invoke.bind(f.bridge);f.bridge.invoke=(command,args)=>command==='filesystem_create_folder'?Promise.reject(new Error('Folder write failed')):normal(command,args);
let staged;const stage=f.client.stageCreate.bind(f.client);f.client.stageCreate=async(...args)=>(staged=await stage(...args));
await assert.rejects(importProject(f.client,bytes,{bridge:f.bridge}),error=>error.message==='Folder write failed'&&Boolean(error.project));
assert.equal(f.client.active,source);assert.equal(staged.signal.aborted,true);
});
test('export preparation flushes the captured session before snapshot and fences a closed session',async()=>{
const f=fixture(),session=await f.client.activate(f.original);
session.markDirty();
const bytes=await exportProject(session,{bridge:f.bridge,beforeExport:async captured=>{
assert.equal(captured,session);
f.stores.get(f.kvPath).entries[2].value={flushed:true};
f.stores.get(f.kvPath).revision++;
captured.markDirty(false);
}});
const sidecar=JSON.parse(strFromU8(unpackZip(bytes).get(TRANSFER_MANIFEST)));
assert.deepEqual(sidecar.kvStores[0].entries[2].value,{flushed:true});
const before=f.calls.filter(call=>call.command==='filesystem_list_dir').length;
await assert.rejects(exportProject(session,{bridge:f.bridge,beforeExport:()=>session.close()}),{name:'AbortError'});
assert.equal(f.calls.filter(call=>call.command==='filesystem_list_dir').length,before);
});