import type {RecoveryImage} from './storage-port.ts'; import {isSealedRecoveryImage,sealedRecoveryByteLength,encodedRecoveryByteLength} from './recovery-encoding.ts'; import {createImportBudget,type ImportScheduling} from './import-budget.ts'; import {fault} from '../canvas-core/values.ts'; function* stringTokens(value:string):Generator{ if(value.length<=4096){yield JSON.stringify(value);return;} yield '"'; for(let start=0;start=0xd800&&a<=0xdbff&&b>=0xdc00&&b<=0xdfff)end--;yield JSON.stringify(value.slice(start,end)).slice(1,-1);start=end;} yield '"'; } /** Only traverse codec-owned normalized JSON. Small owned subtrees use native stringify. */ function* tokens(value:unknown):Generator{ if(value&&typeof value==='object'){ const size=encodedRecoveryByteLength(value);if(size!==undefined&&size<=16384){yield JSON.stringify(value);return;} if(Array.isArray(value)){yield '[';for(let i=0;i)[key]);}yield '}';return; } if(typeof value==='string')yield* stringTokens(value);else yield JSON.stringify(value); } /** Preserve exact JSON.stringify bytes; scheduling never exposes a partial recovery image. */ export async function serializeRecoveryImage(image:RecoveryImage,options:ImportScheduling&{check?:()=>void}={}):Promise{ options.check?.(); if(!isSealedRecoveryImage(image)){const bytes=new Blob([JSON.stringify(image)],{type:'application/json'});options.check?.();return bytes;} const budget=createImportBudget(new AbortController().signal,options),parts:BlobPart[]=[];let pending:string[]=[],length=0; for(const token of tokens(image)){ pending.push(token);length+=token.length; if(length>=8192){parts.push(pending.join(''));pending=[];length=0;options.check?.();await budget.step(128);options.check?.();} } if(pending.length)parts.push(pending.join(''));options.check?.(); const bytes=new Blob(parts,{type:'application/json'});if(bytes.size!==sealedRecoveryByteLength(image))throw fault('recovery_encoding_size_mismatch');return bytes; }