@vcp-dev/site-edit-engine 0.8.4 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +1 -1
  2. package/package.json +2 -2
package/dist/index.js CHANGED
@@ -10,4 +10,4 @@ import{SiteEditOperationRequestSchema as xk,SiteEditPatchPlanSchema as Sk}from"@
10
10
  `||p==="\r"?(a=!1,l=!0):l=!1;continue}if(o){if(i)i=!1;else if(p==="\\")i=!0;else if(p===o)o=null;else if(n==="css"&&(p===`
11
11
  `||p==="\r"))return jn(t,`Unterminated string literal in ${t}.`);l=p===`
12
12
  `||p==="\r";continue}if(p==="/"&&m==="*"){s=!0,d+=1,l=!1;continue}if(n==="mdx"&&p==="/"&&m==="/"){a=!0,d+=1,l=!1;continue}if(p==="'"||p==='"'||n==="mdx"&&p==="`"){o=p,l=!1;continue}if(p==="{"||p==="("||p==="["){r.push({char:p,offset:d}),l=!1;continue}if(p==="}"||p===")"||p==="]"){let g=p==="}"?"{":p===")"?"(":"[",S=r.pop();if(!S||S.char!==g)return jn(t,`Unexpected closing token "${p}" in ${t}.`);l=!1;continue}l=p===`
13
- `||p==="\r"}if(s)return jn(t,`Unterminated block comment in ${t}.`);if(o)return jn(t,`Unterminated string literal in ${t}.`);if(c)return jn(t,`Unterminated MDX code fence in ${t}.`);let u=r.at(-1);return u?jn(t,`Unclosed token "${u.char}" in ${t}.`):{ok:!0}}function jn(e,t){return{ok:!1,errorCode:"ast-error",message:t,details:{path:e}}}function Nr(e){let t="idle",n=e.fileSystem??gv(),r=yf(),o=lp({compositions:e.compositions,initialDocumentVersions:e.initialDocumentVersions}),i=new Map,s=new Map,a=new Set,c=null,l=e.history??(e.historyStore?Qf(e.historyStore):hv()),u=hf(n,{externalAdapters:e.externalAdapters}),d=new Map,p=new Set,m=0,g=e.historyStore?.recoveryRequired??!1,S=Fa(),C=B();function v(f){return(qo.isAbsolute(f)?qo.relative(e.projectRoot,f):f).replace(/\\/g,"/").replace(/^\.\//,"")}function P(f,y){let h=qo.posix.dirname(f),I=y.replace(/\.(?:tsx?|jsx?)$/i,""),R=qo.posix.relative(h,I);return R.startsWith(".")?R:`./${R}`}function w(f,y){return f.startLine===y.startLine&&f.startColumn===y.startColumn&&f.endLine===y.endLine&&f.endColumn===y.endColumn}async function B(){let f=e.historyStore;if(f)try{let y=await f.readTransactionJournal();if(!y)return;let h=await f.readIndex(),I=await Promise.all(y.files.map(async A=>await n.exists(A.path)?ue(await n.readFile(A.path)):null));if(ap({journal:y,index:h,observedFileDigests:I})!=="ambiguous"){await f.clearTransactionJournal(y.transactionId);let A=await f.readStatus();A.recoveryRequired||(await f.cleanupTmp(),A=await f.readStatus()),g=A.recoveryRequired;return}await f.markRecoveryRequired(`Ambiguous transaction journal ${y.transactionId} at phase ${y.phase}`),g=!0}catch(y){g=!0,await f.markRecoveryRequired(`Transaction journal recovery failed: ${Fe(y)}`).catch(()=>{})}}function re(){return t==="disposed"}e.onEvent&&r.subscribe(e.onEvent);for(let f of o.entries){let y=mp(f.context,f.entryFile);i.set(f.key,y),ne(y,y.dependencyFiles)}function ne(f,y){let h=new Set(y);N(f),f.dependencyFiles=h;for(let I of f.dependencyFiles){let R=s.get(I);R||(R=new Set,s.set(I,R)),R.add(f.key)}}function N(f){for(let y of f.dependencyFiles){let h=s.get(y);h&&(h.delete(f.key),h.size===0&&s.delete(y))}f.dependencyFiles.clear()}function X(f){let y=new Set;for(let h of f)for(let I of s.get(h)??[])y.add(I);return y}function M(f){for(let y of f)if(!s.has(y))return!1;return!0}async function D(f,y,h,I,R){let A=new Map,F=Sd(R.values()),L=new Map,T=typeof n.exists=="function"?$=>n.exists($):async()=>!1;for(let[$,K]of f.elements){let me=y.nodes.get($);if(!me)continue;let Q=h.get(K.sourceFile)??I.get(K.sourceFile),Ie=new Map,Y=new Map,ge=new Map,_=[];for(let pe of K.textSegments){if(!Q){Ie.set(pe.index,null);continue}let Kn=await bd({file:K.sourceFile,source:Q,segment:pe,readFile:Ze=>n.readFile(Ze),exists:T,graph:f,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Ze,adapterId:ki,capabilities:Ci})=>({sourceType:Ze,adapterId:ki,capabilities:Ci})),functionCallContracts:e.functionCallContracts,fileCache:F}),we=await Gs({file:K.sourceFile,source:Q,target:{kind:"text-segment",segment:pe},readFile:Ze=>n.readFile(Ze),exists:T,graph:f,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Ze,adapterId:ki,capabilities:Ci})=>({sourceType:Ze,adapterId:ki,capabilities:Ci})),functionCallContracts:e.functionCallContracts,fileCache:F}),gn=Rv(Kn);Ie.set(pe.index,gn),Y.set(pe.index,Kn),ge.set(pe.index,we),_.push({editable:pe.editable,source:gn})}let j=new Map;if(Q)for(let pe of K.attributes??[]){let Kn=await Ed({file:K.sourceFile,source:Q,sourceRange:pe.sourceRange,expression:pe.source?.expression??pe.value,sourceInfo:pe.source,readFile:we=>n.readFile(we),exists:T,graph:f,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:we,adapterId:gn,capabilities:Ze})=>({sourceType:we,adapterId:gn,capabilities:Ze})),functionCallContracts:e.functionCallContracts,fileCache:F});j.set(pe.name,Kn)}let z=Yl(wv(me.writeTarget),_),oe=tu({key:$,element:K,graph:f,provenances:ge}),Se=iu(K),Je=su(K),pn=au(K),mn=Q?await Hd({element:K,graph:f,file:K.sourceFile,source:Q,readFile:pe=>n.readFile(pe),exists:T,fileCache:L}):void 0,Vt=f.regions.find(pe=>pe.kind==="conditional-region"&&pe.childKeys.includes($)),Te,Un=Vt?.sourceCandidates?.[0];if(Q&&Vt&&Un?.kind==="conditional-branch"){let pe=await Gs({file:K.sourceFile,source:Q,target:{kind:"conditional-branch",candidate:Un},readFile:we=>n.readFile(we),exists:T,graph:f,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:we,adapterId:gn,capabilities:Ze})=>({sourceType:we,adapterId:gn,capabilities:Ze})),functionCallContracts:e.functionCallContracts,fileCache:F});Te={currentBranch:Vt.childKeys.indexOf($)<=0?"then":"else",availableBranches:Vt.childKeys.length>1?["then","else"]:["then"],conditionExpression:Un.conditionExpression,provenance:{finalSource:pe.finalSource?{kind:pe.finalSource.kind,file:pe.finalSource.file,displayPath:pe.finalSource.displayPath}:null,chain:pe.chain.map(we=>({kind:we.kind,file:we.file,displayName:we.displayName,canEditHere:we.canEditHere})),confidence:pe.confidence,editMode:pe.editMode,diagnostics:pe.diagnostics.map(we=>({code:we.code,message:we.message}))}}}A.set($,{textSources:Ie,textTargets:Y,elementPropertyTargets:j,provenances:ge,writeTarget:z,componentSemantic:oe,contentModel:Se,mediaModel:Je,styleSource:pn,conditional:Te,dynamicData:mn})}return A}function Z(f){return typeof n.getVersion=="function"?n.getVersion(f):0}function te(f,y){let h=o.initialVersions.get(f.key)??0;for(let I of y.values())h=Math.max(h,I);return Math.max(h,f.graph?.version??0)}function he(f){return i.get(f)?.graph?.version??o.initialVersions.get(f)??0}function H(f){try{return he(o.resolveSelector(f.composition).key)}catch{return 0}}async function q(f,y,h={}){let I=i.get(f);if(!I)return null;let R=h.sourceCache??Ma(d,[]),A=await xe(I.entryFile),{graph:F,allSources:L,diagnostics:T,parsedModules:$,entryModule:K}=await zc(I.entryFile,y,Te=>n.readFile(Te),typeof n.exists=="function"?Te=>n.exists(Te):async()=>!1,{additionalEntries:A,version:I.graph?.version??1});if(T.length>0)throw new Rr(T);let me=new Map;for(let Te of L.keys())me.set(Te,Z(Te));let Q=Math.max(te(I,me),h.minimumVersion??0);h.changed&&Q<=(I.graph?.version??0)&&(Q=(I.graph?.version??0)+1),F.version=Q;for(let[Te,Un]of L)Oa(R,Te,Un,dp);let Ie=await It(I.composition,I.entryFile,L,R);F.routeId=I.routeId,F.composition=I.composition;let Y=Wc(F),ge=Gc(Y,F),_=await D(F,Y,L,R,$),j=am(F,ge,_),z=sm(_),oe=Uv(Xl(F,Y,ge,{canUpdateTextByKey:j,dynamicDataSummaryByKey:z}),F,_),Se=Ll({route:I.routeId,composition:I.composition,entryFile:I.entryFile,version:Q,source:y,ast:K?.ast}),Je=Bl(Se);Se.ok&&_v(oe,F,Se.projection);let pn={...oe,composition:I.composition,...Ie?{styleContext:Ie}:{},pageComposition:Je},mn=new Set([I.entryFile,...L.keys()]);if(Ie){mn.add(Ie.entryCss.path);for(let Te of Ie.stylesheets)mn.add(Te.path)}let Vt={...I,dependencyFiles:mn,graph:F,topology:Y,capabilities:ge,document:pn,pageComposition:Je,pageCompositionProjection:Se.projection,pagePlacementByKey:Se.ok?Se.projection.placementByKey:null,pagePlacementUnitByKey:Se.ok?Se.projection.placementUnitByKey:null,pageUnitByKey:Se.ok?Se.projection.unitByKey:null,pagePlacementsByUnitKey:Se.ok?Se.projection.placementsByUnitKey:null,documentIndex:bv(pn),detailProjections:_,fileVersions:me,styleContext:Ie};if(h.publish===!1)return Vt;Bn(d,R);for(let Te of R.keys())p.delete(Te);return ne(I,mn),Object.assign(I,Vt),I}async function xe(f){let y=[];for(let h of Dv(f))typeof n.exists=="function"&&await n.exists(h)&&y.push({file:h,source:await n.readFile(h)});return y}async function It(f,y,h,I){let R=[];for(let[$,K]of h){if(Ba($)){R.push($);continue}for(let me of Bv(K)){let Q=Sp($,me);Q&&R.push(Q)}}if(!R.length){for(let $ of Lv(y))if(await hc($)){R.push($);break}}let A=new Map,F=kp(R).slice(0,up);for(;F.length>0&&A.size<up;){let $=F.shift();if(A.has($)||!Ba($))continue;let K=await vt($,I);if(K!==null){A.set($,{path:$,content:K});for(let me of jv(K)){let Q=Sp($,me);Q&&!A.has(Q)&&!F.includes(Q)&&F.push(Q)}}}let L=[...A.values()].map($=>({...$,hash:ue($.content)})),T=L[0];return T?{composition:f,revision:ue(JSON.stringify(L.map(({path:$,hash:K})=>({path:$,hash:K})))),entryCss:T,stylesheets:L.slice(1)}:null}async function vt(f,y){let h=y.get(f);if(h!==void 0)return h;if(!await hc(f))return null;let I=await n.readFile(f);return Oa(y,f,I,dp),I}async function hc(f){return typeof n.exists=="function"?n.exists(f):!1}function sm(f){let y=new Map;for(let[h,I]of f)I.dynamicData?.bindings.length&&y.set(h,sf(I.dynamicData.bindings));return y}function am(f,y,h){let I=new Map;for(let[R,A]of f.elements){if(!y.get(R)?.canUpdateText){I.set(R,!1);continue}let L=h.get(R),T=A.textSegments.some($=>{if(!$.editable)return!1;let K=L?.provenances.get($.index)??null;return!K||cm(K)});I.set(R,T)}return I}function cm(f){return f.editMode==="direct"||f.editMode==="proxy"||f.editMode==="upstream"}async function Br(f,y={}){let h=[...new Set(f)],I=y.affectedCompositionKeys!==void 0,R=I?new Set(y.affectedCompositionKeys):X(h);if(!I&&(R.size===0||!M(h)))for(let T of i.values())yc(T,h)&&R.add(T.key);let A=!I&&R.size===0&&h.some(xp),F=y.publish===!1?Ma(d,h):void 0,L={rebuiltRoutes:[],failedRoutes:[],...y.publish===!1?{candidateRouteStates:[],candidateSourceCache:F}:{}};for(let T of i.values())if(!(y.excludedCompositionKeys?.has(T.key)||!(R.has(T.key)||A)))try{let K=!!T.graph,me=await n.readFile(T.entryFile),Q=await q(T.key,me,{...y,...F?{sourceCache:F}:{}});Q?.graph&&(L.rebuiltRoutes.push({documentChanged:K,composition:T.composition,routeId:T.routeId,version:Q.graph.version}),L.candidateRouteStates?.push({composition:T.composition,key:T.key,routeId:T.routeId,state:Q}))}catch(K){L.failedRoutes.push({...sp(T.routeId,K),composition:T.composition})}return L}function un(f){let y=[...new Set(f)],h=X(y);if(h.size>0&&M(y))return[...h];for(let I of i.values())yc(I,y)&&h.add(I.key);return[...h]}function lm(f){let y=new Set(un(f));return o.entries.filter(h=>y.has(h.key)).map(h=>h.context)}function um(f){return[...new Set(un(f))].sort((h,I)=>h<I?-1:h>I?1:0).map(h=>o.getByKey(h)?.context).filter(h=>h!==void 0)}function dm(f,y){let h=new Set(un(y)),I=f.provenance?.affectedCompositions??[];if(I.length===0)return h;let R=new Set(I.map(A=>o.resolveContext(A).key));if(R.size!==h.size||[...R].some(A=>!h.has(A)))throw new Error("History provenance does not match the affected composition index.");return R}function fm(f,y){let h=f.composition??f.provenance?.initiatingComposition;if(h){let A=o.resolveContext(h);return{context:A.context,key:A.key}}let I=[...new Set(un(y))];if(I.length!==1)throw new Error(`Legacy history entry cannot be attributed to a unique composition (affected composition count: ${I.length}).`);let R=o.getByKey(I[0]);if(!R)throw new Error("Legacy history entry references an unknown affected composition.");return{context:R.context,key:R.key}}function Si(f,y){r.emit({type:"operation-completed",composition:f.composition,result:f});for(let{composition:h,version:I}of y.rebuiltRoutes)r.emit({type:"document-changed",composition:h,version:I});for(let{composition:h,message:I}of y.failedRoutes)r.emit({type:"graph-error",composition:h,message:I})}function yc(f,y){return y.some(h=>f.dependencyFiles.has(h)||f.entryFile===h||f.graph?.fileIndex.has(h))}function xc(f){for(let y of f)a.add(y);c||re()||(c=(async()=>{t="building";let y=!1;try{for(;a.size>0;){if(re())return;await pm();let h=[...a];a.clear();let I=await Sc(h);if(I.length===0)continue;let R=un(I);for(let L of R){let T=i.get(L)?.composition;T&&r.emit({type:"graph-invalidated",composition:T})}let{rebuiltRoutes:A,failedRoutes:F}=await Br(I,{changed:!0});for(let{documentChanged:L,composition:T,version:$}of A)r.emit({type:"graph-ready",composition:T,version:$}),L&&r.emit({type:"document-changed",composition:T,version:$});for(let{composition:L,message:T}of F)y=!0,r.emit({type:"graph-error",composition:L,message:T})}}finally{c=null,t!=="disposed"&&(t=!y&&[...i.values()].some(h=>h.graph)?"ready":"idle"),a.size>0&&xc([])}})())}async function pm(){for(;m>0;)await new Promise(f=>setTimeout(f,0))}async function Sc(f){let y=[];for(let h of new Set(f)){let I=d.get(h);if(I===void 0){if(p.has(h)&&!await n.exists(h))continue;p.delete(h),y.push(h);continue}try{await n.readFile(h)!==I&&(p.delete(h),y.push(h))}catch(R){if(!Tv(R))try{if(await n.exists(h))continue}catch{continue}p.add(h),y.push(h)}}return y}function bc(f){op(d,f);for(let y of f)y.exists===!1?p.add(y.file):p.delete(y.file)}function Ec(f){p.clear();for(let y of f)p.add(y)}async function Ic(f){let y=await Sc(f);if(y.length===0)return;let h=un(y);for(let A of h){let F=i.get(A)?.composition;F&&r.emit({type:"graph-invalidated",composition:F})}let{rebuiltRoutes:I,failedRoutes:R}=await Br(y,{changed:!0});for(let{documentChanged:A,composition:F,version:L}of I)r.emit({type:"graph-ready",composition:F,version:L}),A&&r.emit({type:"document-changed",composition:F,version:L});for(let{composition:A,message:F}of R)r.emit({type:"graph-error",composition:A,message:F})}async function mm(f,y){let h=Vn(f,y);if(!h?.graph)return;let I=$e(f)??f,R=h.graph.elements.get(I);R&&await Ic([R.sourceFile])}async function vc(f){let y=new Set;if(f.target.kind==="node"){let h=Vn(f.target.key,f.composition),I=$e(f.target.key)??f.target.key,R=h?.graph?.elements.get(I);R&&y.add(R.sourceFile)}else if(f.target.kind==="route"){let h=i.get(o.resolveSelector(f.target.composition).key);h&&y.add(h.entryFile)}else if(f.target.kind==="page-unit"){let h=i.get(o.resolveSelector(f.target.composition).key);h&&y.add(h.entryFile)}else if(f.target.kind==="source-file")y.add(f.target.path);else if(f.target.kind==="source-batch")for(let h of f.target.paths)y.add(h);await Ic(y)}async function gm(f){if(f.params.kind!=="source-edit")return bi(f,"invalid-params","source-edit requires source-edit params");for(let y of f.params.edits){let h=Av(y);if(!h.ok)return bi(f,h.errorCode,h.message,h.details)}m+=1;try{let y=await Em(f.params.edits);if(!y.ok)return bi(f,y.errorCode,y.message,y.details);await vc(f);let h={operationId:f.id,kind:"source-edit",target:f.target,documentVersion:f.documentVersion,conflictPolicy:f.params.conflictPolicy,edits:f.params.edits.map(I=>I.operation==="delete"?{operation:"delete",file:I.path,baseContentHash:I.baseContentHash??null}:{operation:"upsert",file:I.path,baseContentHash:I.baseContentHash??null,content:I.content})};return await fn({request:f,filePlan:h})}catch(y){return{composition:o.resolveSelector(f.composition).context,requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:H(f),error:{code:O.INTERNAL_ERROR,message:Fe(y)}}}finally{m-=1}}async function hm(f){if(f.target.kind!=="project"||f.params.kind!=="insert-page-resource")return ee(f,O.INVALID_PARAMS,"insert-page-resource requires project target and matching params.");m+=1;try{let y=await wa({files:[...f.params.artifact.components.flatMap(I=>I.materialization.files.map(R=>({path:R.pathTemplate,content:R.content}))),...f.params.artifact.pages.flatMap(I=>I.materialization.files.map(R=>({path:R.pathTemplate,content:R.content})))],exists:I=>n.exists(I),readFile:I=>n.readFile(I)});if(!y.ok)return ee(f,O.MATERIALIZATION_REJECTED,y.message);let h=await Ca({artifact:f.params.artifact,exists:I=>n.exists(I)});return h.ok?await fn({request:f,filePlan:{operationId:f.id,kind:"source-edit",target:f.target,documentVersion:f.documentVersion,conflictPolicy:"overwrite",edits:h.files},output:{kind:"insert-page-resource",package_instance_id:h.packageInstanceId,pages:h.pages},historyPolicy:"none"}):ee(f,h.code==="MATERIALIZATION_CONFLICT"?O.MATERIALIZATION_CONFLICT:O.MATERIALIZATION_REJECTED,h.message,h.path?{path:h.path}:void 0)}catch(y){return ee(f,O.INTERNAL_ERROR,Fe(y))}finally{m-=1}}async function ym(f){if(f.target.kind!=="project"||f.params.kind!=="delete-page-source")return ee(f,O.INVALID_PARAMS,"delete-page-source requires project target and matching params.");if(!n.listFiles)return ee(f,O.PLAN_FAILED,"Complete project file listing is required for page deletion.");m+=1;try{let y=Ep(await n.listFiles({maxFiles:5e4,maxDepth:64}));if(y.truncated)return ee(f,O.PLAN_FAILED,"Project file listing is incomplete; page deletion was refused.",{truncationReasons:y.truncated.reasons});let h=y.files.filter(({path:F})=>/\.(?:tsx?|jsx?)$/.test(F)),I=Object.fromEntries(await Promise.all(h.map(async({path:F})=>[F,await n.readFile(F)]))),R=zf({expectedUrlPath:f.params.expectedUrlPath,files:I});if(!R.ok)return ee(f,R.code==="HOME_PAGE_LOCKED"?O.HOME_PAGE_LOCKED:R.code==="ROUTE_NOT_FOUND"?O.ROUTE_NOT_FOUND:O.PLAN_FAILED,R.message);let A=await Promise.all(R.edits.map(async F=>({...F,baseContentHash:ue(await n.readFile(F.file))})));return fn({request:f,filePlan:{operationId:f.id,kind:"source-edit",target:f.target,documentVersion:f.documentVersion,conflictPolicy:"compare-and-swap",edits:A},output:{kind:"delete-page-source",deleted_files:R.deletedFiles,updated_files:R.updatedFiles,preserved_shared_files:R.preservedSharedFiles,warnings:R.warnings},historyPolicy:"none"})}catch(y){return ee(f,O.INTERNAL_ERROR,Fe(y))}finally{m-=1}}async function xm(f,y){if(f.kind!=="insert-child"||f.params.kind!=="insert-child")return ee(f,O.UNSUPPORTED_OPERATION,"Only page-unit insert-child is currently supported by the page composition transaction.");if(!("kind"in f.params.position)||f.params.position.kind!=="page-composition")return ee(f,O.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.");if(f.params.position.documentVersion!==f.documentVersion)return ee(f,O.VERSION_STALE,"Page-unit insert-child placement belongs to a different document version.");let h=y.document,I=y.pageCompositionProjection;if(!h||h.pageComposition?.status!=="supported"||!I||I.status!=="supported")return ee(f,O.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(f.documentVersion!==h.version||I.documentVersion!==h.version)return ee(f,O.VERSION_STALE,`Document version ${f.documentVersion} is stale (current: ${h.version}).`);let R=f.params.node.kind==="component-call"?f.params.node.materialization:void 0;if(!R)return ee(f,O.UNSUPPORTED_OPERATION,"Page-unit insertion currently requires a static materialization manifest.");let A=f.params.position,F=await wa({files:R.files.map(T=>({path:T.pathTemplate,content:T.content})),exists:T=>n.exists(T),readFile:T=>n.readFile(T)});if(!F.ok)return ee(f,O.MATERIALIZATION_REJECTED,F.message);let L=await Nf({manifest:R,generatedRoot:"components/site/generated",controlledFiles:R.files.map(T=>({pathTemplate:T.pathTemplate})),exists:T=>n.exists(T),commit:async T=>{let $=await n.readFile(y.entryFile),K=y.document,me=y.pageCompositionProjection;if(!K||K.pageComposition?.status!=="supported"||K.version!==f.documentVersion||!me||me.status!=="supported"||me.documentVersion!==K.version)return{ok:!0,data:ee(f,O.VERSION_STALE,"The route changed before the page-unit insertion could commit.")};let Q=T.entry.path,Ie=Nm(T.instanceName),Y=os({routeId:y.routeId,entryFile:y.entryFile,currentDocumentVersion:K.version,expectedDocumentVersion:f.documentVersion,source:$,projection:me,placementKey:A.placementKey,component:{source:Q,exportName:T.entry.export.kind==="default"?"default":T.entry.export.name,localName:Ie}});if(!Y.ok)return{ok:!0,data:ee(f,_c(Y.error.code),Y.error.message,{diagnostics:Y.error.diagnostics})};let ge=Y.plan.returnStep?_l({source:$,jsx:Y.plan.returnStep.node.jsx,placement:Y.plan.returnStep.placement,...Y.plan.returnStep.replaceOriginal?{replaceOriginal:!0}:{}}):Y.plan.insertStep?.parentLocator?Rn({source:$,locator:Y.plan.insertStep.parentLocator,node:Y.plan.insertStep.node,placement:Y.plan.insertStep.placement,...Y.plan.insertStep.anchorLocator?{anchorLocator:Y.plan.insertStep.anchorLocator}:{}}):{ok:!1,source:$,diagnostic:{code:"unsupported-syntax",message:"Route composition rewrite has no insertion step."}};if(!ge.ok)return{ok:!0,data:ee(f,O.AST_PARSE_ERROR,ge.diagnostic.message)};let _=Pn({source:ge.source,moduleSpecifier:Y.plan.importStep.moduleSpecifier,imports:Y.plan.importStep.imports});if(!_.ok)return{ok:!0,data:ee(f,O.AST_PARSE_ERROR,_.diagnostic.message)};let j=T.files.map(oe=>({operation:"create-only",file:oe.path,content:oe.content})),z=[{operation:"upsert",file:y.entryFile,content:_.source,baseContentHash:ue($)},...j];m+=1;try{let oe=await fn({request:f,filePlan:{operationId:f.id,kind:"source-edit",target:{kind:"source-file",path:y.entryFile},documentVersion:f.documentVersion,conflictPolicy:"compare-and-swap",edits:z}});return!oe.ok&&oe.error?.message.includes("MATERIALIZATION_INSTANCE_CONFLICT")?{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:oe.error?.message??"Static prefab instance conflicted during commit."}}:{ok:!0,data:oe}}finally{m-=1}}});return L.ok?L.data:ee(f,O.VERSION_STALE,L.error.message,{materializationCode:L.error.code})}async function Sm(f,y){if(f.kind!=="move-node"&&f.kind!=="remove-node")return ee(f,O.UNSUPPORTED_OPERATION,"Only page-unit move-node and remove-node are currently supported by the page composition transaction.");let h=y.document,I=y.pageCompositionProjection;if(!h||h.pageComposition?.status!=="supported"||!I||I.status!=="supported")return ee(f,O.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(f.documentVersion!==h.version||I.documentVersion!==h.version)return ee(f,O.VERSION_STALE,`Document version ${f.documentVersion} is stale (current: ${h.version}).`);let R=await n.readFile(y.entryFile),A=Fl({routeId:y.routeId,composition:y.composition,entryFile:y.entryFile,currentDocumentVersion:h.version,expectedDocumentVersion:f.documentVersion,source:R,projection:I,placementUnitKey:f.target.placementUnitKey,operation:f.kind,targetPlacement:f.kind==="move-node"&&f.params.kind==="move-node"&&"kind"in f.params.target&&f.params.target.kind==="page-composition"?f.params.target:void 0});if(!A.ok)return ee(f,_c(A.error.code),A.error.message,{diagnostics:A.error.diagnostics});let F=A.plan.rewriteStep.kind==="move-node"?Nn({source:R,locator:A.plan.rewriteStep.locator,targetParentLocator:A.plan.rewriteStep.targetParentLocator,placement:A.plan.rewriteStep.placement,...A.plan.rewriteStep.anchorLocator?{anchorLocator:A.plan.rewriteStep.anchorLocator}:{}}):kn({source:R,locator:A.plan.rewriteStep.locator});if(!F.ok)return ee(f,O.AST_PARSE_ERROR,F.diagnostic.message);let L=F.source,T=[];if(f.kind==="remove-node"){let K=await bm({routeState:y,placementUnitKey:f.target.placementUnitKey,source:R,mutatedSource:L});L=K.source,T=await Promise.all(K.files.map(async me=>({operation:"delete",file:me,baseContentHash:ue(await n.readFile(me))})))}let $=[{operation:"upsert",file:y.entryFile,content:L,baseContentHash:ue(R)},...T];m+=1;try{return await fn({request:f,filePlan:{operationId:f.id,kind:"source-edit",target:{kind:"source-file",path:y.entryFile},documentVersion:f.documentVersion,conflictPolicy:"compare-and-swap",edits:$}})}finally{m-=1}}async function bm(f){let y={source:f.mutatedSource,files:[]},h=f.routeState.graph,I=f.routeState.pageCompositionProjection;if(!h||!I||I.status!=="supported"||!n.listFiles)return y;let A=I.placementUnitByKey.get(f.placementUnitKey)?.sourceRange;if(!A)return y;let F=[...h.elements.values()].find(j=>j.sourceFile===f.routeState.entryFile&&j.importedFrom&&w(j.sourceRange,A));if(!F?.importedFrom||!F.exportName)return y;let L=v(F.importedFrom),T="components/site/generated/";if(!L.startsWith(T))return y;let $=L.slice(T.length).split("/")[0];if(!$||!/-[0-9a-f]{8}$/i.test($))return y;let K=`${T}${$}`;if([...h.elements.values()].filter(j=>j.sourceFile===f.routeState.entryFile&&v(j.importedFrom??"")===L).length!==1)return y;let Q=await n.listFiles({maxFiles:5e3,maxDepth:32}),Ie=Array.isArray(Q)?Q:Q.files;if(!Array.isArray(Q)&&Q.truncated)return y;let Y=Ie.map(({path:j})=>j).filter(j=>j===K||j.startsWith(`${K}/`));if(Y.length===0||!Y.includes(L))return y;for(let{path:j}of Ie)if(!(j===f.routeState.entryFile||j===K||j.startsWith(`${K}/`)))try{if((await n.readFile(j)).includes($))return y}catch{return y}let ge=P(f.routeState.entryFile,L),_=An({source:f.mutatedSource,moduleSpecifier:ge,imports:F.exportName==="default"?[{kind:"default"}]:[{kind:"named",imported:F.exportName}]});return _.ok?{source:_.source,files:Y.sort((j,z)=>j.localeCompare(z))}:y}async function Em(f){if(n.getFileInfo){for(let R of f)if(await n.exists(R.path)&&await n.getFileInfo(R.path)===null)return{ok:!1,errorCode:"invalid-params",message:`Source edit path must resolve to a regular non-symbolic-link file: ${R.path}`,details:{path:R.path}}}let y=Im(f);if(y.length===0)return{ok:!0};let h=Nv(n,f),I=Nr({projectRoot:e.projectRoot,fileSystem:h,compositions:[...i.values()].map(R=>({context:R.composition,entryFile:R.entryFile})),externalAdapters:e.externalAdapters,externalSourceResolvers:e.externalSourceResolvers,functionCallContracts:e.functionCallContracts,dev:e.dev});try{for(let R of y){let A=i.get(R)?.composition;if(!A)continue;let F={routeId:A.routeId,...A.effectiveTemplateId!==void 0?{templateId:A.effectiveTemplateId}:{}};await I.initializeComposition(F),I.getDocument(F)}}catch(R){return{ok:!1,errorCode:"ast-error",message:`Source edit preflight failed: ${Fe(R)}`,details:{compositionKeys:y}}}finally{I.dispose()}return{ok:!0}}function Im(f){return f.map(h=>h.path).some(xp)?[...i.keys()]:[]}function bi(f,y,h,I){let R=wr(y);return{composition:o.resolveSelector(f.composition).context,requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:H(f),error:{code:R,message:h,...I?{details:I}:{}}}}async function Ei(f){let y=[];for(let h of new Set(f))y.push(await vm(h));return y}async function vm(f){if(!(typeof n.exists=="function"?await n.exists(f):!0))return{file:f,content:"",version:Math.max(0,Z(f)),exists:!1};let h=await n.readFile(f);return{file:f,content:h,version:Math.max(1,Z(f)),exists:!0,sha256:ue(h)}}async function kc(f,y,h,I){if(!e.historyStore)return null;let R=new Map(y.map(L=>[L.file,L])),A=new Map(h.map(L=>[L.file,L])),F=[...new Set([...R.keys(),...A.keys()])].sort().map(L=>{let T=R.get(L),$=A.get(L);return{path:L,preDigest:T?.exists===!1||!T?null:ue(T.content),postDigest:$?.exists===!1||!$?null:ue($.content)}});return{schemaVersion:2,transactionId:`${f}:${I.expectedIndexDigest}`,operationId:f,phase:"prepared",historyTransition:I,files:F}}async function Cc(f){return!f||!e.historyStore||await e.historyStore.writeTransactionJournal(f),f}async function dn(f){f&&e.historyStore&&await e.historyStore.clearTransactionJournal(f.transactionId)}async function Ii(f,y){let h=[];try{for(let I of f)await Rc(I),typeof n.bumpVersion=="function"&&n.bumpVersion(I.file),h.push(I.file)}catch(I){let R=await km(y.filter(A=>h.includes(A.file)));return R.ok?{ok:!1,reason:`Writeback failed and committed files were restored: ${Fe(I)}`,rolledBack:!0}:{ok:!1,reason:`Writeback failed, then rollback failed for ${R.failedFiles.join(", ")}: ${Fe(I)}`,rolledBack:!1}}return{ok:!0,snapshots:f.map(Cm)}}async function Rc(f){if(f.exists===!1){await n.deleteFile(f.file);return}await n.writeFile(f.file,f.content)}async function km(f){let y=[];for(let h of f)try{await Rc(h),typeof n.bumpVersion=="function"&&n.bumpVersion(h.file)}catch{y.push(h.file)}return y.length===0?{ok:!0}:{ok:!1,failedFiles:y}}function Cm(f){let y=f.exists!==!1;return{file:f.file,content:y?f.content:"",version:f.version,exists:y,...y?{sha256:ue(f.content)}:{}}}async function fn(f){return S.runExclusive(()=>Rm(f))}async function Rm(f){let y=f.filePlan.edits.map(_=>_.file),h=o.resolveSelector(f.request.composition).context,I=f.historyPolicy==="none"?void 0:{initiatingComposition:h,affectedCompositions:um(y)},R=await Ei(y),A=new Map(R.filter(_=>_.exists!==!1).map(_=>[_.file,_.content])),F=Nc(),L=new Map(d),T=new Set(p),$=new Set([...i.values()].filter(_=>f.filePlan.edits.some(j=>j.operation==="delete"&&j.file===_.entryFile)).map(_=>_.key)),K=f.filePlan.edits.map(_=>_.operation==="delete"?{file:_.file,content:"",version:0,exists:!1}:{file:_.file,content:_.content,version:0,exists:!0,sha256:ue(_.content)}),me={operationId:f.filePlan.operationId,intents:f.filePlan.edits.map(_=>_.operation==="delete"?{kind:"delete",path:_.file}:{kind:_.operation==="create-only"?"create-only":"upsert",path:_.file,content:_.content})},Q=null,Ie=!1,Y=await Yo({overlay:A,exists:_=>n.exists(_),plan:me,buildCandidate:async({plan:_})=>({plan:_}),prepareHistory:async()=>{let _=f.historyPolicy==="none"?null:await l.prepareAppend({composition:o.resolveSelector(f.request.composition).context,operationId:f.request.id,kind:f.request.kind,target:f.request.target,preSnapshots:R,postSnapshots:K,...f.selectionRef?{selectionRef:f.selectionRef}:{},...f.output?{output:f.output}:{},...I?{provenance:I}:{}}),j=_?.historyTransition?_.historyTransition:e.historyStore?mv(await e.historyStore.readIndex()):null;if(e.historyStore&&!j)throw new Error("Durable history did not provide an exact index transition.");return Q=await kc(f.request.id,R,K,j),Q=await Cc(Q),{history:_,historyTransition:j}},reverify:async()=>{},writeCandidate:async()=>{let _=await u.executeFilePlan(f.filePlan);if(!_.ok)throw new ti(_);return{postSnapshots:await Ei(_.affectedFiles),affectedFiles:_.affectedFiles,internalResultVersion:_.resultVersion}},validateCandidate:async({candidate:_,receipt:j})=>{let z=await Br(j.affectedFiles,{changed:!0,minimumVersion:j.internalResultVersion,publish:!1,excludedCompositionKeys:$});if(z.failedRoutes.length>0)throw new an(z.failedRoutes);let oe=Pc(F,z.candidateRouteStates??[]),Se=Math.max(j.internalResultVersion,...z.rebuiltRoutes.map(Je=>Je.version));return{..._,rebuild:z,routeSnapshots:oe,resultVersion:Se,...gp(f.selectionRef,oe.map(Je=>Je.state.document))?{selectionRef:gp(f.selectionRef,oe.map(Je=>Je.state.document))}:{}}},publishCandidate:async({candidate:_,history:j,receipt:z})=>{j?.history&&(await l.publishPrepared(j.history),Ie=!0);let oe=_.resultVersion??z.internalResultVersion;return{composition:o.resolveSelector(f.request.composition).context,requestId:f.request.id,kind:f.request.kind,target:f.request.target,ok:!0,resultVersion:oe,affectedFiles:z.affectedFiles,...f.output?{output:f.output}:{},..._.selectionRef?{selectionRef:_.selectionRef}:{}}},swapCandidate:({candidate:_,receipt:j})=>{_.routeSnapshots&&jr(_.routeSnapshots),_.rebuild?.candidateSourceCache&&Bn(d,_.rebuild.candidateSourceCache),bc(j.postSnapshots)},finalizeCandidate:async()=>{await dn(Q);for(let _ of $)i.delete(_)},emitCommitted:({candidate:_,published:j})=>{Si(j,_.rebuild??{rebuiltRoutes:[],failedRoutes:[]})},rollbackCandidate:async({history:_,receipt:j})=>{if(Ie)throw new Error("history was published before transaction finalization failed");if(j){let z=await Ii(R,j.postSnapshots);if(!z.ok)throw new Error(z.reason)}jr(F),Bn(d,L),Ec(T),_?.history&&await l.discardPrepared?.(_.history),await dn(Q)}});if(Y.ok)return Y.published;if(Y.stage==="precheck"||Y.stage==="build")try{await dn(Q)}catch(_){let j=await $r(Fe(_));return ee(f.request,j,"Unable to clear an uncommitted transaction journal.")}if(Y.recoveryRequired){let _=await $r(Y.reason);return ee(f.request,_===O.RECOVERY_PERSIST_FAILED?_:O.ROLLBACK_FAILED,Y.reason)}let ge=Y.error;return ge instanceof ti?{...ee(f.request,wr(ge.result.errorCode),ge.result.reason),...ge.result.affectedFiles?{affectedFiles:ge.result.affectedFiles}:{}}:ge instanceof an?ee(f.request,O.ROUTE_REBUILD_FAILED,`Route rebuild failed and source was rolled back: ${Da(ge.failedRoutes)}`,{failedRoutes:ge.failedRoutes}):ee(f.request,Tc(Y.stage),Fe(ge))}async function wc(f){return S.runExclusive(async()=>{let y=f==="undo"?await l.prepareUndo():await l.prepareRedo();return y?wm(f,y):{composition:o.entries[0].context,requestId:f,kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:o.initialVersions.get(o.entries[0].key)??0,error:{code:O.INTERNAL_ERROR,message:f==="undo"?"Nothing to undo":"Nothing to redo"}}})}async function wm(f,y){let h=y.entry,I=f==="undo"?h.preSnapshots:h.postSnapshots,R=f==="undo"?h.postSnapshots:h.preSnapshots,A=I.map(z=>z.file),{context:F,key:L}=fm(h,A),T=await Ei(A),$=new Map(T.filter(z=>z.exists!==!1).map(z=>[z.file,z.content])),K=he(L),me=Nc(),Q=new Map(d),Ie=new Set(p),Y=null,ge=!1,_,j=await Yo({overlay:$,plan:{operationId:`${f}:${h.operationId}`,intents:I.map(z=>z.exists===!1?{kind:"delete",path:z.file}:{kind:"upsert",path:z.file,content:z.content})},buildCandidate:async()=>({}),prepareHistory:async()=>(Y=await kc(`${f}:${h.operationId}`,T,I,y.historyTransition),Y=await Cc(Y),y),reverify:async()=>{},writeCandidate:async()=>{let z=await Ii(I,R);if(!z.ok)throw new Error(z.reason);return{snapshots:z.snapshots}},validateCandidate:async({candidate:z})=>{_=dm(h,A);let oe=await Br(A,{changed:!0,minimumVersion:K+1,publish:!1,affectedCompositionKeys:_});if(oe.failedRoutes.length>0)throw new an(oe.failedRoutes);let Se=Pc(me,oe.candidateRouteStates??[]),Je=Math.max(K+1,...oe.rebuiltRoutes.map(pn=>pn.version));return{...z,rebuild:oe,routeSnapshots:Se,resultVersion:Je}},publishCandidate:async({candidate:z,history:oe})=>{if(!oe)throw new Error("history cursor intent is missing");await l.publishPrepared(oe),ge=!0;let Se=z.resultVersion??K+1;return{composition:F,requestId:f,kind:h.kind,target:h.target,ok:!0,resultVersion:Se,affectedFiles:A,...h.output?{output:h.output}:{}}},swapCandidate:({candidate:z,receipt:oe})=>{z.routeSnapshots&&jr(z.routeSnapshots),z.rebuild?.candidateSourceCache&&Bn(d,z.rebuild.candidateSourceCache),bc(oe.snapshots)},finalizeCandidate:async()=>{await dn(Y)},emitCommitted:({candidate:z,published:oe})=>Si(oe,z.rebuild??{rebuiltRoutes:[],failedRoutes:[]}),rollbackCandidate:async({history:z,receipt:oe})=>{if(ge)throw new Error("history cursor was published before transaction finalization failed");if(oe){let Se=await Ii(R,oe.snapshots);if(!Se.ok)throw new Error(Se.reason)}jr(me),Bn(d,Q),Ec(Ie),z&&await l.discardPrepared?.(z),await dn(Y)}});if(j.ok)return j.published;if(j.stage==="precheck"||j.stage==="build")try{await dn(Y)}catch(z){let oe=await $r(Fe(z));return{composition:F,requestId:f,kind:h.kind,target:h.target,ok:!1,resultVersion:K,error:{code:oe,message:"Unable to clear an uncommitted transaction journal."}}}if(j.recoveryRequired){let z=await $r(j.reason);return{composition:F,requestId:f,kind:h.kind,target:h.target,ok:!1,resultVersion:K,affectedFiles:A,error:{code:z===O.RECOVERY_PERSIST_FAILED?z:O.ROLLBACK_FAILED,message:j.reason}}}return{composition:F,requestId:f,kind:h.kind,target:h.target,ok:!1,resultVersion:K,affectedFiles:A,error:{code:j.error instanceof an?O.ROUTE_REBUILD_FAILED:Tc(j.stage),message:Fe(j.error),...j.error instanceof an?{details:{failedRoutes:j.error.failedRoutes}}:{}}}}function Nc(){return[...i.values()].map(f=>({composition:f.composition,key:f.key,routeId:f.routeId,state:{...f,dependencyFiles:new Set(f.dependencyFiles),fileVersions:new Map(f.fileVersions)}}))}function Pc(f,y){let h=new Map(f.map(I=>[I.key,I]));for(let I of y)h.set(I.key,I);return[...h.values()]}function jr(f){for(let y of i.values())N(y);for(let y of f){let h={...y.state,dependencyFiles:new Set(y.state.dependencyFiles),fileVersions:new Map(y.state.fileVersions)};i.set(y.key,h),ne(h,h.dependencyFiles)}}async function vi(f){let y=i.get(f);if(!y)throw new Error(`Composition not found: ${f}`);if(y.graph)return;let h=await n.readFile(y.entryFile);await q(f,h)}function Vn(f,y){let h=i.get(o.resolveSelector(y).key)??null;return!h||!Ac(h,f)?null:h}function Ac(f,y){if(f.documentIndex?.entriesByKey.has(y)||f.graph?.elements.has(y))return!0;let h=$e(y);return h&&h!==y?f.graph?.elements.has(h)===!0:!1}function ee(f,y,h,I){return{composition:o.resolveSelector(f.composition).context,requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:H(f),error:{code:y,message:h,...I?{details:I}:{}}}}function Tc(f){return f==="validate"?O.ROUTE_REBUILD_FAILED:f==="publish"?O.HISTORY_COMMIT_FAILED:O.WRITE_IO_ERROR}async function $r(f){if(g=!0,!l.markRecoveryRequired)return O.RECOVERY_REQUIRED;try{return await l.markRecoveryRequired(f),O.RECOVERY_REQUIRED}catch{return O.RECOVERY_PERSIST_FAILED}}function Nm(f){let h=f.split(/[^a-zA-Z0-9]+/).filter(Boolean).map(I=>I.charAt(0).toUpperCase()+I.slice(1)).join("").replace(/^[^a-zA-Z_$]+/,"");return h?`Prefab${h}`:"GeneratedPrefab"}function _c(f){return f==="VERSION_STALE"?O.VERSION_STALE:f==="CROSS_PAGE_MOVE_UNSUPPORTED"?O.CROSS_PAGE_MOVE_UNSUPPORTED:O.UNSUPPORTED_OPERATION}async function Fc(f){if(f.target.kind==="route"){let h=i.get(o.resolveSelector(f.target.composition).key)??null;return h?(h.graph||await vi(h.key),h):ee(f,O.ROUTE_NOT_FOUND,"Composition not found for route target.")}if(f.target.kind==="page-unit"){let h=i.get(o.resolveSelector(f.target.composition).key)??null;return h?(h.graph||await vi(h.key),h):ee(f,O.ROUTE_NOT_FOUND,"Composition not found for page-unit target.")}if(f.target.kind!=="node")return ee(f,O.UNSUPPORTED_OPERATION,`${f.kind} source target execution is not implemented yet.`);let y=i.get(o.resolveSelector(f.composition).key)??null;return y?(y.graph||await vi(y.key),Ac(y,f.target.key)?y:ee(f,O.NODE_NOT_FOUND,`Target key not found: ${f.target.key}`)):ee(f,O.ROUTE_NOT_FOUND,"Composition not found for node target.")}return{get status(){return t},dispose(){t="disposed",a.clear(),i.clear(),s.clear(),d.clear(),p.clear()},registerComposition(f,y){let h=o.register({context:f,entryFile:y}),I=i.get(h.key);if(I?.entryFile===y)return;I&&N(I);let R=mp(h.context,y);i.set(h.key,R),ne(R,R.dependencyFiles),r.emit({type:"graph-invalidated",composition:h.context})},unregisterComposition(f){let y=o.resolveSelector(f),h=i.get(y.key);h&&(N(h),i.delete(y.key),o.unregister(y.key),i.size===0&&(t="idle"),r.emit({type:"graph-invalidated",composition:y.context}))},getCompositionEntryFiles(){return[...i.values()].map(f=>f.entryFile)},getCompositionContext(f){return o.resolveSelector(f).context},async initializeComposition(f){let y=o.resolveSelector(f),h=i.get(y.key);if(!h)throw new Error(`Composition not registered: ${y.key}`);if(h.graph)t="ready";else{t="building";try{let I=await n.readFile(h.entryFile);await q(y.key,I),t="ready",r.emit({type:"graph-ready",composition:y.context,version:i.get(y.key)?.graph?.version??0})}catch(I){throw t="idle",r.emit({type:"graph-error",composition:y.context,message:Fe(I)}),I}}},getDocument(f){let y=o.resolveSelector(f),h=i.get(y.key);if(!h)throw new Error(`Composition not registered: ${y.key}`);if(!h.document)throw new Error(`Composition not built: ${y.key}`);return h.document},async getHistoryStatus(){await C;let f=await l.getStatus?.();return f?{...f,recoveryRequired:g}:{canUndo:!1,canRedo:!1,undoDepth:0,redoDepth:0,recoveryRequired:g}},getObjectEditContext(f,y){let h=Vn(f,y),I=$e(f)??f;if(h?.graph&&h.topology&&h.capabilities&&h.detailProjections){let R=h.detailProjections.get(I);if(R){let A=Wl(I,h.graph,h.topology,h.capabilities,R.textSources,R.provenances,R.dynamicData);return f===I?A:Hv(A,f,h.document??null,h.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${f}`)},getRenderDetail(f,y){let h=Vn(f,y),I=$e(f)??f;if(h?.graph&&h.topology&&h.capabilities&&h.detailProjections){let R=h.detailProjections.get(I);if(R){let A=zl(I,h.graph,h.topology,h.capabilities,R.textSources,R.writeTarget,R.provenances,R.conditional,R.componentSemantic,R.contentModel,R.mediaModel,R.styleSource,R.dynamicData);return f===I?A:Wv(A,f,h.document??null,h.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${f}`)},getClassNameSource(f,y){let h=Vn(f,y),I=$e(f)??f;if(!h?.graph)throw new Error(`Key not found: ${f}`);let R=h.graph.elements.get(I);if(!R)throw new Error(`Key not found: ${f}`);let A=d.get(R.sourceFile);if(A===void 0)throw new Error(`Source not loaded: ${R.sourceFile}`);return uu({key:I,route:{composition:h.composition,routeId:h.routeId,graph:h.graph,source:A}})},refreshSourceForKey:mm,async execute(f){if(await C,g)return ee(f,O.RECOVERY_REQUIRED,"The edit engine requires explicit recovery before accepting mutations.");if(f.kind==="source-edit")return gm(f);if(f.kind==="insert-page-resource")return hm(f);if(f.kind==="delete-page-source")return ym(f);let y=await Fc(f);if("ok"in y)return y;await vc(f);let h=await Fc(f);if("ok"in h)return h;let I=h;if(f.target.kind==="page-unit"){let L=f;return f.kind==="insert-child"?xm(L,I):f.kind==="move-node"||f.kind==="remove-node"?Sm(L,I):ee(f,O.UNSUPPORTED_OPERATION,"Only page-unit insert-child, move-node, and remove-node are currently supported by the page composition transaction.")}if(!I.graph||!I.topology||!I.capabilities)return{composition:o.resolveSelector(f.composition).context,requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:H(f),error:{code:f.target.kind==="route"?O.ROUTE_NOT_FOUND:O.NODE_NOT_FOUND,message:f.target.kind==="route"?"Composition not ready for route target.":f.target.kind==="node"?`Target key not found: ${f.target.key}`:`${f.kind} source target execution is not implemented yet.`}};let R=Mv(I,I.graph,I.capabilities,d,i),A=await new _o(R).plan(f);if(!A.ok)return{composition:o.resolveSelector(f.composition).context,requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:H(f),error:{code:wr(A.errorCode),message:A.reason}};let F=A.plan;if(F.steps.length===0)return f.kind==="set-props"?{composition:o.resolveSelector(f.composition).context,requestId:f.id,kind:f.kind,target:f.target,ok:!0,resultVersion:H(f),affectedFiles:[]}:{composition:o.resolveSelector(f.composition).context,requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:H(f),error:{code:O.PLAN_FAILED,message:"Planner could not generate a valid execution plan"}};m+=1;try{if(F.steps.some(T=>T.type==="invoke-external-adapter")){let T=await u.execute(F);if(!T.ok)return ee(f,wr(T.errorCode),T.reason);let $={composition:o.resolveSelector(f.composition).context,requestId:f.id,kind:f.kind,target:f.target,ok:!0,resultVersion:Math.max(H(f),T.resultVersion),affectedFiles:T.affectedFiles,...T.selectionRef?{selectionRef:T.selectionRef}:{}};return Si($,{rebuiltRoutes:[],failedRoutes:[]}),$}let L=await u.prepareRewritePlan(F);return L.ok?await fn({request:f,filePlan:L.filePlan,...L.selectionRef?{selectionRef:L.selectionRef}:{}}):ee(f,wr(L.errorCode),L.reason)}catch(L){return{composition:o.resolveSelector(f.composition).context,requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:H(f),error:{code:O.INTERNAL_ERROR,message:Fe(L)}}}finally{m-=1}},async undo(f){if(await C,g)return{composition:o.entries[0].context,requestId:"undo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:he(o.entries[0].key),error:{code:O.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting undo."}};m+=1;try{return await wc("undo")}finally{m-=1}},async redo(f){if(await C,g)return{composition:o.entries[0].context,requestId:"redo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:he(o.entries[0].key),error:{code:O.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting redo."}};m+=1;try{return await wc("redo")}finally{m-=1}},notifyFileChanged(f){xc([f])},getAffectedCompositions(f){return lm(f)},subscribe(f){return r.subscribe(f)}}}function Tv(e){return e instanceof Error&&"code"in e&&(e.code==="ENOENT"||e.code==="ENOTDIR")}function _v(e,t,n){let r=new Map,o=new Map;for(let s of t.elements.values()){if(s.sourceFile!==n.entryFile||!s.importedFrom||!/^[A-Z]/.test(s.tag))continue;let a=n.placements.find(l=>l.members.some(u=>u.sourceRange!==null&&La(s.sourceRange,u.sourceRange)));if(!a)continue;let c=a.placementUnitKey;if(r.set(`${s.importedFrom}#${s.tag}`,c),s.exportName==="default"){let l=o.get(s.importedFrom)??new Set;l.add(c),o.set(s.importedFrom,l)}s.exportName&&s.exportName!=="default"&&s.exportName!==s.tag&&r.set(`${s.importedFrom}#${s.exportName}`,c)}let i=n.placements.find(s=>s.placementKey===n.container.placementKey&&s.relation==="append");for(let s of e.entries){let a=$e(s.key)??s.key,c=t.elements.get(s.key)??t.elements.get(a);if(!c)continue;if(c.sourceFile===n.entryFile){if(n.container.sourceRange&&La(c.sourceRange,n.container.sourceRange)&&i){s.pageCompositionUnitKey=i.placementUnitKey;continue}let d=n.placements.find(p=>p.members.some(m=>m.sourceRange!==null&&(La(c.sourceRange,m.sourceRange)||Fv(m.sourceRange,c.sourceRange))));if(d){s.pageCompositionUnitKey=d.placementUnitKey;continue}}let l=r.get(`${c.sourceFile}#${c.componentName}`);if(l){s.pageCompositionUnitKey=l;continue}let u=o.get(c.sourceFile);u?.size===1&&(s.pageCompositionUnitKey=u.values().next().value)}}function La(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function Fv(e,t){return yp(e.startLine,e.startColumn,t.startLine,t.startColumn)<=0&&yp(e.endLine,e.endColumn,t.endLine,t.endColumn)>=0}function yp(e,t,n,r){return e!==n?e-n:t-r}function Mv(e,t,n,r,o){let i=new Map,s=new Map,a=(u,d)=>{if(s.has(u))return;s.set(u,d);let p=t.elements.get(u);for(let m of p?.childKeys??[])a(m,d)};for(let u of t.regions)if(u.kind==="repeat-region")for(let d of u.childKeys)i.set(d,u.ownerKey),a(d,u.ownerKey);return{getNode(u){let d=c(u),p=t.elements.get(d.baseKey);return p?l(u,p):null},getChildNodes(u){let d=c(u),m=e.documentIndex?.entriesByKey.get(u)?.childKeys;if(m)return m.map(S=>{let C=$e(S)??S,v=t.elements.get(C);return v?l(S,v):null}).filter(S=>S!==null);let g=t.elements.get(d.baseKey);return g?g.childKeys.map(S=>{let C=t.elements.get(S);return C?l(S,C):null}).filter(S=>S!==null):[]},getKnownSourceFiles(){return[...r.entries()].map(([u,d])=>({file:u,content:d}))},getRouteEntryFiles(){return[...o.values()].map(u=>u.entryFile)},getCapability(u){let d=c(u),p=n.get(d.baseKey);return p?{...p,key:u,constraints:p.constraints.map(m=>({...m})),...p.editModes?{editModes:{...p.editModes}}:{}}:{composition:e.composition,key:u,canUpdateText:!1,canRemove:!1,canInsertChild:!1,canMove:!1,constraints:[]}},getFileContent(u){return r.get(u)??""},getFileVersion(u){return Math.max(e.fileVersions.get(u)??0,t.version)},getRouteEntryFile(u){return e.routeId===u?e.entryFile:null},getComponentSemantic(u){let d=c(u);return e.detailProjections?.get(d.baseKey)?.componentSemantic??null},getEditableTextSegmentIndex(u){let d=c(u),m=e.detailProjections?.get(d.baseKey)?.textTargets.keys()?.next();return m&&!m.done?m.value:null},async getTextWriteTarget(u,d){let p=c(u);return bp(e.detailProjections?.get(p.baseKey)?.textTargets.get(d)??null,p.repeatIndex)},async getElementPropertyWriteTarget(u,d){let p=c(u);return bp(e.detailProjections?.get(p.baseKey)?.elementPropertyTargets.get(d)??null,p.repeatIndex)},getTextProvenance(u,d){let p=c(u);return e.detailProjections?.get(p.baseKey)?.provenances.get(d)??null}};function c(u){let d=lv(u);return d?{baseKey:d.baseKey,repeatIndex:Jv(e.document??null,u,d.baseKey,e.documentIndex)??Kv(d)}:{baseKey:u,repeatIndex:null}}function l(u,d){let p=$e(u)??u,m=e.documentIndex?.entriesByKey.get(u),g=e.detailProjections?.get(p);return{key:u,file:d.sourceFile,component:d.componentName,tag:d.tag,structuralPath:d.identity.structuralPath,sourceRange:d.sourceRange,parentKey:m?.parentKey??d.parentKey??void 0,isRepeatRegion:d.boundaryKind==="repeat-region"||s.has(p),isBoundary:!1,importedFrom:d.importedFrom,exportName:d.exportName,isRepeatItemRoot:i.has(p),repeatOwnerKey:i.get(p)??s.get(p),contentModel:g?.contentModel,attributes:d.attributes?.map(S=>({name:S.name,value:S.value,source:S.source?{expression:S.source.expression,base:S.source.base,path:S.source.path.map(C=>({...C}))}:null,resolvedValue:S.resolvedValue}))}}}var Ov={"stale-version":O.VERSION_STALE,"capability-denied":O.CAPABILITY_REJECTED,"invalid-params":O.INVALID_PARAMS,"locator-miss":O.LOCATOR_FAILED,"route-not-found":O.ROUTE_NOT_FOUND,"unsupported-operation":O.UNSUPPORTED_OPERATION,"invalid-target":O.INVALID_TARGET,"ast-error":O.AST_PARSE_ERROR,"writeback-failed":O.WRITE_IO_ERROR,"rollback-failed":O.RECOVERY_REQUIRED,unknown:O.INTERNAL_ERROR};function wr(e){return Ov[e]}function Fe(e){return e instanceof Error&&e.message?e.message:String(e)}function xp(e){return/\.(?:[cm]?[jt]sx?|css|scss|sass|mdx|json)$/i.test(e)}function Dv(e){let t=cn(e);if(!fv.test(t))return[];let n=t.startsWith("src/app/")?"src/app":"app",r=t.slice(0,t.lastIndexOf("/")),o=[],i=r;for(;(i===n||i.startsWith(`${n}/`))&&(o.unshift(i),i!==n);)i=i.slice(0,i.lastIndexOf("/"));return o.flatMap(s=>pv.map(a=>`${s}/${a}`))}function Lv(e){let n=cn(e).startsWith("src/app/")?"src/app":"app";return[`${n}/globals.css`,`${n}/global.css`]}function Bv(e){return Ip(e,/\bimport\s+(?:[^'";]+?\s+from\s+)?["']([^"']+\.css(?:\?[^"']*)?)["']/g)}function jv(e){return Ip(e,/@import\s+(?:url\(\s*)?["']([^"']+)["']/g)}function Ip(e,t){let n=[];for(let r of e.matchAll(t)){let o=vp(r[1]??"");o&&n.push(o)}return n}function Sp(e,t){let n=vp(t);return!n||n.startsWith("tailwindcss")||n.startsWith("http:")||n.startsWith("https:")?null:n.startsWith("@/")?cn(`src/${n.slice(2)}`):n.startsWith("./")||n.startsWith("../")?cn(`${$v(e)}/${n}`):n.startsWith("/")?cn(n.slice(1)):Ba(n)?cn(n):null}function vp(e){return e.split(/[?#]/,1)[0]?.trim()??""}function Ba(e){return/\.css$/i.test(e)}function $v(e){let t=cn(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function kp(e){return Array.from(new Set(e))}function cn(e){let t=e.replace(/\\/g,"/").replace(/^\.\//,""),n=[];for(let r of t.split("/"))if(!(!r||r===".")){if(r===".."){n.pop();continue}n.push(r)}return n.join("/")}function Vv(e){let t=1;for(let n of e?.textTargets.values()??[])n?.kind==="value-binding"&&n.sourceKind==="repeat-template"&&(t=Math.max(t,n.collectionIndexMap?.length??0,n.collectionPathMap?.length??0));return t}function ei(e){return e?.map(t=>({...t}))}function bp(e,t){if(t===null||e?.kind!=="value-binding"||e.sourceKind!=="repeat-template")return e;let n=e.collectionIndexMap?.[t]??t,r=ei(e.collectionPathMap?.[t])??ei(e.locator?.path);if(r)for(let o=r.length-1;o>=0;o-=1){let i=r[o];if(i.kind==="index"){i.index=n;break}}return{...e,path:ei(e.path),locator:e.locator?{...e.locator,path:r}:e.locator,collectionIndexMap:e.collectionIndexMap?[...e.collectionIndexMap]:void 0,collectionPathMap:e.collectionPathMap?.map(o=>ei(o)??[])}}function Uv(e,t,n){let r=new Set;for(let m of t.regions)if(m.kind==="repeat-region")for(let g of m.childKeys)r.add(g);if(r.size===0)return e;let o=new Map(e.entries.map(m=>[m.key,m])),i=[],s=new Map,a=(m,g)=>sv(m,g),c=(m,g,S)=>{let C=o.get(m);if(!C)return a(m,S);let v=a(m,S),P={...C,key:v,parentKey:g,childKeys:[]};return i.push(P),P.childKeys=C.childKeys.flatMap(w=>l(w,S,v)),v},l=(m,g,S)=>{if(!r.has(m))return[c(m,S,g)];let C=d(m,g),v=[];for(let P=0;P<C;P+=1)v.push(c(m,S,[...g,P]));return v},u=kp([...e.rootKeys,...e.entries.filter(m=>m.parentKey===null).map(m=>m.key)]);for(let m of u){if(!r.has(m)){c(m,null,[]);continue}let g=d(m,[]);for(let S=0;S<g;S+=1)c(m,null,[S])}return{...e,rootKeys:[...e.rootKeys],entries:i};function d(m,g){let S=new Set;for(let C of p(m)){let v=n.get(C);if(v){for(let P of[...v.textTargets.values(),...v.elementPropertyTargets.values()])if(!(P?.kind!=="value-binding"||P.sourceKind!=="repeat-template"))for(let w of Xv(P))w.length<=g.length||zv(w,g)&&S.add(w[g.length])}}return S.size>0?S.size:Vv(n.get(m))}function p(m){let g=s.get(m);if(g)return g;let S=[m],C=o.get(m);for(let v of C?.childKeys??[])S.push(...p(v));return s.set(m,S),S}}function Kv(e){let t=e.parts.at(-1);return typeof t?.repeatIndex=="number"?t.repeatIndex:null}function Jv(e,t,n,r){let o=r?.repeatOccurrenceIndexByKey.get(t);if(o!==void 0)return o;if(!e)return null;let i=0;for(let s of e.entries)if(($e(s.key)??s.key)===n){if(s.key===t)return i;i+=1}return null}function Xv(e){return e.collectionPathMap?.length?e.collectionPathMap.map(t=>t.filter(n=>n.kind==="index").map(n=>n.index)):e.collectionIndexMap?.length?e.collectionIndexMap.map(t=>[t]):[]}function zv(e,t){if(t.length>e.length)return!1;for(let n=0;n<t.length;n+=1)if(e[n]!==t[n])return!1;return!0}function Wv(e,t,n,r){if(!n)return{...e,key:t};let o=r??new Map(n.entries.map(u=>[u.key,u])),i=o.get(t);if(!i)return{...e,key:t};let s=[],a=i.parentKey;for(;a;){let u=o.get(a);if(!u)break;s.push({key:u.key,tag:u.tag,label:u.label}),a=u.parentKey}s.reverse();let c=i.childKeys.map(u=>o.get(u)).filter(u=>u!==void 0).map(u=>({key:u.key,tag:u.tag,label:u.label})),l=i.parentKey===null?[]:(o.get(i.parentKey)?.childKeys??[]).filter(u=>u!==i.key).map(u=>o.get(u)).filter(u=>u!==void 0).map(u=>({key:u.key,tag:u.tag,label:u.label}));return{...e,key:i.key,ancestors:s,children:c,siblings:l}}function Hv(e,t,n,r){if(!n)return{...e,key:t};let o=r??new Map(n.entries.map(c=>[c.key,c])),i=o.get(t);if(!i)return{...e,key:t};let s=[],a=i.parentKey;for(;a;){let c=o.get(a);if(!c)break;s.push({key:c.key,tag:c.tag,label:c.label}),a=c.parentKey}return s.reverse(),{...e,key:i.key,ancestors:s}}import Ka from"node:path";import{TextDecoder as Gv}from"node:util";import{SITE_EDIT_SOURCE_ALLOWED_APP_FILES as Rp,SITE_EDIT_SOURCE_ALLOWED_DIRS as wp,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as Np,SiteEditCompositionContextSchema as Yv,SiteEditSourceFileResponseSchema as ja,SiteEditSourceLocationSchema as Zv,SiteEditSourcePathSchema as ni,SiteEditSourceTreeResponseSchema as Qv,isSiteEditTextSourcePath as qv}from"@vcp-dev/contracts";var ek=[...Np,...Rp,...wp];function Ja(e){if(!e.composition)throw new Error("Composition unavailable for source access policy.");return Yv.parse(e.composition)}var $a=2e3,Va=12,Ua=24*1024*1024,Cp=512*1024,tk=new Set(["image/avif","image/gif","image/jpeg","image/png","image/webp","image/x-icon"]),nk={".avif":"image/avif",".bin":"application/octet-stream",".eot":"application/vnd.ms-fontobject",".gif":"image/gif",".glb":"model/gltf-binary",".ico":"image/x-icon",".jpeg":"image/jpeg",".jpg":"image/jpeg",".mp3":"audio/mpeg",".mp4":"video/mp4",".pdf":"application/pdf",".png":"image/png",".svg":"image/svg+xml",".ttf":"font/ttf",".wasm":"application/wasm",".webm":"video/webm",".webp":"image/webp",".woff":"font/woff",".woff2":"font/woff2",".zip":"application/zip"},rk={".cjs":"javascript",".css":"css",".cts":"typescript",".html":"html",".js":"javascript",".jsx":"javascript",".json":"json",".md":"markdown",".mdx":"markdown",".mjs":"javascript",".mts":"typescript",".ts":"typescript",".tsx":"typescript",".txt":"plaintext",".yaml":"yaml",".yml":"yaml"},ok=new Gv("utf-8",{fatal:!0});async function ri(e,t={}){let n=Ja(t),{files:r,truncated:o}=await fk(e,t),i=gk(r.map(s=>s.metadata));return Qv.parse({composition:n,nodes:i,defaultPath:hk(r.map(s=>s.metadata)),totalFiles:r.length,...o?{truncated:o}:{}})}async function oi(e,t,n={}){let r=Ja(n),o=ni.parse(t.path),i=await ak(e,o,n);if(!i)throw new Error(`Source file not found: ${o}`);if(Xa(o)){let a=Tp(o),c=await lk(e,{path:o,sizeBytes:i.sizeBytes,mimeType:a});return ja.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:i.sizeBytes,mimeType:a,readonly:!0,...c})}let s=await ik(e,o);return s.ok?ja.parse({composition:r,path:o,kind:"text",language:_p(o),sizeBytes:s.sizeBytes,contentHash:ue(s.content),readonly:!1,content:s.content}):ja.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:s.sizeBytes,mimeType:"application/octet-stream",readonly:!0,previewUnavailableReason:"unsupported-mime"})}async function ik(e,t){if(e.readFileBytes){let o=await e.readFileBytes(t),i=sk(o);return i===null?{ok:!1,sizeBytes:o.byteLength}:{ok:!0,content:i,sizeBytes:o.byteLength}}let n=await e.readFile(t),r=Buffer.byteLength(n,"utf8");return n.includes("\0")?{ok:!1,sizeBytes:r}:{ok:!0,content:n,sizeBytes:r}}function sk(e){if(e.includes(0))return null;try{return ok.decode(e)}catch{return null}}async function ak(e,t,n){if(!uk(t,n))return null;let r=await ck(e,t);return r?{path:t,sizeBytes:r.sizeBytes}:null}async function ck(e,t){if(e.getFileInfo)return e.getFileInfo(t);if(e.listFiles){let o=Pp(await e.listFiles({roots:[t],maxFiles:1,maxDepth:t.split("/").length})).files.find(i=>i.path===t);if(o)return o}if(!await e.exists(t))return null;if(e.readFileBytes){let r=await e.readFileBytes(t);return{path:t,sizeBytes:r.byteLength}}if(Xa(t))return{path:t,sizeBytes:0};let n=await e.readFile(t);return{path:t,sizeBytes:Buffer.byteLength(n,"utf8")}}async function lk(e,t){if(!tk.has(t.mimeType))return{previewUnavailableReason:"unsupported-mime"};if(t.sizeBytes>Cp)return{previewUnavailableReason:"too-large"};if(!e.readFileBytes)return{previewUnavailableReason:"bytes-unavailable"};let n=await e.readFileBytes(t.path);return n.byteLength>Cp?{previewUnavailableReason:"too-large"}:{contentBase64:Buffer.from(n).toString("base64")}}function uk(e,t){return Np.some(n=>n===e)||Rp.some(n=>n===e)||wp.some(n=>e===n||e.startsWith(`${n}/`))?!0:!e.startsWith("app/")&&!e.startsWith("src/app/")?!1:(t.routeEntryFiles??[]).some(n=>{let r=ni.safeParse(n);return r.success&&r.data===e})}function ii(e,t){if(!t.sourceLocator)throw new Error(`Source location not available for key: ${e.key}`);return Zv.parse({key:e.key,composition:t.composition,sourceFile:t.sourceLocator.sourceFile,componentName:t.sourceLocator.componentName,openingElementRange:{startLine:t.sourceLocator.openingElementRange.startLine,startColumn:t.sourceLocator.openingElementRange.startColumn,endLine:t.sourceLocator.openingElementRange.endLine,endColumn:t.sourceLocator.openingElementRange.endColumn},structuralPath:t.sourceLocator.structuralPath,textPreview:t.sourceLocator.textPreview})}function Pp(e){return Array.isArray(e)?{files:e}:e}function dk(e){return["max-files","max-depth","max-total-bytes"].filter(n=>e.includes(n))}async function fk(e,t){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let n=Pp(await e.listFiles({roots:pk(t),maxFiles:$a+1,maxDepth:Va,maxTotalBytes:Ua+1})),r=new Map,o=new Set(n.truncated?.reasons),i=0;for(let a of[...n.files].sort((c,l)=>c.path.localeCompare(l.path))){let c=ni.safeParse(a.path);if(!c.success)continue;let l=c.data;if(l.split("/").length>Va){o.add("max-depth");continue}if(r.size>=$a){o.add("max-files");break}if(i+a.sizeBytes>Ua){o.add("max-total-bytes");break}r.set(l,{path:l,sizeBytes:a.sizeBytes,metadata:mk(l,a.sizeBytes,Ja(t))}),i+=a.sizeBytes}return{files:[...r.values()].sort((a,c)=>a.path.localeCompare(c.path)),...o.size>0?{truncated:{reasons:dk([...o]),maxFiles:$a,maxDepth:Va,maxTotalBytes:Ua}}:{}}}function pk(e){let t=new Set(ek);for(let n of e.routeEntryFiles??[]){let r=ni.safeParse(n);r.success&&(r.data.startsWith("app/")||r.data.startsWith("src/app/"))&&t.add(r.data)}return[...t]}function mk(e,t,n){return Xa(e)?{composition:n,path:e,kind:"binary",language:null,sizeBytes:t,mimeType:Tp(e),readonly:!0}:{composition:n,path:e,kind:"text",language:_p(e),sizeBytes:t,readonly:!1}}function gk(e){let t=[];for(let n of e){let r=n.path.split("/"),o=t,i="";for(let[s,a]of r.entries()){i=i?`${i}/${a}`:a;let c=s===r.length-1,l=o.find(u=>u.name===a);if(l||(l=c?{kind:"file",name:a,path:i,file:n}:{kind:"directory",name:a,path:i,children:[]},o.push(l)),c){if(l.kind!=="file")throw new Error(`Source tree path collision: ${n.path}`);l.file=n}else{if(l.kind!=="directory")throw new Error(`Source tree path collision: ${n.path}`);o=l.children}}}return Ap(t)}function Ap(e){return e.map(t=>t.kind==="directory"?{...t,children:Ap(t.children)}:t).sort((t,n)=>t.kind!==n.kind?t.kind==="directory"?-1:1:t.name.localeCompare(n.name))}function hk(e){let t=e.find(r=>r.path.toLowerCase()==="design.md");if(t)return t.path;let n=e.find(r=>r.path==="app/page.tsx");return n?n.path:e.find(r=>r.kind==="text")?.path??e.at(0)?.path}function Xa(e){return!qv(e)}function Tp(e){let t=Ka.posix.extname(e).toLowerCase();return!t&&Ka.posix.basename(e).toLowerCase()==="favicon"?"image/x-icon":nk[t]??"application/octet-stream"}function _p(e){let t=Ka.posix.extname(e).toLowerCase();return rk[t]??"plaintext"}var si=class{constructor(t){this.options=t,this.fileSystem=new er(t.files),this.engine=this.createEngine(this.fileSystem)}get status(){return this.engine.status}initializeComposition(t){return this.engine.initializeComposition(t)}getDocument(t){return Ur(this.engine.getDocument(t),{siteId:this.options.siteId,snapshotId:this.options.snapshotId})}getInternalDocument(t){return this.engine.getDocument(t)}getStyleContext(t){return this.engine.getDocument(t).styleContext??null}getObjectEditContext(t,n){return Kr(this.engine.getObjectEditContext(t,n))}getClassNameSource(t,n){return this.engine.getClassNameSource(t,n)}getSourceTree(t){return ri(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}getSourceFile(t){return oi(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}resolveSourceLocation(t){return ii(t,this.engine.getRenderDetail(t.key,t.composition))}async planOperation(t){let n=xk.safeParse(t);if(!n.success)return{result:Vr(t,n.error.issues.map(i=>i.message))};let r=new er(this.options.files),o=this.createEngine(r,{emitEvents:!1});try{let i=await o.execute(n.data);if(!i.ok)return{result:{ok:!1,composition:i.composition,error:{code:i.error?.code??"INTERNAL_ERROR",message:i.error?.message??"Operation failed"},data:{requestId:i.requestId,kind:i.kind,target:i.target,resultVersion:i.resultVersion}}};let s={ok:!0,composition:i.composition,data:Ut(i)},a=r.getChangedFiles();if(a.length===0)return{result:s};let c=Sk.parse({siteId:t.siteId,baseSnapshotId:t.baseSnapshotId,operationId:t.id,reason:`site-edit:${t.kind}`,patches:a.map(l=>bk(l,t.kind==="source-edit")),changedCompositions:o.getAffectedCompositions(a.map(l=>l.path)),diagnostics:[]});return this.options.onEvent?.({type:"site-edit.operation.planned",siteId:t.siteId,operationId:t.id,baseSnapshotId:t.baseSnapshotId,changedFiles:c.patches.map(l=>l.path),composition:i.composition,at:new Date().toISOString()}),{result:s,patchPlan:c}}finally{o.dispose()}}dispose(){this.engine.dispose()}createEngine(t,n={}){let r=n.emitEvents??!0;return Nr({projectRoot:"/snapshot",fileSystem:t,compositions:this.options.compositions,onEvent:r&&this.options.onEvent?o=>{let i=Jr(o,{siteId:this.options.siteId,snapshotId:this.options.snapshotId});i&&this.options.onEvent?.(i)}:void 0,dev:this.options.dev,...this.options.historyStore?{historyStore:this.options.historyStore}:{},...this.options.tenantId?{tenantId:this.options.tenantId}:{},siteId:this.options.siteId,snapshotId:this.options.snapshotId,...this.options.initialDocumentVersions?{initialDocumentVersions:this.options.initialDocumentVersions}:{}})}};function bk(e,t){return e.after===void 0?{path:e.path,operation:"delete",...t||e.before===void 0?{}:{expectedHash:ue(e.before)}}:{path:e.path,operation:e.before===void 0?"create":"update",...t||e.before===void 0?{}:{expectedHash:ue(e.before)},fullContent:e.after}}function Ek(e){return new si(e)}import{SiteEditOperationRequestSchema as kk}from"@vcp-dev/contracts";import st from"node:fs/promises";import Me from"node:path";import{SITE_EDIT_SOURCE_ALLOWED_DIRS as Ik,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as vk}from"@vcp-dev/contracts";var ai=class{constructor(t){this.options=t,this.fileSystem=this.createFileSystem(),this.engine=Nr({...t,fileSystem:this.fileSystem})}get status(){return this.engine.status}registerComposition(t,n){this.engine.registerComposition(t,n)}unregisterComposition(t){this.engine.unregisterComposition(t)}getDocument(t){return this.engine.getDocument(t)}getAffectedCompositions(t){return this.engine.getAffectedCompositions(t)}getCompositionContext(t){return this.engine.getCompositionContext(t)}initializeComposition(t){return this.engine.initializeComposition(t)}getHistoryStatus(){return this.engine.getHistoryStatus()}getObjectEditContext(t,n){return this.engine.getObjectEditContext(t,n)}getRenderDetail(t,n){return this.engine.getRenderDetail(t,n)}getClassNameSource(t,n){return this.engine.getClassNameSource(t,n)}getSourceTree(t){return ri(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.engine.getCompositionEntryFiles()})}getSourceFile(t){return oi(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.engine.getCompositionEntryFiles()})}resolveSourceLocation(t){return ii(t,this.engine.getRenderDetail(t.key,t.composition))}refreshSourceForKey(t,n){return this.engine.refreshSourceForKey(t,n)}execute(t){return this.engine.execute(t)}undo(t){return this.engine.undo(t)}redo(t){return this.engine.redo(t)}notifyFileChanged(t){this.engine.notifyFileChanged(t)}subscribe(t){return this.engine.subscribe(t)}dispose(){this.engine.dispose()}createFileSystem(){if(this.options.fileSystem)return this.options.fileSystem;let t=new Map,{projectRoot:n}=this.options;return{async readFile(r){return st.readFile(Me.join(n,r),"utf8")},async readFileBytes(r){return st.readFile(Me.join(n,r))},async getFileInfo(r){let o=Me.join(n,...r.split("/"));try{let i=await st.lstat(o);return!i.isFile()||i.isSymbolicLink()?null:{path:r,sizeBytes:i.size}}catch{return null}},async writeFile(r,o){await Uo(Me.join(n,r),o)},async createExclusive(r,o){let i=Me.join(n,r);await st.mkdir(Me.dirname(i),{recursive:!0});let s=await st.open(i,"wx");try{await s.writeFile(o,"utf8")}catch(a){throw await s.close(),await st.rm(i,{force:!0}),a}await s.close()},async deleteFile(r){await st.rm(Me.join(n,r),{force:!0});let o=r.replace(/\\/g,"/"),i=["components/site/generated","src/components/site/generated"].find(c=>o.startsWith(`${c}/`));if(!i)return;let s=Me.join(n,i),a=Me.dirname(Me.join(n,o));for(;a!==s&&a.startsWith(`${s}${Me.sep}`);){try{await st.rmdir(a)}catch(c){if(c instanceof Error&&"code"in c&&c.code==="ENOENT"){a=Me.dirname(a);continue}break}a=Me.dirname(a)}},async exists(r){try{return await st.access(Me.join(n,r)),!0}catch{return!1}},async listFiles(r={}){let o=r.roots??[...vk,...Ik],i=[],s=new Set,a=new Set,c=0;for(let d of o)await u(d,i,1);let l=i.sort((d,p)=>d.path.localeCompare(p.path));return a.size>0?{files:l,truncated:{reasons:[...a]}}:{files:l};async function u(d,p,m){if(r.maxDepth!==void 0&&m>r.maxDepth){a.add("max-depth");return}let g=Me.join(n,...d.split("/")),S;try{S=await st.lstat(g)}catch{return}if(S.isSymbolicLink())return;if(S.isFile()){let v=S.ino>0?`${String(S.dev)}:${String(S.ino)}`:null;if(v&&s.has(v))return;if(r.maxFiles!==void 0&&p.length>=r.maxFiles){a.add("max-files");return}if(r.maxTotalBytes!==void 0&&c+S.size>r.maxTotalBytes){a.add("max-total-bytes");return}v&&s.add(v),p.push({path:d,sizeBytes:S.size}),c+=S.size;return}if(!S.isDirectory())return;if(r.maxFiles!==void 0&&p.length>=r.maxFiles){a.add("max-files");return}let C=await st.readdir(g,{withFileTypes:!0});for(let v of C)v.isSymbolicLink()||await u(`${d}/${v.name}`,p,m+1)}},getVersion(r){return t.get(r)??1},bumpVersion(r){let o=(t.get(r)??1)+1;return t.set(r,o),o}}}};function za(e){return new ai(e)}var ci=class{constructor(t){this.options=t,this.listeners=new Set,this.engine=za({projectRoot:t.projectRoot,fileSystem:t.fileSystem,compositions:t.compositions,onEvent:n=>{let r=Jr(n,{siteId:t.siteId,snapshotId:t.snapshotId});if(r){t.onEvent?.(r);for(let o of this.listeners)o(r)}},dev:t.dev,...t.historyStore?{historyStore:t.historyStore}:{},...t.tenantId?{tenantId:t.tenantId}:{},...t.initialDocumentVersions!==void 0?{initialDocumentVersions:t.initialDocumentVersions}:{},siteId:t.siteId,snapshotId:t.snapshotId})}get status(){return this.engine.status}initializeComposition(t){return this.engine.initializeComposition(t)}registerComposition(t,n){this.engine.registerComposition(t,n)}unregisterComposition(t){this.engine.unregisterComposition(t)}getDocument(t){return{ok:!0,composition:this.engine.getCompositionContext(t),data:Ur(this.engine.getDocument(t),{siteId:this.options.siteId,snapshotId:this.options.snapshotId})}}getInternalDocument(t){return this.engine.getDocument(t)}getStyleContext(t){return{ok:!0,composition:this.engine.getCompositionContext(t),data:this.engine.getDocument(t).styleContext??null}}async getHistoryStatus(){return{ok:!0,composition:this.options.compositions[0].context,data:await this.engine.getHistoryStatus()}}getObjectEditContext(t,n){return{ok:!0,composition:this.engine.getCompositionContext(n),data:Kr(this.engine.getObjectEditContext(t,n))}}getClassNameSource(t,n){return{ok:!0,composition:this.engine.getCompositionContext(n),data:this.engine.getClassNameSource(t,n)}}async getSourceTree(t){return{ok:!0,composition:this.engine.getCompositionContext(t),data:await this.engine.getSourceTree(t)}}async getSourceFile(t){return{ok:!0,composition:this.engine.getCompositionContext(t.composition),data:await this.engine.getSourceFile(t)}}resolveSourceLocation(t){return{ok:!0,composition:this.engine.getCompositionContext(t.composition),data:this.engine.resolveSourceLocation(t)}}refreshSourceForKey(t,n){return this.engine.refreshSourceForKey(t,n)}async executeOperation(t,n){let r=n===void 0||t.mutationContext!==void 0?t:{...t,mutationContext:n},o=kk.safeParse(r);if(!o.success)return Vr(t,o.error.issues.map(s=>s.message));let i=await this.engine.execute(o.data);if(!i.ok){let s=i.error;if(!s)throw new Error("executeOperation failed without an error payload");return{ok:!1,composition:i.composition,error:{code:s.code,message:s.message},data:{requestId:i.requestId,kind:i.kind,composition:i.composition,target:i.target,resultVersion:i.resultVersion,...i.affectedFiles?.length?{affectedFiles:i.affectedFiles}:{}}}}return{ok:!0,composition:i.composition,data:Ut(i)}}async undo(t){let n=await this.engine.undo();if(!n.ok){let r=n.error;if(!r)throw new Error("undo failed without an error payload");return{ok:!1,composition:n.composition,error:{code:r.code,message:r.message},data:{requestId:n.requestId,kind:n.kind,composition:n.composition,target:n.target,resultVersion:n.resultVersion}}}return{ok:!0,composition:n.composition,data:Ut(n)}}async redo(t){let n=await this.engine.redo();if(!n.ok){let r=n.error;if(!r)throw new Error("redo failed without an error payload");return{ok:!1,composition:n.composition,error:{code:r.code,message:r.message},data:{requestId:n.requestId,kind:n.kind,composition:n.composition,target:n.target,resultVersion:n.resultVersion}}}return{ok:!0,composition:n.composition,data:Ut(n)}}notifyFileChanged(t){this.engine.notifyFileChanged(t)}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}dispose(){this.listeners.clear(),this.engine.dispose()}};function Ck(e){return new ci(e)}import{createHash as Rk,randomUUID as oc}from"node:crypto";import ye from"node:fs/promises";import be from"node:path";var Ye=1,Ha=1,wk=2,Nk="index.json",Pk="recovery.json",Ak="transaction-journal.json",Tk="document-version.json",ui={maxEntries:100,maxSessionBytes:512*1024*1024,maxEntryBytes:128*1024*1024},J={INVALID_ROOT:"INVALID_ROOT",INVALID_PATH:"INVALID_PATH",INVALID_SCHEMA:"INVALID_SCHEMA",INVALID_JSON:"INVALID_JSON",INDEX_CORRUPT:"INDEX_CORRUPT",ENTRY_CORRUPT:"ENTRY_CORRUPT",BLOB_CORRUPT:"BLOB_CORRUPT",RECOVERY_PENDING:"RECOVERY_PENDING",CAPACITY_EXCEEDED:"CAPACITY_EXCEEDED",NOT_FOUND:"NOT_FOUND"},W=class extends Error{constructor(t,n,r){super(n),this.name="FileHistoryStoreError",this.code=t,r?.cause!==void 0&&(this.cause=r.cause)}};async function Up(e,t={}){let n=Xk(e),r=Hk(t.limits),o=Wa(n),i=zk(n),s=await Le(i),a=await Le(o)||s;a||(await Lk(n),await Bk(n)),a||await Gk(n);let c=await Ve(n),l=new Set(a?(await gi(n)).map(d=>d.stageId):[]);a||await Pr(n,c.entryIds);let u=async()=>{if(await Le(o)||s)throw new W(J.RECOVERY_PENDING,"history store requires explicit recovery before accepting writes")};return{rootDir:n,recoveryRequired:a,async readDocumentVersion(){return $p(n)},async writeDocumentVersion(d){if(await u(),!Number.isInteger(d)||d<0)throw new W(J.INVALID_SCHEMA,"document version must be a non-negative integer");let p=await $p(n);await Ar(Gp(n),{schemaVersion:1,version:Math.max(p,d)})},async stageAppend(d,p={}){await u();let m=await Mp(d,r),g={schemaVersion:Ha,stageId:oc(),entryId:m.entryId,blobIds:m.blobs.map(S=>S.digest)};try{await Op(n,m),await Mk(n,g,p.durableManifest!==!1)}catch(S){try{await Lp(n,g)}catch(C){throw new W(J.INDEX_CORRUPT,"staged history cleanup failed after preparation error",{cause:C})}throw S}return{stageId:g.stageId,entryId:g.entryId,blobIds:g.blobIds}},async discardStage(d){await u(),Qa(d);let p=await Ya(n,d);p&&await Lp(n,p)},async previewStagedAppend(d,p){return await u(),(await Fp(n,r,d,p)).transition},async previewCursor(d,p){await u();let m=await Ve(n);return qa(m,p),Ga(d,m.entryIds.length),Kp(m,m.entryIds,d)},async publishStagedAppend(d,p,m){if(await u(),di(d,"entryId"),m){Qa(m);let S=await Ya(n,m);if(!S||S.entryId!==d)throw new W(J.INVALID_SCHEMA,"history stage does not match the published entry")}let g=await Fp(n,r,d,p);return jp({rootDir:n,previousDigest:g.current.digest,entryIds:g.entryIds,cursor:g.cursor,afterWrite:async()=>{m?await fi(n,m):await Dk(n,d),await Pr(n,g.entryIds)}})},async append(d){await u();let p=await Ve(n),m=await Mp(d,r),g=[...p.entryIds];p.cursor<g.length-1&&g.splice(p.cursor+1),g.push(m.entryId);try{await Op(n,m);let S=await Jp(n,g,r);return await sc(n,S.entryIds,S.cursor),await Pr(n,S.entryIds),Ve(n)}catch(S){throw await Pr(n,p.entryIds),S}},async readEntry(d){return di(d,"entryId"),_r(n,d)},async readBlob(d){di(d,"blobId");let p=await mc(n,d),m=await jt(p,J.NOT_FOUND,"blob");return ac(m,d,p),m},async readIndex(){return Ve(n)},async readStatus(){let d=await Ve(n);return{canUndo:d.undoIds.length>0,canRedo:d.redoIds.length>0,undoDepth:d.undoIds.length,redoDepth:d.redoIds.length,cursor:d.cursor,recoveryRequired:await Le(o)||await Le(i)}},async readUndoRedoIds(){let d=await Ve(n);return{undoIds:d.undoIds,redoIds:d.redoIds,currentId:d.currentId}},async setCursor(d,p){await u();let m=await Ve(n);return qa(m,p),Ga(d,m.entryIds.length),jp({rootDir:n,previousDigest:m.digest,entryIds:m.entryIds,cursor:d})},async markRecoveryRequired(d){await Le(o)||await Ar(Wa(n),{schemaVersion:Ye,reason:Wk(d),createdAt:new Date().toISOString()})},async clearRecoveryRequired(){await ye.rm(Wa(n),{force:!0})},async readTransactionJournal(){return await Le(i)?li(i):null},async writeTransactionJournal(d){await u(),Yp(d);try{await Ar(i,d)}catch(m){let g=await li(i).catch(()=>null);if(g&&Buffer.from(Ue(g)).equals(Buffer.from(Ue(d))))return;throw g?new W(J.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous",{cause:m}):m}let p=await li(i);if(!Buffer.from(Ue(p)).equals(Buffer.from(Ue(d))))throw new W(J.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous")},async clearTransactionJournal(d){let p=await Le(i)?await li(i):null;if(p&&p.transactionId!==d)throw new W(J.INVALID_SCHEMA,"transaction journal changed concurrently");try{await ye.rm(i,{force:!0})}catch(m){if(!await Le(i))return;throw m}if(await Le(i))throw new W(J.INDEX_CORRUPT,"transaction journal clear outcome is ambiguous");s=!1},async cleanupTmp(){await u();for(let p of l)await fi(n,p),l.delete(p);await jk(n);let d=await Ve(n);await Pr(n,d.entryIds)}}}async function Fp(e,t,n,r){di(n,"entryId");let o=await Ve(e);qa(o,r);let i=await _r(e,n),s=[...o.entryIds];o.cursor<s.length-1&&s.splice(o.cursor+1),s.push(i.id);let a=await Jp(e,s,t);return{current:o,entryIds:a.entryIds,cursor:a.cursor,transition:Kp(o,a.entryIds,a.cursor)}}function Kp(e,t,n){return Ga(n,t.length),{expectedIndexDigest:e.digest,publishedIndexDigest:_k(t,n),publishedCursor:n,publishedCurrentId:t[n]??null}}function _k(e,t){return $t(Ue({schemaVersion:Ye,entryIds:e,cursor:t}))}function Ga(e,t){if(!Number.isInteger(e)||e<-1||e>=t)throw new W(J.INVALID_SCHEMA,`history cursor is out of bounds: ${e}`)}function Fk(e){if(!at(e))return!1;let t=e.publishedCursor,n=e.publishedCurrentId;return!Ke(e.expectedIndexDigest)||!Ke(e.publishedIndexDigest)||!Number.isInteger(t)||t<-1||n!==null&&!Ke(n)?!1:t===-1?n===null:Ke(n)}async function Mp(e,t){if(!e.kind.trim())throw new W(J.INVALID_JSON,"history entry kind must not be empty");let n=[],r=[];for(let c of e.blobs??[]){if(!c.name.trim())throw new W(J.INVALID_JSON,"history blob name must not be empty");let l=Jk(c.data),u=$t(l);n.push({name:c.name,bytes:l,digest:u,sizeBytes:l.byteLength}),r.push({name:c.name,digest:u,sizeBytes:l.byteLength})}let o={schemaVersion:Ye,kind:e.kind,manifest:e.manifest,blobs:r},i=Ue({...o}),s=$t(i),a=i.byteLength+n.reduce((c,l)=>c+l.sizeBytes,0);if(a>t.maxEntryBytes)throw new W(J.CAPACITY_EXCEEDED,`history entry exceeds maxEntryBytes (${a} > ${t.maxEntryBytes})`);return{entryBody:o,entryId:s,blobs:n}}async function Op(e,t){let n=uc(e,t.entryId),r={id:t.entryId,...t.entryBody},o=[...t.blobs.map(a=>Dp(dc(e,a.digest),a.bytes,{kind:"blob",digest:a.digest},pc(e,a.digest))),Dp(n,Ue(r),{kind:"entry",digest:t.entryId},fc(e,t.entryId))],s=(await Promise.allSettled(o)).find(a=>a.status==="rejected");if(s)throw s.reason}async function Dp(e,t,n,r){let o=await nc(e)??(r?await nc(r):null);if(o!==null){if(Buffer.compare(o,t)!==0)throw new W(n.kind==="blob"?J.BLOB_CORRUPT:J.ENTRY_CORRUPT,`${n.kind} content mismatch for ${n.digest}`);return}await Wp(e,t)}async function Jp(e,t,n){let r=[...t],o=r.length-1;for(;;){if((await zp(e,r)).totalBytes<=n.maxSessionBytes&&r.length<=n.maxEntries)return{entryIds:r,cursor:o};if(o<=0||r.length===0)throw new W(J.CAPACITY_EXCEEDED,"history store exceeds capacity limits and the current entry cannot be trimmed");r.shift(),o-=1}}async function Mk(e,t,n){ic(t);let r=lc(e,t.stageId);if(n){await Ar(r,t);return}await Kk(r,t)}async function Ya(e,t){let n=await nc(lc(e,t));if(n===null)return null;let r=Fr(Buffer.from(n).toString("utf8"),`history stage ${t}`),o=ic(r);if(o.stageId!==t)throw new W(J.INVALID_SCHEMA,`history stage id mismatch: ${t}`);return o}async function gi(e){let t=[];for(let n of await mi(cc(e))){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);Qa(r);let o=await Ya(e,r);o&&t.push(o)}return t}async function Lp(e,t){ic(t);let n=await Ve(e),r=(await gi(e)).filter(s=>s.stageId!==t.stageId),o=new Set(n.entryIds),i=new Set;for(let s of n.entryIds){let a=await _r(e,s);for(let c of a.blobs)i.add(c.digest)}for(let s of r){o.add(s.entryId);for(let a of s.blobIds)i.add(a)}o.has(t.entryId)||await Bp(uc(e,t.entryId),fc(e,t.entryId));for(let s of t.blobIds)i.has(s)||await Bp(dc(e,s),pc(e,s));await fi(e,t.stageId),await rc(Mr(e)),await rc(Or(e))}async function fi(e,t){await Za(lc(e,t)),await Ok(e)}async function Ok(e){try{await ye.rmdir(cc(e))}catch(t){if(Dr(t)||at(t)&&t.code==="ENOTEMPTY")return;throw t}}async function Dk(e,t){for(let n of await gi(e))n.entryId===t&&await fi(e,n.stageId)}async function Za(e){if(await ye.rm(e,{force:!0}),await Le(e))throw new W(J.INDEX_CORRUPT,`unable to remove staged history object: ${e}`)}async function Bp(e,t){await Za(e),await Za(t)}function ic(e){if(!at(e)||e.schemaVersion!==Ha||typeof e.stageId!="string"||!Xp(e.stageId)||!Ke(e.entryId))throw new W(J.INVALID_SCHEMA,"history stage schema is invalid");let t=Hp(e.blobIds,"history stage blobIds");return{schemaVersion:Ha,stageId:e.stageId,entryId:e.entryId,blobIds:t}}function Qa(e){if(!Xp(e))throw new W(J.INVALID_PATH,"history stageId must be a UUID")}function Xp(e){return typeof e=="string"&&/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/iu.test(e)}async function Pr(e,t){let n=new Set(t),r=new Set;for(let c of t){let l=await _r(e,c);for(let u of l.blobs)r.add(u.digest)}for(let c of await gi(e)){n.add(c.entryId);for(let l of c.blobIds)r.add(l)}let o=Mr(e),i=await mi(o);for(let c of i){if(!c.endsWith(".json"))continue;let l=Vp(c.slice(0,-5));l&&!n.has(l)&&await pi(be.join(o,c))}let s=Or(e),a=await mi(s);for(let c of a){let l=Vp(c);l&&!r.has(l)&&await pi(be.join(s,c))}}async function Ve(e){let t=hi(e),n=await jt(t,J.NOT_FOUND,"index"),r=Fr(Buffer.from(n).toString("utf8"),"index"),o=$k(r),i=[...o.entryIds],{totalBytes:s}=await zp(e,i),a=i.slice(0,o.cursor+1).reverse(),c=i.slice(o.cursor+1);return{schemaVersion:Ye,digest:o.digest,entryIds:i,cursor:o.cursor,currentId:i[o.cursor]??null,undoIds:a,redoIds:c,totalBytes:s}}async function zp(e,t){let n=0,r=new Set,o=hi(e),i=await jt(o,J.NOT_FOUND,"index");n+=i.byteLength;for(let s of t){let a=await _r(e,s),c=await Zp(e,s),l=await jt(c,J.NOT_FOUND,"entry");n+=l.byteLength;for(let u of a.blobs){if(r.has(u.digest))continue;r.add(u.digest);let d=await mc(e,u.digest),p=await jt(d,J.NOT_FOUND,"blob");ac(p,u.digest,d),n+=p.byteLength}}return{totalBytes:n}}async function _r(e,t){let n=await Zp(e,t),r=await jt(n,J.NOT_FOUND,"entry"),o=Fr(Buffer.from(r).toString("utf8"),`entry ${t}`),i=Vk(o);if(i.id!==t)throw new W(J.ENTRY_CORRUPT,`entry id mismatch for ${t}`);if($t(Ue({schemaVersion:i.schemaVersion,kind:i.kind,manifest:i.manifest,blobs:i.blobs}))!==t)throw new W(J.ENTRY_CORRUPT,`entry hash mismatch for ${t}`);for(let a of i.blobs){let c=await mc(e,a.digest),l=await jt(c,J.NOT_FOUND,"blob");ac(l,a.digest,c)}return i}async function sc(e,t,n){let r={schemaVersion:Ye,digest:$t(Ue({schemaVersion:Ye,entryIds:t,cursor:n})),entryIds:t,cursor:n};await Ar(hi(e),r)}function qa(e,t){if(t!==void 0&&e.digest!==t)throw new W(J.INVALID_SCHEMA,`history index changed concurrently (expected ${t}, current ${e.digest})`)}async function jp(e){let t=$t(Ue({schemaVersion:Ye,entryIds:e.entryIds,cursor:e.cursor}));try{return await sc(e.rootDir,e.entryIds,e.cursor),await e.afterWrite?.(),await Ve(e.rootDir)}catch(n){let r=await Ve(e.rootDir).catch(()=>null);if(r?.digest===t)return r;throw r?.digest===e.previousDigest?n:new W(J.INDEX_CORRUPT,"history index publish outcome is ambiguous",{cause:n})}}async function Lk(e){await ye.mkdir(e,{recursive:!0}),await ye.mkdir(Mr(e),{recursive:!0}),await ye.mkdir(Or(e),{recursive:!0}),await ye.mkdir(Tr(e),{recursive:!0})}async function Bk(e){await ye.rm(Tr(e),{recursive:!0,force:!0}),await ye.mkdir(Tr(e),{recursive:!0})}async function jk(e){let t=Tr(e);await ye.mkdir(t,{recursive:!0});for(let n of await mi(t))n!=="stages"&&await ye.rm(be.join(t,n),{recursive:!0,force:!0})}function $k(e){if(!at(e))throw new W(J.INDEX_CORRUPT,"index.json must be an object");if(e.schemaVersion!==Ye)throw new W(J.INVALID_SCHEMA,`unsupported index schemaVersion: ${String(e.schemaVersion)}`);let t=Hp(e.entryIds,"index.entryIds"),n=e.cursor;if(!Number.isInteger(n)||n<-1||n>=t.length)throw new W(J.INDEX_CORRUPT,"index cursor is out of bounds");let r=n,o=e.digest;if(!Ke(o))throw new W(J.INDEX_CORRUPT,"index digest is invalid");let i=$t(Ue({schemaVersion:Ye,entryIds:t,cursor:r}));if(o!==i)throw new W(J.INDEX_CORRUPT,"index digest mismatch");return{schemaVersion:Ye,digest:o,entryIds:t,cursor:r}}function Vk(e){if(!at(e))throw new W(J.ENTRY_CORRUPT,"entry must be an object");if(e.schemaVersion!==Ye)throw new W(J.INVALID_SCHEMA,`unsupported entry schemaVersion: ${String(e.schemaVersion)}`);let t=e.id;if(!Ke(t))throw new W(J.ENTRY_CORRUPT,"entry id is invalid");let n=e.kind;if(typeof n!="string"||n.trim().length===0)throw new W(J.ENTRY_CORRUPT,"entry kind is invalid");let r=tc(e.manifest,"entry.manifest"),o=Uk(e.blobs);return{id:t,schemaVersion:Ye,kind:n,manifest:r,blobs:o}}function Uk(e){if(!Array.isArray(e))throw new W(J.ENTRY_CORRUPT,"entry blobs must be an array");return e.map((t,n)=>{if(!at(t))throw new W(J.ENTRY_CORRUPT,`entry blob ref ${n} must be an object`);let r=t.name;if(typeof r!="string"||r.trim().length===0)throw new W(J.ENTRY_CORRUPT,`entry blob ref ${n} name is invalid`);let o=t.digest;if(!Ke(o))throw new W(J.ENTRY_CORRUPT,`entry blob ref ${n} digest is invalid`);let i=t.sizeBytes;if(!Number.isInteger(i)||i<0)throw new W(J.ENTRY_CORRUPT,`entry blob ref ${n} sizeBytes is invalid`);return{name:r,digest:o,sizeBytes:i}})}async function Ar(e,t){await Wp(e,Ue(t))}async function Kk(e,t){let n=be.dirname(e),r=be.basename(e),o=be.join(n,`.${r}.${process.pid}.${oc()}.tmp`);await ye.mkdir(n,{recursive:!0});try{await ye.writeFile(o,Ue(t),{flag:"wx"}),await ye.rename(o,e)}finally{await pi(o)}}async function Wp(e,t){let n=be.dirname(e),r=be.basename(e),o=be.join(n,`.${r}.${process.pid}.${oc()}.tmp`);await ye.mkdir(n,{recursive:!0});try{let i=await ye.open(o,"wx");try{await i.writeFile(t),await i.sync()}finally{await i.close()}await ye.rename(o,e),await rc(n)}finally{await pi(o)}}function Ue(e){return Buffer.from(JSON.stringify(ec(e)),"utf8")}function ec(e){if(Array.isArray(e))return e.map(t=>ec(t));if(at(e)){let t={};for(let n of Object.keys(e).sort())t[n]=ec(e[n]);return t}return e}function Fr(e,t){try{return JSON.parse(e)}catch(n){throw new W(J.INVALID_JSON,`${t} is not valid JSON`,{cause:n})}}function tc(e,t){if(e===null)return null;switch(typeof e){case"boolean":case"number":case"string":return e;case"object":if(Array.isArray(e))return e.map(n=>tc(n,t));if(at(e)){let n={};for(let[r,o]of Object.entries(e))n[r]=tc(o,t);return n}break}throw new W(J.INVALID_JSON,`${t} must be JSON-serializable`)}function Hp(e,t){if(!Array.isArray(e))throw new W(J.INDEX_CORRUPT,`${t} must be an array`);return e.map((n,r)=>{if(!Ke(n))throw new W(J.INDEX_CORRUPT,`${t}[${r}] is invalid`);return n})}function di(e,t){if(!Ke(e))throw new W(J.INVALID_PATH,`${t} must be a sha256 digest`)}function Ke(e){return typeof e=="string"&&/^sha256:[a-f0-9]{64}$/u.test(e)}function $t(e){return`sha256:${Rk("sha256").update(e).digest("hex")}`}function Jk(e){return typeof e=="string"?Buffer.from(e,"utf8"):Buffer.from(e)}async function jt(e,t,n){try{return await ye.readFile(e)}catch(r){throw new W(t,`${n} not found: ${e}`,{cause:r})}}async function nc(e){try{return await ye.readFile(e)}catch(t){if(Dr(t))return null;throw t}}function ac(e,t,n){if($t(e)!==t)throw new W(J.BLOB_CORRUPT,`blob hash mismatch for ${n}`)}async function Le(e){try{return await ye.access(e),!0}catch(t){if(Dr(t))return!1;throw t}}async function pi(e){try{await ye.rm(e,{force:!0,recursive:!0})}catch{}}async function rc(e){try{let t=await ye.open(e,"r");try{await t.sync()}finally{await t.close()}}catch{}}async function mi(e){try{return await ye.readdir(e)}catch(t){if(Dr(t))return[];throw t}}function Xk(e){if(typeof e!="string"||e.trim().length===0)throw new W(J.INVALID_ROOT,"history store rootDir must be a non-empty string");return be.resolve(e)}function hi(e){return be.join(e,Nk)}function Wa(e){return be.join(e,Pk)}function zk(e){return be.join(e,Ak)}function Gp(e){return be.join(e,Tk)}async function $p(e){try{let t=await ye.readFile(Gp(e),"utf8"),n=Fr(t,"document version");if(!at(n)||n.schemaVersion!==1||!Number.isInteger(n.version)||n.version<0)throw new W(J.INVALID_SCHEMA,"document version schema is invalid");return n.version}catch(t){if(Dr(t))return 0;throw t}}async function li(e){let t=await jt(e,J.RECOVERY_PENDING,"transaction journal"),n=Fr(Buffer.from(t).toString("utf8"),"transaction journal");return Yp(n),n}function Yp(e){if(!at(e)||e.schemaVersion!==wk||typeof e.transactionId!="string"||e.transactionId.length===0||typeof e.operationId!="string"||e.operationId.length===0||!["prepared","files-written","history-published"].includes(e.phase)||!Fk(e.historyTransition)||!Array.isArray(e.files))throw new W(J.INVALID_SCHEMA,"transaction journal schema is invalid");for(let t of e.files)if(!at(t)||typeof t.path!="string"||t.path.length===0||t.preDigest!==null&&!Ke(t.preDigest)||t.postDigest!==null&&!Ke(t.postDigest))throw new W(J.INVALID_SCHEMA,"transaction journal file digest is invalid")}function Wk(e){return e.replace(/[\r\n]+/g," ").slice(0,512)}function Mr(e){return be.join(e,"entries")}function Or(e){return be.join(e,"blobs")}function Tr(e){return be.join(e,"tmp")}function cc(e){return be.join(Tr(e),"stages")}function lc(e,t){return be.join(cc(e),`${t}.json`)}function uc(e,t){return be.join(Mr(e),`${qp(t)}.json`)}function dc(e,t){return be.join(Or(e),qp(t))}function fc(e,t){return be.join(Mr(e),`${t}.json`)}function pc(e,t){return be.join(Or(e),t)}async function Zp(e,t){return Qp(uc(e,t),fc(e,t))}async function mc(e,t){return Qp(dc(e,t),pc(e,t))}async function Qp(e,t){return await Le(e)?e:await Le(t)?t:e}function qp(e){return e.slice(7)}function Vp(e){let t=e.startsWith("sha256:")?e:`sha256:${e}`;return Ke(t)?t:null}function at(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Dr(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function Hk(e){return{maxEntries:e?.maxEntries??ui.maxEntries,maxSessionBytes:e?.maxSessionBytes??ui.maxSessionBytes,maxEntryBytes:e?.maxEntryBytes??ui.maxEntryBytes}}async function Gk(e){let t=hi(e);await Le(t)||await sc(e,[],-1)}import{createHash as Yk}from"node:crypto";import{computeSiteEditCompositionKey as tm,ManagedPageTemplateRouteManifestV1Schema as Zk}from"@vcp-dev/contracts";var Qk="app/_vcp/page-templates/runtime.tsx",nm=".vcp/page-templates/routes/",qk="app/_vcp/page-templates/routes/";function rm(e){return e.startsWith(nm)&&e.endsWith(".json")}var Ae=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="PageTemplateManagedSourceError"}};function $n(e){let t=Go(e);return Yk("sha256").update(t,"utf8").digest("hex").slice(0,16)}function xi(e){return e.replace(/[^A-Za-z0-9_-]/g,"_")}function Lr(e,t){let n=$n(e),r=`${qk}${n}`,o=xi(t);return{routeRoot:r,manifestFile:`${nm}${n}.json`,runtimeFile:Qk,registryFile:`${r}/registry.ts`,templateEntryFile:`${r}/templates/${o}/page.tsx`}}function om(e){let t=iC(e),n=new Map;for(let r of t){let o=xi(r),i=n.get(o);if(i!==void 0&&i!==r)throw new Ae("PAGE_TEMPLATE_ID_COLLISION",`Page-template IDs ${JSON.stringify(i)} and ${JSON.stringify(r)} map to the same safe name ${JSON.stringify(o)}.`,{reason:"safe-name-collision",templateId:r,safeName:o});n.set(o,r)}}function gc(e){let t=Go(e.routeId),n=im(e.files),r=Lr(t,""),o=n.get(r.manifestFile);if(o===void 0)return null;let i=rC(t,r.manifestFile,o);return oC({routeId:t,manifest:i,files:n}),i}function eC(e){let t=Go(e.selector.routeId),n=ln(e.canonicalEntryFile),r=gc({routeId:t,files:e.files});if(r===null){if(e.selector.templateId!==void 0)throw new Ae("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Page-template selection ${JSON.stringify(e.selector.templateId)} cannot be resolved without a managed manifest for ${JSON.stringify(t)}.`,{reason:"template-selection-without-manifest",routeId:t,templateId:e.selector.templateId});return{mode:"direct",context:{routeId:t},entryFile:n,effectiveEntryFile:n}}if(ln(r.canonical_entry_file)!==n)throw new Ae("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Managed page-template manifest for ${JSON.stringify(t)} does not match the supplied canonical entry.`,{reason:"canonical-entry-mismatch",routeId:t,path:r.canonical_entry_file});let o=e.selector.templateId??null,i=(o?r.templates.find(c=>c.template_id===o):void 0)??r.templates.find(c=>c.template_id===r.default_template_id);if(!i)throw new Ae("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Managed page-template manifest for ${JSON.stringify(t)} has no resolvable default template.`,{reason:"default-entry-missing",routeId:t});let a={context:{routeId:t,effectiveTemplateId:i.template_id},entryFile:ln(i.entry_file)};return{...a,mode:"delegated",effectiveEntryFile:a.entryFile}}function tC(e){let t=im(e.files),n=[...t.keys()].map(l=>({path:l})),r=kr(n),o=new Set,i=new Map;for(let l of r){if(o.has(l.routeId))throw new Ae("PAGE_TEMPLATE_ROUTE_AMBIGUOUS",`Multiple canonical page entries resolve to route ${JSON.stringify(l.routeId)}.`,{reason:"duplicate-route-id",routeId:l.routeId,candidates:r.filter(p=>p.routeId===l.routeId).map(p=>p.entryFile)});o.add(l.routeId);let u=$n(l.routeId),d=i.get(u);if(d!==void 0&&d!==l.routeId)throw new Ae("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Page-template route-key collision between ${JSON.stringify(d)} and ${JSON.stringify(l.routeId)}.`,{reason:"route-key-collision",routeId:l.routeId});i.set(u,l.routeId)}let s=new Set(r.map(l=>Lr(l.routeId,"").manifestFile));for(let l of t.keys())if(rm(l)&&!s.has(l))throw new Ae("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Managed page-template manifest ${JSON.stringify(l)} does not belong to a scanned canonical route.`,{reason:"unknown-manifest",path:l});let a=[];for(let l of r){let u=gc({routeId:l.routeId,files:t});if(u===null){let d={routeId:l.routeId};a.push(nC(d,l.entryFile));continue}for(let d of[...u.templates].sort(sC)){let p={routeId:l.routeId,effectiveTemplateId:d.template_id},m={context:p,entryFile:ln(d.entry_file)};a.push({key:tm(p),composition:m})}}let c=new Set;for(let{key:l,composition:u}of a){if(c.has(l))throw new Ae("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Duplicate site-edit composition key for ${JSON.stringify(l)}.`,{reason:"duplicate-composition-key",routeId:u.context.routeId});c.add(l)}return a.sort((l,u)=>aC(l.composition,u.composition)||yi(l.key,u.key)).map(({composition:l})=>l)}function nC(e,t){return{key:tm(e),composition:{context:e,entryFile:t}}}function im(e){let t=new Map;if(lC(e)){for(let n of e)em(t,n.path,n.content);return t}for(let[n,r]of e)em(t,n,r);return t}function em(e,t,n){let r=ln(t);if(e.has(r))throw new Ae("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Snapshot contains duplicate file path ${JSON.stringify(r)}.`,{reason:"duplicate-file-path",path:r});e.set(r,n)}function rC(e,t,n){let r;try{r=JSON.parse(n)}catch{throw new Ae("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Managed page-template manifest ${JSON.stringify(t)} is not valid JSON.`,{reason:"invalid-json",routeId:e,path:t})}let o=Zk.safeParse(r);if(!o.success)throw new Ae("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Managed page-template manifest ${JSON.stringify(t)} does not match the known manifest contract.`,{reason:"schema-invalid",routeId:e,path:t,issues:o.error.issues.map(i=>`${i.path.join(".")||"manifest"}: ${i.message}`)});return o.data}function oC(e){let{routeId:t,manifest:n,files:r}=e,o=Lr(t,""),i=kr([...r.keys()].map(l=>({path:l}))).filter(l=>l.routeId===t);if(n.route_id!==t&&mt(t,"route-id-mismatch",o.manifestFile),n.route_key!==$n(t)&&mt(t,"route-key-mismatch",o.manifestFile),i.length!==1)throw new Ae("PAGE_TEMPLATE_ROUTE_AMBIGUOUS",`Managed page-template route ${JSON.stringify(t)} has ${i.length} canonical entries.`,{reason:i.length===0?"canonical-entry-missing":"duplicate-route-id",routeId:t,candidates:i.map(l=>l.entryFile)});let s=ln(n.canonical_entry_file);(s!==i[0].entryFile||!r.has(s))&&mt(t,"canonical-entry-mismatch",s),n.default_template_id!==`vcp-default:${$n(t)}`&&mt(t,"default-template-id-mismatch",o.manifestFile),om(n.templates);let a=new Set,c=new Set;for(let l of n.templates){let u=Lr(t,l.template_id),d=ln(l.entry_file),p=xi(l.template_id);l.safe_name!==p&&mt(t,"safe-name-mismatch",o.manifestFile,{templateId:l.template_id}),a.has(l.safe_name)&&mt(t,"duplicate-safe-name",o.manifestFile,{templateId:l.template_id}),a.add(l.safe_name),c.has(d)&&mt(t,"duplicate-entry-file",o.manifestFile,{templateId:l.template_id}),c.add(d),cC(d,u.routeRoot)||mt(t,"entry-outside-route-root",d,{templateId:l.template_id}),d!==u.templateEntryFile&&mt(t,"entry-path-mismatch",d,{templateId:l.template_id}),r.has(d)||mt(t,"template-entry-missing",d,{templateId:l.template_id})}}function mt(e,t,n,r={}){throw new Ae("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Managed page-template source for ${JSON.stringify(e)} failed validation (${t}).`,{reason:t,routeId:e,path:n,...r})}function iC(e){return Array.isArray(e)?e.length===0||typeof e[0]=="string"?e:e.map(t=>t.template_id):"rawTemplateIds"in e?e.rawTemplateIds:"templateIds"in e?e.templateIds:[]}function sC(e,t){return+(t.kind==="default")-+(e.kind==="default")||yi(e.template_id,t.template_id)}function aC(e,t){let n=yi(e.context.routeId,t.context.routeId);if(n!==0)return n;let r=e.context.effectiveTemplateId,o=t.context.effectiveTemplateId;if(r===void 0)return-1;if(o===void 0)return 1;let s=`vcp-default:${$n(e.context.routeId)}`,a=r===s;return Number(o===s)-Number(a)||yi(r,o)}function yi(e,t){return e<t?-1:e>t?1:0}function cC(e,t){return e.startsWith(`${t}/`)}function ln(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function lC(e){return Array.isArray(e)}export{W as FileHistoryStoreError,Ae as PageTemplateManagedSourceError,ci as PreviewFileSystemSiteEditEngineRuntime,Sf as SITE_EDIT_RAW_COLOR_LITERAL_RE,si as SnapshotSiteEditEngineRuntime,om as assertNoPageTemplateSafeNameCollision,Lr as computeManagedPageTemplatePaths,$n as computePageTemplateRouteKey,xi as computePageTemplateSafeName,Ck as createPreviewSiteEditEngineRuntime,Ek as createSiteEditEngineRuntime,rm as isManagedPageTemplateManifestPath,Up as openFileHistoryStore,gc as parseManagedPageTemplateManifest,eC as resolveManagedPageTemplateComposition,tC as scanSiteEditCompositionsFromFiles,Sr as scanSiteEditThemeStyleViolations};
13
+ `||p==="\r"}if(s)return jn(t,`Unterminated block comment in ${t}.`);if(o)return jn(t,`Unterminated string literal in ${t}.`);if(c)return jn(t,`Unterminated MDX code fence in ${t}.`);let u=r.at(-1);return u?jn(t,`Unclosed token "${u.char}" in ${t}.`):{ok:!0}}function jn(e,t){return{ok:!1,errorCode:"ast-error",message:t,details:{path:e}}}function Nr(e){let t="idle",n=e.fileSystem??gv(),r=yf(),o=lp({compositions:e.compositions,initialDocumentVersions:e.initialDocumentVersions}),i=new Map,s=new Map,a=new Set,c=null,l=e.history??(e.historyStore?Qf(e.historyStore):hv()),u=hf(n,{externalAdapters:e.externalAdapters}),d=new Map,p=new Set,m=0,g=e.historyStore?.recoveryRequired??!1,S=Fa(),C=B();function v(f){return(qo.isAbsolute(f)?qo.relative(e.projectRoot,f):f).replace(/\\/g,"/").replace(/^\.\//,"")}function P(f,y){let h=qo.posix.dirname(f),I=y.replace(/\.(?:tsx?|jsx?)$/i,""),R=qo.posix.relative(h,I);return R.startsWith(".")?R:`./${R}`}function w(f,y){return f.startLine===y.startLine&&f.startColumn===y.startColumn&&f.endLine===y.endLine&&f.endColumn===y.endColumn}async function B(){let f=e.historyStore;if(f)try{let y=await f.readTransactionJournal();if(!y)return;let h=await f.readIndex(),I=await Promise.all(y.files.map(async A=>await n.exists(A.path)?ue(await n.readFile(A.path)):null));if(ap({journal:y,index:h,observedFileDigests:I})!=="ambiguous"){await f.clearTransactionJournal(y.transactionId);let A=await f.readStatus();A.recoveryRequired||(await f.cleanupTmp(),A=await f.readStatus()),g=A.recoveryRequired;return}await f.markRecoveryRequired(`Ambiguous transaction journal ${y.transactionId} at phase ${y.phase}`),g=!0}catch(y){g=!0,await f.markRecoveryRequired(`Transaction journal recovery failed: ${Fe(y)}`).catch(()=>{})}}function re(){return t==="disposed"}e.onEvent&&r.subscribe(e.onEvent);for(let f of o.entries){let y=mp(f.context,f.entryFile);i.set(f.key,y),ne(y,y.dependencyFiles)}function ne(f,y){let h=new Set(y);N(f),f.dependencyFiles=h;for(let I of f.dependencyFiles){let R=s.get(I);R||(R=new Set,s.set(I,R)),R.add(f.key)}}function N(f){for(let y of f.dependencyFiles){let h=s.get(y);h&&(h.delete(f.key),h.size===0&&s.delete(y))}f.dependencyFiles.clear()}function X(f){let y=new Set;for(let h of f)for(let I of s.get(h)??[])y.add(I);return y}function M(f){for(let y of f)if(!s.has(y))return!1;return!0}async function D(f,y,h,I,R){let A=new Map,F=Sd(R.values()),L=new Map,T=typeof n.exists=="function"?$=>n.exists($):async()=>!1;for(let[$,K]of f.elements){let me=y.nodes.get($);if(!me)continue;let Q=h.get(K.sourceFile)??I.get(K.sourceFile),Ie=new Map,Y=new Map,ge=new Map,_=[];for(let pe of K.textSegments){if(!Q){Ie.set(pe.index,null);continue}let Kn=await bd({file:K.sourceFile,source:Q,segment:pe,readFile:Ze=>n.readFile(Ze),exists:T,graph:f,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Ze,adapterId:ki,capabilities:Ci})=>({sourceType:Ze,adapterId:ki,capabilities:Ci})),functionCallContracts:e.functionCallContracts,fileCache:F}),we=await Gs({file:K.sourceFile,source:Q,target:{kind:"text-segment",segment:pe},readFile:Ze=>n.readFile(Ze),exists:T,graph:f,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Ze,adapterId:ki,capabilities:Ci})=>({sourceType:Ze,adapterId:ki,capabilities:Ci})),functionCallContracts:e.functionCallContracts,fileCache:F}),gn=Rv(Kn);Ie.set(pe.index,gn),Y.set(pe.index,Kn),ge.set(pe.index,we),_.push({editable:pe.editable,source:gn})}let j=new Map;if(Q)for(let pe of K.attributes??[]){let Kn=await Ed({file:K.sourceFile,source:Q,sourceRange:pe.sourceRange,expression:pe.source?.expression??pe.value,sourceInfo:pe.source,readFile:we=>n.readFile(we),exists:T,graph:f,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:we,adapterId:gn,capabilities:Ze})=>({sourceType:we,adapterId:gn,capabilities:Ze})),functionCallContracts:e.functionCallContracts,fileCache:F});j.set(pe.name,Kn)}let z=Yl(wv(me.writeTarget),_),oe=tu({key:$,element:K,graph:f,provenances:ge}),Se=iu(K),Je=su(K),pn=au(K),mn=Q?await Hd({element:K,graph:f,file:K.sourceFile,source:Q,readFile:pe=>n.readFile(pe),exists:T,fileCache:L}):void 0,Vt=f.regions.find(pe=>pe.kind==="conditional-region"&&pe.childKeys.includes($)),Te,Un=Vt?.sourceCandidates?.[0];if(Q&&Vt&&Un?.kind==="conditional-branch"){let pe=await Gs({file:K.sourceFile,source:Q,target:{kind:"conditional-branch",candidate:Un},readFile:we=>n.readFile(we),exists:T,graph:f,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:we,adapterId:gn,capabilities:Ze})=>({sourceType:we,adapterId:gn,capabilities:Ze})),functionCallContracts:e.functionCallContracts,fileCache:F});Te={currentBranch:Vt.childKeys.indexOf($)<=0?"then":"else",availableBranches:Vt.childKeys.length>1?["then","else"]:["then"],conditionExpression:Un.conditionExpression,provenance:{finalSource:pe.finalSource?{kind:pe.finalSource.kind,file:pe.finalSource.file,displayPath:pe.finalSource.displayPath}:null,chain:pe.chain.map(we=>({kind:we.kind,file:we.file,displayName:we.displayName,canEditHere:we.canEditHere})),confidence:pe.confidence,editMode:pe.editMode,diagnostics:pe.diagnostics.map(we=>({code:we.code,message:we.message}))}}}A.set($,{textSources:Ie,textTargets:Y,elementPropertyTargets:j,provenances:ge,writeTarget:z,componentSemantic:oe,contentModel:Se,mediaModel:Je,styleSource:pn,conditional:Te,dynamicData:mn})}return A}function Z(f){return typeof n.getVersion=="function"?n.getVersion(f):0}function te(f,y){let h=o.initialVersions.get(f.key)??0;for(let I of y.values())h=Math.max(h,I);return Math.max(h,f.graph?.version??0)}function he(f){return i.get(f)?.graph?.version??o.initialVersions.get(f)??0}function H(f){try{return he(o.resolveSelector(f.composition).key)}catch{return 0}}async function q(f,y,h={}){let I=i.get(f);if(!I)return null;let R=h.sourceCache??Ma(d,[]),A=await xe(I.entryFile),{graph:F,allSources:L,diagnostics:T,parsedModules:$,entryModule:K}=await zc(I.entryFile,y,Te=>n.readFile(Te),typeof n.exists=="function"?Te=>n.exists(Te):async()=>!1,{additionalEntries:A,version:I.graph?.version??1});if(T.length>0)throw new Rr(T);let me=new Map;for(let Te of L.keys())me.set(Te,Z(Te));let Q=Math.max(te(I,me),h.minimumVersion??0);h.changed&&Q<=(I.graph?.version??0)&&(Q=(I.graph?.version??0)+1),F.version=Q;for(let[Te,Un]of L)Oa(R,Te,Un,dp);let Ie=await It(I.composition,I.entryFile,L,R);F.routeId=I.routeId,F.composition=I.composition;let Y=Wc(F),ge=Gc(Y,F),_=await D(F,Y,L,R,$),j=am(F,ge,_),z=sm(_),oe=Uv(Xl(F,Y,ge,{canUpdateTextByKey:j,dynamicDataSummaryByKey:z}),F,_),Se=Ll({route:I.routeId,composition:I.composition,entryFile:I.entryFile,version:Q,source:y,ast:K?.ast}),Je=Bl(Se);Se.ok&&_v(oe,F,Se.projection);let pn={...oe,composition:I.composition,...Ie?{styleContext:Ie}:{},pageComposition:Je},mn=new Set([I.entryFile,...L.keys()]);if(Ie){mn.add(Ie.entryCss.path);for(let Te of Ie.stylesheets)mn.add(Te.path)}let Vt={...I,dependencyFiles:mn,graph:F,topology:Y,capabilities:ge,document:pn,pageComposition:Je,pageCompositionProjection:Se.projection,pagePlacementByKey:Se.ok?Se.projection.placementByKey:null,pagePlacementUnitByKey:Se.ok?Se.projection.placementUnitByKey:null,pageUnitByKey:Se.ok?Se.projection.unitByKey:null,pagePlacementsByUnitKey:Se.ok?Se.projection.placementsByUnitKey:null,documentIndex:bv(pn),detailProjections:_,fileVersions:me,styleContext:Ie};if(h.publish===!1)return Vt;Bn(d,R);for(let Te of R.keys())p.delete(Te);return ne(I,mn),Object.assign(I,Vt),I}async function xe(f){let y=[];for(let h of Dv(f))typeof n.exists=="function"&&await n.exists(h)&&y.push({file:h,source:await n.readFile(h)});return y}async function It(f,y,h,I){let R=[];for(let[$,K]of h){if(Ba($)){R.push($);continue}for(let me of Bv(K)){let Q=Sp($,me);Q&&R.push(Q)}}if(!R.length){for(let $ of Lv(y))if(await hc($)){R.push($);break}}let A=new Map,F=kp(R).slice(0,up);for(;F.length>0&&A.size<up;){let $=F.shift();if(A.has($)||!Ba($))continue;let K=await vt($,I);if(K!==null){A.set($,{path:$,content:K});for(let me of jv(K)){let Q=Sp($,me);Q&&!A.has(Q)&&!F.includes(Q)&&F.push(Q)}}}let L=[...A.values()].map($=>({...$,hash:ue($.content)})),T=L[0];return T?{composition:f,revision:ue(JSON.stringify(L.map(({path:$,hash:K})=>({path:$,hash:K})))),entryCss:T,stylesheets:L.slice(1)}:null}async function vt(f,y){let h=y.get(f);if(h!==void 0)return h;if(!await hc(f))return null;let I=await n.readFile(f);return Oa(y,f,I,dp),I}async function hc(f){return typeof n.exists=="function"?n.exists(f):!1}function sm(f){let y=new Map;for(let[h,I]of f)I.dynamicData?.bindings.length&&y.set(h,sf(I.dynamicData.bindings));return y}function am(f,y,h){let I=new Map;for(let[R,A]of f.elements){if(!y.get(R)?.canUpdateText){I.set(R,!1);continue}let L=h.get(R),T=A.textSegments.some($=>{if(!$.editable)return!1;let K=L?.provenances.get($.index)??null;return!K||cm(K)});I.set(R,T)}return I}function cm(f){return f.editMode==="direct"||f.editMode==="proxy"||f.editMode==="upstream"}async function Br(f,y={}){let h=[...new Set(f)],I=y.affectedCompositionKeys!==void 0,R=I?new Set(y.affectedCompositionKeys):X(h);if(!I&&(R.size===0||!M(h)))for(let T of i.values())yc(T,h)&&R.add(T.key);let A=!I&&R.size===0&&h.some(xp),F=y.publish===!1?Ma(d,h):void 0,L={rebuiltRoutes:[],failedRoutes:[],...y.publish===!1?{candidateRouteStates:[],candidateSourceCache:F}:{}};for(let T of i.values())if(!(y.excludedCompositionKeys?.has(T.key)||!(R.has(T.key)||A)))try{let K=!!T.graph,me=await n.readFile(T.entryFile),Q=await q(T.key,me,{...y,...F?{sourceCache:F}:{}});Q?.graph&&(L.rebuiltRoutes.push({documentChanged:K,composition:T.composition,routeId:T.routeId,version:Q.graph.version}),L.candidateRouteStates?.push({composition:T.composition,key:T.key,routeId:T.routeId,state:Q}))}catch(K){L.failedRoutes.push({...sp(T.routeId,K),composition:T.composition})}return L}function un(f){let y=[...new Set(f)],h=X(y);if(h.size>0&&M(y))return[...h];for(let I of i.values())yc(I,y)&&h.add(I.key);return[...h]}function lm(f){let y=new Set(un(f));return o.entries.filter(h=>y.has(h.key)).map(h=>h.context)}function um(f){return[...new Set(un(f))].sort((h,I)=>h<I?-1:h>I?1:0).map(h=>o.getByKey(h)?.context).filter(h=>h!==void 0)}function dm(f,y){let h=new Set(un(y)),I=f.provenance?.affectedCompositions??[];if(I.length===0)return h;let R=new Set(I.map(A=>o.resolveContext(A).key));if(R.size!==h.size||[...R].some(A=>!h.has(A)))throw new Error("History provenance does not match the affected composition index.");return R}function fm(f,y){let h=f.composition??f.provenance?.initiatingComposition;if(h){let A=o.resolveContext(h);return{context:A.context,key:A.key}}let I=[...new Set(un(y))];if(I.length!==1)throw new Error(`Legacy history entry cannot be attributed to a unique composition (affected composition count: ${I.length}).`);let R=o.getByKey(I[0]);if(!R)throw new Error("Legacy history entry references an unknown affected composition.");return{context:R.context,key:R.key}}function Si(f,y){r.emit({type:"operation-completed",composition:f.composition,result:f});for(let{composition:h,version:I}of y.rebuiltRoutes)r.emit({type:"document-changed",composition:h,version:I});for(let{composition:h,message:I}of y.failedRoutes)r.emit({type:"graph-error",composition:h,message:I})}function yc(f,y){return y.some(h=>f.dependencyFiles.has(h)||f.entryFile===h||f.graph?.fileIndex.has(h))}function xc(f){for(let y of f)a.add(y);c||re()||(c=(async()=>{t="building";let y=!1;try{for(;a.size>0;){if(re())return;await pm();let h=[...a];a.clear();let I=await Sc(h);if(I.length===0)continue;let R=un(I);for(let L of R){let T=i.get(L)?.composition;T&&r.emit({type:"graph-invalidated",composition:T})}let{rebuiltRoutes:A,failedRoutes:F}=await Br(I,{changed:!0});for(let{documentChanged:L,composition:T,version:$}of A)r.emit({type:"graph-ready",composition:T,version:$}),L&&r.emit({type:"document-changed",composition:T,version:$});for(let{composition:L,message:T}of F)y=!0,r.emit({type:"graph-error",composition:L,message:T})}}finally{c=null,t!=="disposed"&&(t=!y&&[...i.values()].some(h=>h.graph)?"ready":"idle"),a.size>0&&xc([])}})())}async function pm(){for(;m>0;)await new Promise(f=>setTimeout(f,0))}async function Sc(f){let y=[];for(let h of new Set(f)){let I=d.get(h);if(I===void 0){if(p.has(h)&&!await n.exists(h))continue;p.delete(h),y.push(h);continue}try{await n.readFile(h)!==I&&(p.delete(h),y.push(h))}catch(R){if(!Tv(R))try{if(await n.exists(h))continue}catch{continue}p.add(h),y.push(h)}}return y}function bc(f){op(d,f);for(let y of f)y.exists===!1?p.add(y.file):p.delete(y.file)}function Ec(f){p.clear();for(let y of f)p.add(y)}async function Ic(f){let y=await Sc(f);if(y.length===0)return;let h=un(y);for(let A of h){let F=i.get(A)?.composition;F&&r.emit({type:"graph-invalidated",composition:F})}let{rebuiltRoutes:I,failedRoutes:R}=await Br(y,{changed:!0});for(let{documentChanged:A,composition:F,version:L}of I)r.emit({type:"graph-ready",composition:F,version:L}),A&&r.emit({type:"document-changed",composition:F,version:L});for(let{composition:A,message:F}of R)r.emit({type:"graph-error",composition:A,message:F})}async function mm(f,y){let h=Vn(f,y);if(!h?.graph)return;let I=$e(f)??f,R=h.graph.elements.get(I);R&&await Ic([R.sourceFile])}async function vc(f){let y=new Set;if(f.target.kind==="node"){let h=Vn(f.target.key,f.composition),I=$e(f.target.key)??f.target.key,R=h?.graph?.elements.get(I);R&&y.add(R.sourceFile)}else if(f.target.kind==="route"){let h=i.get(o.resolveSelector(f.target.composition).key);h&&y.add(h.entryFile)}else if(f.target.kind==="page-unit"){let h=i.get(o.resolveSelector(f.target.composition).key);h&&y.add(h.entryFile)}else if(f.target.kind==="source-file")y.add(f.target.path);else if(f.target.kind==="source-batch")for(let h of f.target.paths)y.add(h);await Ic(y)}async function gm(f){if(f.params.kind!=="source-edit")return bi(f,"invalid-params","source-edit requires source-edit params");for(let y of f.params.edits){let h=Av(y);if(!h.ok)return bi(f,h.errorCode,h.message,h.details)}m+=1;try{let y=await Em(f.params.edits);if(!y.ok)return bi(f,y.errorCode,y.message,y.details);await vc(f);let h={operationId:f.id,kind:"source-edit",target:f.target,documentVersion:f.documentVersion,conflictPolicy:f.params.conflictPolicy,edits:f.params.edits.map(I=>I.operation==="delete"?{operation:"delete",file:I.path,baseContentHash:I.baseContentHash??null}:{operation:"upsert",file:I.path,baseContentHash:I.baseContentHash??null,content:I.content})};return await fn({request:f,filePlan:h})}catch(y){return{composition:o.resolveSelector(f.composition).context,requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:H(f),error:{code:O.INTERNAL_ERROR,message:Fe(y)}}}finally{m-=1}}async function hm(f){if(f.target.kind!=="project"||f.params.kind!=="insert-page-resource")return ee(f,O.INVALID_PARAMS,"insert-page-resource requires project target and matching params.");m+=1;try{let y=await wa({files:[...f.params.artifact.components.flatMap(I=>I.materialization.files.map(R=>({path:R.pathTemplate,content:R.content}))),...f.params.artifact.pages.flatMap(I=>I.materialization.files.map(R=>({path:R.pathTemplate,content:R.content})))],exists:I=>n.exists(I),readFile:I=>n.readFile(I)});if(!y.ok)return ee(f,O.MATERIALIZATION_REJECTED,y.message);let h=await Ca({artifact:f.params.artifact,exists:I=>n.exists(I)});return h.ok?await fn({request:f,filePlan:{operationId:f.id,kind:"source-edit",target:f.target,documentVersion:f.documentVersion,conflictPolicy:"overwrite",edits:h.files},output:{kind:"insert-page-resource",package_instance_id:h.packageInstanceId,pages:h.pages},historyPolicy:"none"}):ee(f,h.code==="MATERIALIZATION_CONFLICT"?O.MATERIALIZATION_CONFLICT:O.MATERIALIZATION_REJECTED,h.message,h.path?{path:h.path}:void 0)}catch(y){return ee(f,O.INTERNAL_ERROR,Fe(y))}finally{m-=1}}async function ym(f){if(f.target.kind!=="project"||f.params.kind!=="delete-page-source")return ee(f,O.INVALID_PARAMS,"delete-page-source requires project target and matching params.");if(!n.listFiles)return ee(f,O.PLAN_FAILED,"Complete project file listing is required for page deletion.");m+=1;try{let y=Ep(await n.listFiles({maxFiles:5e4,maxDepth:64}));if(y.truncated)return ee(f,O.PLAN_FAILED,"Project file listing is incomplete; page deletion was refused.",{truncationReasons:y.truncated.reasons});let h=y.files.filter(({path:F})=>/\.(?:tsx?|jsx?)$/.test(F)),I=Object.fromEntries(await Promise.all(h.map(async({path:F})=>[F,await n.readFile(F)]))),R=zf({expectedUrlPath:f.params.expectedUrlPath,files:I});if(!R.ok)return ee(f,R.code==="HOME_PAGE_LOCKED"?O.HOME_PAGE_LOCKED:R.code==="ROUTE_NOT_FOUND"?O.ROUTE_NOT_FOUND:O.PLAN_FAILED,R.message);let A=await Promise.all(R.edits.map(async F=>({...F,baseContentHash:ue(await n.readFile(F.file))})));return fn({request:f,filePlan:{operationId:f.id,kind:"source-edit",target:f.target,documentVersion:f.documentVersion,conflictPolicy:"compare-and-swap",edits:A},output:{kind:"delete-page-source",deleted_files:R.deletedFiles,updated_files:R.updatedFiles,preserved_shared_files:R.preservedSharedFiles,warnings:R.warnings},historyPolicy:"none"})}catch(y){return ee(f,O.INTERNAL_ERROR,Fe(y))}finally{m-=1}}async function xm(f,y){if(f.kind!=="insert-child"||f.params.kind!=="insert-child")return ee(f,O.UNSUPPORTED_OPERATION,"Only page-unit insert-child is currently supported by the page composition transaction.");if(!("kind"in f.params.position)||f.params.position.kind!=="page-composition")return ee(f,O.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.");if(f.params.position.documentVersion!==f.documentVersion)return ee(f,O.VERSION_STALE,"Page-unit insert-child placement belongs to a different document version.");let h=y.document,I=y.pageCompositionProjection;if(!h||h.pageComposition?.status!=="supported"||!I||I.status!=="supported")return ee(f,O.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(f.documentVersion!==h.version||I.documentVersion!==h.version)return ee(f,O.VERSION_STALE,`Document version ${f.documentVersion} is stale (current: ${h.version}).`);let R=f.params.node.kind==="component-call"?f.params.node.materialization:void 0;if(!R)return ee(f,O.UNSUPPORTED_OPERATION,"Page-unit insertion currently requires a static materialization manifest.");let A=f.params.position,F=await wa({files:R.files.map(T=>({path:T.pathTemplate,content:T.content})),exists:T=>n.exists(T),readFile:T=>n.readFile(T)});if(!F.ok)return ee(f,O.MATERIALIZATION_REJECTED,F.message);let L=await Nf({manifest:R,generatedRoot:"components/site/generated",controlledFiles:R.files.map(T=>({pathTemplate:T.pathTemplate})),exists:T=>n.exists(T),commit:async T=>{let $=await n.readFile(y.entryFile),K=y.document,me=y.pageCompositionProjection;if(!K||K.pageComposition?.status!=="supported"||K.version!==f.documentVersion||!me||me.status!=="supported"||me.documentVersion!==K.version)return{ok:!0,data:ee(f,O.VERSION_STALE,"The route changed before the page-unit insertion could commit.")};let Q=T.entry.path,Ie=Nm(T.instanceName),Y=os({routeId:y.routeId,entryFile:y.entryFile,currentDocumentVersion:K.version,expectedDocumentVersion:f.documentVersion,source:$,projection:me,placementKey:A.placementKey,component:{source:Q,exportName:T.entry.export.kind==="default"?"default":T.entry.export.name,localName:Ie}});if(!Y.ok)return{ok:!0,data:ee(f,_c(Y.error.code),Y.error.message,{diagnostics:Y.error.diagnostics})};let ge=Y.plan.returnStep?_l({source:$,jsx:Y.plan.returnStep.node.jsx,placement:Y.plan.returnStep.placement,...Y.plan.returnStep.replaceOriginal?{replaceOriginal:!0}:{}}):Y.plan.insertStep?.parentLocator?Rn({source:$,locator:Y.plan.insertStep.parentLocator,node:Y.plan.insertStep.node,placement:Y.plan.insertStep.placement,...Y.plan.insertStep.anchorLocator?{anchorLocator:Y.plan.insertStep.anchorLocator}:{}}):{ok:!1,source:$,diagnostic:{code:"unsupported-syntax",message:"Route composition rewrite has no insertion step."}};if(!ge.ok)return{ok:!0,data:ee(f,O.AST_PARSE_ERROR,ge.diagnostic.message)};let _=Pn({source:ge.source,moduleSpecifier:Y.plan.importStep.moduleSpecifier,imports:Y.plan.importStep.imports});if(!_.ok)return{ok:!0,data:ee(f,O.AST_PARSE_ERROR,_.diagnostic.message)};let j=T.files.map(oe=>({operation:"create-only",file:oe.path,content:oe.content})),z=[{operation:"upsert",file:y.entryFile,content:_.source,baseContentHash:ue($)},...j];m+=1;try{let oe=await fn({request:f,filePlan:{operationId:f.id,kind:"source-edit",target:{kind:"source-file",path:y.entryFile},documentVersion:f.documentVersion,conflictPolicy:"compare-and-swap",edits:z}});return!oe.ok&&oe.error?.message.includes("MATERIALIZATION_INSTANCE_CONFLICT")?{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:oe.error?.message??"Static prefab instance conflicted during commit."}}:{ok:!0,data:oe}}finally{m-=1}}});return L.ok?L.data:ee(f,O.VERSION_STALE,L.error.message,{materializationCode:L.error.code})}async function Sm(f,y){if(f.kind!=="move-node"&&f.kind!=="remove-node")return ee(f,O.UNSUPPORTED_OPERATION,"Only page-unit move-node and remove-node are currently supported by the page composition transaction.");let h=y.document,I=y.pageCompositionProjection;if(!h||h.pageComposition?.status!=="supported"||!I||I.status!=="supported")return ee(f,O.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(f.documentVersion!==h.version||I.documentVersion!==h.version)return ee(f,O.VERSION_STALE,`Document version ${f.documentVersion} is stale (current: ${h.version}).`);let R=await n.readFile(y.entryFile),A=Fl({routeId:y.routeId,composition:y.composition,entryFile:y.entryFile,currentDocumentVersion:h.version,expectedDocumentVersion:f.documentVersion,source:R,projection:I,placementUnitKey:f.target.placementUnitKey,operation:f.kind,targetPlacement:f.kind==="move-node"&&f.params.kind==="move-node"&&"kind"in f.params.target&&f.params.target.kind==="page-composition"?f.params.target:void 0});if(!A.ok)return ee(f,_c(A.error.code),A.error.message,{diagnostics:A.error.diagnostics});let F=A.plan.rewriteStep.kind==="move-node"?Nn({source:R,locator:A.plan.rewriteStep.locator,targetParentLocator:A.plan.rewriteStep.targetParentLocator,placement:A.plan.rewriteStep.placement,...A.plan.rewriteStep.anchorLocator?{anchorLocator:A.plan.rewriteStep.anchorLocator}:{}}):kn({source:R,locator:A.plan.rewriteStep.locator});if(!F.ok)return ee(f,O.AST_PARSE_ERROR,F.diagnostic.message);let L=F.source,T=[];if(f.kind==="remove-node"){let K=await bm({routeState:y,placementUnitKey:f.target.placementUnitKey,source:R,mutatedSource:L});L=K.source,T=await Promise.all(K.files.map(async me=>({operation:"delete",file:me,baseContentHash:ue(await n.readFile(me))})))}let $=[{operation:"upsert",file:y.entryFile,content:L,baseContentHash:ue(R)},...T];m+=1;try{return await fn({request:f,filePlan:{operationId:f.id,kind:"source-edit",target:{kind:"source-file",path:y.entryFile},documentVersion:f.documentVersion,conflictPolicy:"compare-and-swap",edits:$}})}finally{m-=1}}async function bm(f){let y={source:f.mutatedSource,files:[]},h=f.routeState.graph,I=f.routeState.pageCompositionProjection;if(!h||!I||I.status!=="supported"||!n.listFiles)return y;let A=I.placementUnitByKey.get(f.placementUnitKey)?.sourceRange;if(!A)return y;let F=[...h.elements.values()].find(j=>j.sourceFile===f.routeState.entryFile&&j.importedFrom&&w(j.sourceRange,A));if(!F?.importedFrom||!F.exportName)return y;let L=v(F.importedFrom),T="components/site/generated/";if(!L.startsWith(T))return y;let $=L.slice(T.length).split("/")[0];if(!$||!/-[0-9a-f]{8}$/i.test($))return y;let K=`${T}${$}`;if([...h.elements.values()].filter(j=>j.sourceFile===f.routeState.entryFile&&v(j.importedFrom??"")===L).length!==1)return y;let Q=await n.listFiles({maxFiles:5e3,maxDepth:32}),Ie=Array.isArray(Q)?Q:Q.files;if(!Array.isArray(Q)&&Q.truncated)return y;let Y=Ie.map(({path:j})=>j).filter(j=>j===K||j.startsWith(`${K}/`));if(Y.length===0||!Y.includes(L))return y;for(let{path:j}of Ie)if(!(j===f.routeState.entryFile||j===K||j.startsWith(`${K}/`)))try{if((await n.readFile(j)).includes($))return y}catch{return y}let ge=P(f.routeState.entryFile,L),_=An({source:f.mutatedSource,moduleSpecifier:ge,imports:F.exportName==="default"?[{kind:"default"}]:[{kind:"named",imported:F.exportName}]});return _.ok?{source:_.source,files:Y.sort((j,z)=>j.localeCompare(z))}:y}async function Em(f){if(n.getFileInfo){for(let R of f)if(await n.exists(R.path)&&await n.getFileInfo(R.path)===null)return{ok:!1,errorCode:"invalid-params",message:`Source edit path must resolve to a regular non-symbolic-link file: ${R.path}`,details:{path:R.path}}}let y=Im(f);if(y.length===0)return{ok:!0};let h=Nv(n,f),I=Nr({projectRoot:e.projectRoot,fileSystem:h,compositions:[...i.values()].map(R=>({context:R.composition,entryFile:R.entryFile})),externalAdapters:e.externalAdapters,externalSourceResolvers:e.externalSourceResolvers,functionCallContracts:e.functionCallContracts,dev:e.dev});try{for(let R of y){let A=i.get(R)?.composition;if(!A)continue;let F={routeId:A.routeId,...A.effectiveTemplateId!==void 0?{templateId:A.effectiveTemplateId}:{}};await I.initializeComposition(F),I.getDocument(F)}}catch(R){return{ok:!1,errorCode:"ast-error",message:`Source edit preflight failed: ${Fe(R)}`,details:{compositionKeys:y}}}finally{I.dispose()}return{ok:!0}}function Im(f){return f.map(h=>h.path).some(xp)?[...i.keys()]:[]}function bi(f,y,h,I){let R=wr(y);return{composition:o.resolveSelector(f.composition).context,requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:H(f),error:{code:R,message:h,...I?{details:I}:{}}}}async function Ei(f){let y=[];for(let h of new Set(f))y.push(await vm(h));return y}async function vm(f){if(!(typeof n.exists=="function"?await n.exists(f):!0))return{file:f,content:"",version:Math.max(0,Z(f)),exists:!1};let h=await n.readFile(f);return{file:f,content:h,version:Math.max(1,Z(f)),exists:!0,sha256:ue(h)}}async function kc(f,y,h,I){if(!e.historyStore)return null;let R=new Map(y.map(L=>[L.file,L])),A=new Map(h.map(L=>[L.file,L])),F=[...new Set([...R.keys(),...A.keys()])].sort().map(L=>{let T=R.get(L),$=A.get(L);return{path:L,preDigest:T?.exists===!1||!T?null:ue(T.content),postDigest:$?.exists===!1||!$?null:ue($.content)}});return{schemaVersion:2,transactionId:`${f}:${I.expectedIndexDigest}`,operationId:f,phase:"prepared",historyTransition:I,files:F}}async function Cc(f){return!f||!e.historyStore||await e.historyStore.writeTransactionJournal(f),f}async function dn(f){f&&e.historyStore&&await e.historyStore.clearTransactionJournal(f.transactionId)}async function Ii(f,y){let h=[];try{for(let I of f)await Rc(I),typeof n.bumpVersion=="function"&&n.bumpVersion(I.file),h.push(I.file)}catch(I){let R=await km(y.filter(A=>h.includes(A.file)));return R.ok?{ok:!1,reason:`Writeback failed and committed files were restored: ${Fe(I)}`,rolledBack:!0}:{ok:!1,reason:`Writeback failed, then rollback failed for ${R.failedFiles.join(", ")}: ${Fe(I)}`,rolledBack:!1}}return{ok:!0,snapshots:f.map(Cm)}}async function Rc(f){if(f.exists===!1){await n.deleteFile(f.file);return}await n.writeFile(f.file,f.content)}async function km(f){let y=[];for(let h of f)try{await Rc(h),typeof n.bumpVersion=="function"&&n.bumpVersion(h.file)}catch{y.push(h.file)}return y.length===0?{ok:!0}:{ok:!1,failedFiles:y}}function Cm(f){let y=f.exists!==!1;return{file:f.file,content:y?f.content:"",version:f.version,exists:y,...y?{sha256:ue(f.content)}:{}}}async function fn(f){return S.runExclusive(()=>Rm(f))}async function Rm(f){let y=f.filePlan.edits.map(_=>_.file),h=o.resolveSelector(f.request.composition).context,I=f.historyPolicy==="none"?void 0:{initiatingComposition:h,affectedCompositions:um(y)},R=await Ei(y),A=new Map(R.filter(_=>_.exists!==!1).map(_=>[_.file,_.content])),F=Nc(),L=new Map(d),T=new Set(p),$=new Set([...i.values()].filter(_=>f.filePlan.edits.some(j=>j.operation==="delete"&&j.file===_.entryFile)).map(_=>_.key)),K=f.filePlan.edits.map(_=>_.operation==="delete"?{file:_.file,content:"",version:0,exists:!1}:{file:_.file,content:_.content,version:0,exists:!0,sha256:ue(_.content)}),me={operationId:f.filePlan.operationId,intents:f.filePlan.edits.map(_=>_.operation==="delete"?{kind:"delete",path:_.file}:{kind:_.operation==="create-only"?"create-only":"upsert",path:_.file,content:_.content})},Q=null,Ie=!1,Y=await Yo({overlay:A,exists:_=>n.exists(_),plan:me,buildCandidate:async({plan:_})=>({plan:_}),prepareHistory:async()=>{let _=f.historyPolicy==="none"?null:await l.prepareAppend({composition:o.resolveSelector(f.request.composition).context,operationId:f.request.id,kind:f.request.kind,target:f.request.target,preSnapshots:R,postSnapshots:K,...f.selectionRef?{selectionRef:f.selectionRef}:{},...f.output?{output:f.output}:{},...I?{provenance:I}:{}}),j=_?.historyTransition?_.historyTransition:e.historyStore?mv(await e.historyStore.readIndex()):null;if(e.historyStore&&!j)throw new Error("Durable history did not provide an exact index transition.");return Q=await kc(f.request.id,R,K,j),Q=await Cc(Q),{history:_,historyTransition:j}},reverify:async()=>{},writeCandidate:async()=>{let _=await u.executeFilePlan(f.filePlan);if(!_.ok)throw new ti(_);return{postSnapshots:await Ei(_.affectedFiles),affectedFiles:_.affectedFiles,internalResultVersion:_.resultVersion}},validateCandidate:async({candidate:_,receipt:j})=>{let z=await Br(j.affectedFiles,{changed:!0,minimumVersion:j.internalResultVersion,publish:!1,excludedCompositionKeys:$});if(z.failedRoutes.length>0)throw new an(z.failedRoutes);let oe=Pc(F,z.candidateRouteStates??[]),Se=Math.max(j.internalResultVersion,...z.rebuiltRoutes.map(Je=>Je.version));return{..._,rebuild:z,routeSnapshots:oe,resultVersion:Se,...gp(f.selectionRef,oe.map(Je=>Je.state.document))?{selectionRef:gp(f.selectionRef,oe.map(Je=>Je.state.document))}:{}}},publishCandidate:async({candidate:_,history:j,receipt:z})=>{j?.history&&(await l.publishPrepared(j.history),Ie=!0);let oe=_.resultVersion??z.internalResultVersion;return{composition:o.resolveSelector(f.request.composition).context,requestId:f.request.id,kind:f.request.kind,target:f.request.target,ok:!0,resultVersion:oe,affectedFiles:z.affectedFiles,...f.output?{output:f.output}:{},..._.selectionRef?{selectionRef:_.selectionRef}:{}}},swapCandidate:({candidate:_,receipt:j})=>{_.routeSnapshots&&jr(_.routeSnapshots),_.rebuild?.candidateSourceCache&&Bn(d,_.rebuild.candidateSourceCache),bc(j.postSnapshots)},finalizeCandidate:async()=>{await dn(Q);for(let _ of $)i.delete(_)},emitCommitted:({candidate:_,published:j})=>{Si(j,_.rebuild??{rebuiltRoutes:[],failedRoutes:[]})},rollbackCandidate:async({history:_,receipt:j})=>{if(Ie)throw new Error("history was published before transaction finalization failed");if(j){let z=await Ii(R,j.postSnapshots);if(!z.ok)throw new Error(z.reason)}jr(F),Bn(d,L),Ec(T),_?.history&&await l.discardPrepared?.(_.history),await dn(Q)}});if(Y.ok)return Y.published;if(Y.stage==="precheck"||Y.stage==="build")try{await dn(Q)}catch(_){let j=await $r(Fe(_));return ee(f.request,j,"Unable to clear an uncommitted transaction journal.")}if(Y.recoveryRequired){let _=await $r(Y.reason);return ee(f.request,_===O.RECOVERY_PERSIST_FAILED?_:O.ROLLBACK_FAILED,Y.reason)}let ge=Y.error;return ge instanceof ti?{...ee(f.request,wr(ge.result.errorCode),ge.result.reason),...ge.result.affectedFiles?{affectedFiles:ge.result.affectedFiles}:{}}:ge instanceof an?ee(f.request,O.ROUTE_REBUILD_FAILED,`Route rebuild failed and source was rolled back: ${Da(ge.failedRoutes)}`,{failedRoutes:ge.failedRoutes}):ee(f.request,Tc(Y.stage),Fe(ge))}async function wc(f){return S.runExclusive(async()=>{let y=f==="undo"?await l.prepareUndo():await l.prepareRedo();return y?wm(f,y):{composition:o.entries[0].context,requestId:f,kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:o.initialVersions.get(o.entries[0].key)??0,error:{code:O.INTERNAL_ERROR,message:f==="undo"?"Nothing to undo":"Nothing to redo"}}})}async function wm(f,y){let h=y.entry,I=f==="undo"?h.preSnapshots:h.postSnapshots,R=f==="undo"?h.postSnapshots:h.preSnapshots,A=I.map(z=>z.file),{context:F,key:L}=fm(h,A),T=await Ei(A),$=new Map(T.filter(z=>z.exists!==!1).map(z=>[z.file,z.content])),K=he(L),me=Nc(),Q=new Map(d),Ie=new Set(p),Y=null,ge=!1,_,j=await Yo({overlay:$,plan:{operationId:`${f}:${h.operationId}`,intents:I.map(z=>z.exists===!1?{kind:"delete",path:z.file}:{kind:"upsert",path:z.file,content:z.content})},buildCandidate:async()=>({}),prepareHistory:async()=>(Y=await kc(`${f}:${h.operationId}`,T,I,y.historyTransition),Y=await Cc(Y),y),reverify:async()=>{},writeCandidate:async()=>{let z=await Ii(I,R);if(!z.ok)throw new Error(z.reason);return{snapshots:z.snapshots}},validateCandidate:async({candidate:z})=>{_=dm(h,A);let oe=await Br(A,{changed:!0,minimumVersion:K+1,publish:!1,affectedCompositionKeys:_});if(oe.failedRoutes.length>0)throw new an(oe.failedRoutes);let Se=Pc(me,oe.candidateRouteStates??[]),Je=Math.max(K+1,...oe.rebuiltRoutes.map(pn=>pn.version));return{...z,rebuild:oe,routeSnapshots:Se,resultVersion:Je}},publishCandidate:async({candidate:z,history:oe})=>{if(!oe)throw new Error("history cursor intent is missing");await l.publishPrepared(oe),ge=!0;let Se=z.resultVersion??K+1;return{composition:F,requestId:f,kind:h.kind,target:h.target,ok:!0,resultVersion:Se,affectedFiles:A,...h.output?{output:h.output}:{}}},swapCandidate:({candidate:z,receipt:oe})=>{z.routeSnapshots&&jr(z.routeSnapshots),z.rebuild?.candidateSourceCache&&Bn(d,z.rebuild.candidateSourceCache),bc(oe.snapshots)},finalizeCandidate:async()=>{await dn(Y)},emitCommitted:({candidate:z,published:oe})=>Si(oe,z.rebuild??{rebuiltRoutes:[],failedRoutes:[]}),rollbackCandidate:async({history:z,receipt:oe})=>{if(ge)throw new Error("history cursor was published before transaction finalization failed");if(oe){let Se=await Ii(R,oe.snapshots);if(!Se.ok)throw new Error(Se.reason)}jr(me),Bn(d,Q),Ec(Ie),z&&await l.discardPrepared?.(z),await dn(Y)}});if(j.ok)return j.published;if(j.stage==="precheck"||j.stage==="build")try{await dn(Y)}catch(z){let oe=await $r(Fe(z));return{composition:F,requestId:f,kind:h.kind,target:h.target,ok:!1,resultVersion:K,error:{code:oe,message:"Unable to clear an uncommitted transaction journal."}}}if(j.recoveryRequired){let z=await $r(j.reason);return{composition:F,requestId:f,kind:h.kind,target:h.target,ok:!1,resultVersion:K,affectedFiles:A,error:{code:z===O.RECOVERY_PERSIST_FAILED?z:O.ROLLBACK_FAILED,message:j.reason}}}return{composition:F,requestId:f,kind:h.kind,target:h.target,ok:!1,resultVersion:K,affectedFiles:A,error:{code:j.error instanceof an?O.ROUTE_REBUILD_FAILED:Tc(j.stage),message:Fe(j.error),...j.error instanceof an?{details:{failedRoutes:j.error.failedRoutes}}:{}}}}function Nc(){return[...i.values()].map(f=>({composition:f.composition,key:f.key,routeId:f.routeId,state:{...f,dependencyFiles:new Set(f.dependencyFiles),fileVersions:new Map(f.fileVersions)}}))}function Pc(f,y){let h=new Map(f.map(I=>[I.key,I]));for(let I of y)h.set(I.key,I);return[...h.values()]}function jr(f){for(let y of i.values())N(y);for(let y of f){let h={...y.state,dependencyFiles:new Set(y.state.dependencyFiles),fileVersions:new Map(y.state.fileVersions)};i.set(y.key,h),ne(h,h.dependencyFiles)}}async function vi(f){let y=i.get(f);if(!y)throw new Error(`Composition not found: ${f}`);if(y.graph)return;let h=await n.readFile(y.entryFile);await q(f,h)}function Vn(f,y){let h=i.get(o.resolveSelector(y).key)??null;return!h||!Ac(h,f)?null:h}function Ac(f,y){if(f.documentIndex?.entriesByKey.has(y)||f.graph?.elements.has(y))return!0;let h=$e(y);return h&&h!==y?f.graph?.elements.has(h)===!0:!1}function ee(f,y,h,I){return{composition:o.resolveSelector(f.composition).context,requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:H(f),error:{code:y,message:h,...I?{details:I}:{}}}}function Tc(f){return f==="validate"?O.ROUTE_REBUILD_FAILED:f==="publish"?O.HISTORY_COMMIT_FAILED:O.WRITE_IO_ERROR}async function $r(f){if(g=!0,!l.markRecoveryRequired)return O.RECOVERY_REQUIRED;try{return await l.markRecoveryRequired(f),O.RECOVERY_REQUIRED}catch{return O.RECOVERY_PERSIST_FAILED}}function Nm(f){let h=f.split(/[^a-zA-Z0-9]+/).filter(Boolean).map(I=>I.charAt(0).toUpperCase()+I.slice(1)).join("").replace(/^[^a-zA-Z_$]+/,"");return h?`Prefab${h}`:"GeneratedPrefab"}function _c(f){return f==="VERSION_STALE"?O.VERSION_STALE:f==="CROSS_PAGE_MOVE_UNSUPPORTED"?O.CROSS_PAGE_MOVE_UNSUPPORTED:O.UNSUPPORTED_OPERATION}async function Fc(f){if(f.target.kind==="route"){let h=i.get(o.resolveSelector(f.target.composition).key)??null;return h?(h.graph||await vi(h.key),h):ee(f,O.ROUTE_NOT_FOUND,"Composition not found for route target.")}if(f.target.kind==="page-unit"){let h=i.get(o.resolveSelector(f.target.composition).key)??null;return h?(h.graph||await vi(h.key),h):ee(f,O.ROUTE_NOT_FOUND,"Composition not found for page-unit target.")}if(f.target.kind!=="node")return ee(f,O.UNSUPPORTED_OPERATION,`${f.kind} source target execution is not implemented yet.`);let y=i.get(o.resolveSelector(f.composition).key)??null;return y?(y.graph||await vi(y.key),Ac(y,f.target.key)?y:ee(f,O.NODE_NOT_FOUND,`Target key not found: ${f.target.key}`)):ee(f,O.ROUTE_NOT_FOUND,"Composition not found for node target.")}return{get status(){return t},dispose(){t="disposed",a.clear(),i.clear(),s.clear(),d.clear(),p.clear()},registerComposition(f,y){let h=o.register({context:f,entryFile:y}),I=i.get(h.key);if(I?.entryFile===y)return;I&&N(I);let R=mp(h.context,y);i.set(h.key,R),ne(R,R.dependencyFiles),r.emit({type:"graph-invalidated",composition:h.context})},unregisterComposition(f){let y=o.resolveSelector(f),h=i.get(y.key);h&&(N(h),i.delete(y.key),o.unregister(y.key),i.size===0&&(t="idle"),r.emit({type:"graph-invalidated",composition:y.context}))},getCompositionEntryFiles(){return[...i.values()].map(f=>f.entryFile)},getCompositionContext(f){return o.resolveSelector(f).context},async initializeComposition(f){let y=o.resolveSelector(f),h=i.get(y.key);if(!h)throw new Error(`Composition not registered: ${y.key}`);if(h.graph)t="ready";else{t="building";try{let I=await n.readFile(h.entryFile);await q(y.key,I),t="ready",r.emit({type:"graph-ready",composition:y.context,version:i.get(y.key)?.graph?.version??0})}catch(I){throw t="idle",r.emit({type:"graph-error",composition:y.context,message:Fe(I)}),I}}},getDocument(f){let y=o.resolveSelector(f),h=i.get(y.key);if(!h)throw new Error(`Composition not registered: ${y.key}`);if(!h.document)throw new Error(`Composition not built: ${y.key}`);return h.document},async getHistoryStatus(){await C;let f=await l.getStatus?.();return f?{...f,recoveryRequired:g}:{canUndo:!1,canRedo:!1,undoDepth:0,redoDepth:0,recoveryRequired:g}},getObjectEditContext(f,y){let h=Vn(f,y),I=$e(f)??f;if(h?.graph&&h.topology&&h.capabilities&&h.detailProjections){let R=h.detailProjections.get(I);if(R){let A=Wl(I,h.graph,h.topology,h.capabilities,R.textSources,R.provenances,R.dynamicData);return f===I?A:Hv(A,f,h.document??null,h.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${f}`)},getRenderDetail(f,y){let h=Vn(f,y),I=$e(f)??f;if(h?.graph&&h.topology&&h.capabilities&&h.detailProjections){let R=h.detailProjections.get(I);if(R){let A=zl(I,h.graph,h.topology,h.capabilities,R.textSources,R.writeTarget,R.provenances,R.conditional,R.componentSemantic,R.contentModel,R.mediaModel,R.styleSource,R.dynamicData);return f===I?A:Wv(A,f,h.document??null,h.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${f}`)},getClassNameSource(f,y){let h=Vn(f,y),I=$e(f)??f;if(!h?.graph)throw new Error(`Key not found: ${f}`);let R=h.graph.elements.get(I);if(!R)throw new Error(`Key not found: ${f}`);let A=d.get(R.sourceFile);if(A===void 0)throw new Error(`Source not loaded: ${R.sourceFile}`);return uu({key:I,route:{composition:h.composition,routeId:h.routeId,graph:h.graph,source:A}})},refreshSourceForKey:mm,async execute(f){if(await C,g)return ee(f,O.RECOVERY_REQUIRED,"The edit engine requires explicit recovery before accepting mutations.");if(f.kind==="source-edit")return gm(f);if(f.kind==="insert-page-resource")return hm(f);if(f.kind==="delete-page-source")return ym(f);let y=await Fc(f);if("ok"in y)return y;await vc(f);let h=await Fc(f);if("ok"in h)return h;let I=h;if(f.target.kind==="page-unit"){let L=f;return f.kind==="insert-child"?xm(L,I):f.kind==="move-node"||f.kind==="remove-node"?Sm(L,I):ee(f,O.UNSUPPORTED_OPERATION,"Only page-unit insert-child, move-node, and remove-node are currently supported by the page composition transaction.")}if(!I.graph||!I.topology||!I.capabilities)return{composition:o.resolveSelector(f.composition).context,requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:H(f),error:{code:f.target.kind==="route"?O.ROUTE_NOT_FOUND:O.NODE_NOT_FOUND,message:f.target.kind==="route"?"Composition not ready for route target.":f.target.kind==="node"?`Target key not found: ${f.target.key}`:`${f.kind} source target execution is not implemented yet.`}};let R=Mv(I,I.graph,I.capabilities,d,i),A=await new _o(R).plan(f);if(!A.ok)return{composition:o.resolveSelector(f.composition).context,requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:H(f),error:{code:wr(A.errorCode),message:A.reason}};let F=A.plan;if(F.steps.length===0)return f.kind==="set-props"?{composition:o.resolveSelector(f.composition).context,requestId:f.id,kind:f.kind,target:f.target,ok:!0,resultVersion:H(f),affectedFiles:[]}:{composition:o.resolveSelector(f.composition).context,requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:H(f),error:{code:O.PLAN_FAILED,message:"Planner could not generate a valid execution plan"}};m+=1;try{if(F.steps.some(T=>T.type==="invoke-external-adapter")){let T=await u.execute(F);if(!T.ok)return ee(f,wr(T.errorCode),T.reason);let $={composition:o.resolveSelector(f.composition).context,requestId:f.id,kind:f.kind,target:f.target,ok:!0,resultVersion:Math.max(H(f),T.resultVersion),affectedFiles:T.affectedFiles,...T.selectionRef?{selectionRef:T.selectionRef}:{}};return Si($,{rebuiltRoutes:[],failedRoutes:[]}),$}let L=await u.prepareRewritePlan(F);return L.ok?await fn({request:f,filePlan:L.filePlan,...L.selectionRef?{selectionRef:L.selectionRef}:{}}):ee(f,wr(L.errorCode),L.reason)}catch(L){return{composition:o.resolveSelector(f.composition).context,requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:H(f),error:{code:O.INTERNAL_ERROR,message:Fe(L)}}}finally{m-=1}},async undo(f){if(await C,g)return{composition:o.entries[0].context,requestId:"undo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:he(o.entries[0].key),error:{code:O.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting undo."}};m+=1;try{return await wc("undo")}finally{m-=1}},async redo(f){if(await C,g)return{composition:o.entries[0].context,requestId:"redo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:he(o.entries[0].key),error:{code:O.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting redo."}};m+=1;try{return await wc("redo")}finally{m-=1}},notifyFileChanged(f){xc([f])},getAffectedCompositions(f){return lm(f)},subscribe(f){return r.subscribe(f)}}}function Tv(e){return e instanceof Error&&"code"in e&&(e.code==="ENOENT"||e.code==="ENOTDIR")}function _v(e,t,n){let r=new Map,o=new Map,i=(u,d,p)=>{let m=u.get(d)??new Set,g=m.size;return m.add(p),u.set(d,m),m.size!==g},s=(u,d)=>{if(!u.importedFrom)return!1;if(u.exportName==="default")return i(o,u.importedFrom,d);let p=i(r,`${u.importedFrom}#${u.tag}`,d);return u.exportName&&u.exportName!==u.tag&&(p=i(r,`${u.importedFrom}#${u.exportName}`,d)||p),p},a=u=>r.get(`${u.sourceFile}#${u.componentName}`)??o.get(u.sourceFile);for(let u of t.elements.values()){if(u.sourceFile!==n.entryFile||!u.importedFrom||!/^[A-Z]/.test(u.tag))continue;let d=n.placements.find(m=>m.members.some(g=>g.sourceRange!==null&&La(u.sourceRange,g.sourceRange)));if(!d)continue;let p=d.placementUnitKey;s(u,p)}let c=!0;for(;c;){c=!1;for(let u of t.elements.values()){if(u.sourceFile===n.entryFile||!u.importedFrom||!/^[A-Z]/.test(u.tag))continue;let d=a(u);if(d)for(let p of d)c=s(u,p)||c}}let l=n.placements.find(u=>u.placementKey===n.container.placementKey&&u.relation==="append");for(let u of e.entries){let d=$e(u.key)??u.key,p=t.elements.get(u.key)??t.elements.get(d);if(!p)continue;if(p.sourceFile===n.entryFile){if(n.container.sourceRange&&La(p.sourceRange,n.container.sourceRange)&&l){u.pageCompositionUnitKey=l.placementUnitKey;continue}let S=n.placements.find(C=>C.members.some(v=>v.sourceRange!==null&&(La(p.sourceRange,v.sourceRange)||Fv(v.sourceRange,p.sourceRange))));if(S){u.pageCompositionUnitKey=S.placementUnitKey;continue}}let m=r.get(`${p.sourceFile}#${p.componentName}`);if(m){m.size===1&&(u.pageCompositionUnitKey=m.values().next().value);continue}let g=o.get(p.sourceFile);g?.size===1&&(u.pageCompositionUnitKey=g.values().next().value)}}function La(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function Fv(e,t){return yp(e.startLine,e.startColumn,t.startLine,t.startColumn)<=0&&yp(e.endLine,e.endColumn,t.endLine,t.endColumn)>=0}function yp(e,t,n,r){return e!==n?e-n:t-r}function Mv(e,t,n,r,o){let i=new Map,s=new Map,a=(u,d)=>{if(s.has(u))return;s.set(u,d);let p=t.elements.get(u);for(let m of p?.childKeys??[])a(m,d)};for(let u of t.regions)if(u.kind==="repeat-region")for(let d of u.childKeys)i.set(d,u.ownerKey),a(d,u.ownerKey);return{getNode(u){let d=c(u),p=t.elements.get(d.baseKey);return p?l(u,p):null},getChildNodes(u){let d=c(u),m=e.documentIndex?.entriesByKey.get(u)?.childKeys;if(m)return m.map(S=>{let C=$e(S)??S,v=t.elements.get(C);return v?l(S,v):null}).filter(S=>S!==null);let g=t.elements.get(d.baseKey);return g?g.childKeys.map(S=>{let C=t.elements.get(S);return C?l(S,C):null}).filter(S=>S!==null):[]},getKnownSourceFiles(){return[...r.entries()].map(([u,d])=>({file:u,content:d}))},getRouteEntryFiles(){return[...o.values()].map(u=>u.entryFile)},getCapability(u){let d=c(u),p=n.get(d.baseKey);return p?{...p,key:u,constraints:p.constraints.map(m=>({...m})),...p.editModes?{editModes:{...p.editModes}}:{}}:{composition:e.composition,key:u,canUpdateText:!1,canRemove:!1,canInsertChild:!1,canMove:!1,constraints:[]}},getFileContent(u){return r.get(u)??""},getFileVersion(u){return Math.max(e.fileVersions.get(u)??0,t.version)},getRouteEntryFile(u){return e.routeId===u?e.entryFile:null},getComponentSemantic(u){let d=c(u);return e.detailProjections?.get(d.baseKey)?.componentSemantic??null},getEditableTextSegmentIndex(u){let d=c(u),m=e.detailProjections?.get(d.baseKey)?.textTargets.keys()?.next();return m&&!m.done?m.value:null},async getTextWriteTarget(u,d){let p=c(u);return bp(e.detailProjections?.get(p.baseKey)?.textTargets.get(d)??null,p.repeatIndex)},async getElementPropertyWriteTarget(u,d){let p=c(u);return bp(e.detailProjections?.get(p.baseKey)?.elementPropertyTargets.get(d)??null,p.repeatIndex)},getTextProvenance(u,d){let p=c(u);return e.detailProjections?.get(p.baseKey)?.provenances.get(d)??null}};function c(u){let d=lv(u);return d?{baseKey:d.baseKey,repeatIndex:Jv(e.document??null,u,d.baseKey,e.documentIndex)??Kv(d)}:{baseKey:u,repeatIndex:null}}function l(u,d){let p=$e(u)??u,m=e.documentIndex?.entriesByKey.get(u),g=e.detailProjections?.get(p);return{key:u,file:d.sourceFile,component:d.componentName,tag:d.tag,structuralPath:d.identity.structuralPath,sourceRange:d.sourceRange,parentKey:m?.parentKey??d.parentKey??void 0,isRepeatRegion:d.boundaryKind==="repeat-region"||s.has(p),isBoundary:!1,importedFrom:d.importedFrom,exportName:d.exportName,isRepeatItemRoot:i.has(p),repeatOwnerKey:i.get(p)??s.get(p),contentModel:g?.contentModel,attributes:d.attributes?.map(S=>({name:S.name,value:S.value,source:S.source?{expression:S.source.expression,base:S.source.base,path:S.source.path.map(C=>({...C}))}:null,resolvedValue:S.resolvedValue}))}}}var Ov={"stale-version":O.VERSION_STALE,"capability-denied":O.CAPABILITY_REJECTED,"invalid-params":O.INVALID_PARAMS,"locator-miss":O.LOCATOR_FAILED,"route-not-found":O.ROUTE_NOT_FOUND,"unsupported-operation":O.UNSUPPORTED_OPERATION,"invalid-target":O.INVALID_TARGET,"ast-error":O.AST_PARSE_ERROR,"writeback-failed":O.WRITE_IO_ERROR,"rollback-failed":O.RECOVERY_REQUIRED,unknown:O.INTERNAL_ERROR};function wr(e){return Ov[e]}function Fe(e){return e instanceof Error&&e.message?e.message:String(e)}function xp(e){return/\.(?:[cm]?[jt]sx?|css|scss|sass|mdx|json)$/i.test(e)}function Dv(e){let t=cn(e);if(!fv.test(t))return[];let n=t.startsWith("src/app/")?"src/app":"app",r=t.slice(0,t.lastIndexOf("/")),o=[],i=r;for(;(i===n||i.startsWith(`${n}/`))&&(o.unshift(i),i!==n);)i=i.slice(0,i.lastIndexOf("/"));return o.flatMap(s=>pv.map(a=>`${s}/${a}`))}function Lv(e){let n=cn(e).startsWith("src/app/")?"src/app":"app";return[`${n}/globals.css`,`${n}/global.css`]}function Bv(e){return Ip(e,/\bimport\s+(?:[^'";]+?\s+from\s+)?["']([^"']+\.css(?:\?[^"']*)?)["']/g)}function jv(e){return Ip(e,/@import\s+(?:url\(\s*)?["']([^"']+)["']/g)}function Ip(e,t){let n=[];for(let r of e.matchAll(t)){let o=vp(r[1]??"");o&&n.push(o)}return n}function Sp(e,t){let n=vp(t);return!n||n.startsWith("tailwindcss")||n.startsWith("http:")||n.startsWith("https:")?null:n.startsWith("@/")?cn(`src/${n.slice(2)}`):n.startsWith("./")||n.startsWith("../")?cn(`${$v(e)}/${n}`):n.startsWith("/")?cn(n.slice(1)):Ba(n)?cn(n):null}function vp(e){return e.split(/[?#]/,1)[0]?.trim()??""}function Ba(e){return/\.css$/i.test(e)}function $v(e){let t=cn(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function kp(e){return Array.from(new Set(e))}function cn(e){let t=e.replace(/\\/g,"/").replace(/^\.\//,""),n=[];for(let r of t.split("/"))if(!(!r||r===".")){if(r===".."){n.pop();continue}n.push(r)}return n.join("/")}function Vv(e){let t=1;for(let n of e?.textTargets.values()??[])n?.kind==="value-binding"&&n.sourceKind==="repeat-template"&&(t=Math.max(t,n.collectionIndexMap?.length??0,n.collectionPathMap?.length??0));return t}function ei(e){return e?.map(t=>({...t}))}function bp(e,t){if(t===null||e?.kind!=="value-binding"||e.sourceKind!=="repeat-template")return e;let n=e.collectionIndexMap?.[t]??t,r=ei(e.collectionPathMap?.[t])??ei(e.locator?.path);if(r)for(let o=r.length-1;o>=0;o-=1){let i=r[o];if(i.kind==="index"){i.index=n;break}}return{...e,path:ei(e.path),locator:e.locator?{...e.locator,path:r}:e.locator,collectionIndexMap:e.collectionIndexMap?[...e.collectionIndexMap]:void 0,collectionPathMap:e.collectionPathMap?.map(o=>ei(o)??[])}}function Uv(e,t,n){let r=new Set;for(let m of t.regions)if(m.kind==="repeat-region")for(let g of m.childKeys)r.add(g);if(r.size===0)return e;let o=new Map(e.entries.map(m=>[m.key,m])),i=[],s=new Map,a=(m,g)=>sv(m,g),c=(m,g,S)=>{let C=o.get(m);if(!C)return a(m,S);let v=a(m,S),P={...C,key:v,parentKey:g,childKeys:[]};return i.push(P),P.childKeys=C.childKeys.flatMap(w=>l(w,S,v)),v},l=(m,g,S)=>{if(!r.has(m))return[c(m,S,g)];let C=d(m,g),v=[];for(let P=0;P<C;P+=1)v.push(c(m,S,[...g,P]));return v},u=kp([...e.rootKeys,...e.entries.filter(m=>m.parentKey===null).map(m=>m.key)]);for(let m of u){if(!r.has(m)){c(m,null,[]);continue}let g=d(m,[]);for(let S=0;S<g;S+=1)c(m,null,[S])}return{...e,rootKeys:[...e.rootKeys],entries:i};function d(m,g){let S=new Set;for(let C of p(m)){let v=n.get(C);if(v){for(let P of[...v.textTargets.values(),...v.elementPropertyTargets.values()])if(!(P?.kind!=="value-binding"||P.sourceKind!=="repeat-template"))for(let w of Xv(P))w.length<=g.length||zv(w,g)&&S.add(w[g.length])}}return S.size>0?S.size:Vv(n.get(m))}function p(m){let g=s.get(m);if(g)return g;let S=[m],C=o.get(m);for(let v of C?.childKeys??[])S.push(...p(v));return s.set(m,S),S}}function Kv(e){let t=e.parts.at(-1);return typeof t?.repeatIndex=="number"?t.repeatIndex:null}function Jv(e,t,n,r){let o=r?.repeatOccurrenceIndexByKey.get(t);if(o!==void 0)return o;if(!e)return null;let i=0;for(let s of e.entries)if(($e(s.key)??s.key)===n){if(s.key===t)return i;i+=1}return null}function Xv(e){return e.collectionPathMap?.length?e.collectionPathMap.map(t=>t.filter(n=>n.kind==="index").map(n=>n.index)):e.collectionIndexMap?.length?e.collectionIndexMap.map(t=>[t]):[]}function zv(e,t){if(t.length>e.length)return!1;for(let n=0;n<t.length;n+=1)if(e[n]!==t[n])return!1;return!0}function Wv(e,t,n,r){if(!n)return{...e,key:t};let o=r??new Map(n.entries.map(u=>[u.key,u])),i=o.get(t);if(!i)return{...e,key:t};let s=[],a=i.parentKey;for(;a;){let u=o.get(a);if(!u)break;s.push({key:u.key,tag:u.tag,label:u.label}),a=u.parentKey}s.reverse();let c=i.childKeys.map(u=>o.get(u)).filter(u=>u!==void 0).map(u=>({key:u.key,tag:u.tag,label:u.label})),l=i.parentKey===null?[]:(o.get(i.parentKey)?.childKeys??[]).filter(u=>u!==i.key).map(u=>o.get(u)).filter(u=>u!==void 0).map(u=>({key:u.key,tag:u.tag,label:u.label}));return{...e,key:i.key,ancestors:s,children:c,siblings:l}}function Hv(e,t,n,r){if(!n)return{...e,key:t};let o=r??new Map(n.entries.map(c=>[c.key,c])),i=o.get(t);if(!i)return{...e,key:t};let s=[],a=i.parentKey;for(;a;){let c=o.get(a);if(!c)break;s.push({key:c.key,tag:c.tag,label:c.label}),a=c.parentKey}return s.reverse(),{...e,key:i.key,ancestors:s}}import Ka from"node:path";import{TextDecoder as Gv}from"node:util";import{SITE_EDIT_SOURCE_ALLOWED_APP_FILES as Rp,SITE_EDIT_SOURCE_ALLOWED_DIRS as wp,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as Np,SiteEditCompositionContextSchema as Yv,SiteEditSourceFileResponseSchema as ja,SiteEditSourceLocationSchema as Zv,SiteEditSourcePathSchema as ni,SiteEditSourceTreeResponseSchema as Qv,isSiteEditTextSourcePath as qv}from"@vcp-dev/contracts";var ek=[...Np,...Rp,...wp];function Ja(e){if(!e.composition)throw new Error("Composition unavailable for source access policy.");return Yv.parse(e.composition)}var $a=2e3,Va=12,Ua=24*1024*1024,Cp=512*1024,tk=new Set(["image/avif","image/gif","image/jpeg","image/png","image/webp","image/x-icon"]),nk={".avif":"image/avif",".bin":"application/octet-stream",".eot":"application/vnd.ms-fontobject",".gif":"image/gif",".glb":"model/gltf-binary",".ico":"image/x-icon",".jpeg":"image/jpeg",".jpg":"image/jpeg",".mp3":"audio/mpeg",".mp4":"video/mp4",".pdf":"application/pdf",".png":"image/png",".svg":"image/svg+xml",".ttf":"font/ttf",".wasm":"application/wasm",".webm":"video/webm",".webp":"image/webp",".woff":"font/woff",".woff2":"font/woff2",".zip":"application/zip"},rk={".cjs":"javascript",".css":"css",".cts":"typescript",".html":"html",".js":"javascript",".jsx":"javascript",".json":"json",".md":"markdown",".mdx":"markdown",".mjs":"javascript",".mts":"typescript",".ts":"typescript",".tsx":"typescript",".txt":"plaintext",".yaml":"yaml",".yml":"yaml"},ok=new Gv("utf-8",{fatal:!0});async function ri(e,t={}){let n=Ja(t),{files:r,truncated:o}=await fk(e,t),i=gk(r.map(s=>s.metadata));return Qv.parse({composition:n,nodes:i,defaultPath:hk(r.map(s=>s.metadata)),totalFiles:r.length,...o?{truncated:o}:{}})}async function oi(e,t,n={}){let r=Ja(n),o=ni.parse(t.path),i=await ak(e,o,n);if(!i)throw new Error(`Source file not found: ${o}`);if(Xa(o)){let a=Tp(o),c=await lk(e,{path:o,sizeBytes:i.sizeBytes,mimeType:a});return ja.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:i.sizeBytes,mimeType:a,readonly:!0,...c})}let s=await ik(e,o);return s.ok?ja.parse({composition:r,path:o,kind:"text",language:_p(o),sizeBytes:s.sizeBytes,contentHash:ue(s.content),readonly:!1,content:s.content}):ja.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:s.sizeBytes,mimeType:"application/octet-stream",readonly:!0,previewUnavailableReason:"unsupported-mime"})}async function ik(e,t){if(e.readFileBytes){let o=await e.readFileBytes(t),i=sk(o);return i===null?{ok:!1,sizeBytes:o.byteLength}:{ok:!0,content:i,sizeBytes:o.byteLength}}let n=await e.readFile(t),r=Buffer.byteLength(n,"utf8");return n.includes("\0")?{ok:!1,sizeBytes:r}:{ok:!0,content:n,sizeBytes:r}}function sk(e){if(e.includes(0))return null;try{return ok.decode(e)}catch{return null}}async function ak(e,t,n){if(!uk(t,n))return null;let r=await ck(e,t);return r?{path:t,sizeBytes:r.sizeBytes}:null}async function ck(e,t){if(e.getFileInfo)return e.getFileInfo(t);if(e.listFiles){let o=Pp(await e.listFiles({roots:[t],maxFiles:1,maxDepth:t.split("/").length})).files.find(i=>i.path===t);if(o)return o}if(!await e.exists(t))return null;if(e.readFileBytes){let r=await e.readFileBytes(t);return{path:t,sizeBytes:r.byteLength}}if(Xa(t))return{path:t,sizeBytes:0};let n=await e.readFile(t);return{path:t,sizeBytes:Buffer.byteLength(n,"utf8")}}async function lk(e,t){if(!tk.has(t.mimeType))return{previewUnavailableReason:"unsupported-mime"};if(t.sizeBytes>Cp)return{previewUnavailableReason:"too-large"};if(!e.readFileBytes)return{previewUnavailableReason:"bytes-unavailable"};let n=await e.readFileBytes(t.path);return n.byteLength>Cp?{previewUnavailableReason:"too-large"}:{contentBase64:Buffer.from(n).toString("base64")}}function uk(e,t){return Np.some(n=>n===e)||Rp.some(n=>n===e)||wp.some(n=>e===n||e.startsWith(`${n}/`))?!0:!e.startsWith("app/")&&!e.startsWith("src/app/")?!1:(t.routeEntryFiles??[]).some(n=>{let r=ni.safeParse(n);return r.success&&r.data===e})}function ii(e,t){if(!t.sourceLocator)throw new Error(`Source location not available for key: ${e.key}`);return Zv.parse({key:e.key,composition:t.composition,sourceFile:t.sourceLocator.sourceFile,componentName:t.sourceLocator.componentName,openingElementRange:{startLine:t.sourceLocator.openingElementRange.startLine,startColumn:t.sourceLocator.openingElementRange.startColumn,endLine:t.sourceLocator.openingElementRange.endLine,endColumn:t.sourceLocator.openingElementRange.endColumn},structuralPath:t.sourceLocator.structuralPath,textPreview:t.sourceLocator.textPreview})}function Pp(e){return Array.isArray(e)?{files:e}:e}function dk(e){return["max-files","max-depth","max-total-bytes"].filter(n=>e.includes(n))}async function fk(e,t){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let n=Pp(await e.listFiles({roots:pk(t),maxFiles:$a+1,maxDepth:Va,maxTotalBytes:Ua+1})),r=new Map,o=new Set(n.truncated?.reasons),i=0;for(let a of[...n.files].sort((c,l)=>c.path.localeCompare(l.path))){let c=ni.safeParse(a.path);if(!c.success)continue;let l=c.data;if(l.split("/").length>Va){o.add("max-depth");continue}if(r.size>=$a){o.add("max-files");break}if(i+a.sizeBytes>Ua){o.add("max-total-bytes");break}r.set(l,{path:l,sizeBytes:a.sizeBytes,metadata:mk(l,a.sizeBytes,Ja(t))}),i+=a.sizeBytes}return{files:[...r.values()].sort((a,c)=>a.path.localeCompare(c.path)),...o.size>0?{truncated:{reasons:dk([...o]),maxFiles:$a,maxDepth:Va,maxTotalBytes:Ua}}:{}}}function pk(e){let t=new Set(ek);for(let n of e.routeEntryFiles??[]){let r=ni.safeParse(n);r.success&&(r.data.startsWith("app/")||r.data.startsWith("src/app/"))&&t.add(r.data)}return[...t]}function mk(e,t,n){return Xa(e)?{composition:n,path:e,kind:"binary",language:null,sizeBytes:t,mimeType:Tp(e),readonly:!0}:{composition:n,path:e,kind:"text",language:_p(e),sizeBytes:t,readonly:!1}}function gk(e){let t=[];for(let n of e){let r=n.path.split("/"),o=t,i="";for(let[s,a]of r.entries()){i=i?`${i}/${a}`:a;let c=s===r.length-1,l=o.find(u=>u.name===a);if(l||(l=c?{kind:"file",name:a,path:i,file:n}:{kind:"directory",name:a,path:i,children:[]},o.push(l)),c){if(l.kind!=="file")throw new Error(`Source tree path collision: ${n.path}`);l.file=n}else{if(l.kind!=="directory")throw new Error(`Source tree path collision: ${n.path}`);o=l.children}}}return Ap(t)}function Ap(e){return e.map(t=>t.kind==="directory"?{...t,children:Ap(t.children)}:t).sort((t,n)=>t.kind!==n.kind?t.kind==="directory"?-1:1:t.name.localeCompare(n.name))}function hk(e){let t=e.find(r=>r.path.toLowerCase()==="design.md");if(t)return t.path;let n=e.find(r=>r.path==="app/page.tsx");return n?n.path:e.find(r=>r.kind==="text")?.path??e.at(0)?.path}function Xa(e){return!qv(e)}function Tp(e){let t=Ka.posix.extname(e).toLowerCase();return!t&&Ka.posix.basename(e).toLowerCase()==="favicon"?"image/x-icon":nk[t]??"application/octet-stream"}function _p(e){let t=Ka.posix.extname(e).toLowerCase();return rk[t]??"plaintext"}var si=class{constructor(t){this.options=t,this.fileSystem=new er(t.files),this.engine=this.createEngine(this.fileSystem)}get status(){return this.engine.status}initializeComposition(t){return this.engine.initializeComposition(t)}getDocument(t){return Ur(this.engine.getDocument(t),{siteId:this.options.siteId,snapshotId:this.options.snapshotId})}getInternalDocument(t){return this.engine.getDocument(t)}getStyleContext(t){return this.engine.getDocument(t).styleContext??null}getObjectEditContext(t,n){return Kr(this.engine.getObjectEditContext(t,n))}getClassNameSource(t,n){return this.engine.getClassNameSource(t,n)}getSourceTree(t){return ri(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}getSourceFile(t){return oi(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}resolveSourceLocation(t){return ii(t,this.engine.getRenderDetail(t.key,t.composition))}async planOperation(t){let n=xk.safeParse(t);if(!n.success)return{result:Vr(t,n.error.issues.map(i=>i.message))};let r=new er(this.options.files),o=this.createEngine(r,{emitEvents:!1});try{let i=await o.execute(n.data);if(!i.ok)return{result:{ok:!1,composition:i.composition,error:{code:i.error?.code??"INTERNAL_ERROR",message:i.error?.message??"Operation failed"},data:{requestId:i.requestId,kind:i.kind,target:i.target,resultVersion:i.resultVersion}}};let s={ok:!0,composition:i.composition,data:Ut(i)},a=r.getChangedFiles();if(a.length===0)return{result:s};let c=Sk.parse({siteId:t.siteId,baseSnapshotId:t.baseSnapshotId,operationId:t.id,reason:`site-edit:${t.kind}`,patches:a.map(l=>bk(l,t.kind==="source-edit")),changedCompositions:o.getAffectedCompositions(a.map(l=>l.path)),diagnostics:[]});return this.options.onEvent?.({type:"site-edit.operation.planned",siteId:t.siteId,operationId:t.id,baseSnapshotId:t.baseSnapshotId,changedFiles:c.patches.map(l=>l.path),composition:i.composition,at:new Date().toISOString()}),{result:s,patchPlan:c}}finally{o.dispose()}}dispose(){this.engine.dispose()}createEngine(t,n={}){let r=n.emitEvents??!0;return Nr({projectRoot:"/snapshot",fileSystem:t,compositions:this.options.compositions,onEvent:r&&this.options.onEvent?o=>{let i=Jr(o,{siteId:this.options.siteId,snapshotId:this.options.snapshotId});i&&this.options.onEvent?.(i)}:void 0,dev:this.options.dev,...this.options.historyStore?{historyStore:this.options.historyStore}:{},...this.options.tenantId?{tenantId:this.options.tenantId}:{},siteId:this.options.siteId,snapshotId:this.options.snapshotId,...this.options.initialDocumentVersions?{initialDocumentVersions:this.options.initialDocumentVersions}:{}})}};function bk(e,t){return e.after===void 0?{path:e.path,operation:"delete",...t||e.before===void 0?{}:{expectedHash:ue(e.before)}}:{path:e.path,operation:e.before===void 0?"create":"update",...t||e.before===void 0?{}:{expectedHash:ue(e.before)},fullContent:e.after}}function Ek(e){return new si(e)}import{SiteEditOperationRequestSchema as kk}from"@vcp-dev/contracts";import st from"node:fs/promises";import Me from"node:path";import{SITE_EDIT_SOURCE_ALLOWED_DIRS as Ik,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as vk}from"@vcp-dev/contracts";var ai=class{constructor(t){this.options=t,this.fileSystem=this.createFileSystem(),this.engine=Nr({...t,fileSystem:this.fileSystem})}get status(){return this.engine.status}registerComposition(t,n){this.engine.registerComposition(t,n)}unregisterComposition(t){this.engine.unregisterComposition(t)}getDocument(t){return this.engine.getDocument(t)}getAffectedCompositions(t){return this.engine.getAffectedCompositions(t)}getCompositionContext(t){return this.engine.getCompositionContext(t)}initializeComposition(t){return this.engine.initializeComposition(t)}getHistoryStatus(){return this.engine.getHistoryStatus()}getObjectEditContext(t,n){return this.engine.getObjectEditContext(t,n)}getRenderDetail(t,n){return this.engine.getRenderDetail(t,n)}getClassNameSource(t,n){return this.engine.getClassNameSource(t,n)}getSourceTree(t){return ri(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.engine.getCompositionEntryFiles()})}getSourceFile(t){return oi(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.engine.getCompositionEntryFiles()})}resolveSourceLocation(t){return ii(t,this.engine.getRenderDetail(t.key,t.composition))}refreshSourceForKey(t,n){return this.engine.refreshSourceForKey(t,n)}execute(t){return this.engine.execute(t)}undo(t){return this.engine.undo(t)}redo(t){return this.engine.redo(t)}notifyFileChanged(t){this.engine.notifyFileChanged(t)}subscribe(t){return this.engine.subscribe(t)}dispose(){this.engine.dispose()}createFileSystem(){if(this.options.fileSystem)return this.options.fileSystem;let t=new Map,{projectRoot:n}=this.options;return{async readFile(r){return st.readFile(Me.join(n,r),"utf8")},async readFileBytes(r){return st.readFile(Me.join(n,r))},async getFileInfo(r){let o=Me.join(n,...r.split("/"));try{let i=await st.lstat(o);return!i.isFile()||i.isSymbolicLink()?null:{path:r,sizeBytes:i.size}}catch{return null}},async writeFile(r,o){await Uo(Me.join(n,r),o)},async createExclusive(r,o){let i=Me.join(n,r);await st.mkdir(Me.dirname(i),{recursive:!0});let s=await st.open(i,"wx");try{await s.writeFile(o,"utf8")}catch(a){throw await s.close(),await st.rm(i,{force:!0}),a}await s.close()},async deleteFile(r){await st.rm(Me.join(n,r),{force:!0});let o=r.replace(/\\/g,"/"),i=["components/site/generated","src/components/site/generated"].find(c=>o.startsWith(`${c}/`));if(!i)return;let s=Me.join(n,i),a=Me.dirname(Me.join(n,o));for(;a!==s&&a.startsWith(`${s}${Me.sep}`);){try{await st.rmdir(a)}catch(c){if(c instanceof Error&&"code"in c&&c.code==="ENOENT"){a=Me.dirname(a);continue}break}a=Me.dirname(a)}},async exists(r){try{return await st.access(Me.join(n,r)),!0}catch{return!1}},async listFiles(r={}){let o=r.roots??[...vk,...Ik],i=[],s=new Set,a=new Set,c=0;for(let d of o)await u(d,i,1);let l=i.sort((d,p)=>d.path.localeCompare(p.path));return a.size>0?{files:l,truncated:{reasons:[...a]}}:{files:l};async function u(d,p,m){if(r.maxDepth!==void 0&&m>r.maxDepth){a.add("max-depth");return}let g=Me.join(n,...d.split("/")),S;try{S=await st.lstat(g)}catch{return}if(S.isSymbolicLink())return;if(S.isFile()){let v=S.ino>0?`${String(S.dev)}:${String(S.ino)}`:null;if(v&&s.has(v))return;if(r.maxFiles!==void 0&&p.length>=r.maxFiles){a.add("max-files");return}if(r.maxTotalBytes!==void 0&&c+S.size>r.maxTotalBytes){a.add("max-total-bytes");return}v&&s.add(v),p.push({path:d,sizeBytes:S.size}),c+=S.size;return}if(!S.isDirectory())return;if(r.maxFiles!==void 0&&p.length>=r.maxFiles){a.add("max-files");return}let C=await st.readdir(g,{withFileTypes:!0});for(let v of C)v.isSymbolicLink()||await u(`${d}/${v.name}`,p,m+1)}},getVersion(r){return t.get(r)??1},bumpVersion(r){let o=(t.get(r)??1)+1;return t.set(r,o),o}}}};function za(e){return new ai(e)}var ci=class{constructor(t){this.options=t,this.listeners=new Set,this.engine=za({projectRoot:t.projectRoot,fileSystem:t.fileSystem,compositions:t.compositions,onEvent:n=>{let r=Jr(n,{siteId:t.siteId,snapshotId:t.snapshotId});if(r){t.onEvent?.(r);for(let o of this.listeners)o(r)}},dev:t.dev,...t.historyStore?{historyStore:t.historyStore}:{},...t.tenantId?{tenantId:t.tenantId}:{},...t.initialDocumentVersions!==void 0?{initialDocumentVersions:t.initialDocumentVersions}:{},siteId:t.siteId,snapshotId:t.snapshotId})}get status(){return this.engine.status}initializeComposition(t){return this.engine.initializeComposition(t)}registerComposition(t,n){this.engine.registerComposition(t,n)}unregisterComposition(t){this.engine.unregisterComposition(t)}getDocument(t){return{ok:!0,composition:this.engine.getCompositionContext(t),data:Ur(this.engine.getDocument(t),{siteId:this.options.siteId,snapshotId:this.options.snapshotId})}}getInternalDocument(t){return this.engine.getDocument(t)}getStyleContext(t){return{ok:!0,composition:this.engine.getCompositionContext(t),data:this.engine.getDocument(t).styleContext??null}}async getHistoryStatus(){return{ok:!0,composition:this.options.compositions[0].context,data:await this.engine.getHistoryStatus()}}getObjectEditContext(t,n){return{ok:!0,composition:this.engine.getCompositionContext(n),data:Kr(this.engine.getObjectEditContext(t,n))}}getClassNameSource(t,n){return{ok:!0,composition:this.engine.getCompositionContext(n),data:this.engine.getClassNameSource(t,n)}}async getSourceTree(t){return{ok:!0,composition:this.engine.getCompositionContext(t),data:await this.engine.getSourceTree(t)}}async getSourceFile(t){return{ok:!0,composition:this.engine.getCompositionContext(t.composition),data:await this.engine.getSourceFile(t)}}resolveSourceLocation(t){return{ok:!0,composition:this.engine.getCompositionContext(t.composition),data:this.engine.resolveSourceLocation(t)}}refreshSourceForKey(t,n){return this.engine.refreshSourceForKey(t,n)}async executeOperation(t,n){let r=n===void 0||t.mutationContext!==void 0?t:{...t,mutationContext:n},o=kk.safeParse(r);if(!o.success)return Vr(t,o.error.issues.map(s=>s.message));let i=await this.engine.execute(o.data);if(!i.ok){let s=i.error;if(!s)throw new Error("executeOperation failed without an error payload");return{ok:!1,composition:i.composition,error:{code:s.code,message:s.message},data:{requestId:i.requestId,kind:i.kind,composition:i.composition,target:i.target,resultVersion:i.resultVersion,...i.affectedFiles?.length?{affectedFiles:i.affectedFiles}:{}}}}return{ok:!0,composition:i.composition,data:Ut(i)}}async undo(t){let n=await this.engine.undo();if(!n.ok){let r=n.error;if(!r)throw new Error("undo failed without an error payload");return{ok:!1,composition:n.composition,error:{code:r.code,message:r.message},data:{requestId:n.requestId,kind:n.kind,composition:n.composition,target:n.target,resultVersion:n.resultVersion}}}return{ok:!0,composition:n.composition,data:Ut(n)}}async redo(t){let n=await this.engine.redo();if(!n.ok){let r=n.error;if(!r)throw new Error("redo failed without an error payload");return{ok:!1,composition:n.composition,error:{code:r.code,message:r.message},data:{requestId:n.requestId,kind:n.kind,composition:n.composition,target:n.target,resultVersion:n.resultVersion}}}return{ok:!0,composition:n.composition,data:Ut(n)}}notifyFileChanged(t){this.engine.notifyFileChanged(t)}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}dispose(){this.listeners.clear(),this.engine.dispose()}};function Ck(e){return new ci(e)}import{createHash as Rk,randomUUID as oc}from"node:crypto";import ye from"node:fs/promises";import be from"node:path";var Ye=1,Ha=1,wk=2,Nk="index.json",Pk="recovery.json",Ak="transaction-journal.json",Tk="document-version.json",ui={maxEntries:100,maxSessionBytes:512*1024*1024,maxEntryBytes:128*1024*1024},J={INVALID_ROOT:"INVALID_ROOT",INVALID_PATH:"INVALID_PATH",INVALID_SCHEMA:"INVALID_SCHEMA",INVALID_JSON:"INVALID_JSON",INDEX_CORRUPT:"INDEX_CORRUPT",ENTRY_CORRUPT:"ENTRY_CORRUPT",BLOB_CORRUPT:"BLOB_CORRUPT",RECOVERY_PENDING:"RECOVERY_PENDING",CAPACITY_EXCEEDED:"CAPACITY_EXCEEDED",NOT_FOUND:"NOT_FOUND"},W=class extends Error{constructor(t,n,r){super(n),this.name="FileHistoryStoreError",this.code=t,r?.cause!==void 0&&(this.cause=r.cause)}};async function Up(e,t={}){let n=Xk(e),r=Hk(t.limits),o=Wa(n),i=zk(n),s=await Le(i),a=await Le(o)||s;a||(await Lk(n),await Bk(n)),a||await Gk(n);let c=await Ve(n),l=new Set(a?(await gi(n)).map(d=>d.stageId):[]);a||await Pr(n,c.entryIds);let u=async()=>{if(await Le(o)||s)throw new W(J.RECOVERY_PENDING,"history store requires explicit recovery before accepting writes")};return{rootDir:n,recoveryRequired:a,async readDocumentVersion(){return $p(n)},async writeDocumentVersion(d){if(await u(),!Number.isInteger(d)||d<0)throw new W(J.INVALID_SCHEMA,"document version must be a non-negative integer");let p=await $p(n);await Ar(Gp(n),{schemaVersion:1,version:Math.max(p,d)})},async stageAppend(d,p={}){await u();let m=await Mp(d,r),g={schemaVersion:Ha,stageId:oc(),entryId:m.entryId,blobIds:m.blobs.map(S=>S.digest)};try{await Op(n,m),await Mk(n,g,p.durableManifest!==!1)}catch(S){try{await Lp(n,g)}catch(C){throw new W(J.INDEX_CORRUPT,"staged history cleanup failed after preparation error",{cause:C})}throw S}return{stageId:g.stageId,entryId:g.entryId,blobIds:g.blobIds}},async discardStage(d){await u(),Qa(d);let p=await Ya(n,d);p&&await Lp(n,p)},async previewStagedAppend(d,p){return await u(),(await Fp(n,r,d,p)).transition},async previewCursor(d,p){await u();let m=await Ve(n);return qa(m,p),Ga(d,m.entryIds.length),Kp(m,m.entryIds,d)},async publishStagedAppend(d,p,m){if(await u(),di(d,"entryId"),m){Qa(m);let S=await Ya(n,m);if(!S||S.entryId!==d)throw new W(J.INVALID_SCHEMA,"history stage does not match the published entry")}let g=await Fp(n,r,d,p);return jp({rootDir:n,previousDigest:g.current.digest,entryIds:g.entryIds,cursor:g.cursor,afterWrite:async()=>{m?await fi(n,m):await Dk(n,d),await Pr(n,g.entryIds)}})},async append(d){await u();let p=await Ve(n),m=await Mp(d,r),g=[...p.entryIds];p.cursor<g.length-1&&g.splice(p.cursor+1),g.push(m.entryId);try{await Op(n,m);let S=await Jp(n,g,r);return await sc(n,S.entryIds,S.cursor),await Pr(n,S.entryIds),Ve(n)}catch(S){throw await Pr(n,p.entryIds),S}},async readEntry(d){return di(d,"entryId"),_r(n,d)},async readBlob(d){di(d,"blobId");let p=await mc(n,d),m=await jt(p,J.NOT_FOUND,"blob");return ac(m,d,p),m},async readIndex(){return Ve(n)},async readStatus(){let d=await Ve(n);return{canUndo:d.undoIds.length>0,canRedo:d.redoIds.length>0,undoDepth:d.undoIds.length,redoDepth:d.redoIds.length,cursor:d.cursor,recoveryRequired:await Le(o)||await Le(i)}},async readUndoRedoIds(){let d=await Ve(n);return{undoIds:d.undoIds,redoIds:d.redoIds,currentId:d.currentId}},async setCursor(d,p){await u();let m=await Ve(n);return qa(m,p),Ga(d,m.entryIds.length),jp({rootDir:n,previousDigest:m.digest,entryIds:m.entryIds,cursor:d})},async markRecoveryRequired(d){await Le(o)||await Ar(Wa(n),{schemaVersion:Ye,reason:Wk(d),createdAt:new Date().toISOString()})},async clearRecoveryRequired(){await ye.rm(Wa(n),{force:!0})},async readTransactionJournal(){return await Le(i)?li(i):null},async writeTransactionJournal(d){await u(),Yp(d);try{await Ar(i,d)}catch(m){let g=await li(i).catch(()=>null);if(g&&Buffer.from(Ue(g)).equals(Buffer.from(Ue(d))))return;throw g?new W(J.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous",{cause:m}):m}let p=await li(i);if(!Buffer.from(Ue(p)).equals(Buffer.from(Ue(d))))throw new W(J.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous")},async clearTransactionJournal(d){let p=await Le(i)?await li(i):null;if(p&&p.transactionId!==d)throw new W(J.INVALID_SCHEMA,"transaction journal changed concurrently");try{await ye.rm(i,{force:!0})}catch(m){if(!await Le(i))return;throw m}if(await Le(i))throw new W(J.INDEX_CORRUPT,"transaction journal clear outcome is ambiguous");s=!1},async cleanupTmp(){await u();for(let p of l)await fi(n,p),l.delete(p);await jk(n);let d=await Ve(n);await Pr(n,d.entryIds)}}}async function Fp(e,t,n,r){di(n,"entryId");let o=await Ve(e);qa(o,r);let i=await _r(e,n),s=[...o.entryIds];o.cursor<s.length-1&&s.splice(o.cursor+1),s.push(i.id);let a=await Jp(e,s,t);return{current:o,entryIds:a.entryIds,cursor:a.cursor,transition:Kp(o,a.entryIds,a.cursor)}}function Kp(e,t,n){return Ga(n,t.length),{expectedIndexDigest:e.digest,publishedIndexDigest:_k(t,n),publishedCursor:n,publishedCurrentId:t[n]??null}}function _k(e,t){return $t(Ue({schemaVersion:Ye,entryIds:e,cursor:t}))}function Ga(e,t){if(!Number.isInteger(e)||e<-1||e>=t)throw new W(J.INVALID_SCHEMA,`history cursor is out of bounds: ${e}`)}function Fk(e){if(!at(e))return!1;let t=e.publishedCursor,n=e.publishedCurrentId;return!Ke(e.expectedIndexDigest)||!Ke(e.publishedIndexDigest)||!Number.isInteger(t)||t<-1||n!==null&&!Ke(n)?!1:t===-1?n===null:Ke(n)}async function Mp(e,t){if(!e.kind.trim())throw new W(J.INVALID_JSON,"history entry kind must not be empty");let n=[],r=[];for(let c of e.blobs??[]){if(!c.name.trim())throw new W(J.INVALID_JSON,"history blob name must not be empty");let l=Jk(c.data),u=$t(l);n.push({name:c.name,bytes:l,digest:u,sizeBytes:l.byteLength}),r.push({name:c.name,digest:u,sizeBytes:l.byteLength})}let o={schemaVersion:Ye,kind:e.kind,manifest:e.manifest,blobs:r},i=Ue({...o}),s=$t(i),a=i.byteLength+n.reduce((c,l)=>c+l.sizeBytes,0);if(a>t.maxEntryBytes)throw new W(J.CAPACITY_EXCEEDED,`history entry exceeds maxEntryBytes (${a} > ${t.maxEntryBytes})`);return{entryBody:o,entryId:s,blobs:n}}async function Op(e,t){let n=uc(e,t.entryId),r={id:t.entryId,...t.entryBody},o=[...t.blobs.map(a=>Dp(dc(e,a.digest),a.bytes,{kind:"blob",digest:a.digest},pc(e,a.digest))),Dp(n,Ue(r),{kind:"entry",digest:t.entryId},fc(e,t.entryId))],s=(await Promise.allSettled(o)).find(a=>a.status==="rejected");if(s)throw s.reason}async function Dp(e,t,n,r){let o=await nc(e)??(r?await nc(r):null);if(o!==null){if(Buffer.compare(o,t)!==0)throw new W(n.kind==="blob"?J.BLOB_CORRUPT:J.ENTRY_CORRUPT,`${n.kind} content mismatch for ${n.digest}`);return}await Wp(e,t)}async function Jp(e,t,n){let r=[...t],o=r.length-1;for(;;){if((await zp(e,r)).totalBytes<=n.maxSessionBytes&&r.length<=n.maxEntries)return{entryIds:r,cursor:o};if(o<=0||r.length===0)throw new W(J.CAPACITY_EXCEEDED,"history store exceeds capacity limits and the current entry cannot be trimmed");r.shift(),o-=1}}async function Mk(e,t,n){ic(t);let r=lc(e,t.stageId);if(n){await Ar(r,t);return}await Kk(r,t)}async function Ya(e,t){let n=await nc(lc(e,t));if(n===null)return null;let r=Fr(Buffer.from(n).toString("utf8"),`history stage ${t}`),o=ic(r);if(o.stageId!==t)throw new W(J.INVALID_SCHEMA,`history stage id mismatch: ${t}`);return o}async function gi(e){let t=[];for(let n of await mi(cc(e))){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);Qa(r);let o=await Ya(e,r);o&&t.push(o)}return t}async function Lp(e,t){ic(t);let n=await Ve(e),r=(await gi(e)).filter(s=>s.stageId!==t.stageId),o=new Set(n.entryIds),i=new Set;for(let s of n.entryIds){let a=await _r(e,s);for(let c of a.blobs)i.add(c.digest)}for(let s of r){o.add(s.entryId);for(let a of s.blobIds)i.add(a)}o.has(t.entryId)||await Bp(uc(e,t.entryId),fc(e,t.entryId));for(let s of t.blobIds)i.has(s)||await Bp(dc(e,s),pc(e,s));await fi(e,t.stageId),await rc(Mr(e)),await rc(Or(e))}async function fi(e,t){await Za(lc(e,t)),await Ok(e)}async function Ok(e){try{await ye.rmdir(cc(e))}catch(t){if(Dr(t)||at(t)&&t.code==="ENOTEMPTY")return;throw t}}async function Dk(e,t){for(let n of await gi(e))n.entryId===t&&await fi(e,n.stageId)}async function Za(e){if(await ye.rm(e,{force:!0}),await Le(e))throw new W(J.INDEX_CORRUPT,`unable to remove staged history object: ${e}`)}async function Bp(e,t){await Za(e),await Za(t)}function ic(e){if(!at(e)||e.schemaVersion!==Ha||typeof e.stageId!="string"||!Xp(e.stageId)||!Ke(e.entryId))throw new W(J.INVALID_SCHEMA,"history stage schema is invalid");let t=Hp(e.blobIds,"history stage blobIds");return{schemaVersion:Ha,stageId:e.stageId,entryId:e.entryId,blobIds:t}}function Qa(e){if(!Xp(e))throw new W(J.INVALID_PATH,"history stageId must be a UUID")}function Xp(e){return typeof e=="string"&&/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/iu.test(e)}async function Pr(e,t){let n=new Set(t),r=new Set;for(let c of t){let l=await _r(e,c);for(let u of l.blobs)r.add(u.digest)}for(let c of await gi(e)){n.add(c.entryId);for(let l of c.blobIds)r.add(l)}let o=Mr(e),i=await mi(o);for(let c of i){if(!c.endsWith(".json"))continue;let l=Vp(c.slice(0,-5));l&&!n.has(l)&&await pi(be.join(o,c))}let s=Or(e),a=await mi(s);for(let c of a){let l=Vp(c);l&&!r.has(l)&&await pi(be.join(s,c))}}async function Ve(e){let t=hi(e),n=await jt(t,J.NOT_FOUND,"index"),r=Fr(Buffer.from(n).toString("utf8"),"index"),o=$k(r),i=[...o.entryIds],{totalBytes:s}=await zp(e,i),a=i.slice(0,o.cursor+1).reverse(),c=i.slice(o.cursor+1);return{schemaVersion:Ye,digest:o.digest,entryIds:i,cursor:o.cursor,currentId:i[o.cursor]??null,undoIds:a,redoIds:c,totalBytes:s}}async function zp(e,t){let n=0,r=new Set,o=hi(e),i=await jt(o,J.NOT_FOUND,"index");n+=i.byteLength;for(let s of t){let a=await _r(e,s),c=await Zp(e,s),l=await jt(c,J.NOT_FOUND,"entry");n+=l.byteLength;for(let u of a.blobs){if(r.has(u.digest))continue;r.add(u.digest);let d=await mc(e,u.digest),p=await jt(d,J.NOT_FOUND,"blob");ac(p,u.digest,d),n+=p.byteLength}}return{totalBytes:n}}async function _r(e,t){let n=await Zp(e,t),r=await jt(n,J.NOT_FOUND,"entry"),o=Fr(Buffer.from(r).toString("utf8"),`entry ${t}`),i=Vk(o);if(i.id!==t)throw new W(J.ENTRY_CORRUPT,`entry id mismatch for ${t}`);if($t(Ue({schemaVersion:i.schemaVersion,kind:i.kind,manifest:i.manifest,blobs:i.blobs}))!==t)throw new W(J.ENTRY_CORRUPT,`entry hash mismatch for ${t}`);for(let a of i.blobs){let c=await mc(e,a.digest),l=await jt(c,J.NOT_FOUND,"blob");ac(l,a.digest,c)}return i}async function sc(e,t,n){let r={schemaVersion:Ye,digest:$t(Ue({schemaVersion:Ye,entryIds:t,cursor:n})),entryIds:t,cursor:n};await Ar(hi(e),r)}function qa(e,t){if(t!==void 0&&e.digest!==t)throw new W(J.INVALID_SCHEMA,`history index changed concurrently (expected ${t}, current ${e.digest})`)}async function jp(e){let t=$t(Ue({schemaVersion:Ye,entryIds:e.entryIds,cursor:e.cursor}));try{return await sc(e.rootDir,e.entryIds,e.cursor),await e.afterWrite?.(),await Ve(e.rootDir)}catch(n){let r=await Ve(e.rootDir).catch(()=>null);if(r?.digest===t)return r;throw r?.digest===e.previousDigest?n:new W(J.INDEX_CORRUPT,"history index publish outcome is ambiguous",{cause:n})}}async function Lk(e){await ye.mkdir(e,{recursive:!0}),await ye.mkdir(Mr(e),{recursive:!0}),await ye.mkdir(Or(e),{recursive:!0}),await ye.mkdir(Tr(e),{recursive:!0})}async function Bk(e){await ye.rm(Tr(e),{recursive:!0,force:!0}),await ye.mkdir(Tr(e),{recursive:!0})}async function jk(e){let t=Tr(e);await ye.mkdir(t,{recursive:!0});for(let n of await mi(t))n!=="stages"&&await ye.rm(be.join(t,n),{recursive:!0,force:!0})}function $k(e){if(!at(e))throw new W(J.INDEX_CORRUPT,"index.json must be an object");if(e.schemaVersion!==Ye)throw new W(J.INVALID_SCHEMA,`unsupported index schemaVersion: ${String(e.schemaVersion)}`);let t=Hp(e.entryIds,"index.entryIds"),n=e.cursor;if(!Number.isInteger(n)||n<-1||n>=t.length)throw new W(J.INDEX_CORRUPT,"index cursor is out of bounds");let r=n,o=e.digest;if(!Ke(o))throw new W(J.INDEX_CORRUPT,"index digest is invalid");let i=$t(Ue({schemaVersion:Ye,entryIds:t,cursor:r}));if(o!==i)throw new W(J.INDEX_CORRUPT,"index digest mismatch");return{schemaVersion:Ye,digest:o,entryIds:t,cursor:r}}function Vk(e){if(!at(e))throw new W(J.ENTRY_CORRUPT,"entry must be an object");if(e.schemaVersion!==Ye)throw new W(J.INVALID_SCHEMA,`unsupported entry schemaVersion: ${String(e.schemaVersion)}`);let t=e.id;if(!Ke(t))throw new W(J.ENTRY_CORRUPT,"entry id is invalid");let n=e.kind;if(typeof n!="string"||n.trim().length===0)throw new W(J.ENTRY_CORRUPT,"entry kind is invalid");let r=tc(e.manifest,"entry.manifest"),o=Uk(e.blobs);return{id:t,schemaVersion:Ye,kind:n,manifest:r,blobs:o}}function Uk(e){if(!Array.isArray(e))throw new W(J.ENTRY_CORRUPT,"entry blobs must be an array");return e.map((t,n)=>{if(!at(t))throw new W(J.ENTRY_CORRUPT,`entry blob ref ${n} must be an object`);let r=t.name;if(typeof r!="string"||r.trim().length===0)throw new W(J.ENTRY_CORRUPT,`entry blob ref ${n} name is invalid`);let o=t.digest;if(!Ke(o))throw new W(J.ENTRY_CORRUPT,`entry blob ref ${n} digest is invalid`);let i=t.sizeBytes;if(!Number.isInteger(i)||i<0)throw new W(J.ENTRY_CORRUPT,`entry blob ref ${n} sizeBytes is invalid`);return{name:r,digest:o,sizeBytes:i}})}async function Ar(e,t){await Wp(e,Ue(t))}async function Kk(e,t){let n=be.dirname(e),r=be.basename(e),o=be.join(n,`.${r}.${process.pid}.${oc()}.tmp`);await ye.mkdir(n,{recursive:!0});try{await ye.writeFile(o,Ue(t),{flag:"wx"}),await ye.rename(o,e)}finally{await pi(o)}}async function Wp(e,t){let n=be.dirname(e),r=be.basename(e),o=be.join(n,`.${r}.${process.pid}.${oc()}.tmp`);await ye.mkdir(n,{recursive:!0});try{let i=await ye.open(o,"wx");try{await i.writeFile(t),await i.sync()}finally{await i.close()}await ye.rename(o,e),await rc(n)}finally{await pi(o)}}function Ue(e){return Buffer.from(JSON.stringify(ec(e)),"utf8")}function ec(e){if(Array.isArray(e))return e.map(t=>ec(t));if(at(e)){let t={};for(let n of Object.keys(e).sort())t[n]=ec(e[n]);return t}return e}function Fr(e,t){try{return JSON.parse(e)}catch(n){throw new W(J.INVALID_JSON,`${t} is not valid JSON`,{cause:n})}}function tc(e,t){if(e===null)return null;switch(typeof e){case"boolean":case"number":case"string":return e;case"object":if(Array.isArray(e))return e.map(n=>tc(n,t));if(at(e)){let n={};for(let[r,o]of Object.entries(e))n[r]=tc(o,t);return n}break}throw new W(J.INVALID_JSON,`${t} must be JSON-serializable`)}function Hp(e,t){if(!Array.isArray(e))throw new W(J.INDEX_CORRUPT,`${t} must be an array`);return e.map((n,r)=>{if(!Ke(n))throw new W(J.INDEX_CORRUPT,`${t}[${r}] is invalid`);return n})}function di(e,t){if(!Ke(e))throw new W(J.INVALID_PATH,`${t} must be a sha256 digest`)}function Ke(e){return typeof e=="string"&&/^sha256:[a-f0-9]{64}$/u.test(e)}function $t(e){return`sha256:${Rk("sha256").update(e).digest("hex")}`}function Jk(e){return typeof e=="string"?Buffer.from(e,"utf8"):Buffer.from(e)}async function jt(e,t,n){try{return await ye.readFile(e)}catch(r){throw new W(t,`${n} not found: ${e}`,{cause:r})}}async function nc(e){try{return await ye.readFile(e)}catch(t){if(Dr(t))return null;throw t}}function ac(e,t,n){if($t(e)!==t)throw new W(J.BLOB_CORRUPT,`blob hash mismatch for ${n}`)}async function Le(e){try{return await ye.access(e),!0}catch(t){if(Dr(t))return!1;throw t}}async function pi(e){try{await ye.rm(e,{force:!0,recursive:!0})}catch{}}async function rc(e){try{let t=await ye.open(e,"r");try{await t.sync()}finally{await t.close()}}catch{}}async function mi(e){try{return await ye.readdir(e)}catch(t){if(Dr(t))return[];throw t}}function Xk(e){if(typeof e!="string"||e.trim().length===0)throw new W(J.INVALID_ROOT,"history store rootDir must be a non-empty string");return be.resolve(e)}function hi(e){return be.join(e,Nk)}function Wa(e){return be.join(e,Pk)}function zk(e){return be.join(e,Ak)}function Gp(e){return be.join(e,Tk)}async function $p(e){try{let t=await ye.readFile(Gp(e),"utf8"),n=Fr(t,"document version");if(!at(n)||n.schemaVersion!==1||!Number.isInteger(n.version)||n.version<0)throw new W(J.INVALID_SCHEMA,"document version schema is invalid");return n.version}catch(t){if(Dr(t))return 0;throw t}}async function li(e){let t=await jt(e,J.RECOVERY_PENDING,"transaction journal"),n=Fr(Buffer.from(t).toString("utf8"),"transaction journal");return Yp(n),n}function Yp(e){if(!at(e)||e.schemaVersion!==wk||typeof e.transactionId!="string"||e.transactionId.length===0||typeof e.operationId!="string"||e.operationId.length===0||!["prepared","files-written","history-published"].includes(e.phase)||!Fk(e.historyTransition)||!Array.isArray(e.files))throw new W(J.INVALID_SCHEMA,"transaction journal schema is invalid");for(let t of e.files)if(!at(t)||typeof t.path!="string"||t.path.length===0||t.preDigest!==null&&!Ke(t.preDigest)||t.postDigest!==null&&!Ke(t.postDigest))throw new W(J.INVALID_SCHEMA,"transaction journal file digest is invalid")}function Wk(e){return e.replace(/[\r\n]+/g," ").slice(0,512)}function Mr(e){return be.join(e,"entries")}function Or(e){return be.join(e,"blobs")}function Tr(e){return be.join(e,"tmp")}function cc(e){return be.join(Tr(e),"stages")}function lc(e,t){return be.join(cc(e),`${t}.json`)}function uc(e,t){return be.join(Mr(e),`${qp(t)}.json`)}function dc(e,t){return be.join(Or(e),qp(t))}function fc(e,t){return be.join(Mr(e),`${t}.json`)}function pc(e,t){return be.join(Or(e),t)}async function Zp(e,t){return Qp(uc(e,t),fc(e,t))}async function mc(e,t){return Qp(dc(e,t),pc(e,t))}async function Qp(e,t){return await Le(e)?e:await Le(t)?t:e}function qp(e){return e.slice(7)}function Vp(e){let t=e.startsWith("sha256:")?e:`sha256:${e}`;return Ke(t)?t:null}function at(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Dr(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function Hk(e){return{maxEntries:e?.maxEntries??ui.maxEntries,maxSessionBytes:e?.maxSessionBytes??ui.maxSessionBytes,maxEntryBytes:e?.maxEntryBytes??ui.maxEntryBytes}}async function Gk(e){let t=hi(e);await Le(t)||await sc(e,[],-1)}import{createHash as Yk}from"node:crypto";import{computeSiteEditCompositionKey as tm,ManagedPageTemplateRouteManifestV1Schema as Zk}from"@vcp-dev/contracts";var Qk="app/_vcp/page-templates/runtime.tsx",nm=".vcp/page-templates/routes/",qk="app/_vcp/page-templates/routes/";function rm(e){return e.startsWith(nm)&&e.endsWith(".json")}var Ae=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="PageTemplateManagedSourceError"}};function $n(e){let t=Go(e);return Yk("sha256").update(t,"utf8").digest("hex").slice(0,16)}function xi(e){return e.replace(/[^A-Za-z0-9_-]/g,"_")}function Lr(e,t){let n=$n(e),r=`${qk}${n}`,o=xi(t);return{routeRoot:r,manifestFile:`${nm}${n}.json`,runtimeFile:Qk,registryFile:`${r}/registry.ts`,templateEntryFile:`${r}/templates/${o}/page.tsx`}}function om(e){let t=iC(e),n=new Map;for(let r of t){let o=xi(r),i=n.get(o);if(i!==void 0&&i!==r)throw new Ae("PAGE_TEMPLATE_ID_COLLISION",`Page-template IDs ${JSON.stringify(i)} and ${JSON.stringify(r)} map to the same safe name ${JSON.stringify(o)}.`,{reason:"safe-name-collision",templateId:r,safeName:o});n.set(o,r)}}function gc(e){let t=Go(e.routeId),n=im(e.files),r=Lr(t,""),o=n.get(r.manifestFile);if(o===void 0)return null;let i=rC(t,r.manifestFile,o);return oC({routeId:t,manifest:i,files:n}),i}function eC(e){let t=Go(e.selector.routeId),n=ln(e.canonicalEntryFile),r=gc({routeId:t,files:e.files});if(r===null){if(e.selector.templateId!==void 0)throw new Ae("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Page-template selection ${JSON.stringify(e.selector.templateId)} cannot be resolved without a managed manifest for ${JSON.stringify(t)}.`,{reason:"template-selection-without-manifest",routeId:t,templateId:e.selector.templateId});return{mode:"direct",context:{routeId:t},entryFile:n,effectiveEntryFile:n}}if(ln(r.canonical_entry_file)!==n)throw new Ae("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Managed page-template manifest for ${JSON.stringify(t)} does not match the supplied canonical entry.`,{reason:"canonical-entry-mismatch",routeId:t,path:r.canonical_entry_file});let o=e.selector.templateId??null,i=(o?r.templates.find(c=>c.template_id===o):void 0)??r.templates.find(c=>c.template_id===r.default_template_id);if(!i)throw new Ae("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Managed page-template manifest for ${JSON.stringify(t)} has no resolvable default template.`,{reason:"default-entry-missing",routeId:t});let a={context:{routeId:t,effectiveTemplateId:i.template_id},entryFile:ln(i.entry_file)};return{...a,mode:"delegated",effectiveEntryFile:a.entryFile}}function tC(e){let t=im(e.files),n=[...t.keys()].map(l=>({path:l})),r=kr(n),o=new Set,i=new Map;for(let l of r){if(o.has(l.routeId))throw new Ae("PAGE_TEMPLATE_ROUTE_AMBIGUOUS",`Multiple canonical page entries resolve to route ${JSON.stringify(l.routeId)}.`,{reason:"duplicate-route-id",routeId:l.routeId,candidates:r.filter(p=>p.routeId===l.routeId).map(p=>p.entryFile)});o.add(l.routeId);let u=$n(l.routeId),d=i.get(u);if(d!==void 0&&d!==l.routeId)throw new Ae("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Page-template route-key collision between ${JSON.stringify(d)} and ${JSON.stringify(l.routeId)}.`,{reason:"route-key-collision",routeId:l.routeId});i.set(u,l.routeId)}let s=new Set(r.map(l=>Lr(l.routeId,"").manifestFile));for(let l of t.keys())if(rm(l)&&!s.has(l))throw new Ae("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Managed page-template manifest ${JSON.stringify(l)} does not belong to a scanned canonical route.`,{reason:"unknown-manifest",path:l});let a=[];for(let l of r){let u=gc({routeId:l.routeId,files:t});if(u===null){let d={routeId:l.routeId};a.push(nC(d,l.entryFile));continue}for(let d of[...u.templates].sort(sC)){let p={routeId:l.routeId,effectiveTemplateId:d.template_id},m={context:p,entryFile:ln(d.entry_file)};a.push({key:tm(p),composition:m})}}let c=new Set;for(let{key:l,composition:u}of a){if(c.has(l))throw new Ae("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Duplicate site-edit composition key for ${JSON.stringify(l)}.`,{reason:"duplicate-composition-key",routeId:u.context.routeId});c.add(l)}return a.sort((l,u)=>aC(l.composition,u.composition)||yi(l.key,u.key)).map(({composition:l})=>l)}function nC(e,t){return{key:tm(e),composition:{context:e,entryFile:t}}}function im(e){let t=new Map;if(lC(e)){for(let n of e)em(t,n.path,n.content);return t}for(let[n,r]of e)em(t,n,r);return t}function em(e,t,n){let r=ln(t);if(e.has(r))throw new Ae("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Snapshot contains duplicate file path ${JSON.stringify(r)}.`,{reason:"duplicate-file-path",path:r});e.set(r,n)}function rC(e,t,n){let r;try{r=JSON.parse(n)}catch{throw new Ae("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Managed page-template manifest ${JSON.stringify(t)} is not valid JSON.`,{reason:"invalid-json",routeId:e,path:t})}let o=Zk.safeParse(r);if(!o.success)throw new Ae("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Managed page-template manifest ${JSON.stringify(t)} does not match the known manifest contract.`,{reason:"schema-invalid",routeId:e,path:t,issues:o.error.issues.map(i=>`${i.path.join(".")||"manifest"}: ${i.message}`)});return o.data}function oC(e){let{routeId:t,manifest:n,files:r}=e,o=Lr(t,""),i=kr([...r.keys()].map(l=>({path:l}))).filter(l=>l.routeId===t);if(n.route_id!==t&&mt(t,"route-id-mismatch",o.manifestFile),n.route_key!==$n(t)&&mt(t,"route-key-mismatch",o.manifestFile),i.length!==1)throw new Ae("PAGE_TEMPLATE_ROUTE_AMBIGUOUS",`Managed page-template route ${JSON.stringify(t)} has ${i.length} canonical entries.`,{reason:i.length===0?"canonical-entry-missing":"duplicate-route-id",routeId:t,candidates:i.map(l=>l.entryFile)});let s=ln(n.canonical_entry_file);(s!==i[0].entryFile||!r.has(s))&&mt(t,"canonical-entry-mismatch",s),n.default_template_id!==`vcp-default:${$n(t)}`&&mt(t,"default-template-id-mismatch",o.manifestFile),om(n.templates);let a=new Set,c=new Set;for(let l of n.templates){let u=Lr(t,l.template_id),d=ln(l.entry_file),p=xi(l.template_id);l.safe_name!==p&&mt(t,"safe-name-mismatch",o.manifestFile,{templateId:l.template_id}),a.has(l.safe_name)&&mt(t,"duplicate-safe-name",o.manifestFile,{templateId:l.template_id}),a.add(l.safe_name),c.has(d)&&mt(t,"duplicate-entry-file",o.manifestFile,{templateId:l.template_id}),c.add(d),cC(d,u.routeRoot)||mt(t,"entry-outside-route-root",d,{templateId:l.template_id}),d!==u.templateEntryFile&&mt(t,"entry-path-mismatch",d,{templateId:l.template_id}),r.has(d)||mt(t,"template-entry-missing",d,{templateId:l.template_id})}}function mt(e,t,n,r={}){throw new Ae("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Managed page-template source for ${JSON.stringify(e)} failed validation (${t}).`,{reason:t,routeId:e,path:n,...r})}function iC(e){return Array.isArray(e)?e.length===0||typeof e[0]=="string"?e:e.map(t=>t.template_id):"rawTemplateIds"in e?e.rawTemplateIds:"templateIds"in e?e.templateIds:[]}function sC(e,t){return+(t.kind==="default")-+(e.kind==="default")||yi(e.template_id,t.template_id)}function aC(e,t){let n=yi(e.context.routeId,t.context.routeId);if(n!==0)return n;let r=e.context.effectiveTemplateId,o=t.context.effectiveTemplateId;if(r===void 0)return-1;if(o===void 0)return 1;let s=`vcp-default:${$n(e.context.routeId)}`,a=r===s;return Number(o===s)-Number(a)||yi(r,o)}function yi(e,t){return e<t?-1:e>t?1:0}function cC(e,t){return e.startsWith(`${t}/`)}function ln(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function lC(e){return Array.isArray(e)}export{W as FileHistoryStoreError,Ae as PageTemplateManagedSourceError,ci as PreviewFileSystemSiteEditEngineRuntime,Sf as SITE_EDIT_RAW_COLOR_LITERAL_RE,si as SnapshotSiteEditEngineRuntime,om as assertNoPageTemplateSafeNameCollision,Lr as computeManagedPageTemplatePaths,$n as computePageTemplateRouteKey,xi as computePageTemplateSafeName,Ck as createPreviewSiteEditEngineRuntime,Ek as createSiteEditEngineRuntime,rm as isManagedPageTemplateManifestPath,Up as openFileHistoryStore,gc as parseManagedPageTemplateManifest,eC as resolveManagedPageTemplateComposition,tC as scanSiteEditCompositionsFromFiles,Sr as scanSiteEditThemeStyleViolations};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vcp-dev/site-edit-engine",
3
- "version": "0.8.4",
3
+ "version": "0.9.0",
4
4
  "type": "module",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -60,7 +60,7 @@
60
60
  "@babel/parser": "^7.29.3",
61
61
  "@babel/traverse": "^7.29.0",
62
62
  "@babel/types": "^7.29.0",
63
- "@vcp-dev/contracts": "0.8.4",
63
+ "@vcp-dev/contracts": "0.9.0",
64
64
  "yaml": "^2.9.0"
65
65
  },
66
66
  "devDependencies": {