@vcp-dev/site-edit-engine 0.11.21 → 0.11.22

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 +8 -8
  2. package/package.json +2 -2
package/dist/index.js CHANGED
@@ -1,21 +1,21 @@
1
- import*as mk from"@babel/parser";import*as Ct from"@babel/types";import*as ir from"node:path";var Kl=[".tsx",".ts",".jsx",".js"],gk=Kl.map(e=>`/index${e}`),hk=new Set(["json","css","scss","sass","less","svg","png","jpg","jpeg","gif","webp","avif","ico","bmp","woff","woff2","ttf","otf","eot","mp4","webm","mp3","wav","ogg","pdf","txt","md","csv","xml","yaml","yml"]);function Hm(e){let t=e.replace(/[?#].*$/,""),n=/\.([a-z0-9]+)$/i.exec(t);return n!==null&&hk.has(n[1].toLowerCase())}function Wm(e){let t=[];for(let n of e.program.body)Ct.isImportDeclaration(n)&&typeof n.source.value=="string"&&nt(n.source.value)&&t.push(n.source.value),Ct.isExportNamedDeclaration(n)&&n.source&&typeof n.source.value=="string"&&nt(n.source.value)&&t.push(n.source.value),Ct.isExportAllDeclaration(n)&&typeof n.source.value=="string"&&nt(n.source.value)&&t.push(n.source.value);return Ct.traverseFast(e.program,n=>{let r=Ct.isImportExpression(n)?n.source:Ct.isCallExpression(n)&&Ct.isImport(n.callee)?n.arguments[0]:null;Ct.isStringLiteral(r)&&nt(r.value)&&t.push(r.value)}),t}function nt(e){return e.startsWith("./")||e.startsWith("../")||e.startsWith("@/")}function Cn(e,t){if(t.startsWith("@/"))return t.slice(2).replace(/\\/g,"/");let n=ir.dirname(e);return ir.join(n,t).replace(/\\/g,"/")}async function yk(e,t){for(let n of Gm(e))if(await t(n))return n;return null}function Gm(e){return[...Kl.some(t=>e.endsWith(t))?[e]:[],...Kl.map(t=>`${e}${t}`),...gk.map(t=>`${e}${t}`)]}function sr(e,t,n){let r=Cn(e,t);if(!nt(t)||!Ym(e,t,r))return null;for(let o of Gm(r))if(n.has(o))return o;return null}async function Jr(e,t,n){let r=await js(e,t,n);return r.ok?r.path:null}async function js(e,t,n){let r=Cn(e,t);try{if(!Ym(e,t,r))return{ok:!1,diagnostic:{path:r,code:"import-not-found",message:`Local import not found: ${t}`,details:{fromFile:e,specifier:t}}};let o=await yk(r,n);return o?{ok:!0,path:o}:{ok:!1,diagnostic:{path:r,code:"import-not-found",message:`Local import not found: ${t}`,details:{fromFile:e,specifier:t}}}}catch(o){return{ok:!1,diagnostic:{path:r,code:"import-resolve-failed",message:`Failed to resolve local import: ${t}`,details:{fromFile:e,specifier:t,reason:o instanceof Error?o.message:String(o)}}}}}function Ym(e,t,n){if(!nt(t)||t.includes("\0")||t.includes("\\")||ir.posix.isAbsolute(n))return!1;let r=ir.posix.normalize(n);if(r===".."||r.startsWith("../"))return!1;if(t.startsWith("@/")){let o=t.slice(2);return o.length>0&&!o.split("/").some(i=>i==="..")}return!ir.posix.isAbsolute(e)}import{createHash as bk}from"node:crypto";import*as Zm from"@babel/parser";function Xr(e,t,n,r){return{code:e,message:t,locatorKind:n,details:r}}function ee(e,t,n,r,o){return{ok:!1,source:e,diagnostic:Xr(t,n,r,o)}}function Jl(e,t,n,r,o){return{ok:!1,source:e,diagnostic:Xr(t,n,r,o)}}var xk={"tsx-module":["jsx","typescript"],"ts-module":["typescript"],"next-app-entry":["jsx","typescript"]};function Rn(e){let{source:t,profile:n}=e;try{return{ok:!0,ast:Zm.parse(t,{sourceType:"module",plugins:xk[n]})}}catch(r){return{ok:!1,source:t,diagnostic:Xr("parse-failed",`AST parse failed: ${r instanceof Error?r.message:String(r)}`)}}}function Xl(e,t){return Rn({source:e,profile:qm(t.kind)})}function pi(e,t){return Rn({source:e,profile:qm(t)})}function qm(e){return"next-app-entry"}function zr(e){let{filePath:t,source:n}=e,r=t.toLowerCase().split(".").pop()??"";return r==="tsx"?"tsx-module":r==="ts"?"ts-module":r==="jsx"||r==="js"||r===""&&/<\w[\s\S]*>/.test(n)?"tsx-module":"next-app-entry"}var je=(e,t)=>{let n=Rn({source:t,profile:zr({filePath:e,source:t})});return n.ok?{ok:!0,module:{file:e,source:t,sourceHash:`sha256:${bk("sha256").update(t).digest("hex")}`,ast:n.ast,imports:Wm(n.ast).map(r=>({specifier:r}))}}:{ok:!1,diagnostic:{path:e,code:"parse-failed",message:n.diagnostic.message}}};function Ek(e,t){return je(e,t)}function Sk(e,t){return Cn(e,t)}import{COMPONENT_I18N_FILE_SUFFIX as Ik,parseComponentI18nResourcesJson as vk,resolveSiteTextDirection as kk,SiteLocaleSchema as _k}from"@vcp-dev/contracts";var Ck=["i18next","react-i18next"],Rk="components/ui/site-locale-provider.tsx",Nk="components/ui/component-i18n-provider.tsx",Qm="app/layout.tsx";async function mi(e){let t=e.files.filter(f=>f.path.endsWith(Ik));if(t.length===0)return{ok:!0};for(let f of["package.json",Qm,Rk,Nk])if(!await e.exists(f))return ar(`Target snapshot is missing required i18n host file: ${f}`);let n;try{n=JSON.parse(await e.readFile("package.json"))}catch{return ar("Target snapshot package.json is invalid.")}let r=eg(n)&&eg(n.dependencies)?n.dependencies:{},o=Ck.filter(f=>typeof r[f]!="string"||r[f].trim().length===0);if(o.length>0)return ar(`Target snapshot must already declare: ${o.join(", ")}.`);let i=await e.readFile(Qm),s=zl(i,"html","lang"),a=zl(i,"html","dir"),c=zl(i,"SiteLocaleProvider","locale"),l=_k.safeParse(s);if(!l.success||!a||!c||s!==c||a!==kk(l.data))return ar("Target snapshot app/layout.tsx must keep html lang/dir and SiteLocaleProvider locale consistent.");if(!i.includes('from "@/components/ui/site-locale-provider"')||!/<SiteLocaleProvider\b/.test(i)||!/<\/SiteLocaleProvider>/.test(i))return ar("Target snapshot root layout is not wired to SiteLocaleProvider.");let u=l.data;if(e.targetLocale&&e.targetLocale!==u)return ar("Target snapshot locale does not match the authoritative site language.");let d=u.split("-")[0];for(let f of t){let g=vk(f.content);if(!g.success)return ar(`Component i18n resource is invalid: ${f.path}.`);if(!e.deferTargetLocale&&!Object.hasOwn(g.data,u)&&!Object.hasOwn(g.data,d))return ar(`Component i18n resource ${f.path} has no locale for ${u} or ${d}.`)}return{ok:!0}}function zl(e,t,n){let r=e.match(new RegExp(`<${t}\\b[^>]*>`))?.[0];if(!r)return null;let o=[...r.matchAll(new RegExp(`\\b${n}=(?:"([^"]+)"|\\{"([^"]+)"\\})`,"g"))];return o.length!==1?null:o[0]?.[1]??o[0]?.[2]??null}function eg(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ar(e){return{ok:!1,message:e}}import Wl from"@babel/generator";import*as sg from"@babel/parser";import Gl from"@babel/traverse";import*as He from"@babel/types";import{computeSiteEditSourceIdentityKey as Ak}from"@vcp-dev/contracts";var tg="data-vcp-ui-component",$s="components/ui";function Kn(e){if(!e)return!1;let t=Hl(e);return t===$s||t.startsWith(`${$s}/`)||t.includes(`/${$s}/`)||t.endsWith(`/${$s}`)}function Hr(e,t){return e?e.startsWith("@/")||e.startsWith("~/")?Kn(e.slice(2)):e.startsWith("./")||e.startsWith("../")?Kn(Hl(`${Pk(t)}/${e}`)):Kn(e):!1}function Hl(e){let n=(e.split("?")[0]??e).replace(/\\/g,"/").replace(/^\.\//,""),r=[];for(let o of n.split("/"))if(!(!o||o===".")){if(o===".."){r.pop();continue}r.push(o)}return r.join("/")}function Pk(e){let t=Hl(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}import{stripSiteEditRepeatInstanceKeys as i$}from"@vcp-dev/contracts";import{isSiteEditRuntimeContainerTag as a$,isSiteEditRuntimeTextTag as c$}from"@vcp-dev/contracts/site-edit-runtime-capability";var ng={key:"data-vcp-edit-key",parentKey:"data-vcp-edit-parent-key",movable:"data-vcp-movable",removable:"data-vcp-removable",flags:"data-vcp-flags",publicUiComponent:"data-vcp-ui-component"};var Tk=typeof Wl=="function"?Wl:Wl.default,wk=typeof Gl=="function"?Gl:Gl.default,Ok=new Set(["base","body","head","html","link","meta","noscript","script","style","template","title"]),Fk="suppressHydrationWarning",Lk=new Set(["SiteEditBootstrap"]);function Dk(e){let t=jk(e.file,e.projectRoot);if(!Bk(e.source)||Kn(t))return{code:e.source,elements:[]};let n=e.attributes??ng,r=sg.parse(e.source,{sourceType:"module",plugins:["jsx","typescript"]}),o=[],i=Vk(r,t);return wk(r,{JSXElement(s){let a=s.node.openingElement,c=a.name;if(!Kk(c)||ag(a,n.key))return;let l=Xk(s)??"default",u=Hk(s),d=Ak(t,l,u),f=Us(c)??"unknown",g=$k(c)?"jsx":"component-call";if(g==="component-call"&&!zk(s.node.children)&&Lk.has(f))return;let p=g==="component-call"&&Uk(f,i);Jk(a,n.key,d),p&&rg(a,tg),Mk(s)&&rg(a,Fk),o.push({key:d,tag:f,componentName:l,sourceFile:t,sourceKind:g})}}),o.length===0?{code:e.source,elements:o}:{code:Tk(r,{jsescOption:{minimal:!0}}).code,elements:o}}function Mk(e){return!e.findParent(t=>t.isJSXElement())}function Bk(e){return/(?:^|[=(:,?;\[{>&|\n\r]|return\s+)\s*<(?:[A-Za-z][\w.:-]*|>)(?:\s|>|\/)/m.test(e)}function jk(e,t){let n=e.replace(/\\/g,"/").replace(/^\.\//,""),r=t?.replace(/\\/g,"/").replace(/\/+$/,"");if(r&&n.startsWith(`${r}/`))return n.slice(r.length+1);for(let[i,s]of[["/src/app/",1],["/src/components/",1],["/app/",1],["/components/",1]]){let a=n.indexOf(i);if(a>=0)return n.slice(a+s)}return n.match(/(?:^|\/)((?:src\/app|src\/components|app|components)\/.+)$/)?.[1]??n}function $k(e){return He.isJSXIdentifier(e)&&/^[a-z]/.test(e.name)}function Us(e){return He.isJSXIdentifier(e)?e.name:He.isJSXMemberExpression(e)?lg(e):null}function Vk(e,t){let n=new Set;for(let r of e.program.body)if(!(!He.isImportDeclaration(r)||!Hr(r.source.value,t)))for(let o of r.specifiers)n.add(o.local.name);return n}function Uk(e,t){let n=e.split(".")[0]??e;return t.has(n)}function Kk(e){let t=Us(e);return!t||t==="Fragment"||t.endsWith(".Fragment")?!1:!Ok.has(t)}function ag(e,t){return e.attributes.some(n=>He.isJSXAttribute(n)&&He.isJSXIdentifier(n.name,{name:t}))}function Jk(e,t,n){cg(e,He.jsxAttribute(He.jsxIdentifier(t),He.stringLiteral(n)))}function rg(e,t){ag(e,t)||cg(e,He.jsxAttribute(He.jsxIdentifier(t),null))}function cg(e,t){let n=e.attributes.findIndex(r=>He.isJSXSpreadAttribute(r));if(n>=0){e.attributes.splice(n,0,t);return}e.attributes.push(t)}function lg(e){return`${He.isJSXIdentifier(e.object)?e.object.name:lg(e.object)}.${e.property.name}`}function Xk(e){let t=e;for(;t;){if(t.isFunctionDeclaration()||t.isClassDeclaration())return t.node.id?.name??null;if(t.isVariableDeclarator()&&He.isIdentifier(t.node.id)){let n=t.get("init");if(!Array.isArray(n)&&(n.isArrowFunctionExpression()||n.isFunctionExpression()))return t.node.id.name}t=t.parentPath}return null}function zk(e){return e.some(t=>He.isJSXElement(t)||He.isJSXFragment(t))}var og=new WeakMap,Vs=new WeakMap,Yl=new WeakMap;function Hk(e){let t=og.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=Wk(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return og.set(e.node,o),o}function Wk(e){let t=Us(e.node.openingElement.name);return!t||t==="Fragment"||t.endsWith(".Fragment")?null:/^[A-Z]/.test(t)?`component:${t}#${ig(e,t)}`:`${t}#${ig(e,t)}`}function ig(e,t){let n=ug(e)??e.getFunctionParent();if(!n)return 0;let r=Yl.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=Yl.get(n.node);o||(o=new Map,Yl.set(n.node,o));let i=o.get(t);i||(i=new WeakMap,o.set(t,i));let s=0,a=n.isJSXElement()||n.isJSXFragment()?Ks(n):Gk(n);for(let c of a)if(Us(c.node.openingElement.name)===t){if(i.set(c.node,s),c.node===e.node)return s;s+=1}return i.get(e.node)??0}function Gk(e){let t=Vs.get(e.node);if(t)return t;let n=[];return e.traverse({JSXElement(r){r.getFunctionParent()?.node===e.node&&!ug(r)&&n.push(r)}}),Vs.set(e.node,n),n}function ug(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement())return t;t=t.parentPath}return n}function Ks(e){let t=Vs.get(e.node);if(t)return t;let n=[],r=e.get("children");for(let o of r)if(!Array.isArray(o)){if(o.isJSXElement()){n.push(o);continue}if(o.isJSXFragment()){n.push(...Ks(o));continue}o.isJSXExpressionContainer()&&n.push(...Wr(o.get("expression")))}return Vs.set(e.node,n),n}function Wr(e){if(e.isJSXElement())return[e];if(e.isJSXFragment())return Ks(e);if(e.isParenthesizedExpression())return Wr(e.get("expression"));if(e.isLogicalExpression()&&e.node.operator==="&&")return Wr(e.get("right"));if(e.isConditionalExpression())return[...Wr(e.get("consequent")),...Wr(e.get("alternate"))];if(e.isCallExpression()&&Zk(e.node)){let t=e.get("arguments")[0];return Yk(t)}return[]}function Yk(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return[t];if(t.isJSXFragment())return Ks(t);if(t.isParenthesizedExpression())return Wr(t.get("expression"));if(!t.isBlockStatement())return[];for(let n of t.get("body")){if(!n.isReturnStatement())continue;let r=n.get("argument");return r.node?Wr(r):[]}return[]}function Zk(e){return He.isMemberExpression(e.callee)&&He.isIdentifier(e.callee.property)&&e.callee.property.name==="map"}import{SiteEditOperationRequestSchema as mM,SiteEditPatchPlanSchema as gM}from"@vcp-dev/contracts";function Gr(e){return{requestId:e.requestId,kind:e.kind,composition:e.composition,target:e.target,resultVersion:e.resultVersion,affectedFiles:e.affectedFiles,...e.fileChanges?{fileChanges:e.fileChanges}:{},...e.output?{output:e.output}:{},...e.selectionRef?{selectionRef:e.selectionRef}:{}}}function Js(e,t){let n=t[0]??"Site edit operation request failed contract validation.";return{ok:!1,composition:{routeId:e.composition.routeId,...e.composition.templateId!==void 0?{effectiveTemplateId:e.composition.templateId}:{}},error:{code:"INVALID_PARAMS",message:n},data:{requestId:e.id,kind:e.kind,composition:{routeId:e.composition.routeId,...e.composition.templateId!==void 0?{effectiveTemplateId:e.composition.templateId}:{}},target:e.target,resultVersion:e.documentVersion}}}function Xs(e,t){if(!e.pageComposition)throw new Error("RenderDocument is missing the required Page Composition projection.");return{siteId:t.siteId,snapshotId:t.snapshotId,composition:e.composition,version:e.version,entries:e.entries.map(n=>({key:n.key,parentKey:n.parentKey,...n.pageCompositionUnitKey?{pageCompositionUnitKey:n.pageCompositionUnitKey}:{},...n.pageCompositionActionScope?{pageCompositionActionScope:n.pageCompositionActionScope}:{},operationSummary:{canUpdateText:n.operationSummary.canUpdateText,canInsertChild:n.operationSummary.canInsertChild,canMove:n.operationSummary.canMove,canRemove:n.operationSummary.canRemove},...n.dynamicDataSummary?{dynamicDataSummary:n.dynamicDataSummary}:{}})),...e.pageBlocks!==void 0?{pageBlocks:e.pageBlocks}:{},pageComposition:e.pageComposition.status==="unsupported"?{status:"unsupported",reason:e.pageComposition.reason,diagnostics:e.pageComposition.diagnostics}:{status:"supported",containerKey:e.pageComposition.container.key,hasBusinessMembers:e.pageComposition.businessMembers.length>0,placementUnitKeys:e.pageComposition.placementUnits.map(n=>n.key),placements:e.pageComposition.placements.map(n=>({placementKey:n.placementKey,placementUnitKey:n.placementUnitKey,relation:n.relation}))}}}function zs(e){return{composition:e.composition,key:e.key,tag:e.tag,...e.linkSourceKind?{linkSourceKind:e.linkSourceKind}:{},label:e.label,sourceLocator:e.sourceLocator,isOpaque:e.isOpaque,ancestors:e.ancestors,componentName:e.componentName,sourceFile:e.sourceFile,capabilities:qk(e.capabilities),provenanceChain:e.provenanceChain?{editMode:e.provenanceChain.editMode,diagnostics:e.provenanceChain.diagnostics}:void 0,dynamicData:e.dynamicData,...e.properties?{properties:e.properties}:{},textSegments:e.textSegments.map(t=>({index:t.index,editable:t.editable,sourceKind:t.source?.kind??null})),boundaryKind:e.boundaryKind}}function Hs(e,t){let n=new Date().toISOString();return e.type==="document-changed"?{type:"site-edit.document.changed",siteId:t.siteId,snapshotId:t.snapshotId,composition:e.composition,version:e.version,at:n}:e.type==="operation-completed"?{type:"site-edit.operation.completed",siteId:t.siteId,composition:e.composition,result:Gr(e.result),at:n}:e.type==="operation-failed"?{type:"site-edit.operation.failed",siteId:t.siteId,requestId:e.requestId,composition:e.composition,error:e.error,at:n}:e.type==="capability-changed"?{type:"site-edit.capability.changed",siteId:t.siteId,composition:e.composition,keys:e.keys,at:n}:e.type==="graph-invalidated"?{type:"site-edit.graph.invalidated",siteId:t.siteId,composition:e.composition,at:n}:e.type==="graph-ready"?{type:"site-edit.graph.ready",siteId:t.siteId,composition:e.composition,version:e.version,at:n}:e.type==="graph-error"?{type:"site-edit.graph.error",siteId:t.siteId,composition:e.composition,message:e.message,at:n}:null}function qk(e){return{composition:e.composition,key:e.key,canUpdateText:e.canUpdateText,canInsertChild:e.canInsertChild,canMove:e.canMove,canRemove:e.canRemove,editModes:e.editModes?{updateText:e.editModes.updateText?{mode:e.editModes.updateText.mode,reasonCode:e.editModes.updateText.reasonCode}:void 0,insertChild:e.editModes.insertChild?{mode:e.editModes.insertChild.mode,reasonCode:e.editModes.insertChild.reasonCode}:void 0,move:e.editModes.move?{mode:e.editModes.move.mode,reasonCode:e.editModes.move.reasonCode}:void 0,remove:e.editModes.remove?{mode:e.editModes.remove.mode,reasonCode:e.editModes.remove.reasonCode}:void 0}:void 0,constraints:e.constraints}}import{checkGlobalsCssEdit as _D,computeSiteEditCompositionKey as CD,getSiteEditSourceDeleteProtectionReason as RD,isSiteEditTextSourcePath as ND,parseSiteEditRepeatInstanceKey as PD,SITE_EDIT_SOURCE_DELETE_CAPABILITY as AD,stripSiteEditRepeatInstanceKeys as $t}from"@vcp-dev/contracts";import ol from"node:path";import{parse as TD}from"yaml";import tu from"node:path";import{TextDecoder as e_}from"node:util";import{SITE_EDIT_SOURCE_ALLOWED_APP_FILES as fg,SITE_EDIT_SOURCE_ALLOWED_DIRS as pg,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as mg,SiteEditCompositionContextSchema as t_,SiteEditSourceFileResponseSchema as Zl,SiteEditSourceLocationSchema as n_,SiteEditSourcePathSchema as Ws,SiteEditSourceTreeResponseSchema as r_,isSiteEditTextSourcePath as o_}from"@vcp-dev/contracts";import{createHash as Qk}from"node:crypto";var gi=class{constructor(t){this.original=new Map,this.files=new Map,this.versions=new Map;for(let n of t)this.original.set(n.path,n.content),this.files.set(n.path,n.content),this.versions.set(n.path,n.version??1)}async readFile(t){let n=this.files.get(t);if(n===void 0)throw new Error(`Snapshot file not found: ${t}`);return n}async readFileBytes(t){return Buffer.from(await this.readFile(t),"utf8")}async getFileInfo(t){let n=this.files.get(t);return n===void 0?null:{path:t,sizeBytes:Buffer.byteLength(n,"utf8")}}async writeFile(t,n){this.files.set(t,n)}async createExclusive(t,n){if(this.files.has(t))throw Object.assign(new Error(`Snapshot file already exists: ${t}`),{code:"EEXIST"});this.files.set(t,n)}async deleteFile(t){this.files.delete(t)}async exists(t){return this.files.has(t)}async listFiles(t={}){let n=t.roots??[],r=[...this.files.keys()].filter(a=>n.length===0?!0:n.some(c=>a===c||a.startsWith(`${c}/`))),o=[],i=new Set,s=0;for(let a of r.sort()){let c=Buffer.byteLength(this.files.get(a)??"","utf8"),l=a.split("/").length;if(t.maxDepth!==void 0&&l>t.maxDepth){i.add("max-depth");continue}if(t.maxFiles!==void 0&&o.length>=t.maxFiles){i.add("max-files");break}if(t.maxTotalBytes!==void 0&&s+c>t.maxTotalBytes){i.add("max-total-bytes");break}o.push({path:a,sizeBytes:c}),s+=c}return i.size>0?{files:o,truncated:{reasons:[...i]}}:{files:o}}getVersion(t){return this.versions.get(t)??0}bumpVersion(t){let n=this.getVersion(t)+1;return this.versions.set(t,n),n}getChangedFiles(){let t=new Set([...this.original.keys(),...this.files.keys()]),n=[];for(let r of[...t].sort()){let o=this.original.get(r),i=this.files.get(r);o!==i&&n.push({path:r,before:o,after:i})}return n}};function ke(e){return`sha256:${Qk("sha256").update(e).digest("hex")}`}var i_=[...mg,...fg,...pg];function nu(e){if(!e.composition)throw new Error("Composition unavailable for source access policy.");return t_.parse(e.composition)}var ql=2e3,Ql=12,eu=24*1024*1024,dg=512*1024,s_=new Set(["image/avif","image/gif","image/jpeg","image/png","image/webp","image/x-icon"]),a_={".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"},c_={".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"},l_=new e_("utf-8",{fatal:!0});async function Gs(e,t={}){let n=nu(t),{files:r,truncated:o}=await h_(e,t),i=b_(r.map(s=>s.metadata));return r_.parse({composition:n,nodes:i,defaultPath:E_(r.map(s=>s.metadata)),totalFiles:r.length,...o?{truncated:o}:{}})}async function Ys(e,t,n={}){let r=nu(n),o=Ws.parse(t.path),i=await d_(e,o,n);if(!i)throw new Error(`Source file not found: ${o}`);if(ou(o)){let a=yg(o),c=await p_(e,{path:o,sizeBytes:i.sizeBytes,mimeType:a});return Zl.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:i.sizeBytes,mimeType:a,readonly:!0,...c})}let s=await ru(e,o);return s.ok?Zl.parse({composition:r,path:o,kind:"text",language:xg(o),sizeBytes:s.sizeBytes,contentHash:ke(s.content),readonly:!1,content:s.content}):Zl.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:s.sizeBytes,mimeType:"application/octet-stream",readonly:!0,previewUnavailableReason:"unsupported-mime"})}async function ru(e,t){if(e.readFileBytes){let o=await e.readFileBytes(t),i=u_(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 u_(e){if(e.includes(0))return null;try{return l_.decode(e)}catch{return null}}async function d_(e,t,n){if(!m_(t,n))return null;let r=await f_(e,t);return r?{path:t,sizeBytes:r.sizeBytes}:null}async function f_(e,t){if(e.getFileInfo)return e.getFileInfo(t);if(e.listFiles){let o=gg(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(ou(t))return{path:t,sizeBytes:0};let n=await e.readFile(t);return{path:t,sizeBytes:Buffer.byteLength(n,"utf8")}}async function p_(e,t){if(!s_.has(t.mimeType))return{previewUnavailableReason:"unsupported-mime"};if(t.sizeBytes>dg)return{previewUnavailableReason:"too-large"};if(!e.readFileBytes)return{previewUnavailableReason:"bytes-unavailable"};let n=await e.readFileBytes(t.path);return n.byteLength>dg?{previewUnavailableReason:"too-large"}:{contentBase64:Buffer.from(n).toString("base64")}}function m_(e,t){return mg.some(n=>n===e)||fg.some(n=>n===e)||pg.some(n=>e===n||e.startsWith(`${n}/`))?!0:!e.startsWith("app/")&&!e.startsWith("src/app/")?!1:(t.routeEntryFiles??[]).some(n=>{let r=Ws.safeParse(n);return r.success&&r.data===e})}function Zs(e,t){if(!t.sourceLocator)throw new Error(`Source location not available for key: ${e.key}`);return n_.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 gg(e){return Array.isArray(e)?{files:e}:e}function g_(e){return["max-files","max-depth","max-total-bytes"].filter(n=>e.includes(n))}async function h_(e,t){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let n=gg(await e.listFiles({roots:y_(t),maxFiles:ql+1,maxDepth:Ql,maxTotalBytes:eu+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=Ws.safeParse(a.path);if(!c.success)continue;let l=c.data;if(l.split("/").length>Ql){o.add("max-depth");continue}if(r.size>=ql){o.add("max-files");break}if(i+a.sizeBytes>eu){o.add("max-total-bytes");break}r.set(l,{path:l,sizeBytes:a.sizeBytes,metadata:x_(l,a.sizeBytes,nu(t))}),i+=a.sizeBytes}return{files:[...r.values()].sort((a,c)=>a.path.localeCompare(c.path)),...o.size>0?{truncated:{reasons:g_([...o]),maxFiles:ql,maxDepth:Ql,maxTotalBytes:eu}}:{}}}function y_(e){let t=new Set(i_);for(let n of e.routeEntryFiles??[]){let r=Ws.safeParse(n);r.success&&(r.data.startsWith("app/")||r.data.startsWith("src/app/"))&&t.add(r.data)}return[...t]}function x_(e,t,n){return ou(e)?{composition:n,path:e,kind:"binary",language:null,sizeBytes:t,mimeType:yg(e),readonly:!0}:{composition:n,path:e,kind:"text",language:xg(e),sizeBytes:t,readonly:!1}}function b_(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 hg(t)}function hg(e){return e.map(t=>t.kind==="directory"?{...t,children:hg(t.children)}:t).sort((t,n)=>t.kind!==n.kind?t.kind==="directory"?-1:1:t.name.localeCompare(n.name))}function E_(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 ou(e){return!o_(e)}function yg(e){let t=tu.posix.extname(e).toLowerCase();return!t&&tu.posix.basename(e).toLowerCase()==="favicon"?"image/x-icon":a_[t]??"application/octet-stream"}function xg(e){let t=tu.posix.extname(e).toLowerCase();return c_[t]??"plaintext"}import*as Zr from"@babel/types";import iu from"@babel/traverse";import*as Nn from"@babel/types";function Ye(e){if(e.isJSXFragment())return!0;if(!e.isJSXElement())return!1;let t=e.node.openingElement.name;if(Nn.isJSXIdentifier(t)){let o=e.scope.getBinding(t.name);if(!o)return!1;let i=o.path;if(!i.isImportSpecifier())return!1;let s=i.node.imported;return(Nn.isIdentifier(s)&&s.name==="Fragment"||Nn.isStringLiteral(s)&&s.value==="Fragment")&&bg(i.parentPath)}if(!Nn.isJSXMemberExpression(t)||!Nn.isJSXIdentifier(t.property)||t.property.name!=="Fragment"||!Nn.isJSXIdentifier(t.object))return!1;let n=e.scope.getBinding(t.object.name);if(!n)return!1;let r=n.path;return(r.isImportDefaultSpecifier()||r.isImportNamespaceSpecifier())&&bg(r.parentPath)}function bg(e){return e?.isImportDeclaration()===!0&&e.node.source.value==="react"}var cr=typeof iu=="function"?iu:iu.default,qs=new WeakMap,Qs=new WeakMap;function Pn(e,t){let n=Xl(e,t);if(!n.ok)return Jl(e,n.diagnostic.code,n.diagnostic.message,t.kind);let r=Ie(n.ast,t);return r.ok?{ok:!0,match:{locatorKind:r.match.locatorKind,node:r.match.node,start:r.match.start,end:r.match.end}}:Jl(e,r.diagnostic.code,r.diagnostic.message,t.kind,r.diagnostic.details)}function Ie(e,t){return t.kind==="jsx-node"?vg(e,t):t.kind==="jsx-attribute"?C_(e,t):t.kind==="value"?R_(e,t):t.kind==="expression"?N_(e,t):t.kind==="directive"?P_(e,t):t.kind==="export"?A_(e,t):{ok:!1,diagnostic:Xr("unsupported-syntax",`Unsupported locator kind: ${t.kind}`)}}function vg(e,t){return t.strategy==="source-range"?S_(e,t):I_(e,t)}function S_(e,t){let n=null;if(cr(e,{JSXElement(o){if(!Yr(o.node,t.sourceRange))return;let i=it("jsx-node",o);if(i){if(!n){n=i;return}i.end-i.start<n.end-n.start&&(n=i)}},JSXFragment(o){if(!Yr(o.node,t.sourceRange))return;let i=it("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXExpressionContainer(o){if(!Yr(o.node,t.sourceRange))return;let i=it("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXText(o){if(!Yr(o.node,t.sourceRange))return;let i=it("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)}}),!n)return ut("jsx-node","locator-miss","JSX node not found for source-range locator");let r=n;return t.expectedIdentity&&!U_(r.path,t.expectedIdentity)?ut("jsx-node","locator-miss","JSX node failed expected identity validation"):{ok:!0,match:r}}function I_(e,t){if(t.structuralPath===""){let r=k_(e,t.component);if(r){let o=__(r);if(o)return o}}let n=null;return cr(e,{JSXElement(r){if(yi(r)!==t.component||au(r)!==t.structuralPath)return;let i=it("jsx-node",r);i&&(n=i,r.stop())},JSXFragment(r){if(yi(r)!==t.component||au(r)!==t.structuralPath)return;let i=it("jsx-node",r);i&&(n=i,r.stop())}}),!n&&t.expectedRange&&(n=v_(e,t.component,t.expectedRange)),n?{ok:!0,match:n}:ut("jsx-node","locator-miss","JSX node not found for structural-path locator")}function v_(e,t,n){let r=null;return cr(e,{JSXElement(o){if(yi(o)!==t||!Yr(o.node,n))return;let i=it("jsx-node",o);i&&(r=i,o.stop())},JSXFragment(o){if(yi(o)!==t||!Yr(o.node,n))return;let i=it("jsx-node",o);i&&(r=i,o.stop())}}),r}function k_(e,t){let n=null;return cr(e,{FunctionDeclaration(r){r.node.id?.name===t&&(n=r,r.stop())},VariableDeclarator(r){if(r.node.id.type==="Identifier"&&r.node.id.name===t){let o=r.get("init");(o.isArrowFunctionExpression()||o.isFunctionExpression())&&(n=o),r.stop()}}}),n}function __(e){if(e.isArrowFunctionExpression()){let t=e.get("body");if(t.isBlockStatement()){let r=t.get("body").find(o=>o.isReturnStatement());if(r){let o=r.get("argument");if((o.isParenthesizedExpression()?o.get("expression"):o).isJSXFragment())return ut("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}return null}return(t.isParenthesizedExpression()?t.get("expression"):t).isJSXFragment()?ut("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target"):null}if(e.isFunctionDeclaration()||e.isFunctionExpression()){let t=e.get("body");if(t.isBlockStatement()){let n=t.get("body").find(r=>r.isReturnStatement());if(n){let r=n.get("argument");if((r.isParenthesizedExpression()?r.get("expression"):r).isJSXFragment())return ut("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}}}return null}function C_(e,t){let n=vg(e,t.element);if(!n.ok)return n;let s=n.match.path.get("openingElement").get("attributes").find(c=>K_(c,t.name));if(!s||!s.isJSXAttribute())return ut("jsx-attribute","locator-miss",`JSX attribute '${t.name}' not found`);let a=it("jsx-attribute",s);return a?{ok:!0,match:a}:ut("jsx-attribute","locator-miss",`JSX attribute '${t.name}' has no source range`)}function R_(e,t){let n=T_(e,t);if(!n.ok)return n;let r=w_(n.match.path,t.path??[]);return r.ok?t.expectedRange&&!Xn(r.match.path.node.loc,t.expectedRange)?ut("value","locator-miss","Resolved value does not match expected range"):{ok:!0,match:r.match}:r}function N_(e,t){let n=null;return cr(e,{Identifier(r){if(!B_(r))return;let o=Sg(r);if(!o||!Ig(o,t))return;let i=it("expression",r);i&&(t.expectedRange&&!Xn(r.node.loc,t.expectedRange)||(n=i,r.stop()))},MemberExpression(r){let o=Sg(r);if(!o||!Ig(o,t))return;let i=it("expression",r);i&&(t.expectedRange&&!Xn(r.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:ut("expression","locator-miss","Expression not found")}function P_(e,t){let n=null;return cr(e,{Program(r){let i=r.get("directives").find(a=>a.node.value.value===t.value);if(!i||t.expectedRange&&!Xn(i.node.loc,t.expectedRange))return;let s=it("directive",i);s&&(n=s,r.stop())}}),n?{ok:!0,match:n}:ut("directive","locator-miss",`Directive '${t.value}' not found`)}function A_(e,t){let n=null;return cr(e,{ExportNamedDeclaration(r){if(t.exportKind==="generate-metadata"){let c=r.get("declaration");if(c.isFunctionDeclaration()&&c.node.id?.name==="generateMetadata"){let f=it("export",c);if(!f||t.expectedRange&&!Xn(c.node.loc,t.expectedRange))return;n=f,r.stop();return}if(!c.isVariableDeclaration())return;let l=cu(c,"generateMetadata");if(!l||!l.isVariableDeclarator())return;let u=l.get("init");if(!u.node)return;let d=it("export",u);if(!d||t.expectedRange&&!Xn(u.node.loc,t.expectedRange))return;n=d,r.stop();return}let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=cu(o,t.exportKind==="named"?t.name:"metadata");if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node||t.expectedRange&&!Xn(s.node.loc,t.expectedRange))return;let a=it("export",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(t.exportKind!=="default")return;let o=r.get("declaration"),i=it("export",o);i&&(t.expectedRange&&!Xn(o.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:ut("export","export-not-found",`Export '${V_(t)}' not found`)}function T_(e,t){let n=null;return cr(e,{Expression(r){if(n||t.root.kind!=="expression"||!Yr(r.node,t.root.sourceRange))return;let o=it("value",r);o&&(n=o,r.stop())},VariableDeclarator(r){if(n)return;if(t.root.kind==="binding"){if(r.node.id.type!=="Identifier"||r.node.id.name!==t.root.name)return;let g=r.get("init");if(!g.node)return;let p=it("value",g);if(!p)return;n=p,r.stop();return}if(t.root.kind!=="hook-state")return;let o=t.root,i=r.get("id"),s=r.get("init");if(!i.isArrayPattern()||!s.isCallExpression()||i.node.elements.findIndex(g=>g?.type==="Identifier"&&g.name===o.name)!==0)return;let c=s.node.callee;if((c.type==="Identifier"?c.name:c.type==="MemberExpression"&&c.property.type==="Identifier"?c.property.name:null)!==o.hook)return;let u=o.hook==="useReducer"?1:0,d=r.get(`init.arguments.${u}`);if(!d||Array.isArray(d)||!d.node)return;let f=it("value",d);f&&(n=f,r.stop())},ExportNamedDeclaration(r){if(n||t.root.kind!=="named-export")return;let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=cu(o,t.root.name);if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node)return;let a=it("value",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(n||t.root.kind!=="default-export")return;let o=r.get("declaration"),i=it("value",o);i&&(n=i,r.stop())}}),n?{ok:!0,match:n}:ut("value",t.root.kind==="named-export"||t.root.kind==="default-export"?"export-not-found":t.root.kind==="expression"?"locator-miss":"binding-not-found","Value root was not found")}function w_(e,t){let n=su(e);for(let o of t){if(n=su(n),o.kind==="property"){if(!n.isObjectExpression())return ut("value","unsupported-syntax","Property path requires object expression");let a=n.get("properties");if(a.some(l=>!l.isObjectProperty()))return ut("value","unsupported-syntax","Spread properties are not supported");let c=a.find(l=>J_(l,o.name));if(!c||!c.isObjectProperty())return ut("value","property-not-found",`Property '${o.name}' not found`);n=c.get("value");continue}if(!n.isArrayExpression())return ut("value","unsupported-syntax","Array index path requires array expression");let i=n.get("elements");if(i.some(a=>a.node?.type==="SpreadElement"))return ut("value","unsupported-syntax","Spread array elements are not supported");let s=i[o.index];if(!s?.node)return ut("value","array-index-out-of-range",`Array index ${o.index} is out of range`);n=s}n=su(n);let r=it("value",n);return r?{ok:!0,match:r}:ut("value","locator-miss","Resolved value has no source range")}function su(e){let t=e;for(;t.isTSAsExpression()||t.isTSSatisfiesExpression()||t.isTSNonNullExpression();)t=t.get("expression");return t}function it(e,t){let n=t.node;return n.start==null||n.end==null?null:{locatorKind:e,node:n,start:n.start,end:n.end,path:t}}function Yr(e,t){return Xn(e.loc,t)}function Xn(e,t){return e?e.start.line===t.startLine&&e.start.column===t.startColumn&&e.end.line===t.endLine&&e.end.column===t.endColumn:!1}function au(e){let t=[],n=e,r=e.node;for(;n;){if(n.isJSXElement()){if(!Ye(n)){let o=_g(n.node.openingElement);o&&(/^[A-Z]/.test(o)?t.unshift(`component:${o}#${Eg(n,o)}`):t.unshift(`${o}#${Eg(n,o)}`))}}else n.isJSXFragment()&&n.node===r&&t.unshift("fragment");if(!n.parentPath||D_(n.parentPath)&&!M_(n.parentPath))break;n=n.parentPath}return t.join("/")}function Eg(e,t){let n=kg(e)??e.getFunctionParent();if(!n)return 0;let r=qs.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=0,i=qs.get(n.node)?.get(t);if(!i){let a=qs.get(n.node);a||(a=new Map,qs.set(n.node,a)),i=new WeakMap,a.set(t,i)}let s=n.isJSXElement()||n.isJSXFragment()?hi(n):O_(n);for(let a of s)if(_g(a.node.openingElement)===t){if(i.set(a.node,o),a.node===e.node)return o;o++}return i.get(e.node)??0}function O_(e){let t=Qs.get(e.node);if(t)return t;let n=[];return e.traverse({JSXElement(r){r.getFunctionParent()?.node===e.node&&!kg(r)&&n.push(r)}}),Qs.set(e.node,n),n}function kg(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(Ye(t)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function hi(e){let t=Qs.get(e.node);if(t)return t;let n=[],r=e.get("children");for(let o of r)if(!Array.isArray(o)){if(o.isJSXElement()){if(Ye(o)){n.push(...hi(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...hi(o));continue}o.isJSXExpressionContainer()&&n.push(...Jn(o.get("expression")))}return Qs.set(e.node,n),n}function Jn(e){if(e.isJSXElement())return Ye(e)?hi(e):[e];if(e.isJSXFragment())return hi(e);if(e.isParenthesizedExpression())return Jn(e.get("expression"));if(e.isLogicalExpression()&&F_(e.node.operator))return Jn(e.get("right"));if(e.isCallExpression()||e.isOptionalCallExpression()){let t=e.get("callee"),n=!Array.isArray(t)&&(t.isMemberExpression()||t.isOptionalMemberExpression())?t.get("property"):null;if(!Array.isArray(t)&&(t.isMemberExpression()||t.isOptionalMemberExpression())&&!t.node.computed&&n!==null&&!Array.isArray(n)&&n.isIdentifier()&&n.node.name==="map"){let r=e.get("arguments").find(o=>!Array.isArray(o)&&(o.isArrowFunctionExpression()||o.isFunctionExpression()));if(r&&!Array.isArray(r)){let o=r.get("body");if(!Array.isArray(o)){if(o.isBlockStatement()){let i=[];for(let s of o.get("body")){if(s.isVariableDeclaration())for(let a of s.get("declarations")){let c=a.get("init");(c.isJSXElement()||c.isJSXFragment())&&i.push(...Jn(c))}if(s.isReturnStatement()){let a=s.get("argument");a.isExpression()&&i.push(...Jn(a));break}}return i}else if(o.node&&o.isExpression())return Jn(o)}}}}return e.isConditionalExpression()?[...Jn(e.get("consequent")),...Jn(e.get("alternate"))]:e.isArrayExpression()?e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:Jn(t)):[]}function F_(e){return e==="&&"||e==="||"||e==="??"}function _g(e){return e.name.type==="JSXIdentifier"?e.name.name:e.name.type==="JSXMemberExpression"?L_(e.name):null}function L_(e){let t=[],n=e;for(;n.type==="JSXMemberExpression";)t.unshift(n.property.name),n=n.object;return t.unshift(n.name),t.join(".")}function yi(e){let t=e;for(;t;){if(t.isFunctionDeclaration())return t.node.id?.name??null;if((t.isArrowFunctionExpression()||t.isFunctionExpression())&&t.parentPath?.isVariableDeclarator()){let n=t.parentPath.node.id;return n.type==="Identifier"?n.name:null}t=t.parentPath}return null}function D_(e){return!!(e.isFunctionDeclaration()||e.isFunctionExpression()||e.isArrowFunctionExpression())}function M_(e){let t=e.parentPath;if(!t||!t.isCallExpression()&&!t.isOptionalCallExpression())return!1;let n=t.get("callee"),r=!Array.isArray(n)&&(n.isMemberExpression()||n.isOptionalMemberExpression())?n.get("property"):null;if(Array.isArray(n)||!n.isMemberExpression()&&!n.isOptionalMemberExpression()||n.node.computed||r===null||Array.isArray(r)||!r.isIdentifier()||r.node.name!=="map")return!1;let o=t.get("arguments");return Array.isArray(o)?o.some(i=>!Array.isArray(i)&&i.node===e.node):!1}function B_(e){return!(!e.isExpression()||e.parentPath?.isMemberExpression({property:e.node}))}function Sg(e){if(e.isIdentifier())return{base:e.node.name,path:[]};if(!e.isMemberExpression())return null;let t=[],n=e.node;for(;n.type==="MemberExpression";){if(n.computed)if(n.property.type==="NumericLiteral")t.unshift({kind:"index",index:n.property.value});else if(n.property.type==="StringLiteral")t.unshift({kind:"property",name:n.property.value});else return null;else if(n.property.type==="Identifier")t.unshift({kind:"property",name:n.property.name});else return null;if(n.object.type==="Identifier")return{base:n.object.name,path:t};if(n.object.type!=="MemberExpression")return null;n=n.object}return null}function Ig(e,t){return e.base===t.base&&j_(e.path,t.path??[])}function j_(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],o=t[n];if(r.kind!==o.kind)return!1;if(r.kind==="property"){if(o.kind!=="property"||r.name!==o.name)return!1;continue}if(o.kind!=="index"||r.index!==o.index)return!1}return!0}function $_(e){return e.key.type==="Identifier"?e.key.name:e.key.type==="StringLiteral"?e.key.value:null}function V_(e){return e.exportKind==="named"?e.name:e.exportKind}function ut(e,t,n,r){return{ok:!1,diagnostic:Xr(t,n,e,r)}}function U_(e,t){return yi(e)!==t.component?!1:au(e)===t.structuralPath}function K_(e,t){return!e.isJSXAttribute()||e.node.name.type!=="JSXIdentifier"?!1:e.node.name.name===t}function cu(e,t){return e.get("declarations").find(n=>!n.isVariableDeclarator()||n.node.id.type!=="Identifier"?!1:n.node.id.name===t)}function J_(e,t){return e.isObjectProperty()?$_(e.node)===t:!1}import*as Rg from"@babel/parser";import{arrayExpression as G_,booleanLiteral as Y_,identifier as Z_,jsxAttribute as q_,jsxExpressionContainer as Q_,jsxIdentifier as eC,nullLiteral as tC,numericLiteral as nC,objectExpression as rC,objectProperty as oC,stringLiteral as uu}from"@babel/types";import lu from"@babel/generator";var X_=typeof lu=="function"?lu:lu.default;function z_(e){let t=e.split(`
1
+ import*as mk from"@babel/parser";import*as Ct from"@babel/types";import*as ir from"node:path";var Kl=[".tsx",".ts",".jsx",".js"],gk=Kl.map(e=>`/index${e}`),hk=new Set(["json","css","scss","sass","less","svg","png","jpg","jpeg","gif","webp","avif","ico","bmp","woff","woff2","ttf","otf","eot","mp4","webm","mp3","wav","ogg","pdf","txt","md","csv","xml","yaml","yml"]);function Gm(e){let t=e.replace(/[?#].*$/,""),n=/\.([a-z0-9]+)$/i.exec(t);return n!==null&&hk.has(n[1].toLowerCase())}function Ym(e){let t=[];for(let n of e.program.body)Ct.isImportDeclaration(n)&&typeof n.source.value=="string"&&nt(n.source.value)&&t.push(n.source.value),Ct.isExportNamedDeclaration(n)&&n.source&&typeof n.source.value=="string"&&nt(n.source.value)&&t.push(n.source.value),Ct.isExportAllDeclaration(n)&&typeof n.source.value=="string"&&nt(n.source.value)&&t.push(n.source.value);return Ct.traverseFast(e.program,n=>{let r=Ct.isImportExpression(n)?n.source:Ct.isCallExpression(n)&&Ct.isImport(n.callee)?n.arguments[0]:null;Ct.isStringLiteral(r)&&nt(r.value)&&t.push(r.value)}),t}function nt(e){return e.startsWith("./")||e.startsWith("../")||e.startsWith("@/")}function Cn(e,t){if(t.startsWith("@/"))return t.slice(2).replace(/\\/g,"/");let n=ir.dirname(e);return ir.join(n,t).replace(/\\/g,"/")}async function yk(e,t){for(let n of Zm(e))if(await t(n))return n;return null}function Zm(e){return[...Kl.some(t=>e.endsWith(t))?[e]:[],...Kl.map(t=>`${e}${t}`),...gk.map(t=>`${e}${t}`)]}function sr(e,t,n){let r=Cn(e,t);if(!nt(t)||!qm(e,t,r))return null;for(let o of Zm(r))if(n.has(o))return o;return null}async function Jr(e,t,n){let r=await js(e,t,n);return r.ok?r.path:null}async function js(e,t,n){let r=Cn(e,t);try{if(!qm(e,t,r))return{ok:!1,diagnostic:{path:r,code:"import-not-found",message:`Local import not found: ${t}`,details:{fromFile:e,specifier:t}}};let o=await yk(r,n);return o?{ok:!0,path:o}:{ok:!1,diagnostic:{path:r,code:"import-not-found",message:`Local import not found: ${t}`,details:{fromFile:e,specifier:t}}}}catch(o){return{ok:!1,diagnostic:{path:r,code:"import-resolve-failed",message:`Failed to resolve local import: ${t}`,details:{fromFile:e,specifier:t,reason:o instanceof Error?o.message:String(o)}}}}}function qm(e,t,n){if(!nt(t)||t.includes("\0")||t.includes("\\")||ir.posix.isAbsolute(n))return!1;let r=ir.posix.normalize(n);if(r===".."||r.startsWith("../"))return!1;if(t.startsWith("@/")){let o=t.slice(2);return o.length>0&&!o.split("/").some(i=>i==="..")}return!ir.posix.isAbsolute(e)}import{createHash as bk}from"node:crypto";import*as Qm from"@babel/parser";function Xr(e,t,n,r){return{code:e,message:t,locatorKind:n,details:r}}function ee(e,t,n,r,o){return{ok:!1,source:e,diagnostic:Xr(t,n,r,o)}}function Jl(e,t,n,r,o){return{ok:!1,source:e,diagnostic:Xr(t,n,r,o)}}var xk={"tsx-module":["jsx","typescript"],"ts-module":["typescript"],"next-app-entry":["jsx","typescript"]};function Rn(e){let{source:t,profile:n}=e;try{return{ok:!0,ast:Qm.parse(t,{sourceType:"module",plugins:xk[n]})}}catch(r){return{ok:!1,source:t,diagnostic:Xr("parse-failed",`AST parse failed: ${r instanceof Error?r.message:String(r)}`)}}}function Xl(e,t){return Rn({source:e,profile:eg(t.kind)})}function pi(e,t){return Rn({source:e,profile:eg(t)})}function eg(e){return"next-app-entry"}function zr(e){let{filePath:t,source:n}=e,r=t.toLowerCase().split(".").pop()??"";return r==="tsx"?"tsx-module":r==="ts"?"ts-module":r==="jsx"||r==="js"||r===""&&/<\w[\s\S]*>/.test(n)?"tsx-module":"next-app-entry"}var je=(e,t)=>{let n=Rn({source:t,profile:zr({filePath:e,source:t})});return n.ok?{ok:!0,module:{file:e,source:t,sourceHash:`sha256:${bk("sha256").update(t).digest("hex")}`,ast:n.ast,imports:Ym(n.ast).map(r=>({specifier:r}))}}:{ok:!1,diagnostic:{path:e,code:"parse-failed",message:n.diagnostic.message}}};function Ek(e,t){return je(e,t)}function Sk(e,t){return Cn(e,t)}import{COMPONENT_I18N_FILE_SUFFIX as Ik,parseComponentI18nResourcesJson as vk,resolveSiteTextDirection as kk,SiteLocaleSchema as _k}from"@vcp-dev/contracts";var Ck=["i18next","react-i18next"],Rk="components/ui/site-locale-provider.tsx",Nk="components/ui/component-i18n-provider.tsx",tg="app/layout.tsx";async function mi(e){let t=e.files.filter(f=>f.path.endsWith(Ik));if(t.length===0)return{ok:!0};for(let f of["package.json",tg,Rk,Nk])if(!await e.exists(f))return ar(`Target snapshot is missing required i18n host file: ${f}`);let n;try{n=JSON.parse(await e.readFile("package.json"))}catch{return ar("Target snapshot package.json is invalid.")}let r=ng(n)&&ng(n.dependencies)?n.dependencies:{},o=Ck.filter(f=>typeof r[f]!="string"||r[f].trim().length===0);if(o.length>0)return ar(`Target snapshot must already declare: ${o.join(", ")}.`);let i=await e.readFile(tg),s=zl(i,"html","lang"),a=zl(i,"html","dir"),c=zl(i,"SiteLocaleProvider","locale"),l=_k.safeParse(s);if(!l.success||!a||!c||s!==c||a!==kk(l.data))return ar("Target snapshot app/layout.tsx must keep html lang/dir and SiteLocaleProvider locale consistent.");if(!i.includes('from "@/components/ui/site-locale-provider"')||!/<SiteLocaleProvider\b/.test(i)||!/<\/SiteLocaleProvider>/.test(i))return ar("Target snapshot root layout is not wired to SiteLocaleProvider.");let u=l.data;if(e.targetLocale&&e.targetLocale!==u)return ar("Target snapshot locale does not match the authoritative site language.");let d=u.split("-")[0];for(let f of t){let g=vk(f.content);if(!g.success)return ar(`Component i18n resource is invalid: ${f.path}.`);if(!e.deferTargetLocale&&!Object.hasOwn(g.data,u)&&!Object.hasOwn(g.data,d))return ar(`Component i18n resource ${f.path} has no locale for ${u} or ${d}.`)}return{ok:!0}}function zl(e,t,n){let r=e.match(new RegExp(`<${t}\\b[^>]*>`))?.[0];if(!r)return null;let o=[...r.matchAll(new RegExp(`\\b${n}=(?:"([^"]+)"|\\{"([^"]+)"\\})`,"g"))];return o.length!==1?null:o[0]?.[1]??o[0]?.[2]??null}function ng(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ar(e){return{ok:!1,message:e}}import Wl from"@babel/generator";import*as cg from"@babel/parser";import Gl from"@babel/traverse";import*as He from"@babel/types";import{computeSiteEditSourceIdentityKey as Ak}from"@vcp-dev/contracts";var rg="data-vcp-ui-component",$s="components/ui";function Kn(e){if(!e)return!1;let t=Hl(e);return t===$s||t.startsWith(`${$s}/`)||t.includes(`/${$s}/`)||t.endsWith(`/${$s}`)}function Hr(e,t){return e?e.startsWith("@/")||e.startsWith("~/")?Kn(e.slice(2)):e.startsWith("./")||e.startsWith("../")?Kn(Hl(`${Pk(t)}/${e}`)):Kn(e):!1}function Hl(e){let n=(e.split("?")[0]??e).replace(/\\/g,"/").replace(/^\.\//,""),r=[];for(let o of n.split("/"))if(!(!o||o===".")){if(o===".."){r.pop();continue}r.push(o)}return r.join("/")}function Pk(e){let t=Hl(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}import{stripSiteEditRepeatInstanceKeys as i$}from"@vcp-dev/contracts";import{isSiteEditRuntimeContainerTag as a$,isSiteEditRuntimeTextTag as c$}from"@vcp-dev/contracts/site-edit-runtime-capability";var og={key:"data-vcp-edit-key",parentKey:"data-vcp-edit-parent-key",movable:"data-vcp-movable",removable:"data-vcp-removable",flags:"data-vcp-flags",publicUiComponent:"data-vcp-ui-component"};var Tk=typeof Wl=="function"?Wl:Wl.default,wk=typeof Gl=="function"?Gl:Gl.default,Ok=new Set(["base","body","head","html","link","meta","noscript","script","style","template","title"]),Fk="suppressHydrationWarning",Lk=new Set(["SiteEditBootstrap"]);function Mk(e){let t=jk(e.file,e.projectRoot);if(!Bk(e.source)||Kn(t))return{code:e.source,elements:[]};let n=e.attributes??og,r=cg.parse(e.source,{sourceType:"module",plugins:["jsx","typescript"]}),o=[],i=Vk(r,t);return wk(r,{JSXElement(s){let a=s.node.openingElement,c=a.name;if(!Kk(c)||lg(a,n.key))return;let l=Xk(s)??"default",u=Hk(s),d=Ak(t,l,u),f=Us(c)??"unknown",g=$k(c)?"jsx":"component-call";if(g==="component-call"&&!zk(s.node.children)&&Lk.has(f))return;let p=g==="component-call"&&Uk(f,i);Jk(a,n.key,d),p&&ig(a,rg),Dk(s)&&ig(a,Fk),o.push({key:d,tag:f,componentName:l,sourceFile:t,sourceKind:g})}}),o.length===0?{code:e.source,elements:o}:{code:Tk(r,{jsescOption:{minimal:!0}}).code,elements:o}}function Dk(e){return!e.findParent(t=>t.isJSXElement())}function Bk(e){return/(?:^|[=(:,?;\[{>&|\n\r]|return\s+)\s*<(?:[A-Za-z][\w.:-]*|>)(?:\s|>|\/)/m.test(e)}function jk(e,t){let n=e.replace(/\\/g,"/").replace(/^\.\//,""),r=t?.replace(/\\/g,"/").replace(/\/+$/,"");if(r&&n.startsWith(`${r}/`))return n.slice(r.length+1);for(let[i,s]of[["/src/app/",1],["/src/components/",1],["/app/",1],["/components/",1]]){let a=n.indexOf(i);if(a>=0)return n.slice(a+s)}return n.match(/(?:^|\/)((?:src\/app|src\/components|app|components)\/.+)$/)?.[1]??n}function $k(e){return He.isJSXIdentifier(e)&&/^[a-z]/.test(e.name)}function Us(e){return He.isJSXIdentifier(e)?e.name:He.isJSXMemberExpression(e)?dg(e):null}function Vk(e,t){let n=new Set;for(let r of e.program.body)if(!(!He.isImportDeclaration(r)||!Hr(r.source.value,t)))for(let o of r.specifiers)n.add(o.local.name);return n}function Uk(e,t){let n=e.split(".")[0]??e;return t.has(n)}function Kk(e){let t=Us(e);return!t||t==="Fragment"||t.endsWith(".Fragment")?!1:!Ok.has(t)}function lg(e,t){return e.attributes.some(n=>He.isJSXAttribute(n)&&He.isJSXIdentifier(n.name,{name:t}))}function Jk(e,t,n){ug(e,He.jsxAttribute(He.jsxIdentifier(t),He.stringLiteral(n)))}function ig(e,t){lg(e,t)||ug(e,He.jsxAttribute(He.jsxIdentifier(t),null))}function ug(e,t){let n=e.attributes.findIndex(r=>He.isJSXSpreadAttribute(r));if(n>=0){e.attributes.splice(n,0,t);return}e.attributes.push(t)}function dg(e){return`${He.isJSXIdentifier(e.object)?e.object.name:dg(e.object)}.${e.property.name}`}function Xk(e){let t=e;for(;t;){if(t.isFunctionDeclaration()||t.isClassDeclaration())return t.node.id?.name??null;if(t.isVariableDeclarator()&&He.isIdentifier(t.node.id)){let n=t.get("init");if(!Array.isArray(n)&&(n.isArrowFunctionExpression()||n.isFunctionExpression()))return t.node.id.name}t=t.parentPath}return null}function zk(e){return e.some(t=>He.isJSXElement(t)||He.isJSXFragment(t))}var sg=new WeakMap,Vs=new WeakMap,Yl=new WeakMap;function Hk(e){let t=sg.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=Wk(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return sg.set(e.node,o),o}function Wk(e){let t=Us(e.node.openingElement.name);return!t||t==="Fragment"||t.endsWith(".Fragment")?null:/^[A-Z]/.test(t)?`component:${t}#${ag(e,t)}`:`${t}#${ag(e,t)}`}function ag(e,t){let n=fg(e)??e.getFunctionParent();if(!n)return 0;let r=Yl.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=Yl.get(n.node);o||(o=new Map,Yl.set(n.node,o));let i=o.get(t);i||(i=new WeakMap,o.set(t,i));let s=0,a=n.isJSXElement()||n.isJSXFragment()?Ks(n):Gk(n);for(let c of a)if(Us(c.node.openingElement.name)===t){if(i.set(c.node,s),c.node===e.node)return s;s+=1}return i.get(e.node)??0}function Gk(e){let t=Vs.get(e.node);if(t)return t;let n=[];return e.traverse({JSXElement(r){r.getFunctionParent()?.node===e.node&&!fg(r)&&n.push(r)}}),Vs.set(e.node,n),n}function fg(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement())return t;t=t.parentPath}return n}function Ks(e){let t=Vs.get(e.node);if(t)return t;let n=[],r=e.get("children");for(let o of r)if(!Array.isArray(o)){if(o.isJSXElement()){n.push(o);continue}if(o.isJSXFragment()){n.push(...Ks(o));continue}o.isJSXExpressionContainer()&&n.push(...Wr(o.get("expression")))}return Vs.set(e.node,n),n}function Wr(e){if(e.isJSXElement())return[e];if(e.isJSXFragment())return Ks(e);if(e.isParenthesizedExpression())return Wr(e.get("expression"));if(e.isLogicalExpression()&&e.node.operator==="&&")return Wr(e.get("right"));if(e.isConditionalExpression())return[...Wr(e.get("consequent")),...Wr(e.get("alternate"))];if(e.isCallExpression()&&Zk(e.node)){let t=e.get("arguments")[0];return Yk(t)}return[]}function Yk(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return[t];if(t.isJSXFragment())return Ks(t);if(t.isParenthesizedExpression())return Wr(t.get("expression"));if(!t.isBlockStatement())return[];for(let n of t.get("body")){if(!n.isReturnStatement())continue;let r=n.get("argument");return r.node?Wr(r):[]}return[]}function Zk(e){return He.isMemberExpression(e.callee)&&He.isIdentifier(e.callee.property)&&e.callee.property.name==="map"}import{SiteEditOperationRequestSchema as mD,SiteEditPatchPlanSchema as gD}from"@vcp-dev/contracts";function Gr(e){return{requestId:e.requestId,kind:e.kind,composition:e.composition,target:e.target,resultVersion:e.resultVersion,affectedFiles:e.affectedFiles,...e.fileChanges?{fileChanges:e.fileChanges}:{},...e.output?{output:e.output}:{},...e.selectionRef?{selectionRef:e.selectionRef}:{}}}function Js(e,t){let n=t[0]??"Site edit operation request failed contract validation.";return{ok:!1,composition:{routeId:e.composition.routeId,...e.composition.templateId!==void 0?{effectiveTemplateId:e.composition.templateId}:{}},error:{code:"INVALID_PARAMS",message:n},data:{requestId:e.id,kind:e.kind,composition:{routeId:e.composition.routeId,...e.composition.templateId!==void 0?{effectiveTemplateId:e.composition.templateId}:{}},target:e.target,resultVersion:e.documentVersion}}}function Xs(e,t){if(!e.pageComposition)throw new Error("RenderDocument is missing the required Page Composition projection.");return{siteId:t.siteId,snapshotId:t.snapshotId,composition:e.composition,version:e.version,entries:e.entries.map(n=>({key:n.key,parentKey:n.parentKey,...n.pageCompositionUnitKey?{pageCompositionUnitKey:n.pageCompositionUnitKey}:{},...n.pageCompositionActionScope?{pageCompositionActionScope:n.pageCompositionActionScope}:{},operationSummary:{canUpdateText:n.operationSummary.canUpdateText,canInsertChild:n.operationSummary.canInsertChild,canMove:n.operationSummary.canMove,canRemove:n.operationSummary.canRemove},...n.dynamicDataSummary?{dynamicDataSummary:n.dynamicDataSummary}:{}})),...e.pageBlocks!==void 0?{pageBlocks:e.pageBlocks}:{},pageComposition:e.pageComposition.status==="unsupported"?{status:"unsupported",reason:e.pageComposition.reason,diagnostics:e.pageComposition.diagnostics}:{status:"supported",containerKey:e.pageComposition.container.key,hasBusinessMembers:e.pageComposition.businessMembers.length>0,placementUnitKeys:e.pageComposition.placementUnits.map(n=>n.key),placements:e.pageComposition.placements.map(n=>({placementKey:n.placementKey,placementUnitKey:n.placementUnitKey,relation:n.relation}))}}}function zs(e){return{composition:e.composition,key:e.key,tag:e.tag,...e.linkSourceKind?{linkSourceKind:e.linkSourceKind}:{},label:e.label,sourceLocator:e.sourceLocator,isOpaque:e.isOpaque,ancestors:e.ancestors,componentName:e.componentName,sourceFile:e.sourceFile,capabilities:qk(e.capabilities),provenanceChain:e.provenanceChain?{editMode:e.provenanceChain.editMode,diagnostics:e.provenanceChain.diagnostics}:void 0,dynamicData:e.dynamicData,...e.properties?{properties:e.properties}:{},textSegments:e.textSegments.map(t=>({index:t.index,editable:t.editable,sourceKind:t.source?.kind??null})),boundaryKind:e.boundaryKind}}function Hs(e,t){let n=new Date().toISOString();return e.type==="document-changed"?{type:"site-edit.document.changed",siteId:t.siteId,snapshotId:t.snapshotId,composition:e.composition,version:e.version,at:n}:e.type==="operation-completed"?{type:"site-edit.operation.completed",siteId:t.siteId,composition:e.composition,result:Gr(e.result),at:n}:e.type==="operation-failed"?{type:"site-edit.operation.failed",siteId:t.siteId,requestId:e.requestId,composition:e.composition,error:e.error,at:n}:e.type==="capability-changed"?{type:"site-edit.capability.changed",siteId:t.siteId,composition:e.composition,keys:e.keys,at:n}:e.type==="graph-invalidated"?{type:"site-edit.graph.invalidated",siteId:t.siteId,composition:e.composition,at:n}:e.type==="graph-ready"?{type:"site-edit.graph.ready",siteId:t.siteId,composition:e.composition,version:e.version,at:n}:e.type==="graph-error"?{type:"site-edit.graph.error",siteId:t.siteId,composition:e.composition,message:e.message,at:n}:null}function qk(e){return{composition:e.composition,key:e.key,canUpdateText:e.canUpdateText,canInsertChild:e.canInsertChild,canMove:e.canMove,canRemove:e.canRemove,editModes:e.editModes?{updateText:e.editModes.updateText?{mode:e.editModes.updateText.mode,reasonCode:e.editModes.updateText.reasonCode}:void 0,insertChild:e.editModes.insertChild?{mode:e.editModes.insertChild.mode,reasonCode:e.editModes.insertChild.reasonCode}:void 0,move:e.editModes.move?{mode:e.editModes.move.mode,reasonCode:e.editModes.move.reasonCode}:void 0,remove:e.editModes.remove?{mode:e.editModes.remove.mode,reasonCode:e.editModes.remove.reasonCode}:void 0}:void 0,constraints:e.constraints}}import{checkGlobalsCssEdit as _M,computeSiteEditCompositionKey as CM,getSiteEditSourceDeleteProtectionReason as RM,isSiteEditTextSourcePath as NM,parseSiteEditRepeatInstanceKey as PM,SITE_EDIT_SOURCE_DELETE_CAPABILITY as AM,stripSiteEditRepeatInstanceKeys as $t}from"@vcp-dev/contracts";import ol from"node:path";import{parse as TM}from"yaml";import tu from"node:path";import{TextDecoder as e_}from"node:util";import{SITE_EDIT_SOURCE_ALLOWED_APP_FILES as mg,SITE_EDIT_SOURCE_ALLOWED_DIRS as gg,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as hg,SiteEditCompositionContextSchema as t_,SiteEditSourceFileResponseSchema as Zl,SiteEditSourceLocationSchema as n_,SiteEditSourcePathSchema as Ws,SiteEditSourceTreeResponseSchema as r_,isSiteEditTextSourcePath as o_}from"@vcp-dev/contracts";import{createHash as Qk}from"node:crypto";var gi=class{constructor(t){this.original=new Map,this.files=new Map,this.versions=new Map;for(let n of t)this.original.set(n.path,n.content),this.files.set(n.path,n.content),this.versions.set(n.path,n.version??1)}async readFile(t){let n=this.files.get(t);if(n===void 0)throw new Error(`Snapshot file not found: ${t}`);return n}async readFileBytes(t){return Buffer.from(await this.readFile(t),"utf8")}async getFileInfo(t){let n=this.files.get(t);return n===void 0?null:{path:t,sizeBytes:Buffer.byteLength(n,"utf8")}}async writeFile(t,n){this.files.set(t,n)}async createExclusive(t,n){if(this.files.has(t))throw Object.assign(new Error(`Snapshot file already exists: ${t}`),{code:"EEXIST"});this.files.set(t,n)}async deleteFile(t){this.files.delete(t)}async exists(t){return this.files.has(t)}async listFiles(t={}){let n=t.roots??[],r=[...this.files.keys()].filter(a=>n.length===0?!0:n.some(c=>a===c||a.startsWith(`${c}/`))),o=[],i=new Set,s=0;for(let a of r.sort()){let c=Buffer.byteLength(this.files.get(a)??"","utf8"),l=a.split("/").length;if(t.maxDepth!==void 0&&l>t.maxDepth){i.add("max-depth");continue}if(t.maxFiles!==void 0&&o.length>=t.maxFiles){i.add("max-files");break}if(t.maxTotalBytes!==void 0&&s+c>t.maxTotalBytes){i.add("max-total-bytes");break}o.push({path:a,sizeBytes:c}),s+=c}return i.size>0?{files:o,truncated:{reasons:[...i]}}:{files:o}}getVersion(t){return this.versions.get(t)??0}bumpVersion(t){let n=this.getVersion(t)+1;return this.versions.set(t,n),n}getChangedFiles(){let t=new Set([...this.original.keys(),...this.files.keys()]),n=[];for(let r of[...t].sort()){let o=this.original.get(r),i=this.files.get(r);o!==i&&n.push({path:r,before:o,after:i})}return n}};function ke(e){return`sha256:${Qk("sha256").update(e).digest("hex")}`}var i_=[...hg,...mg,...gg];function nu(e){if(!e.composition)throw new Error("Composition unavailable for source access policy.");return t_.parse(e.composition)}var ql=2e3,Ql=12,eu=24*1024*1024,pg=512*1024,s_=new Set(["image/avif","image/gif","image/jpeg","image/png","image/webp","image/x-icon"]),a_={".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"},c_={".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"},l_=new e_("utf-8",{fatal:!0});async function Gs(e,t={}){let n=nu(t),{files:r,truncated:o}=await h_(e,t),i=b_(r.map(s=>s.metadata));return r_.parse({composition:n,nodes:i,defaultPath:E_(r.map(s=>s.metadata)),totalFiles:r.length,...o?{truncated:o}:{}})}async function Ys(e,t,n={}){let r=nu(n),o=Ws.parse(t.path),i=await d_(e,o,n);if(!i)throw new Error(`Source file not found: ${o}`);if(ou(o)){let a=bg(o),c=await p_(e,{path:o,sizeBytes:i.sizeBytes,mimeType:a});return Zl.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:i.sizeBytes,mimeType:a,readonly:!0,...c})}let s=await ru(e,o);return s.ok?Zl.parse({composition:r,path:o,kind:"text",language:Eg(o),sizeBytes:s.sizeBytes,contentHash:ke(s.content),readonly:!1,content:s.content}):Zl.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:s.sizeBytes,mimeType:"application/octet-stream",readonly:!0,previewUnavailableReason:"unsupported-mime"})}async function ru(e,t){if(e.readFileBytes){let o=await e.readFileBytes(t),i=u_(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 u_(e){if(e.includes(0))return null;try{return l_.decode(e)}catch{return null}}async function d_(e,t,n){if(!m_(t,n))return null;let r=await f_(e,t);return r?{path:t,sizeBytes:r.sizeBytes}:null}async function f_(e,t){if(e.getFileInfo)return e.getFileInfo(t);if(e.listFiles){let o=yg(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(ou(t))return{path:t,sizeBytes:0};let n=await e.readFile(t);return{path:t,sizeBytes:Buffer.byteLength(n,"utf8")}}async function p_(e,t){if(!s_.has(t.mimeType))return{previewUnavailableReason:"unsupported-mime"};if(t.sizeBytes>pg)return{previewUnavailableReason:"too-large"};if(!e.readFileBytes)return{previewUnavailableReason:"bytes-unavailable"};let n=await e.readFileBytes(t.path);return n.byteLength>pg?{previewUnavailableReason:"too-large"}:{contentBase64:Buffer.from(n).toString("base64")}}function m_(e,t){return hg.some(n=>n===e)||mg.some(n=>n===e)||gg.some(n=>e===n||e.startsWith(`${n}/`))?!0:!e.startsWith("app/")&&!e.startsWith("src/app/")?!1:(t.routeEntryFiles??[]).some(n=>{let r=Ws.safeParse(n);return r.success&&r.data===e})}function Zs(e,t){if(!t.sourceLocator)throw new Error(`Source location not available for key: ${e.key}`);return n_.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 yg(e){return Array.isArray(e)?{files:e}:e}function g_(e){return["max-files","max-depth","max-total-bytes"].filter(n=>e.includes(n))}async function h_(e,t){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let n=yg(await e.listFiles({roots:y_(t),maxFiles:ql+1,maxDepth:Ql,maxTotalBytes:eu+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=Ws.safeParse(a.path);if(!c.success)continue;let l=c.data;if(l.split("/").length>Ql){o.add("max-depth");continue}if(r.size>=ql){o.add("max-files");break}if(i+a.sizeBytes>eu){o.add("max-total-bytes");break}r.set(l,{path:l,sizeBytes:a.sizeBytes,metadata:x_(l,a.sizeBytes,nu(t))}),i+=a.sizeBytes}return{files:[...r.values()].sort((a,c)=>a.path.localeCompare(c.path)),...o.size>0?{truncated:{reasons:g_([...o]),maxFiles:ql,maxDepth:Ql,maxTotalBytes:eu}}:{}}}function y_(e){let t=new Set(i_);for(let n of e.routeEntryFiles??[]){let r=Ws.safeParse(n);r.success&&(r.data.startsWith("app/")||r.data.startsWith("src/app/"))&&t.add(r.data)}return[...t]}function x_(e,t,n){return ou(e)?{composition:n,path:e,kind:"binary",language:null,sizeBytes:t,mimeType:bg(e),readonly:!0}:{composition:n,path:e,kind:"text",language:Eg(e),sizeBytes:t,readonly:!1}}function b_(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 xg(t)}function xg(e){return e.map(t=>t.kind==="directory"?{...t,children:xg(t.children)}:t).sort((t,n)=>t.kind!==n.kind?t.kind==="directory"?-1:1:t.name.localeCompare(n.name))}function E_(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 ou(e){return!o_(e)}function bg(e){let t=tu.posix.extname(e).toLowerCase();return!t&&tu.posix.basename(e).toLowerCase()==="favicon"?"image/x-icon":a_[t]??"application/octet-stream"}function Eg(e){let t=tu.posix.extname(e).toLowerCase();return c_[t]??"plaintext"}import*as Zr from"@babel/types";import iu from"@babel/traverse";import*as Nn from"@babel/types";function Ye(e){if(e.isJSXFragment())return!0;if(!e.isJSXElement())return!1;let t=e.node.openingElement.name;if(Nn.isJSXIdentifier(t)){let o=e.scope.getBinding(t.name);if(!o)return!1;let i=o.path;if(!i.isImportSpecifier())return!1;let s=i.node.imported;return(Nn.isIdentifier(s)&&s.name==="Fragment"||Nn.isStringLiteral(s)&&s.value==="Fragment")&&Sg(i.parentPath)}if(!Nn.isJSXMemberExpression(t)||!Nn.isJSXIdentifier(t.property)||t.property.name!=="Fragment"||!Nn.isJSXIdentifier(t.object))return!1;let n=e.scope.getBinding(t.object.name);if(!n)return!1;let r=n.path;return(r.isImportDefaultSpecifier()||r.isImportNamespaceSpecifier())&&Sg(r.parentPath)}function Sg(e){return e?.isImportDeclaration()===!0&&e.node.source.value==="react"}var cr=typeof iu=="function"?iu:iu.default,qs=new WeakMap,Qs=new WeakMap;function Pn(e,t){let n=Xl(e,t);if(!n.ok)return Jl(e,n.diagnostic.code,n.diagnostic.message,t.kind);let r=Ie(n.ast,t);return r.ok?{ok:!0,match:{locatorKind:r.match.locatorKind,node:r.match.node,start:r.match.start,end:r.match.end}}:Jl(e,r.diagnostic.code,r.diagnostic.message,t.kind,r.diagnostic.details)}function Ie(e,t){return t.kind==="jsx-node"?_g(e,t):t.kind==="jsx-attribute"?C_(e,t):t.kind==="value"?R_(e,t):t.kind==="expression"?N_(e,t):t.kind==="directive"?P_(e,t):t.kind==="export"?A_(e,t):{ok:!1,diagnostic:Xr("unsupported-syntax",`Unsupported locator kind: ${t.kind}`)}}function _g(e,t){return t.strategy==="source-range"?S_(e,t):I_(e,t)}function S_(e,t){let n=null;if(cr(e,{JSXElement(o){if(!Yr(o.node,t.sourceRange))return;let i=it("jsx-node",o);if(i){if(!n){n=i;return}i.end-i.start<n.end-n.start&&(n=i)}},JSXFragment(o){if(!Yr(o.node,t.sourceRange))return;let i=it("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXExpressionContainer(o){if(!Yr(o.node,t.sourceRange))return;let i=it("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXText(o){if(!Yr(o.node,t.sourceRange))return;let i=it("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)}}),!n)return ut("jsx-node","locator-miss","JSX node not found for source-range locator");let r=n;return t.expectedIdentity&&!U_(r.path,t.expectedIdentity)?ut("jsx-node","locator-miss","JSX node failed expected identity validation"):{ok:!0,match:r}}function I_(e,t){if(t.structuralPath===""){let r=k_(e,t.component);if(r){let o=__(r);if(o)return o}}let n=null;return cr(e,{JSXElement(r){if(yi(r)!==t.component||au(r)!==t.structuralPath)return;let i=it("jsx-node",r);i&&(n=i,r.stop())},JSXFragment(r){if(yi(r)!==t.component||au(r)!==t.structuralPath)return;let i=it("jsx-node",r);i&&(n=i,r.stop())}}),!n&&t.expectedRange&&(n=v_(e,t.component,t.expectedRange)),n?{ok:!0,match:n}:ut("jsx-node","locator-miss","JSX node not found for structural-path locator")}function v_(e,t,n){let r=null;return cr(e,{JSXElement(o){if(yi(o)!==t||!Yr(o.node,n))return;let i=it("jsx-node",o);i&&(r=i,o.stop())},JSXFragment(o){if(yi(o)!==t||!Yr(o.node,n))return;let i=it("jsx-node",o);i&&(r=i,o.stop())}}),r}function k_(e,t){let n=null;return cr(e,{FunctionDeclaration(r){r.node.id?.name===t&&(n=r,r.stop())},VariableDeclarator(r){if(r.node.id.type==="Identifier"&&r.node.id.name===t){let o=r.get("init");(o.isArrowFunctionExpression()||o.isFunctionExpression())&&(n=o),r.stop()}}}),n}function __(e){if(e.isArrowFunctionExpression()){let t=e.get("body");if(t.isBlockStatement()){let r=t.get("body").find(o=>o.isReturnStatement());if(r){let o=r.get("argument");if((o.isParenthesizedExpression()?o.get("expression"):o).isJSXFragment())return ut("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}return null}return(t.isParenthesizedExpression()?t.get("expression"):t).isJSXFragment()?ut("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target"):null}if(e.isFunctionDeclaration()||e.isFunctionExpression()){let t=e.get("body");if(t.isBlockStatement()){let n=t.get("body").find(r=>r.isReturnStatement());if(n){let r=n.get("argument");if((r.isParenthesizedExpression()?r.get("expression"):r).isJSXFragment())return ut("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}}}return null}function C_(e,t){let n=_g(e,t.element);if(!n.ok)return n;let s=n.match.path.get("openingElement").get("attributes").find(c=>K_(c,t.name));if(!s||!s.isJSXAttribute())return ut("jsx-attribute","locator-miss",`JSX attribute '${t.name}' not found`);let a=it("jsx-attribute",s);return a?{ok:!0,match:a}:ut("jsx-attribute","locator-miss",`JSX attribute '${t.name}' has no source range`)}function R_(e,t){let n=T_(e,t);if(!n.ok)return n;let r=w_(n.match.path,t.path??[]);return r.ok?t.expectedRange&&!Xn(r.match.path.node.loc,t.expectedRange)?ut("value","locator-miss","Resolved value does not match expected range"):{ok:!0,match:r.match}:r}function N_(e,t){let n=null;return cr(e,{Identifier(r){if(!B_(r))return;let o=vg(r);if(!o||!kg(o,t))return;let i=it("expression",r);i&&(t.expectedRange&&!Xn(r.node.loc,t.expectedRange)||(n=i,r.stop()))},MemberExpression(r){let o=vg(r);if(!o||!kg(o,t))return;let i=it("expression",r);i&&(t.expectedRange&&!Xn(r.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:ut("expression","locator-miss","Expression not found")}function P_(e,t){let n=null;return cr(e,{Program(r){let i=r.get("directives").find(a=>a.node.value.value===t.value);if(!i||t.expectedRange&&!Xn(i.node.loc,t.expectedRange))return;let s=it("directive",i);s&&(n=s,r.stop())}}),n?{ok:!0,match:n}:ut("directive","locator-miss",`Directive '${t.value}' not found`)}function A_(e,t){let n=null;return cr(e,{ExportNamedDeclaration(r){if(t.exportKind==="generate-metadata"){let c=r.get("declaration");if(c.isFunctionDeclaration()&&c.node.id?.name==="generateMetadata"){let f=it("export",c);if(!f||t.expectedRange&&!Xn(c.node.loc,t.expectedRange))return;n=f,r.stop();return}if(!c.isVariableDeclaration())return;let l=cu(c,"generateMetadata");if(!l||!l.isVariableDeclarator())return;let u=l.get("init");if(!u.node)return;let d=it("export",u);if(!d||t.expectedRange&&!Xn(u.node.loc,t.expectedRange))return;n=d,r.stop();return}let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=cu(o,t.exportKind==="named"?t.name:"metadata");if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node||t.expectedRange&&!Xn(s.node.loc,t.expectedRange))return;let a=it("export",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(t.exportKind!=="default")return;let o=r.get("declaration"),i=it("export",o);i&&(t.expectedRange&&!Xn(o.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:ut("export","export-not-found",`Export '${V_(t)}' not found`)}function T_(e,t){let n=null;return cr(e,{Expression(r){if(n||t.root.kind!=="expression"||!Yr(r.node,t.root.sourceRange))return;let o=it("value",r);o&&(n=o,r.stop())},VariableDeclarator(r){if(n)return;if(t.root.kind==="binding"){if(r.node.id.type!=="Identifier"||r.node.id.name!==t.root.name)return;let g=r.get("init");if(!g.node)return;let p=it("value",g);if(!p)return;n=p,r.stop();return}if(t.root.kind!=="hook-state")return;let o=t.root,i=r.get("id"),s=r.get("init");if(!i.isArrayPattern()||!s.isCallExpression()||i.node.elements.findIndex(g=>g?.type==="Identifier"&&g.name===o.name)!==0)return;let c=s.node.callee;if((c.type==="Identifier"?c.name:c.type==="MemberExpression"&&c.property.type==="Identifier"?c.property.name:null)!==o.hook)return;let u=o.hook==="useReducer"?1:0,d=r.get(`init.arguments.${u}`);if(!d||Array.isArray(d)||!d.node)return;let f=it("value",d);f&&(n=f,r.stop())},ExportNamedDeclaration(r){if(n||t.root.kind!=="named-export")return;let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=cu(o,t.root.name);if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node)return;let a=it("value",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(n||t.root.kind!=="default-export")return;let o=r.get("declaration"),i=it("value",o);i&&(n=i,r.stop())}}),n?{ok:!0,match:n}:ut("value",t.root.kind==="named-export"||t.root.kind==="default-export"?"export-not-found":t.root.kind==="expression"?"locator-miss":"binding-not-found","Value root was not found")}function w_(e,t){let n=su(e);for(let o of t){if(n=su(n),o.kind==="property"){if(!n.isObjectExpression())return ut("value","unsupported-syntax","Property path requires object expression");let a=n.get("properties");if(a.some(l=>!l.isObjectProperty()))return ut("value","unsupported-syntax","Spread properties are not supported");let c=a.find(l=>J_(l,o.name));if(!c||!c.isObjectProperty())return ut("value","property-not-found",`Property '${o.name}' not found`);n=c.get("value");continue}if(!n.isArrayExpression())return ut("value","unsupported-syntax","Array index path requires array expression");let i=n.get("elements");if(i.some(a=>a.node?.type==="SpreadElement"))return ut("value","unsupported-syntax","Spread array elements are not supported");let s=i[o.index];if(!s?.node)return ut("value","array-index-out-of-range",`Array index ${o.index} is out of range`);n=s}n=su(n);let r=it("value",n);return r?{ok:!0,match:r}:ut("value","locator-miss","Resolved value has no source range")}function su(e){let t=e;for(;t.isTSAsExpression()||t.isTSSatisfiesExpression()||t.isTSNonNullExpression();)t=t.get("expression");return t}function it(e,t){let n=t.node;return n.start==null||n.end==null?null:{locatorKind:e,node:n,start:n.start,end:n.end,path:t}}function Yr(e,t){return Xn(e.loc,t)}function Xn(e,t){return e?e.start.line===t.startLine&&e.start.column===t.startColumn&&e.end.line===t.endLine&&e.end.column===t.endColumn:!1}function au(e){let t=[],n=e,r=e.node;for(;n;){if(n.isJSXElement()){if(!Ye(n)){let o=Rg(n.node.openingElement);o&&(/^[A-Z]/.test(o)?t.unshift(`component:${o}#${Ig(n,o)}`):t.unshift(`${o}#${Ig(n,o)}`))}}else n.isJSXFragment()&&n.node===r&&t.unshift("fragment");if(!n.parentPath||M_(n.parentPath)&&!D_(n.parentPath))break;n=n.parentPath}return t.join("/")}function Ig(e,t){let n=Cg(e)??e.getFunctionParent();if(!n)return 0;let r=qs.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=0,i=qs.get(n.node)?.get(t);if(!i){let a=qs.get(n.node);a||(a=new Map,qs.set(n.node,a)),i=new WeakMap,a.set(t,i)}let s=n.isJSXElement()||n.isJSXFragment()?hi(n):O_(n);for(let a of s)if(Rg(a.node.openingElement)===t){if(i.set(a.node,o),a.node===e.node)return o;o++}return i.get(e.node)??0}function O_(e){let t=Qs.get(e.node);if(t)return t;let n=[];return e.traverse({JSXElement(r){r.getFunctionParent()?.node===e.node&&!Cg(r)&&n.push(r)}}),Qs.set(e.node,n),n}function Cg(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(Ye(t)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function hi(e){let t=Qs.get(e.node);if(t)return t;let n=[],r=e.get("children");for(let o of r)if(!Array.isArray(o)){if(o.isJSXElement()){if(Ye(o)){n.push(...hi(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...hi(o));continue}o.isJSXExpressionContainer()&&n.push(...Jn(o.get("expression")))}return Qs.set(e.node,n),n}function Jn(e){if(e.isJSXElement())return Ye(e)?hi(e):[e];if(e.isJSXFragment())return hi(e);if(e.isParenthesizedExpression())return Jn(e.get("expression"));if(e.isLogicalExpression()&&F_(e.node.operator))return Jn(e.get("right"));if(e.isCallExpression()||e.isOptionalCallExpression()){let t=e.get("callee"),n=!Array.isArray(t)&&(t.isMemberExpression()||t.isOptionalMemberExpression())?t.get("property"):null;if(!Array.isArray(t)&&(t.isMemberExpression()||t.isOptionalMemberExpression())&&!t.node.computed&&n!==null&&!Array.isArray(n)&&n.isIdentifier()&&n.node.name==="map"){let r=e.get("arguments").find(o=>!Array.isArray(o)&&(o.isArrowFunctionExpression()||o.isFunctionExpression()));if(r&&!Array.isArray(r)){let o=r.get("body");if(!Array.isArray(o)){if(o.isBlockStatement()){let i=[];for(let s of o.get("body")){if(s.isVariableDeclaration())for(let a of s.get("declarations")){let c=a.get("init");(c.isJSXElement()||c.isJSXFragment())&&i.push(...Jn(c))}if(s.isReturnStatement()){let a=s.get("argument");a.isExpression()&&i.push(...Jn(a));break}}return i}else if(o.node&&o.isExpression())return Jn(o)}}}}return e.isConditionalExpression()?[...Jn(e.get("consequent")),...Jn(e.get("alternate"))]:e.isArrayExpression()?e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:Jn(t)):[]}function F_(e){return e==="&&"||e==="||"||e==="??"}function Rg(e){return e.name.type==="JSXIdentifier"?e.name.name:e.name.type==="JSXMemberExpression"?L_(e.name):null}function L_(e){let t=[],n=e;for(;n.type==="JSXMemberExpression";)t.unshift(n.property.name),n=n.object;return t.unshift(n.name),t.join(".")}function yi(e){let t=e;for(;t;){if(t.isFunctionDeclaration())return t.node.id?.name??null;if((t.isArrowFunctionExpression()||t.isFunctionExpression())&&t.parentPath?.isVariableDeclarator()){let n=t.parentPath.node.id;return n.type==="Identifier"?n.name:null}t=t.parentPath}return null}function M_(e){return!!(e.isFunctionDeclaration()||e.isFunctionExpression()||e.isArrowFunctionExpression())}function D_(e){let t=e.parentPath;if(!t||!t.isCallExpression()&&!t.isOptionalCallExpression())return!1;let n=t.get("callee"),r=!Array.isArray(n)&&(n.isMemberExpression()||n.isOptionalMemberExpression())?n.get("property"):null;if(Array.isArray(n)||!n.isMemberExpression()&&!n.isOptionalMemberExpression()||n.node.computed||r===null||Array.isArray(r)||!r.isIdentifier()||r.node.name!=="map")return!1;let o=t.get("arguments");return Array.isArray(o)?o.some(i=>!Array.isArray(i)&&i.node===e.node):!1}function B_(e){return!(!e.isExpression()||e.parentPath?.isMemberExpression({property:e.node}))}function vg(e){if(e.isIdentifier())return{base:e.node.name,path:[]};if(!e.isMemberExpression())return null;let t=[],n=e.node;for(;n.type==="MemberExpression";){if(n.computed)if(n.property.type==="NumericLiteral")t.unshift({kind:"index",index:n.property.value});else if(n.property.type==="StringLiteral")t.unshift({kind:"property",name:n.property.value});else return null;else if(n.property.type==="Identifier")t.unshift({kind:"property",name:n.property.name});else return null;if(n.object.type==="Identifier")return{base:n.object.name,path:t};if(n.object.type!=="MemberExpression")return null;n=n.object}return null}function kg(e,t){return e.base===t.base&&j_(e.path,t.path??[])}function j_(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],o=t[n];if(r.kind!==o.kind)return!1;if(r.kind==="property"){if(o.kind!=="property"||r.name!==o.name)return!1;continue}if(o.kind!=="index"||r.index!==o.index)return!1}return!0}function $_(e){return e.key.type==="Identifier"?e.key.name:e.key.type==="StringLiteral"?e.key.value:null}function V_(e){return e.exportKind==="named"?e.name:e.exportKind}function ut(e,t,n,r){return{ok:!1,diagnostic:Xr(t,n,e,r)}}function U_(e,t){return yi(e)!==t.component?!1:au(e)===t.structuralPath}function K_(e,t){return!e.isJSXAttribute()||e.node.name.type!=="JSXIdentifier"?!1:e.node.name.name===t}function cu(e,t){return e.get("declarations").find(n=>!n.isVariableDeclarator()||n.node.id.type!=="Identifier"?!1:n.node.id.name===t)}function J_(e,t){return e.isObjectProperty()?$_(e.node)===t:!1}import*as Pg from"@babel/parser";import{arrayExpression as G_,booleanLiteral as Y_,identifier as Z_,jsxAttribute as q_,jsxExpressionContainer as Q_,jsxIdentifier as eC,nullLiteral as tC,numericLiteral as nC,objectExpression as rC,objectProperty as oC,stringLiteral as uu}from"@babel/types";import lu from"@babel/generator";var X_=typeof lu=="function"?lu:lu.default;function z_(e){let t=e.split(`
2
2
  `),n=[],r=!1;for(let s of t){let a=s.match(/^(\s+)/);if(a){let c=a[1];c.includes(" ")?r=!0:c.length>0&&n.push(c.length)}}if(r&&t.every(a=>{let c=a.match(/^(\s+)/);return!c||c[1].includes(" ")}))return"tab";if(n.length===0)return"2";function o(s,a){return a===0?s:o(a,s%a)}let i=n[0];for(let s=1;s<n.length;s++)i=o(i,n[s]);return i>=4?"4":"2"}function H_(e,t){let n=e.match(/^(\s+)(.*)/s);if(!n)return e;let r=n[1],o=n[2];if(r.length===0)return e;let i=r.includes(" ")?r.split(" ").length-1:Math.max(1,Math.round(r.length/2)),s=Math.min(Math.max(i,0),20);return t==="tab"?" ".repeat(s)+o:t==="4"?" ".repeat(s)+o:" ".repeat(s)+o}function W_(e,t){return e.split(`
3
3
  `).map(r=>H_(r,t)).join(`
4
- `)}function ea(e){let{ast:t,source:n}=e;try{let r=z_(n),i=X_(t,{comments:!0,jsescOption:{minimal:!0,quotes:"single"}},n).code;return r!=="2"&&(i=W_(i,r)),{ok:!0,source:i}}catch(r){return ee(n,"printer-failed",`AST print failed: ${r instanceof Error?r.message:String(r)}`)}}function Cg(e){let t=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);t=(t<<5)-t+r,t|=0}return`0x${Math.abs(t).toString(16)}`}function xi(e,t,n){return{ok:!0,source:t,operation:{type:n.kind,nodeId:n.target,kind:n.kind,target:n.target,beforeSourceHash:Cg(e),afterSourceHash:Cg(t),inverse:n.inverse}}}function De(e,t,n){let r=ea({ast:e,source:t});return r.ok?xi(t,r.source,n):r}function We(e,t){let n=pi(e,t);return n.ok?{ok:!0,ast:n.ast}:{ok:!1,result:{ok:!1,source:e,diagnostic:n.diagnostic}}}function ta(e,t){return ea({ast:e,source:t})}function iC(e,t,n){let r=Ie(e,t);return r.ok?{ok:!0,match:r.match}:{ok:!1,result:{ok:!1,source:n,diagnostic:r.diagnostic}}}function vo(e,t,n){let r=iC(e,t,n);return r.ok?r.match.path.isJSXElement()?r:{ok:!1,result:ee(n,"unsupported-syntax","JSX locator must resolve to JSXElement","jsx-node")}:r}function lr(e){return typeof e=="string"?uu(e):typeof e=="number"?nC(e):typeof e=="boolean"?Y_(e):e===null?tC():Array.isArray(e)?G_(e.map(t=>lr(t))):rC(Object.entries(e).map(([t,n])=>{let r=oC(du(t),lr(n));return t==="__proto__"&&(r.computed=!0),r}))}function sC(e){return typeof e=="string"?uu(e):Q_(lr(e))}function bi(e,t){return q_(eC(e),sC(t))}function na(e,t){try{let r=Rg.parse(`const __VD_NODE__ = (${t});`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0];return r?.type!=="VariableDeclaration"||r.declarations[0]?.type!=="VariableDeclarator"||!r.declarations[0].init||r.declarations[0].init.type!=="JSXElement"&&r.declarations[0].init.type!=="JSXFragment"?{ok:!1,result:ee(e,"unsupported-syntax","Provided JSX source does not resolve to a JSX node","jsx-node")}:{ok:!0,node:r.declarations[0].init}}catch(n){return{ok:!1,result:ee(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function du(e){return/^[$A-Z_][0-9A-Z_$]*$/i.test(e)?Z_(e):uu(e)}function ra(e){let{source:t,locator:n,segmentIndex:r,newText:o}=e,i=We(t,"jsx-node");if(!i.ok)return i.result;let s=Ie(i.ast,n);if(!s.ok)return{ok:!1,source:t,diagnostic:s.diagnostic};let c=aC(s.match.path)[r];if(!c)return ee(t,"locator-miss",`Text segment ${r} not found`,"jsx-node");switch(c.kind){case"jsx-text":{let l=c.path.node.value;if(o.trim().length===0){let d=l.match(/^\s*/)?.[0]??"",f=l.match(/\s*$/)?.[0]??"";c.path.replaceWithMultiple([...d?[Zr.jsxText(d)]:[],Zr.jsxExpressionContainer(Zr.stringLiteral("")),...f?[Zr.jsxText(f)]:[]]);break}let u=cC(l,o);c.path.node.value=u,c.path.node.extra={rawValue:u,raw:u.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/{/g,"&#123;").replace(/}/g,"&#125;")};break}case"string-literal":c.path.node.value=o;break;case"template-literal":{let l=c.quasiIndex;c.path.node.quasis[l].value.raw=o.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\$\{/g,"\\${").replace(/\r/g,"\\r"),c.path.node.quasis[l].value.cooked=o;break}}return De(i.ast,t,{kind:"update-text",target:"jsx-node",inverse:"restore-text"})}function aC(e){let t=[],n=e.isJSXElement()||e.isJSXFragment()?e.get("children"):[];for(let r of n){if(r.isJSXText()){r.node.value.trim().length>0&&t.push({kind:"jsx-text",path:r});continue}if(r.isJSXExpressionContainer()){let o=lC(r.get("expression"));o.length>0&&t.push(...o)}}return t}function cC(e,t){let n=e.match(/^\s*/)?.[0]??"",r=e.match(/\s*$/)?.[0]??"";return`${n}${t.trim()}${r}`}function lC(e){if(e.isStringLiteral())return[{kind:"string-literal",path:e}];if(e.isTemplateLiteral()){let t=[],n=e.node.quasis;for(let r=0;r<n.length;r++)(n[r].value.raw.trim().length>0||n.length===1&&e.node.expressions.length===0)&&t.push({kind:"template-literal",path:e,quasiIndex:r});if(t.length>0)return t}return e.isCallExpression()?[]:[]}import{nullLiteral as fu}from"@babel/types";function qr(e){let{source:t,locator:n}=e,r=We(t,"jsx-node");if(!r.ok)return r.result;let o=Ie(r.ast,n);return o.ok?(uC(o.match.path),De(r.ast,t,{kind:"remove-node",target:"jsx-node",inverse:"insert-child"})):{ok:!1,source:t,diagnostic:o.diagnostic}}function uC(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(fu());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(fu());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(fu());return}e.remove()}import{cloneNode as dC}from"@babel/types";function ko(e){let t=We(e.source,"jsx-node");if(!t.ok)return t.result;let n=Ie(t.ast,e.locator);if(!n.ok)return{ok:!1,source:e.source,diagnostic:n.diagnostic};let r=na(e.source,e.node.jsx);return r.ok?(n.match.path.replaceWith(dC(r.node,!0)),De(t.ast,e.source,{kind:"replace-node",target:"jsx-node",inverse:"replace-node"})):r.result}import{cloneNode as IC}from"@babel/types";import pu from"@babel/traverse";import*as me from"@babel/types";function Ei(e,t,n){return`${e}::${t}::${n}`}var U={NODE_NOT_FOUND:"NODE_NOT_FOUND",HOME_PAGE_LOCKED:"HOME_PAGE_LOCKED",ROUTE_NOT_FOUND:"ROUTE_NOT_FOUND",CAPABILITY_REJECTED:"CAPABILITY_REJECTED",CONSTRAINT_VIOLATED:"CONSTRAINT_VIOLATED",INVALID_PARAMS:"INVALID_PARAMS",PLAN_FAILED:"PLAN_FAILED",TRANSACTION_PREFLIGHT_FAILED:"TRANSACTION_PREFLIGHT_FAILED",ROUTE_REBUILD_FAILED:"ROUTE_REBUILD_FAILED",HISTORY_COMMIT_FAILED:"HISTORY_COMMIT_FAILED",MATERIALIZATION_CONFLICT:"MATERIALIZATION_CONFLICT",MATERIALIZATION_REJECTED:"MATERIALIZATION_REJECTED",MUTATION_ASSERTION_REQUIRED:"MUTATION_ASSERTION_REQUIRED",MUTATION_ASSERTION_INVALID:"MUTATION_ASSERTION_INVALID",VERSION_STALE:"VERSION_STALE",AST_PARSE_ERROR:"AST_PARSE_ERROR",UNSUPPORTED_OPERATION:"UNSUPPORTED_OPERATION",LOCATOR_FAILED:"LOCATOR_FAILED",INVALID_TARGET:"INVALID_TARGET",WRITE_IO_ERROR:"WRITE_IO_ERROR",CONCURRENT_MODIFIED:"CONCURRENT_MODIFIED",ROLLBACK_FAILED:"ROLLBACK_FAILED",RECOVERY_REQUIRED:"RECOVERY_REQUIRED",RECOVERY_PERSIST_FAILED:"RECOVERY_PERSIST_FAILED",MUTATION_SESSION_REQUIRED:"MUTATION_SESSION_REQUIRED",LEASE_ASSERTION_INVALID:"LEASE_ASSERTION_INVALID",LEASE_ASSERTION_EXPIRED:"LEASE_ASSERTION_EXPIRED",LEASE_ASSERTION_SCOPE_MISMATCH:"LEASE_ASSERTION_SCOPE_MISMATCH",CROSS_PAGE_MOVE_UNSUPPORTED:"CROSS_PAGE_MOVE_UNSUPPORTED",INTERNAL_ERROR:"INTERNAL_ERROR"};var fC=typeof pu=="function"?pu:pu.default;function rn(e,t,n,r){if(!e.ok)return e;let o=nn(n,t);if(!o)return e;let i=pC(t,o,r);return i?{...e,selectionRef:i}:e}function pC(e,t,n){let r=mC(e,t);if(!r)return;let o=n.sourceLocator?Ng(n.sourceLocator):void 0,i=n.targetParentLocator?Ng(n.targetParentLocator):void 0,s=n.file??i?.file??o?.file,a=n.component??hC(r)??i?.component??o?.component;if(!(!s||!a))return{key:Ei(s,a,yC(r))}}function Ng(e){return e.strategy==="structural-path"?{file:e.file,component:e.component,structuralPath:e.structuralPath}:e.expectedIdentity}function mC(e,t){let n=Fg(e,t);return!n||n.node.type!=="JSXElement"?null:n}function Fg(e,t){let n=null;return fC(e,{JSXElement(r){r.node===t&&(n=r,r.stop())},JSXFragment(r){r.node===t&&(n=r,r.stop())}}),n}function nn(e,t){if(!e)return null;if(me.isJSXElement(e))return SC(t,e)?Pg(e.children,t):e;if(me.isJSXFragment(e))return Pg(e.children,t);if(me.isJSXExpressionContainer(e)||me.isParenthesizedExpression(e)||me.isTSAsExpression(e)||me.isTSSatisfiesExpression(e)||me.isTSTypeAssertion(e)||me.isTSNonNullExpression(e))return nn(e.expression,t);if(me.isLogicalExpression(e))return nn(e.right,t);if(me.isConditionalExpression(e))return nn(e.consequent,t)??nn(e.alternate,t);if(me.isCallExpression(e)||me.isOptionalCallExpression(e))return Lg(e)?gC(e.arguments[0],t):null;if(me.isArrayExpression(e))for(let n of e.elements){if(!n)continue;let r=nn(n,t);if(r)return r}return null}function Pg(e,t){for(let n of e){let r=nn(n,t);if(r)return r}return null}function gC(e,t){return!e||!me.isArrowFunctionExpression(e)&&!me.isFunctionExpression(e)?null:me.isBlockStatement(e.body)?Si(e.body.body,t):nn(e.body,t)}function Si(e,t){for(let n of e){if(me.isReturnStatement(n)){let r=nn(n.argument,t);if(r)return r;continue}if(me.isBlockStatement(n)){let r=Si(n.body,t);if(r)return r;continue}if(me.isIfStatement(n)){let r=Ag(n.consequent,t);if(r)return r;let o=n.alternate?Ag(n.alternate,t):null;if(o)return o;continue}if(me.isSwitchStatement(n))for(let r of n.cases){let o=Si(r.consequent,t);if(o)return o}}return null}function Ag(e,t){return me.isBlockStatement(e)?Si(e.body,t):Si([e],t)}function hC(e){let t=e;for(;t;){if(t.isFunctionDeclaration()||t.isClassDeclaration())return t.node.id?.name??null;if(t.isExportDefaultDeclaration()){let n=t.node.declaration;if(me.isFunctionDeclaration(n))return n.id?.name??"default"}if(t.isVariableDeclarator()&&me.isIdentifier(t.node.id)){let n=t.get("init");if(!Array.isArray(n)&&(n.isArrowFunctionExpression()||n.isFunctionExpression()))return t.node.id.name}t=t.parentPath}return null}var Tg=new WeakMap,wg=new WeakMap,mu=new WeakMap;function yC(e){let t=Tg.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=xC(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return Tg.set(e.node,o),o}function xC(e){let t=Dg(e.node.openingElement.name);return!t||Ye(e)?null:/^[A-Z]/.test(t)?`component:${t}#${Og(e,t)}`:`${t}#${Og(e,t)}`}function Og(e,t){let n=bC(e);if(!n)return 0;let r=mu.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=mu.get(n.node);o||(o=new Map,mu.set(n.node,o));let i=o.get(t);i||(i=new WeakMap,o.set(t,i));let s=0;for(let a of Qr(n))if(Dg(a.node.openingElement.name)===t){if(i.set(a.node,s),a.node===e.node)return s;s+=1}return i.get(e.node)??0}function bC(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(Ye(t)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function Qr(e){let t=wg.get(e.node);if(t)return t;let n=[],r=e.get("children");for(let o of r)if(!Array.isArray(o)){if(o.isJSXElement()){if(Ye(o)){n.push(...Qr(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...Qr(o));continue}o.isJSXExpressionContainer()&&n.push(...An(o.get("expression")))}return wg.set(e.node,n),n}function An(e){if(e.isJSXElement())return Ye(e)?Qr(e):[e];if(e.isJSXFragment())return Qr(e);if(e.isParenthesizedExpression())return An(e.get("expression"));if(e.isLogicalExpression())return An(e.get("right"));if(e.isConditionalExpression())return[...An(e.get("consequent")),...An(e.get("alternate"))];if(e.isArrayExpression())return e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:An(t));if((e.isCallExpression()||e.isOptionalCallExpression())&&Lg(e.node)){let t=e.get("arguments"),n=Array.isArray(t)?t[0]:void 0;return n?EC(n):[]}return[]}function EC(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return Ye(t)?Qr(t):[t];if(t.isJSXFragment())return Qr(t);if(t.isParenthesizedExpression())return An(t.get("expression"));if(t.isLogicalExpression()||t.isConditionalExpression())return An(t);if(!t.isBlockStatement())return[];let n=[];for(let r of t.get("body")){if(r.isVariableDeclaration())for(let i of r.get("declarations")){let s=i.get("init");(s.isJSXElement()||s.isJSXFragment())&&n.push(...An(s))}if(!r.isReturnStatement())continue;let o=r.get("argument");return o.node&&n.push(...An(o)),n}return n}function Lg(e){let t=e.callee;return(me.isMemberExpression(t)||me.isOptionalMemberExpression(t))&&me.isIdentifier(t.property)&&t.property.name==="map"&&!t.computed}function SC(e,t){let n=Fg(e,t);return n?Ye(n):!1}function Dg(e){return me.isJSXIdentifier(e)?e.name:me.isJSXMemberExpression(e)?Mg(e):me.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function Mg(e){return`${me.isJSXIdentifier(e.object)?e.object.name:Mg(e.object)}.${e.property.name}`}function ur(e,t){if(t.parentPath===e&&t.listKey==="children"&&gu(e))return e;if(!t.parentPath||t.listKey!=="children")return null;let n=t.parentPath;if(!gu(n))return null;let r=n;for(;r&&r!==e;){if(!gu(r)||!Ye(r)||r.listKey!=="children")return null;r=r.parentPath}return r===e?n:null}function gu(e){return e.isJSXElement()||e.isJSXFragment()}function on(e){let{source:t,locator:n,node:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=We(t,"jsx-node");if(!a.ok)return a.result;let c=Ie(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};if(!c.match.path.isJSXElement()&&!c.match.path.isJSXFragment())return ee(t,"unsupported-syntax","insert-child target must be a JSXElement or JSXFragment","jsx-node");let l=c.match.path;if(c.match.path.isJSXElement()){let b=c.match.path.node;if(!b.closingElement||b.openingElement.selfClosing)return ee(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=na(t,r.jsx);if(!u.ok)return u.result;let d=IC(u.node,!0),f=l.node.children,g={...s,targetParentLocator:n},p=b=>s?rn(b,a.ast,d,g):b;if(o==="append")return f.push(d),p(De(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return f.unshift(d),p(De(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(!i)return ee(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let m=Ie(a.ast,i);if(!m.ok)return{ok:!1,source:t,diagnostic:m.diagnostic};let y=ur(c.match.path,m.match.path);if(!y)return ee(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");l=y;let x=l.node.children,S=x.findIndex(b=>b===m.match.path.node);return S===-1?ee(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(x.splice(o==="before"?S:S+1,0,d),p(De(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"})))}import*as Bg from"@babel/parser";import{cloneNode as vC}from"@babel/types";function oa(e){let{source:t,locator:n,expression:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=We(t,"jsx-node");if(!a.ok)return a.result;let c=kC(t,r);if(!c.ok)return c.result;let l=Ie(a.ast,n);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return ee(t,"unsupported-syntax","insert-jsx-expression-child target must be a JSXElement or JSXFragment","jsx-node");if(l.match.path.isJSXElement()){let x=l.match.path.node;if(!x.closingElement||x.openingElement.selfClosing)return ee(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=l.match.path,d=null;if(i){let x=Ie(a.ast,i);if(!x.ok)return{ok:!1,source:t,diagnostic:x.diagnostic};let S=ur(l.match.path,x.match.path);if(!S)return ee(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=S,d=x.match.path.node}else if(o==="before"||o==="after")return ee(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let f=vC(c.node,!0),g=u.node.children,p={...s,targetParentLocator:n},m=x=>s?rn(x,a.ast,f,p):x;if(o==="append")return g.push(f),m(De(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return g.unshift(f),m(De(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));let y=g.findIndex(x=>x===d);return y===-1?ee(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(g.splice(o==="before"?y:y+1,0,f),m(De(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"})))}function kC(e,t){try{let r=Bg.parse(`const __VD_EXPR__ = <>{${t}}</>;`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0],o=r?.type==="VariableDeclaration"?r.declarations[0]?.init:null,i=o?.type==="JSXFragment"?o.children[0]:void 0;return i?.type!=="JSXExpressionContainer"?{ok:!1,result:ee(e,"unsupported-syntax","Expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:ee(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}import{cloneNode as _C,nullLiteral as hu}from"@babel/types";import*as dr from"@babel/types";import*as jg from"@babel/types";function Ii(e,t){let n=e.parentPath;if(!n?.isConditionalExpression()||e.key!=="consequent"||!jg.isNullLiteral(n.node.alternate))return e;let r=n.parentPath;return!r?.isJSXExpressionContainer()||r.parentPath?.node!==t.node||r.listKey!=="children"?e:r}function eo(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=We(t,"jsx-node");if(!a.ok)return a.result;let c=Ie(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};let l=Ie(a.ast,r);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return ee(t,"unsupported-syntax","move-node target parent must be a JSXElement or JSXFragment","jsx-node");let u=l.match.path;if(l.match.path.isJSXElement()){let b=l.match.path.node;if(!b.closingElement||b.openingElement.selfClosing)return ee(t,"self-closing-element","Cannot move child into self-closing element","jsx-node")}let d=null;if(i){let b=Ie(a.ast,i);if(!b.ok)return{ok:!1,source:t,diagnostic:b.diagnostic};let E=b.match.path.isJSXElement()?Ii(b.match.path,l.match.path):b.match.path,k=ur(l.match.path,E);if(!k)return ee(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=k,d=E}else if(o==="before"||o==="after")return ee(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let f=d&&typeof d.key=="number"?d.key:-1;if(d&&f===-1)return ee(t,"locator-miss","Anchor node does not exist in target parent","jsx-node");let g=c.match.path.isJSXElement()?Ii(c.match.path,l.match.path):c.match.path,p=_C(g.node,!0);if(!dr.isJSXElement(p)&&!dr.isJSXExpressionContainer(p)&&!dr.isJSXFragment(p)&&!dr.isJSXText(p))return ee(t,"unsupported-syntax","move-node source must resolve to a JSX child","jsx-node");let m=g.parentPath?.node===u.node&&typeof g.key=="number"?g.key:-1;if(d&&g.parentPath?.node===d.parentPath?.node&&g.key===d.key)return ee(t,"invalid-parent-child-relation","Cannot move a node relative to itself","jsx-node");CC(g);let y=u.node.children,x={...s,sourceLocator:n,targetParentLocator:r};if(o==="append")return y.push(p),rn(ta(a.ast,t),a.ast,p,x);if(o==="prepend")return y.unshift(p),rn(ta(a.ast,t),a.ast,p,x);let S=f-(m!==-1&&m<f?1:0);return y.splice(o==="before"?S:S+1,0,p),rn(ta(a.ast,t),a.ast,p,x)}function CC(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(hu());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(hu());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(hu());return}e.remove()}import*as $g from"@babel/parser";import{cloneNode as RC,nullLiteral as yu}from"@babel/types";function ia(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,repeatExpression:s,selectionContext:a}=e,c=We(t,"jsx-node");if(!c.ok)return c.result;let l=NC(t,s);if(!l.ok)return l.result;let u=Ie(c.ast,n);if(!u.ok)return{ok:!1,source:t,diagnostic:u.diagnostic};let d=Ie(c.ast,r);if(!d.ok)return{ok:!1,source:t,diagnostic:d.diagnostic};if(!d.match.path.isJSXElement()&&!d.match.path.isJSXFragment())return ee(t,"unsupported-syntax","move-repeat-template-child target parent must be a JSXElement or JSXFragment","jsx-node");if(d.match.path.isJSXElement()){let b=d.match.path.node;if(!b.closingElement||b.openingElement.selfClosing)return ee(t,"self-closing-element","Cannot move repeat child into self-closing element","jsx-node")}let f=d.match.path,g=null;if(i){let b=Ie(c.ast,i);if(!b.ok)return{ok:!1,source:t,diagnostic:b.diagnostic};let E=ur(d.match.path,b.match.path);if(!E)return ee(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");f=E,g=b.match.path.node}else if(o==="before"||o==="after")return ee(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");if(!u.match.path.isJSXElement())return ee(t,"unsupported-syntax","move-repeat-template-child source must be a JSXElement","jsx-node");let p=f.node,m=RC(l.node,!0);PC(u.match.path);let y={...a,sourceLocator:n,targetParentLocator:r},x=p.children;if(o==="append")return x.push(m),rn(De(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,m,y);if(o==="prepend")return x.unshift(m),rn(De(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,m,y);let S=x.findIndex(b=>b===g);return S===-1?ee(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(x.splice(o==="before"?S:S+1,0,m),rn(De(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,m,y))}function NC(e,t){try{let r=$g.parse(`const __VD_EXPR__ = <>{${t}}</>;`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0],o=r?.type==="VariableDeclaration"?r.declarations[0]?.init:null,i=o?.type==="JSXFragment"?o.children[0]:void 0;return i?.type!=="JSXExpressionContainer"?{ok:!1,result:ee(e,"unsupported-syntax","Repeat expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:ee(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function PC(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(yu());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(yu());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(yu());return}e.remove()}import{SiteEditSetPropsParamsSchema as AC,classifySiteEditPropertyName as TC}from"@vcp-dev/contracts";import*as _o from"@babel/types";function sa(e){let t=AC.safeParse({kind:"set-props",scope:"selection",changes:e.changes});if(!t.success)return ee(e.source,"unsupported-syntax","Invalid typed JSX property changes","jsx-node",{issues:t.error.issues});let n=We(e.source,"jsx-node");if(!n.ok)return n.result;let r=vo(n.ast,e.locator,e.source);if(!r.ok)return r.result;for(let a of t.data.changes){let c=TC(a.name);if(c.owner!=="generic")return ee(e.source,"unsupported-syntax",c.diagnostic?.message??`Property '${a.name}' is not owned by the generic JSX primitive`,"jsx-node")}let o=r.match.path.node.openingElement,i=o.attributes.filter(_o.isJSXAttribute),s=new Map;for(let a of i){let c=wC(a);if(!c)continue;let l=s.get(c)??[];l.push(a),s.set(c,l)}for(let a of t.data.changes)if((s.get(a.name)??[]).length>1)return ee(e.source,"unsupported-syntax",`JSX attribute '${a.name}' has multiple sources`,"jsx-node");for(let a of t.data.changes){let c=s.get(a.name)?.[0];if(a.operation==="remove"){c&&(o.attributes=o.attributes.filter(u=>u!==c));continue}let l=bi(a.name,a.value).value;c?c.value=l:o.attributes.push(bi(a.name,a.value))}return De(n.ast,e.source,{kind:"set-props",target:"jsx-node",inverse:"set-props"})}function wC(e){return _o.isJSXIdentifier(e.name)?e.name.name:_o.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:null}import{SiteEditOperationParamsSchema as OC}from"@vcp-dev/contracts";import*as re from"@babel/types";var Vg=["prefetch","replace","scroll","locale","onNavigate"],FC=/^on(?:Click|DoubleClick|AuxClick|MouseDown|MouseUp|PointerDown|PointerUp|TouchStart|TouchEnd|KeyDown|KeyUp|ContextMenu)(?:Capture)?$/;function LC(e){let t=e;for(;t;){if(t.isJSXElement()&&t.node.openingElement.attributes.some(n=>re.isJSXAttribute(n)&&re.isJSXIdentifier(n.name)&&FC.test(n.name.name)))return!0;t=t.parentPath}return!1}function aa(e){let t=We(e.source,"jsx-node");if(!t.ok)return t.result;let n=vo(t.ast,e.locator,e.source);if(!n.ok)return n.result;let r=OC.safeParse({kind:"set-link-target",scope:"selection",link:e.link,changes:e.changes});if(!r.success||r.data.kind!=="set-link-target")return zn(e.source,"Invalid typed link-target changes");let o=n.match.path,i=o.node,s=i.openingElement,a=UC(s.name);if(!a)return zn(e.source,"Unsupported JSX link tag");if(s.attributes.some(re.isJSXSpreadAttribute))return zn(e.source,"Link elements with spread props cannot be transformed safely");let c=new Map;for(let p of s.attributes){if(!re.isJSXAttribute(p))continue;let m=bu(p);if(!m)return zn(e.source,"Unsupported JSX attribute name");let y=c.get(m)??[];y.push(p),c.set(m,y)}if([...c.values()].some(p=>p.length>1))return zn(e.source,"Duplicate JSX attributes cannot be transformed safely");let l=c.get("href")?.[0];if(l&&!VC(l))return zn(e.source,"Dynamic link href cannot be transformed safely");let u=a==="a",d=u?null:BC(o,s.name);if(!u&&!d)return zn(e.source,"Only native anchors and imported next/link components are supported");if(e.link.kind==="none"&&LC(o))return zn(e.source,"A link with an active event handler in its JSX ancestry cannot become an inert anchor");let f=null;if(e.link.kind==="internal-route")if(d)f=a;else{let p=jC(t.ast,o);if(!p.ok)return zn(e.source,p.reason);f=p.localName}if(d&&e.link.kind!=="internal-route"){let p=re.jsxIdentifier("a");s.name=p,i.closingElement&&(i.closingElement.name=re.jsxIdentifier("a")),$C(t.ast,d,o)}else f&&u&&(s.name=re.jsxIdentifier(f),i.closingElement&&(i.closingElement.name=re.jsxIdentifier(f)));let g=new Set;return e.link.kind==="none"?(g.add("href"),g.add("target"),g.add("rel"),Vg.forEach(p=>g.add(p))):(g.add("href"),e.link.kind==="native-link"&&Vg.forEach(p=>g.add(p))),s.attributes=s.attributes.filter(p=>{if(!re.isJSXAttribute(p))return!0;let m=bu(p);return!m||!g.has(m)}),e.link.kind!=="none"&&s.attributes.push(re.jsxAttribute(re.jsxIdentifier("href"),re.stringLiteral(e.link.href))),DC(s,e.changes),De(t.ast,e.source,{kind:"set-link-target",target:"jsx-node",inverse:"set-link-target"})}function DC(e,t){for(let n of t){let r=e.attributes.find(s=>re.isJSXAttribute(s)&&bu(s)===n.name);if(n.operation==="remove"){e.attributes=e.attributes.filter(s=>s!==r);continue}let o=typeof n.value=="string"?re.stringLiteral(n.value):re.jsxExpressionContainer(xu(n.value)),i=re.jsxAttribute(re.jsxIdentifier(n.name),o);r&&re.isJSXAttribute(r)?r.value=i.value:e.attributes.push(i)}}function xu(e){return e===null?re.nullLiteral():typeof e=="string"?re.stringLiteral(e):typeof e=="number"?re.numericLiteral(e):typeof e=="boolean"?re.booleanLiteral(e):Array.isArray(e)?re.arrayExpression(e.map(t=>xu(t))):typeof e=="object"?re.objectExpression(Object.entries(e).map(([t,n])=>re.objectProperty(re.isValidIdentifier(t)?re.identifier(t):re.stringLiteral(t),xu(n)))):re.nullLiteral()}function MC(e){return re.isImportDefaultSpecifier(e)||re.isImportSpecifier(e)&&e.importKind!=="type"&&(re.isIdentifier(e.imported,{name:"default"})||re.isStringLiteral(e.imported,{value:"default"}))}function Ug(e){return!e.parentPath?.isImportDeclaration()||e.parentPath.node.importKind==="type"?!1:e.isImportDefaultSpecifier()||e.isImportSpecifier()&&e.node.importKind!=="type"&&(re.isIdentifier(e.node.imported,{name:"default"})||re.isStringLiteral(e.node.imported,{value:"default"}))}function BC(e,t){if(!re.isJSXIdentifier(t))return null;let n=e.scope.getBinding(t.name);if(!n||!Ug(n.path))return null;let r=n.path.parentPath;return!r?.isImportDeclaration()||r.node.source.value!=="next/link"?null:t.name}function jC(e,t){let n=e.program.body.filter(c=>re.isImportDeclaration(c)&&c.source.value==="next/link"&&c.importKind!=="type"),r=n[0],o=n.flatMap(c=>c.specifiers).find(MC);if(o)return t.scope.getBinding(o.local.name)?.path.node!==o?{ok:!1,reason:"The next/link import is shadowed at the selected element"}:{ok:!0,localName:o.local.name};let i=t.scope.getProgramParent(),s=["Link","NextLink",...Array.from({length:20},(c,l)=>`NextLink${l+2}`)].find(c=>!i.hasBinding(c)&&!t.scope.hasBinding(c));if(!s)return{ok:!1,reason:"Cannot create an unshadowed runtime next/link import"};let a=re.importDefaultSpecifier(re.identifier(s));if(r)r.specifiers.unshift(a);else{let c=re.importDeclaration([a],re.stringLiteral("next/link")),l=0;for(;l<e.program.body.length&&re.isImportDeclaration(e.program.body[l]);)l+=1;e.program.body.splice(l,0,c)}return{ok:!0,localName:s}}function $C(e,t,n){let r=n.scope.getProgramParent();r.crawl();let o=r.getBinding(t);if(!o||!Ug(o.path)||o.referenced)return;let i=o.path.parentPath;if(!(!i?.isImportDeclaration()||i.node.source.value!=="next/link")&&(i.node.specifiers=i.node.specifiers.filter(s=>s!==o.path.node),i.node.specifiers.length===0)){let s=e.program.body.indexOf(i.node);s>=0&&e.program.body.splice(s,1)}}function VC(e){return!e.value||re.isStringLiteral(e.value)}function UC(e){return re.isJSXIdentifier(e)?e.name:null}function bu(e){return re.isJSXIdentifier(e.name)?e.name.name:null}function zn(e,t){return ee(e,"unsupported-syntax",t,"jsx-node")}import*as ht from"@babel/types";import{classifySiteEditPropertyName as Kg}from"@vcp-dev/contracts";function ca(e){let t=Kg(e.name),n=Kg(e.property);if(t.owner!=="generic"||n.owner!=="generic")return ee(e.source,"unsupported-syntax","Property binding is only available for generic properties","jsx-node");if(!Jg(e.object))return ee(e.source,"unsupported-syntax","Property binding object must be a single identifier","jsx-node");if(e.property.length===0)return ee(e.source,"unsupported-syntax","Property binding requires a non-empty property name","jsx-node");let r=We(e.source,"jsx-node");if(!r.ok)return r.result;let o=vo(r.ast,e.locator,e.source);if(!o.ok)return o.result;let i=o.match.path.node.openingElement,s=i.attributes.filter(l=>ht.isJSXAttribute(l)&&JC(l)===e.name);if(s.length>1)return ee(e.source,"unsupported-syntax",`JSX attribute '${e.name}' has multiple sources`,"jsx-node");let a=KC(e.object,e.property),c=s[0];if(c)c.value=ht.jsxExpressionContainer(a);else{let l=bi(e.name,"");l.value=ht.jsxExpressionContainer(a),i.attributes.push(l)}return De(r.ast,e.source,{kind:"set-property-binding",target:"jsx-node",inverse:"restore-property-binding"})}function KC(e,t){return Jg(t)?ht.memberExpression(ht.identifier(e),ht.identifier(t)):ht.memberExpression(ht.identifier(e),ht.stringLiteral(t),!0)}function Jg(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(e)}function JC(e){return ht.isJSXIdentifier(e.name)?e.name.name:ht.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:null}import{getBindingIdentifiers as zC,identifier as vi,importDeclaration as HC,importDefaultSpecifier as WC,importNamespaceSpecifier as GC,importSpecifier as YC,isImportDefaultSpecifier as Xg,isImportNamespaceSpecifier as zg,isImportSpecifier as Hg,stringLiteral as ZC}from"@babel/types";function sn(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(y=>!sR(y));if(o!==-1){let y=r[o],x=y&&typeof y=="object"&&"kind"in y?y.kind:void 0;return ee(t,"unsupported-syntax",`Unsupported import spec kind: ${String(x)}`)}let i=rR(r);if(!i.ok)return ee(t,"unsupported-syntax",i.message);let s=We(t);if(!s.ok)return s.result;let{ast:a}=s,c=a.program,l=c.body.filter(y=>y.type==="ImportDeclaration"&&y.source.value===n),u=new Set(l.flatMap(y=>y.specifiers.flatMap(x=>{let S=aR(y,x);return S?[S]:[]}))),d=i.imports.filter(y=>!u.has(Qg(y)));if(d.length===0)return xi(t,t,{kind:"add-import",target:"import",inverse:"remove-import"});let f=oR(c.body),g=d.find(y=>f.has(Eu(y)));if(g)return ee(t,"unsupported-syntax",`Import local binding already exists: ${Eu(g)}`);let p=nR(d);if(p.reduce((y,x)=>y+x.length,0)!==d.length)return ee(t,"unsupported-syntax","Unsupported import specifier grouping");for(let y of p){if(!Zg(Gg(y)))return ee(t,"unsupported-syntax","Unsupported import specifier combination");let x=l.find(S=>qC(S,y));if(x)QC(x,y);else{let S=HC(Wg(y),ZC(n));iR(c.body,S),l.push(S)}}return De(a,t,{kind:"add-import",target:"import",inverse:"remove-import"})}function qC(e,t){return e.importKind==="type"?!1:Zg(tR(eR(e),Gg(t)))}function QC(e,t){let n=!1,r=new Set(e.specifiers.map(o=>Su(o)));for(let o of Wg(t)){let i=Su(o);r.has(i)||(e.specifiers.push(o),r.add(i),n=!0)}return qg(e.specifiers),{changed:n}}function Wg(e){let t=e.map(n=>{switch(n.kind){case"named":return YC(n.local?vi(n.local):vi(n.imported),vi(n.imported));case"default":return WC(vi(n.local));case"namespace":return GC(vi(n.local));default:return n}});return qg(t),t}function Gg(e){let t=Yg();for(let n of e)n.kind==="default"?t.defaultLocals.add(n.local):n.kind==="named"?t.hasNamed=!0:t.namespaceLocals.add(n.local);return t}function eR(e){let t=Yg();for(let n of e.specifiers)Xg(n)?t.defaultLocals.add(n.local.name):zg(n)?t.namespaceLocals.add(n.local.name):t.hasNamed=!0;return t}function Yg(){return{defaultLocals:new Set,hasNamed:!1,namespaceLocals:new Set}}function tR(e,t){return{defaultLocals:new Set([...e.defaultLocals,...t.defaultLocals]),hasNamed:e.hasNamed||t.hasNamed,namespaceLocals:new Set([...e.namespaceLocals,...t.namespaceLocals])}}function Zg(e){return e.defaultLocals.size>1||e.namespaceLocals.size>1?!1:!(e.hasNamed&&e.namespaceLocals.size>0)}function qg(e){let t=[...e.filter(n=>Xg(n)),...e.filter(n=>zg(n)),...e.filter(n=>Hg(n))];e.splice(0,e.length,...t)}function nR(e){let t=e.filter(i=>i.kind==="default"),n=e.filter(i=>i.kind==="namespace"),r=e.filter(i=>i.kind==="named"),o=[];if(n.length>0){let i=Math.max(t.length,n.length);for(let s=0;s<i;s+=1){let a=[],c=t[s],l=n[s];c&&a.push(c),l&&a.push(l),o.push(a)}return r.length>0&&o.push(r),o}if(t.length>0){o.push([t[0],...r]);for(let i of t.slice(1))o.push([i])}else r.length>0&&o.push(r);return o}function rR(e){let t=new Map,n=new Map;for(let r of e){let o=Qg(r);if(t.has(o))continue;let i=Eu(r),s=n.get(i);if(s&&s!==o)return{ok:!1,message:`Import local binding is requested more than once: ${i}`};t.set(o,r),n.set(i,o)}return{ok:!0,imports:[...t.values()]}}function oR(e){let t=new Set;for(let n of e){if(n.type==="ImportDeclaration"){for(let o of n.specifiers)t.add(o.local.name);continue}let r=(n.type==="ExportNamedDeclaration"||n.type==="ExportDefaultDeclaration")&&n.declaration?n.declaration:n;if(r.type==="VariableDeclaration")for(let o of r.declarations)for(let i of Object.keys(zC(o.id)))t.add(i);else(r.type==="FunctionDeclaration"||r.type==="ClassDeclaration"||r.type==="TSEnumDeclaration")&&r.id&&t.add(r.id.name)}return t}function iR(e,t){let n=[...e].reverse().findIndex(r=>r.type==="ImportDeclaration");if(n===-1)e.unshift(t);else{let r=e.length-n;e.splice(r,0,t)}}function sR(e){if(!e||typeof e!="object"||!("kind"in e))return!1;let t=e.kind;return t==="named"?typeof e.imported=="string"&&(e.local===void 0||typeof e.local=="string"):t==="default"||t==="namespace"?typeof e.local=="string":!1}function Qg(e){switch(e.kind){case"default":return`default:${e.local}`;case"namespace":return`namespace:${e.local}`;case"named":return`named:${e.imported}:${e.local??e.imported}`;default:return e}}function Eu(e){return e.kind==="named"?e.local??e.imported:e.local}function aR(e,t){return e.importKind==="type"||Hg(t)&&t.importKind==="type"?null:Su(t)}function Su(e){if(e.type==="ImportDefaultSpecifier")return`default:${e.local.name}`;if(e.type==="ImportNamespaceSpecifier")return`namespace:${e.local.name}`;let t=e.imported.type==="Identifier"?e.imported.name:e.imported.value,n=e.local.name;return`named:${t}:${n}`}function Co(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(u=>!lR(u));if(o!==-1){let u=r[o],d=u&&typeof u=="object"&&"kind"in u?u.kind:void 0;return ee(t,"unsupported-syntax",`Unsupported remove import spec kind: ${String(d)}`)}let i=We(t);if(!i.ok)return i.result;let{ast:s}=i,a=s.program,c=a.body.findIndex(u=>u.type==="ImportDeclaration"&&u.source.value===n);if(c===-1)return xi(t,t,{kind:"remove-import",target:"import",inverse:"add-import"});let l=a.body[c];return r.length===0?(a.body.splice(c,1),De(s,t,{kind:"remove-import",target:"import",inverse:"add-import"})):(l.specifiers=l.specifiers.filter(u=>!r.some(d=>cR(u,d))),l.specifiers.length===0&&a.body.splice(c,1),De(s,t,{kind:"remove-import",target:"import",inverse:"add-import"}))}function cR(e,t){return t.kind==="default"?e.type==="ImportDefaultSpecifier":t.kind==="namespace"?e.type==="ImportNamespaceSpecifier":e.type!=="ImportSpecifier"?!1:(e.imported.type==="Identifier"?e.imported.name:e.imported.value)===t.imported}function lR(e){if(!e||typeof e!="object"||!("kind"in e))return!1;let t=e.kind;return t==="named"?typeof e.imported=="string":t==="default"||t==="namespace"}function ki(e){let{source:t,locator:n,next:r}=e,o=fa(t,n);return o.ok?(o.path.replaceWith(lr(r)),De(o.ast,t,{kind:"update-value",target:"value",inverse:"restore-value"})):o.result}function la(e){let{source:t,locator:n,index:r,value:o}=e,i=fa(t,n);return i.ok?i.path.isArrayExpression()?i.path.node.elements.some(s=>s?.type==="SpreadElement")?ee(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>i.path.node.elements.length?ee(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(i.path.node.elements.splice(r,0,lr(o)),De(i.ast,t,{kind:"insert-array-element",target:"value",inverse:"remove-array-element"})):ee(t,"unsupported-syntax","Array operations require array expression target","value"):i.result}function ua(e){let{source:t,locator:n,index:r}=e,o=fa(t,n);return o.ok?o.path.isArrayExpression()?o.path.node.elements.some(i=>i?.type==="SpreadElement")?ee(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>=o.path.node.elements.length?ee(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(o.path.node.elements.splice(r,1),De(o.ast,t,{kind:"remove-array-element",target:"value",inverse:"insert-array-element"})):ee(t,"unsupported-syntax","Array operations require array expression target","value"):o.result}function da(e){let{source:t,locator:n,fromIndex:r,toIndex:o}=e,i=fa(t,n);if(!i.ok)return i.result;if(!i.path.isArrayExpression())return ee(t,"unsupported-syntax","Array operations require array expression target","value");if(i.path.node.elements.some(c=>c?.type==="SpreadElement"))return ee(t,"unsupported-syntax","Spread array elements are not supported","value");if(r<0||r>=i.path.node.elements.length||o<0||o>i.path.node.elements.length)return ee(t,"array-index-out-of-range","Array move indices are out of range","value");let[s]=i.path.node.elements.splice(r,1),a=Math.min(o,i.path.node.elements.length);return i.path.node.elements.splice(a,0,s),De(i.ast,t,{kind:"move-array-element",target:"value",inverse:"move-array-element-back"})}function fa(e,t){let n=We(e,"value");if(!n.ok)return{ok:!1,result:n.result};let r=Ie(n.ast,t);return r.ok?{ok:!0,ast:n.ast,path:r.match.path}:{ok:!1,result:{ok:!1,source:e,diagnostic:r.diagnostic}}}import*as Et from"@babel/types";function pa(e){let t=We(e.source,"value");if(!t.ok)return t.result;let n=Ie(t.ast,e.objectLocator);if(!n.ok)return{ok:!1,source:e.source,diagnostic:n.diagnostic};if(!n.match.path.isObjectExpression())return ee(e.source,"unsupported-syntax","Object property upsert requires an ObjectExpression parent","value");let r=n.match.path.node;if(r.properties.some(a=>Et.isSpreadElement(a)||Et.isObjectProperty(a)&&a.computed))return ee(e.source,"unsupported-syntax","Object property upsert does not support spreads or computed keys","value");let o=r.properties.filter(a=>Et.isObjectProperty(a)&&uR(a.key)===e.name);if(o.length>1)return ee(e.source,"unsupported-syntax",`Object property '${e.name}' has multiple sources`,"value");let i=e.value.kind==="undefined"?Et.unaryExpression("void",Et.numericLiteral(0)):lr(e.value.value),s=o[0];if(s)s.value=i,s.shorthand=!1;else{let a=Et.objectProperty(du(e.name),i);e.name==="__proto__"&&(a.computed=!0),r.properties.push(a)}return De(t.ast,e.source,{kind:"upsert-object-property",target:"value",inverse:"restore-object-property"})}function uR(e){return Et.isIdentifier(e)?e.name:Et.isStringLiteral(e)?e.value:Et.isNumericLiteral(e)?String(e.value):null}import{isSiteEditRuntimeContainerTag as dR,isSiteEditRuntimeVoidElementTag as fR}from"@vcp-dev/contracts/site-edit-runtime-capability";function Ro(e){if(!e.composition)throw new Error("Composition unavailable for render source graph.");return e.composition}function pR(e,t,n){let r=Ro(n),o=t.nodes.get(e),i=n.elements.get(e);if(!o||!i)return{composition:r,key:e,canUpdateText:!1,canInsertChild:!1,canMove:!1,canRemove:!1,constraints:[{kind:"opaque-region",message:"Node not found in graph"}]};let s=o.constraints.map(E=>({kind:E.kind,message:E.reason})),a=i.isOpaque,l=o.parentKey===null&&i.componentName==="Page",u=i.tag.toLowerCase(),d=i.tag!==u,f=!d&&fR(u),g=d||dR(u),p=d&&i.childKeys.length>0&&!i.isPublicUiComponent,m=i.textSegments.length>0&&i.textSegments.some(E=>E.editable);f&&!s.some(E=>E.kind==="void-element")&&s.push({kind:"void-element",message:`Element '${i.tag}' is void: children cannot be inserted`}),!f&&!g&&!s.some(E=>E.kind==="void-element")&&s.push({kind:"void-element",message:`Element '${i.tag}' cannot contain structured children`});let y=m&&(!a||i.importedFrom==="next/link"),x=!i.isPublicUiComponent&&!f&&g&&(!a||p);return{composition:r,key:e,canUpdateText:y,canInsertChild:x,canMove:!l,canRemove:!l,constraints:s}}function ma(e,t){let n=new Map;for(let r of e.nodes.keys())n.set(r,pR(r,e,t));return n}function Iu(e){let t=e.route.graph.elements.get(e.key);if(!t)return{key:e.key,composition:e.route.composition,filePath:"",componentName:"",sourceKind:"missing",attrRaw:null,valueRaw:null,attrRange:null,openingElementRange:{start:0,end:0},version:{documentVersion:e.route.graph.version,contentHash:ke(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Key not found: ${e.key}`}]};let n=mR(e.route.source,t);if(!n)return{key:e.key,composition:e.route.composition,filePath:t.sourceFile,componentName:t.componentName,sourceKind:"missing",attrRaw:null,valueRaw:null,attrRange:null,openingElementRange:{start:0,end:0},version:{documentVersion:e.route.graph.version,contentHash:ke(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Unable to locate JSX element for key ${t.identity.key}`}]};let r=n.node.openingElement,o=r.attributes.find(d=>d.type==="JSXAttribute"&&d.name.type==="JSXIdentifier"&&d.name.name==="className"),i={key:e.key,composition:e.route.composition,filePath:t.sourceFile,componentName:t.componentName,openingElementRange:th(r),version:{documentVersion:e.route.graph.version,contentHash:ke(e.route.source)}};if(!o)return{...i,sourceKind:"missing",attrRaw:null,valueRaw:null,attrRange:null,diagnostics:[{code:"missing-class-name",message:"No className attribute is present on this element."}]};let s=o.value,a=s?.type==="StringLiteral"?"stringLiteral":"expression",c=n.get("openingElement").get("attributes").find(d=>d.node===o),l=c?.isJSXAttribute()?c.get("value"):null,u=l?.isJSXExpressionContainer()?gR(l.get("expression")):void 0;return{...i,sourceKind:a,attrRaw:eh(e.route.source,o),valueRaw:s?eh(e.route.source,s):null,...u===void 0?{}:{resolvedClassName:u},attrRange:th(o),diagnostics:[]}}function nh(e){let{source:t,oldAttrRange:n,openingElementRange:r,newAttrRaw:o}=e;if(n){let a=n.start>0&&/\s/.test(t[n.start-1]??"")?n.start-1:n.start,c=o?`${a<n.start?" ":""}${o}`:"";return t.slice(0,a)+c+t.slice(n.end)}if(!o)return t;let i=r.end,s=t.slice(Math.max(0,i-2),i)==="/>"?i-2:i-1;return t.slice(0,s)+` ${o}`+t.slice(s)}function mR(e,t){let n=Rn({source:e,profile:zr({filePath:t.sourceFile,source:e})});if(!n.ok)return null;let r=Ie(n.ast,{kind:"jsx-node",strategy:"structural-path",file:t.identity.file,component:t.identity.component,structuralPath:t.identity.structuralPath,expectedRange:hR(t.sourceRange)});return!r.ok||!r.match.path.isJSXElement()?null:r.match.path}function gR(e){let t=new Set,n=e;if(n.isIdentifier()){for(;n.isIdentifier();){let r=n.scope.getBinding(n.node.name);if(!r?.constant||!r.path.isVariableDeclarator()||!r.path.get("id").isIdentifier({name:n.node.name})||!r.path.parentPath.isVariableDeclaration({kind:"const"})||t.has(r.path.node))return;t.add(r.path.node);let o=r.path.get("init");if(!o.isExpression())return;n=o}if(n.isStringLiteral())return n.node.value;if(n.isTemplateLiteral()&&n.node.expressions.length===0)return n.node.quasis.map(r=>r.value.cooked??r.value.raw).join("")}}function rh(e){let t=Rn({source:`const __v = <div ${e} />;`,profile:"tsx-module"});if(!t.ok)return!1;let n=t.ast.program.body[0],o=(n?.type==="VariableDeclaration"?n.declarations[0]:null)?.init;if(o?.type!=="JSXElement")return!1;let i=o.openingElement.attributes;return i.length===1&&i[0]?.type==="JSXAttribute"&&i[0].name.type==="JSXIdentifier"&&i[0].name.name==="className"}function eh(e,t){return t.start==null||t.end==null?"":e.slice(t.start,t.end)}function th(e){if(e.start==null||e.end==null)throw new Error("AST node does not include offsets.");return{start:e.start,end:e.end}}function hR(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function oh(){let e=new Set;return{emit(t){for(let n of Array.from(e))try{n(t)}catch{}},subscribe(t){return e.add(t),()=>{e.delete(t)}}}}import{randomUUID as yR}from"node:crypto";import ga from"node:fs/promises";import vu from"node:path";import{setTimeout as xR}from"node:timers/promises";var bR={async mkdir(e,t){await ga.mkdir(e,t)},async writeFile(e,t,n){await ga.writeFile(e,t,n)},async rename(e,t){await ga.rename(e,t)},async rm(e,t){await ga.rm(e,t)}},ER=new Set(["EACCES","EBUSY","EPERM"]),SR=[10,20,40,80,160];async function IR(e,t,n){for(let r of SR)try{await e.rename(t,n);return}catch(o){if(!vR(o))throw o;await xR(r)}await e.rename(t,n)}function vR(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&ER.has(e.code)}async function ha(e,t,n=bR){let r=vu.dirname(e),o=vu.basename(e),i=vu.join(r,`.${o}.${process.pid}.${yR()}.tmp`),s=!1;try{await n.mkdir(r,{recursive:!0}),await n.writeFile(i,t,"utf8"),await IR(n,i,e),s=!0}finally{if(!s)try{await n.rm(i,{force:!0})}catch{}}}import ku from"@babel/traverse";import*as P from"@babel/types";import*as we from"@babel/types";function Tn(e,t={}){if(we.isTSAsExpression(e)||we.isTSSatisfiesExpression(e)||we.isTSNonNullExpression(e)||we.isTypeCastExpression(e)||we.isParenthesizedExpression(e))return Tn(e.expression,t);if(we.isStringLiteral(e))return{status:"resolved",value:e.value};if(we.isNumericLiteral(e))return Number.isFinite(e.value)?{status:"resolved",value:e.value}:{status:"unresolved"};if(we.isBooleanLiteral(e))return{status:"resolved",value:e.value};if(we.isNullLiteral(e))return{status:"resolved",value:null};if(we.isTemplateLiteral(e))return e.expressions.length===0&&e.quasis.length===1?{status:"resolved",value:e.quasis[0].value.cooked??e.quasis[0].value.raw}:{status:"unresolved"};if(we.isIdentifier(e))return e.name==="undefined"&&!t.resolveIdentifier?{status:"undefined"}:t.resolveIdentifier?.(e.name)??{status:"unresolved"};if(we.isUnaryExpression(e)&&e.operator==="void"&&we.isNumericLiteral(e.argument)&&e.argument.value===0)return{status:"undefined"};if(we.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||we.isSpreadElement(r))return{status:"unresolved"};let o=Tn(r,t);if(o.status!=="resolved")return{status:"unresolved"};n.push(o.value)}return{status:"resolved",value:n}}if(we.isObjectExpression(e)){let n=Object.create(null);for(let r of e.properties){if(!we.isObjectProperty(r)||r.computed||!we.isExpression(r.value))return{status:"unresolved"};let o=kR(r.key);if(o===null)return{status:"unresolved"};let i=Tn(r.value,t);if(i.status!=="resolved")return{status:"unresolved"};Object.defineProperty(n,o,{configurable:!0,enumerable:!0,value:i.value,writable:!0})}return{status:"resolved",value:n}}return we.isMemberExpression(e)||we.isOptionalMemberExpression(e)?t.resolveMember?.(e)??{status:"unresolved"}:{status:"unresolved"}}function kR(e){return we.isIdentifier(e)?e.name:we.isStringLiteral(e)?e.value:we.isNumericLiteral(e)?String(e.value):null}var _R=typeof ku=="function"?ku:ku.default;function Rt(e){return{startLine:e.loc?.start.line??0,startColumn:e.loc?.start.column??0,endLine:e.loc?.end.line??0,endColumn:e.loc?.end.column??0}}function CR(e){return/^[A-Z]/.test(e)}function Pu(e){let t=e.openingElement;return P.isJSXIdentifier(t.name)?t.name.name==="Fragment":P.isJSXMemberExpression(t.name)?t.name.property.name==="Fragment":!1}function Po(e){return P.isJSXFragment(e)}function sh(e){return P.isJSXIdentifier(e.name)?e.name.name:P.isJSXMemberExpression(e.name)?ah(e.name):P.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:"unknown"}function ah(e){return P.isJSXIdentifier(e.object)?`${e.object.name}.${e.property.name}`:P.isJSXMemberExpression(e.object)?`${ah(e.object)}.${e.property.name}`:e.property.name}function RR(e){return e.split(".")[0]??e}function NR(e){let t=e;for(;t;){let n=t.node;if(P.isFunctionDeclaration(n)&&n.id||P.isVariableDeclarator(n)&&P.isIdentifier(n.id))return n.id.name;if(P.isExportDefaultDeclaration(n)){let r=n.declaration;if(P.isFunctionDeclaration(r)&&r.id)return r.id.name;if(P.isFunctionDeclaration(r)&&!r.id)return"default"}t=t.parentPath}return null}function PR(){let e=new Map;return{getOrdinal(t,n){let r=t??"__root__";e.has(r)||e.set(r,new Map);let o=e.get(r),i=o.get(n)??0;return o.set(n,i+1),i}}}function AR(e){let t=new Map;for(let n of e.program.body){if(!P.isImportDeclaration(n))continue;let r=n.source.value;for(let o of n.specifiers)if(P.isImportDefaultSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"default"});else if(P.isImportNamespaceSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"*"});else if(P.isImportSpecifier(o)){let i=P.isIdentifier(o.imported)?o.imported.name:o.imported.value;t.set(o.local.name,{specifier:r,exportName:i})}}return t}function Hn(e,t=[]){if(P.isIdentifier(e))return t.push(e.name),t;if(P.isObjectPattern(e)){for(let n of e.properties)P.isObjectProperty(n)?Hn(n.value,t):P.isRestElement(n)&&Hn(n.argument,t);return t}if(P.isArrayPattern(e)){for(let n of e.elements)n&&(P.isRestElement(n)?Hn(n.argument,t):Hn(n,t));return t}return P.isAssignmentPattern(e)?(Hn(e.left,t),t):(P.isRestElement(e)&&Hn(e.argument,t),t)}function mn(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function _i(e,t){for(let n=t.length-1;n>=0;n-=1){let r=t[n].get(e);if(r)return r.resolved?{kind:"resolved",value:r.value}:{kind:"unresolved"}}return{kind:"unresolved"}}function TR(e,t,n){e.set(t,{resolved:!0,value:n})}function Au(e,t){e.set(t,{resolved:!1})}function ch(e,t){let n=e;for(let r of t){if(r.kind==="property"){if(n==null||Array.isArray(n)||typeof n!="object"||!(r.name in n))return{kind:"known-empty"};n=n[r.name];continue}if(!Array.isArray(n)||r.index<0||r.index>=n.length)return{kind:"known-empty"};n=n[r.index]}return{kind:"resolved",value:n}}function pt(e,t,n){if(P.isTSAsExpression(e)||P.isTSSatisfiesExpression(e)||P.isTSNonNullExpression(e)||P.isTypeCastExpression(e)||P.isParenthesizedExpression(e))return pt(e.expression,t,n);if(P.isLogicalExpression(e))return ya([pt(e.left,t,n),pt(e.right,t,n)]);if(P.isBinaryExpression(e))return ya([P.isExpression(e.left)?pt(e.left,t,n):null,P.isExpression(e.right)?pt(e.right,t,n):null]);if(P.isConditionalExpression(e))return ya([pt(e.consequent,t,n),pt(e.alternate,t,n)]);if(P.isTemplateLiteral(e))return ya(e.expressions.filter(P.isExpression).map(i=>pt(i,t,n)));if(P.isIdentifier(e))return{kind:"identifier",expression:e.name,base:e.name,path:[]};if(!P.isMemberExpression(e)&&!P.isOptionalMemberExpression(e))return null;let r=[],o=e;for(;P.isMemberExpression(o)||P.isOptionalMemberExpression(o);){if(o.computed)if(P.isNumericLiteral(o.property))r.unshift({kind:"index",index:o.property.value});else if(P.isStringLiteral(o.property))r.unshift({kind:"property",name:o.property.value});else if(n&&P.isExpression(o.property)){let i=fr(o.property,n);if(typeof i=="string")r.unshift({kind:"property",name:i});else if(Number.isInteger(i))r.unshift({kind:"index",index:i});else return null}else return null;else{if(!P.isIdentifier(o.property))return null;r.unshift({kind:"property",name:o.property.name})}o=o.object}return P.isIdentifier(o)?{kind:r.some(i=>i.kind==="index")?"index-expression":"member-expression",expression:mn(e,t),base:o.name,path:r}:null}function ya(e){let t=e.filter(r=>r!==null);if(t.length===0)return null;let n=t[0];return t.some(r=>r.base!==n.base||JSON.stringify(r.path)!==JSON.stringify(n.path))?null:{...n}}function Tu(e,t,n){if(P.isArrayExpression(e)){let r=e.elements[0];return e.elements.length===1&&P.isExpression(r)?pt(r,t,n):null}return P.isCallExpression(e)&&P.isMemberExpression(e.callee)&&!e.callee.computed&&P.isIdentifier(e.callee.property)&&["filter","slice","sort","toSorted","reverse","toReversed"].includes(e.callee.property.name)&&P.isExpression(e.callee.object)?Tu(e.callee.object,t,n):pt(e,t,n)}function fr(e,t){if(P.isStringLiteral(e)||P.isNumericLiteral(e)||P.isBooleanLiteral(e))return e.value;if(P.isNullLiteral(e))return null;if(P.isTemplateLiteral(e))return e.expressions.length===0&&e.quasis.length===1?e.quasis[0].value.cooked??e.quasis[0].value.raw:void 0;if(P.isIdentifier(e)){let n=_i(e.name,t.valueScopes);return n.kind==="resolved"?n.value:void 0}if(P.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||P.isSpreadElement(r))return;let o=fr(r,t);if(o===void 0)return;n.push(o)}return n}if(P.isObjectExpression(e)){let n={};for(let r of e.properties){if(!P.isObjectProperty(r)||r.computed||!P.isExpression(r.value))return;let o=null;if(P.isIdentifier(r.key)?o=r.key.name:P.isStringLiteral(r.key)&&(o=r.key.value),!o)return;let i;if(r.shorthand){if(!P.isIdentifier(r.value))return;let s=_i(r.value.name,t.valueScopes);if(s.kind!=="resolved")return;i=s.value}else i=fr(r.value,t);if(i===void 0)return;n[o]=i}return n}if(P.isMemberExpression(e)){let n=pt(e,"",t);if(!n)return;let r=_i(n.base,t.valueScopes);if(r.kind!=="resolved")return;let o=ch(r.value,n.path);return o.kind==="resolved"?o.value:void 0}if(P.isCallExpression(e))return uh(e,t)??void 0}function lh(e,t,n){let r=pt(e,n,t);if(!r)return P.isMemberExpression(e)||P.isBinaryExpression(e)||P.isLogicalExpression(e)||P.isConditionalExpression(e)||P.isCallExpression(e)?{value:mn(e,n),source:null}:null;let o=_i(r.base,t.valueScopes),i=r.kind==="identifier"?o:o.kind==="resolved"?ch(o.value,r.path):o;return i.kind==="resolved"&&(typeof i.value=="string"||typeof i.value=="number")?{value:String(i.value),source:r}:i.kind==="resolved"&&(typeof i.value=="boolean"||i.value===null)||i.kind==="known-empty"?null:{value:r.expression,source:r}}function _u(e,t,n,r,o,i){return{file:e,componentName:t,elements:n,regions:r,ordinalTracker:PR(),parentStack:[],valueScopes:i,importMap:o}}function Ru(e,t,n){for(let r of e)for(let o of r.declarations){for(let s of Hn(o.id))Au(n,s);if(!P.isIdentifier(o.id)||!o.init||!P.isExpression(o.init))continue;let i=fr(o.init,t);i!==void 0&&TR(n,o.id.name,i)}}function wR(e){let t=[];for(let n of e){if(P.isVariableDeclaration(n)){t.push(n);continue}P.isExportNamedDeclaration(n)&&n.declaration&&P.isVariableDeclaration(n.declaration)&&t.push(n.declaration)}return t}function OR(e,t,n){let r=[],o=0;for(let i of e)if(P.isJSXText(i)){let s=i.value.trim();s&&r.push({index:o++,value:s,sourceRange:Rt(i),editable:!0,source:null})}else if(P.isJSXExpressionContainer(i)&&P.isStringLiteral(i.expression))r.push({index:o++,value:i.expression.value,sourceRange:Rt(i),editable:!0,source:null});else if(P.isJSXExpressionContainer(i)&&P.isTemplateLiteral(i.expression)){let s=i.expression;s.expressions.length===0&&s.quasis.length===1?r.push({index:o++,value:s.quasis[0].value.cooked??s.quasis[0].value.raw,sourceRange:Rt(i),editable:!0,source:null}):r.push({index:o++,value:mn(s,n),sourceRange:Rt(i),editable:!0,source:pt(s,n,t)})}else if(P.isJSXExpressionContainer(i)&&P.isExpression(i.expression)){let s=lh(i.expression,t,n);s&&r.push({index:o++,value:s.value,sourceRange:Rt(i),editable:!0,source:s.source})}return r}function FR(e,t,n){let r=[];for(let[o,i]of e.attributes.entries()){if(!P.isJSXAttribute(i))continue;let s=DR(i.name);if(!s)continue;let a=mn(i,n);if(P.isStringLiteral(i.value)){r.push({name:s,value:i.value.value,sourceRange:Rt(i),source:null,syntaxKind:"literal",raw:a,order:o,resolution:{status:"resolved",value:i.value.value}});continue}if(i.value===null){r.push({name:s,value:"true",sourceRange:Rt(i),source:null,syntaxKind:"boolean-shorthand",raw:a,order:o,resolution:{status:"resolved",value:!0},resolvedValue:!0});continue}if(P.isJSXExpressionContainer(i.value)&&P.isExpression(i.value.expression)){let c=fr(i.value.expression,t);if(s==="className"){let g=typeof c=="string"?c:c===void 0?uh(i.value.expression,t):null;if(g){r.push({name:s,value:g,sourceRange:Rt(i),source:null,resolvedValue:g,syntaxKind:"expression",raw:a,order:o,resolution:{status:"resolved",value:g}});continue}}let l=lh(i.value.expression,t,n);if(c!==void 0){r.push({name:s,value:KR(c),sourceRange:Rt(i),source:pt(i.value.expression,n,t),resolvedValue:c,syntaxKind:"expression",raw:a,order:o,resolution:{status:"resolved",value:c}});continue}let u=MR(i.value.expression,t),d=pt(i.value.expression,n,t),f=l?.value??mn(i.value.expression,n);r.push({name:s,value:u.status==="undefined"?"undefined":f,sourceRange:Rt(i),source:l?.source??d,syntaxKind:"expression",raw:a,order:o,resolution:u})}}return r}function LR(e,t,n){return e.attributes.flatMap((r,o)=>!P.isJSXSpreadAttribute(r)||!P.isExpression(r.argument)?[]:[{raw:mn(r.argument,n),sourceRange:Rt(r),order:o,source:pt(r.argument,n,t)}])}function DR(e){return P.isJSXIdentifier(e)?e.name:P.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function MR(e,t){return Tn(e,{resolveIdentifier(n){let r=_i(n,t.valueScopes);return r.kind==="resolved"?{status:"resolved",value:r.value}:n==="undefined"&&!t.valueScopes.some(o=>o.has(n))?{status:"undefined"}:{status:"unresolved"}},resolveMember(n){let r=fr(n,t);return r===void 0?{status:"unresolved"}:{status:"resolved",value:r}}})}function uh(e,t){let n=No(e,t);return n&&n.map(o=>o.trim()).filter(Boolean).join(" ")||null}function No(e,t){if(P.isStringLiteral(e))return[e.value];if(P.isTemplateLiteral(e))return e.expressions.length>0?null:[e.quasis.map(n=>n.value.cooked??"").join("")];if(P.isNullLiteral(e))return[];if(P.isBooleanLiteral(e))return e.value?null:[];if(P.isIdentifier(e)||P.isMemberExpression(e)){if(P.isIdentifier(e)&&e.name==="undefined")return[];let n=fr(e,t);return typeof n=="string"?[n]:null}if(P.isConditionalExpression(e)){let n=No(e.consequent,t),r=No(e.alternate,t);return!n||!r?null:[...n,...r]}if(P.isLogicalExpression(e)){if(e.operator!=="&&")return null;let n=fr(e.left,t);return n===!1||n===null?[]:No(e.right,t)}if(P.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||P.isSpreadElement(r))return null;let o=No(r,t);if(!o)return null;n.push(...o)}return n}if(P.isObjectExpression(e)){let n=[];for(let r of e.properties){if(!P.isObjectProperty(r))return null;let o=jR(r.key);if(!o)return null;n.push(o)}return n}if(P.isCallExpression(e)){let n=BR(e.callee);if(!n||!["cn","clsx","twMerge"].includes(n))return null;let r=[];for(let o of e.arguments){if(!P.isExpression(o))return null;let i=No(o,t);if(!i)return null;r.push(...i)}return r}return null}function BR(e){return P.isIdentifier(e)?e.name:P.isMemberExpression(e)&&P.isIdentifier(e.property)?e.property.name:null}function jR(e){return P.isIdentifier(e)?e.name:P.isStringLiteral(e)?e.value:null}function $R(e,t){let n=e.attributes.find(r=>P.isJSXAttribute(r)&&P.isJSXIdentifier(r.name)&&r.name.name===t);return!n||!P.isJSXAttribute(n)||!P.isJSXExpressionContainer(n.value)?null:n.value.expression}function VR(e,t){for(let n of t){let r=$R(e,n);if(r)return r}return null}function UR(e){return P.isJSXIdentifier(e.name)?e.name.name:null}function KR(e){return e===null?"null":typeof e=="boolean"?e?"true":"false":JSON.stringify(e)}function JR(e){if(!P.isCallExpression(e)&&!P.isOptionalCallExpression(e))return null;let t=e.callee;return!P.isMemberExpression(t)&&!P.isOptionalMemberExpression(t)||!P.isIdentifier(t.property)||t.property.name!=="map"||t.computed||!P.isExpression(t.object)?null:{call:e,collection:t.object,callback:e.arguments[0]}}function Cu(e){return P.isArrowFunctionExpression(e)||P.isFunctionExpression(e)}function XR(e){return e==="render"||e==="itemRender"||e==="rowRender"||e==="children"}function zR(e){return e==="empty"||e==="emptyRender"||e==="loading"||e==="loadingRender"||e==="error"||e==="errorRender"||e==="fallback"||e==="headerRender"||e==="footerRender"}function ih(e,t,n,r){if(!e||!P.isExpression(e))return null;let o={kind:"repeat-template",collectionExpression:mn(e,n),collectionSource:Tu(e,n,r)};if(t){let i=t.params[0],s=t.params[1];P.isIdentifier(i)&&(o.itemParamName=i.name),P.isIdentifier(s)&&(o.indexParamName=s.name)}return o}function Wn(e,t,n){if(!e)return[];if(P.isJSXElement(e)){if(Pu(e))return Ia(e.children,t,n);let r=Ea(e,t,n);return r?[r]:[]}return Po(e)?Sa(e,t,n):P.isParenthesizedExpression(e)?Wn(e.expression,t,n):P.isExpression(e)?va(e,t,n):[]}function xa(e,t,n){let r=new Map;for(let o of e.params)for(let i of Hn(o))Au(r,i);t.valueScopes.push(r);try{if(!P.isBlockStatement(e.body))return Wn(e.body,t,n);let o=new Map;t.valueScopes.push(o);try{return dh(e.body.body,t,n)}finally{t.valueScopes.pop()}}finally{t.valueScopes.pop()}}function dh(e,t,n){let r=[];for(let o of e){if(P.isVariableDeclaration(o)){let i=t.valueScopes[t.valueScopes.length-1];if(i){Ru([o],t,i);for(let s of o.declarations)P.isIdentifier(s.id)&&(P.isJSXElement(s.init)||P.isJSXFragment(s.init))&&r.push(...Wn(s.init,t,n))}continue}r.push(...Nu(o,t,n))}return r}function Nu(e,t,n){if(P.isReturnStatement(e))return e.argument?Wn(e.argument,t,n):[];if(P.isBlockStatement(e))return to(e.body,t,n);if(P.isIfStatement(e)){let r=P.isBlockStatement(e.consequent)?to(e.consequent.body,t,n):Nu(e.consequent,t,n),o=e.alternate?P.isBlockStatement(e.alternate)?to(e.alternate.body,t,n):Nu(e.alternate,t,n):[];return[...r,...o]}if(P.isSwitchStatement(e))return to(e.cases.flatMap(r=>r.consequent),t,n);if(P.isTryStatement(e)){let r=to(e.block.body,t,n);return e.handler&&r.push(...to(e.handler.body.body,t,n)),e.finalizer&&r.push(...to(e.finalizer.body,t,n)),r}return[]}function to(e,t,n){let r=new Map;t.valueScopes.push(r);try{return dh(e,t,n)}finally{t.valueScopes.pop()}}function ba(e,t,n,r,o,i){o.length!==0&&e.regions.push({kind:t,ownerKey:n,childKeys:o,sourceRange:Rt(r),sourceCandidates:i&&i.length>0?i:void 0})}function HR(e,t,n,r){let o=VR(e.openingElement,["items","dataSource","data"]),i={key:t,tag:sh(e.openingElement)};n.parentStack.push(i);try{for(let s of e.openingElement.attributes){if(!P.isJSXAttribute(s))continue;let a=UR(s);if(!a||!P.isJSXExpressionContainer(s.value))continue;let c=s.value.expression;if(!P.isJSXEmptyExpression(c)){if(XR(a)&&Cu(c)){let l=xa(c,n,r),u=ih(o,c,r,n);ba(n,"repeat-region",t,s,l,u?[u]:void 0);continue}if(zR(a)){let l=Cu(c)?xa(c,n,r):Wn(c,n,r);ba(n,"conditional-region",t,s,l)}}}if(o)for(let s of e.children){if(!P.isJSXExpressionContainer(s)||!Cu(s.expression))continue;let a=xa(s.expression,n,r),c=ih(o,s.expression,r,n);ba(n,"repeat-region",t,s,a,c?[c]:void 0)}}finally{n.parentStack.pop()}}function Ea(e,t,n){let r=sh(e.openingElement);if(r==="Fragment"||Pu(e))return Ia(e.children,t,n),null;let o=t.parentStack[t.parentStack.length-1]??null,i=o?.key??null,s=CR(r),a;if(s){let E=t.ordinalTracker.getOrdinal(i,r);a=`component:${r}#${E}`}else{let E=t.ordinalTracker.getOrdinal(i,r);a=`${r}#${E}`}let c=o?t.elements.get(o.key)?.identity.structuralPath:void 0,l=c?`${c}/${a}`:a,u=Ei(t.file,t.componentName,l),d={file:t.file,component:t.componentName,structuralPath:l,key:u},f=s?"component-boundary":null,g=OR(e.children,t,n),p=FR(e.openingElement,t,n),m=LR(e.openingElement,t,n),y,x,S=!1;if(s){let E=t.importMap.get(r)??t.importMap.get(RR(r));E&&(y=E.specifier,x=E.exportName,S=Hr(E.specifier,t.file))}let b={identity:d,tag:r,componentName:t.componentName,sourceFile:t.file,sourceRange:Rt(e),parentKey:i,childKeys:[],textSegments:g,attributes:p.length>0?p:void 0,attributeSpreads:m.length>0?m:void 0,boundaryKind:f,isOpaque:s,...S?{isPublicUiComponent:!0}:{},importedFrom:y,exportName:x};return t.elements.set(u,b),i&&t.elements.has(i)&&t.elements.get(i).childKeys.push(u),HR(e,u,t,n),(!s||e.children.length>0)&&(t.parentStack.push({key:u,tag:r}),WR(e.children,t,n),t.parentStack.pop()),u}function Sa(e,t,n){return Ia(e.children,t,n)}function Ia(e,t,n){let r=[];for(let o of e)if(P.isJSXElement(o))if(Pu(o))r.push(...Ia(o.children,t,n));else{let i=Ea(o,t,n);i&&r.push(i)}else Po(o)?r.push(...Sa(o,t,n)):P.isJSXExpressionContainer(o)&&r.push(...va(o.expression,t,n));return r}function WR(e,t,n){for(let r of e)P.isJSXElement(r)?Ea(r,t,n):Po(r)?Sa(r,t,n):P.isJSXExpressionContainer(r)&&va(r.expression,t,n)}function GR(e){return e==="&&"||e==="||"||e==="??"}function va(e,t,n){if(P.isJSXEmptyExpression(e))return[];let r=JR(e);if(r){let o=r.call,i=t.parentStack[t.parentStack.length-1]??null,s=[],a=r.callback,c={kind:"repeat-template",collectionExpression:mn(r.collection,n),collectionSource:Tu(r.collection,n,t)};if(P.isArrowFunctionExpression(a)||P.isFunctionExpression(a)){let u=a.params[0],d=a.params[1];P.isIdentifier(u)&&(c.itemParamName=u.name),P.isIdentifier(d)&&(c.indexParamName=d.name)}s.push(c);let l={kind:"repeat-region",ownerKey:i?.key??"",childKeys:[],sourceRange:Rt(o),sourceCandidates:s.length>0?s:void 0};return t.regions.push(l),(P.isArrowFunctionExpression(a)||P.isFunctionExpression(a))&&l.childKeys.push(...xa(a,t,n)),l.childKeys}if(P.isConditionalExpression(e)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:mn(e.test,n),conditionSource:pt(e.test,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:Rt(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...Wn(e.consequent,t,n)),s.childKeys.push(...Wn(e.alternate,t,n)),s.childKeys}if(P.isLogicalExpression(e)&&GR(e.operator)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:mn(e.left,n),conditionSource:pt(e.left,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:Rt(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...Wn(e.right,t,n)),s.childKeys}if(P.isParenthesizedExpression(e))return va(e.expression,t,n);if(P.isJSXElement(e)){let o=Ea(e,t,n);return o?[o]:[]}return Po(e)?Sa(e,t,n):[]}function YR(e){let t=e.argument;return t&&(P.isExpression(t)||Po(t))?t:null}function Ci(e,t){let n=[];for(let r of e){if(P.isReturnStatement(r)){let o=YR(r);o&&n.push({argument:o,statement:r,condition:t});continue}if(P.isIfStatement(r)){let o=P.isBlockStatement(r.consequent)?r.consequent.body:[r.consequent];if(n.push(...Ci(o,r.test)),r.alternate){let i=P.isBlockStatement(r.alternate)?r.alternate.body:[r.alternate];n.push(...Ci(i,r.test))}continue}if(P.isSwitchStatement(r))for(let o of r.cases){let i=o.test?P.binaryExpression("===",r.discriminant,o.test):r.discriminant;n.push(...Ci(o.consequent,i))}}return n}function ka(e){return{routeId:e,rootKeys:[],elements:new Map,regions:[],fileIndex:new Map,version:1,diagnostics:[]}}function fh(e){let{file:t,source:n,ast:r}=e,o=e.imports.map(f=>f.specifier);if(!P.traverseFast(r,f=>{if(P.isJSXElement(f)||P.isJSXFragment(f))return P.traverseFast.stop}))return{graph:ka(t),localImports:o};let s=new Map,a=[],c=[],l=new Map,u=AR(r);_R(r,{"FunctionDeclaration|FunctionExpression|ArrowFunctionExpression"(f){let g=NR(f);if(!g)return;let p=f.node,m=[];if(P.isArrowFunctionExpression(p))P.isExpression(p.body)||Po(p.body)?m=[{argument:p.body,statement:P.returnStatement(P.isExpression(p.body)?p.body:null)}]:P.isBlockStatement(p.body)&&(m=Ci(p.body.body));else{let k=p.body;P.isBlockStatement(k)&&(m=Ci(k.body))}if(m.length===0){f.skip();return}let y=new Map;Ru(wR(r.program.body),_u(t,g,s,a,u,[y]),y);let x=new Map;for(let k of p.params)for(let I of Hn(k))Au(x,I);let S=P.isBlockStatement(p.body)?p.body.body:[],b=m[0]?.statement??null;for(let k of S){if(b&&k===b)break;P.isVariableDeclaration(k)&&Ru([k],_u(t,g,s,a,u,[y,x]),x)}let E=_u(t,g,s,a,u,[y,x]);for(let k of m){let I=Wn(k.argument,E,n);for(let v of I)c.includes(v)||c.push(v);if(k.condition){let v={kind:"conditional-branch",conditionExpression:mn(k.condition,n),conditionSource:pt(k.condition,n,E)};ba(E,"conditional-region","",k.statement,I,[v])}}f.skip()}});let d=[...s.keys()];return d.length>0&&l.set(t,d),{graph:{routeId:t,rootKeys:c,elements:s,regions:a,fileIndex:l,version:1,diagnostics:[]},localImports:o}}function wu(e,t,n,r){return[...e.map(o=>({...o})),{fromFile:t,specifier:n,targetPath:r}]}function _a(e,t,n){return{...e,details:{...e.details??{},entryFile:t,importStack:n.map(r=>({...r}))}}}async function ph(e,t){if(e.length===0)return[];if(e.length===1)return[await t(e[0])];let n=new Array(e.length),r=0,o=Array.from({length:Math.min(8,e.length)},async()=>{for(;r<e.length;){let s=r++;n[s]=await t(e[s])}}),i=await Promise.allSettled(o);for(let s of i)if(s.status==="rejected")throw s.reason;return n}async function Ca(e,t,n,r,o={}){let i=o.maxDepth??10,s=o.version??1,a=o.parseModule??je,c=new Map,l=new Map,u=new Map,d=[],f=new Set,g=x=>{let S=`${x.path}\0${x.code}\0${x.message}\0${JSON.stringify(x.details??{})}`;f.has(S)||(f.add(S),d.push(x))},p=[{file:e,source:t,depth:0,diagnosticEntryFile:e,importStack:[]},...(o.additionalEntries??[]).map(x=>({file:x.file,source:x.source,depth:0,diagnosticEntryFile:x.file,importStack:[]}))],m=new Set;for(;p.length>0;){let x=p.shift(),{file:S,source:b,depth:E,diagnosticEntryFile:k,importStack:I}=x;if(m.has(S))continue;m.add(S),c.set(S,b);let v=o.validationOnly&&E<i?o.validatedImports?.(S,b):void 0,N,A;if(v)N=ka(S),A=v;else{let $=a(S,b);if(!$.ok){g(_a($.diagnostic,k,I));continue}u.set(S,$.module);let G=o.validationOnly&&E<i?{graph:ka(S),localImports:$.module.imports.map(M=>M.specifier)}:fh($.module);N=G.graph,A=G.localImports}let w=[...new Set([...N.elements.values()].map($=>$.importedFrom).filter($=>typeof $=="string"&&nt($)))],F=w.length?await ph(w,$=>js(S,$,r)):[],B=new Map(w.map(($,G)=>[$,F[G]]));for(let $ of N.elements.values())if($.importedFrom&&nt($.importedFrom)){let G=$.importedFrom,M=B.get(G);M.ok?($.importedFrom=M.path,Kn(M.path)&&($.isPublicUiComponent=!0)):Hr(G,S)||g(_a(M.diagnostic,k,wu(I,S,G,M.diagnostic.path)))}if(l.set(S,N),E>=i)continue;let X=await ph(A,async $=>{if(Hm($))return null;let G=B.get($)??await js(S,$,r);if(!G.ok)return Hr($,S)?null:{diagnostic:_a(G.diagnostic,k,wu(I,S,$,G.diagnostic.path))};let M=G.path;if(m.has(M)||Kn(M))return null;let fe=wu(I,S,$,M);try{let Fe=await n(M);return{entry:{file:M,source:Fe,depth:E+1,diagnosticEntryFile:k,importStack:fe}}}catch(Fe){return{diagnostic:_a({path:M,code:"import-read-failed",message:`Failed to read imported file: ${M}`,details:{fromFile:S,specifier:$,reason:Fe instanceof Error?Fe.message:String(Fe)}},k,fe)}}});for(let $ of X)$&&"entry"in $?p.push($.entry):$&&g($.diagnostic)}let y=ZR(e,l,s,(o.additionalEntries??[]).map(x=>x.file));return y.diagnostics=d,{graph:y,allSources:c,diagnostics:d,parsedModules:u,entryModule:u.get(e)??null}}function ZR(e,t,n,r=[]){let o=new Map,i=[],s=new Map,a=[];for(let[c,l]of t){for(let[u,d]of l.elements)o.set(u,d);for(let u of l.regions)i.push(u);for(let[u,d]of l.fileIndex){let f=s.get(u)??[];s.set(u,[...f,...d])}if(c===e){a=l.rootKeys;continue}r.includes(c)&&(a=[...a,...l.rootKeys])}return{routeId:e,rootKeys:a,elements:o,regions:i,fileIndex:s,version:n}}function mh(e=256){if(!Number.isSafeInteger(e)||e<1)throw new RangeError("Validated syntax capacity must be positive.");let t=new Map;return{remember(n){for(let r of n)t.get(r.file)?.source!==r.source&&(t.delete(r.file),t.size>=e&&t.delete(t.keys().next().value),t.set(r.file,{source:r.source,imports:Object.freeze(r.imports.map(o=>o.specifier))}))},getImports(n,r){let o=t.get(n);return o?.source===r?o.imports:void 0},clear(){t.clear()}}}import{SiteEditHistoryProvenanceSchema as CN}from"@vcp-dev/contracts";import{createHash as qR,randomUUID as Uu}from"node:crypto";import et from"node:fs/promises";import rt from"node:path";var kh=new WeakMap;function Ao(e){return kh.get(e)?.()??e.readIndex()}var an=1,Fu=1,QR=2,eN="index.json",tN="recovery.json",nN="transaction-journal.json",rN="document-version.json",Pa={maxEntries:100,maxSessionBytes:512*1024*1024,maxEntryBytes:128*1024*1024},he={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"},xe=class extends Error{constructor(t,n,r){super(n),this.name="FileHistoryStoreError",this.code=t,r?.cause!==void 0&&(this.cause=r.cause)}};function Gn(){return{entries:new Map,blobSizes:new Map}}function Ra(e,t){let n={entries:new Map,blobs:new Map,objectBytes:0};for(let r of e)_h(n,r,t);return n}function _h(e,t,n){let r=e.entries.get(t);if(r){e.entries.set(t,{...r,references:r.references+1});return}let o=n.entries.get(t),i=new Map(o.entry.blobs.map(s=>[s.digest,n.blobSizes.get(s.digest)]));e.entries.set(t,{sizeBytes:o.sizeBytes,references:1,blobs:i}),e.objectBytes+=o.sizeBytes;for(let[s,a]of i){let c=e.blobs.get(s);e.blobs.set(s,{sizeBytes:a,references:(c?.references??0)+1}),c||(e.objectBytes+=a)}}function Ch(e,t){let n=e.entries.get(t);if(n.references>1){e.entries.set(t,{...n,references:n.references-1});return}e.entries.delete(t),e.objectBytes-=n.sizeBytes;for(let r of n.blobs.keys()){let o=e.blobs.get(r);o.references>1?e.blobs.set(r,{...o,references:o.references-1}):(e.blobs.delete(r),e.objectBytes-=o.sizeBytes)}}async function Rh(e,t={}){let n=EN(e),r=kN(t.limits),o=Ou(n),i=SN(n),s=await Dt(i),a=await Dt(o)||s;a||(await fN(n),await pN(n)),a||await _N(n);let c=Gn(),l=await Ta(n,c),u=new Set(a?(await Da(n)).map(S=>S.stageId):[]);a||await bh(n,l.entryIds,c);let d=l.digest,f=Ra(l.entryIds,c),g=async S=>{let{index:b,sizeBytes:E}=await Ti(n);if(Fh(b,S),b.digest!==d){let k=Gn();await Th(n,b.entryIds,k,E),f=Ra(b.entryIds,k),d=b.digest}return{...Ma(b),totalBytes:f.objectBytes+E}},p=async S=>{Ku(S),await g(),await yh(n,f,[S.entryId],S.blobIds,S.stageId),await Aa(n,S.stageId)},m=async(S,b)=>{let E=await g(b);Ph(S,E.entryIds.length);let k=Gn();for(let I of E.entryIds.slice(Math.min(E.cursor,S)+1,Math.max(E.cursor,S)+1))await Ni(n,I,k);return E},y=async()=>{if(await Dt(o)||s)throw new xe(he.RECOVERY_PENDING,"history store requires explicit recovery before accepting writes")},x={rootDir:n,recoveryRequired:a,async readDocumentVersion(){return Ih(n)},async writeDocumentVersion(S){if(await y(),!Number.isInteger(S)||S<0)throw new xe(he.INVALID_SCHEMA,"document version must be a non-negative integer");let b=await Ih(n);S<=b||await Ri(Bh(n),{schemaVersion:1,version:Math.max(b,S)})},async stageAppend(S,b={}){await y();let E=await sN(S,r),k={schemaVersion:Fu,stageId:Uu(),entryId:E.entryId,blobIds:E.blobs.map(I=>I.digest)};try{await aN(n,E),await lN(n,k,b.durableManifest!==!1)}catch(I){try{await p(k)}catch(v){throw new xe(he.INDEX_CORRUPT,"staged history cleanup failed after preparation error",{cause:v})}throw I}return{stageId:k.stageId,entryId:k.entryId,blobIds:k.blobIds}},async discardStage(S){await y(),Mu(S);let b=await Lu(n,S);b&&await p(b)},async previewStagedAppend(S,b){await y();let E=await g(b);return(await gh(n,r,S,E,f)).transition},async previewCursor(S,b){await y();let E=await m(S,b);return Nh(E,E.entryIds,S)},async publishStagedAppend(S,b,E){if(await y(),Oa(S,"entryId"),E){Mu(E);let A=await Lu(n,E);if(!A||A.entryId!==S)throw new xe(he.INVALID_SCHEMA,"history stage does not match the published entry")}let k=await g(b),I=f,v=await gh(n,r,S,k,I),N=await Sh({rootDir:n,previousDigest:v.current.digest,entryIds:v.entryIds,cursor:v.cursor,readback:async()=>Eh(n,v.usage),afterWrite:async()=>{E?await Aa(n,E):await dN(n,S),await yh(n,v.usage,[...I.entries.keys()].filter(A=>!v.usage.entries.has(A)),[...I.blobs.keys()].filter(A=>!v.usage.blobs.has(A)))}});return f=v.usage,d=N.digest,N},async append(S){await y();let b=await g(),E=await x.stageAppend(S);try{return await x.publishStagedAppend(E.entryId,b.digest,E.stageId)}catch(k){throw await x.discardStage(E.stageId),k}},async readEntry(S){return Oa(S,"entryId"),Ni(n,S)},async readBlob(S){Oa(S,"blobId");let b=await $h(n,S),E=await Pi(b,he.NOT_FOUND,"blob");return Mh(E,S,b),E},async readIndex(){let S=Gn(),b=await Ta(n,S);return f=Ra(b.entryIds,S),d=b.digest,b},async readStatus(){let S=await wa(n);return{canUndo:S.undoIds.length>0,canRedo:S.redoIds.length>0,undoDepth:S.undoIds.length,redoDepth:S.redoIds.length,cursor:S.cursor,recoveryRequired:await Dt(o)||await Dt(i)}},async readUndoRedoIds(){let S=await wa(n);return{undoIds:S.undoIds,redoIds:S.redoIds,currentId:S.currentId}},async setCursor(S,b){await y();let E=await m(S,b),k=await Sh({rootDir:n,previousDigest:E.digest,entryIds:E.entryIds,cursor:S,readback:async()=>Eh(n,f)});return d=k.digest,k},async markRecoveryRequired(S){await Dt(o)||await Ri(Ou(n),{schemaVersion:an,reason:IN(S),createdAt:new Date().toISOString()})},async clearRecoveryRequired(){await et.rm(Ou(n),{force:!0})},async readTransactionJournal(){return await Dt(i)?Na(i):null},async writeTransactionJournal(S){await y(),jh(S);try{await Ri(i,S)}catch(E){let k=await Na(i).catch(()=>null);if(k&&Buffer.from(Mt(k)).equals(Buffer.from(Mt(S))))return;throw k?new xe(he.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous",{cause:E}):E}let b=await Na(i);if(!Buffer.from(Mt(b)).equals(Buffer.from(Mt(S))))throw new xe(he.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous")},async clearTransactionJournal(S){let b=await Dt(i)?await Na(i):null;if(b&&b.transactionId!==S)throw new xe(he.INVALID_SCHEMA,"transaction journal changed concurrently");try{await et.rm(i,{force:!0})}catch(E){if(!await Dt(i))return;throw E}if(await Dt(i))throw new xe(he.INDEX_CORRUPT,"transaction journal clear outcome is ambiguous");s=!1},async cleanupTmp(){await y();for(let E of u)await Aa(n,E),u.delete(E);await mN(n);let S=Gn(),b=await Ta(n,S);await bh(n,b.entryIds,S),f=Ra(b.entryIds,S),d=b.digest}};return kh.set(x,()=>wa(n)),x}async function gh(e,t,n,r,o){Oa(n,"entryId");let i=Gn(),s=await Ni(e,n,i),a={entries:new Map(o.entries),blobs:new Map(o.blobs),objectBytes:o.objectBytes},c=r.entryIds.slice(0,r.cursor+1);for(let u of r.entryIds.slice(r.cursor+1))Ch(a,u);_h(a,s.id,i),c.push(s.id);let l=cN(c,t,a);return{current:r,entryIds:l.entryIds,cursor:l.cursor,usage:a,transition:Nh(r,l.entryIds,l.cursor)}}function Nh(e,t,n){return Ph(n,t.length),{expectedIndexDigest:e.digest,publishedIndexDigest:oN(t,n),publishedCursor:n,publishedCurrentId:t[n]??null}}function oN(e,t){return pr(Mt({schemaVersion:an,entryIds:e,cursor:t}))}function Ph(e,t){if(!Number.isInteger(e)||e<-1||e>=t)throw new xe(he.INVALID_SCHEMA,`history cursor is out of bounds: ${e}`)}function iN(e){if(!gn(e))return!1;let t=e.publishedCursor,n=e.publishedCurrentId;return!Ut(e.expectedIndexDigest)||!Ut(e.publishedIndexDigest)||!Number.isInteger(t)||t<-1||n!==null&&!Ut(n)?!1:t===-1?n===null:Ut(n)}async function sN(e,t){if(!e.kind.trim())throw new xe(he.INVALID_JSON,"history entry kind must not be empty");let n=[],r=[];for(let c of e.blobs??[]){if(!c.name.trim())throw new xe(he.INVALID_JSON,"history blob name must not be empty");let l=bN(c.data),u=pr(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:an,kind:e.kind,manifest:e.manifest,blobs:r},i=Mt({...o}),s=pr(i),a=i.byteLength+n.reduce((c,l)=>c+l.sizeBytes,0);if(a>t.maxEntryBytes)throw new xe(he.CAPACITY_EXCEEDED,`history entry exceeds maxEntryBytes (${a} > ${t.maxEntryBytes})`);return{entryBody:o,entryId:s,blobs:n}}async function aN(e,t){let n=Hu(e,t.entryId),r={id:t.entryId,...t.entryBody},o=new Map(t.blobs.map(c=>[c.digest,c])),i=[...Array.from(o.values(),c=>hh(Wu(e,c.digest),c.bytes,{kind:"blob",digest:c.digest},Yu(e,c.digest))),hh(n,Mt(r),{kind:"entry",digest:t.entryId},Gu(e,t.entryId))],a=(await Promise.allSettled(i)).find(c=>c.status==="rejected");if(a)throw a.reason}async function hh(e,t,n,r){let o=await $u(e)??(r?await $u(r):null);if(o!==null){if(Buffer.compare(o,t)!==0)throw new xe(n.kind==="blob"?he.BLOB_CORRUPT:he.ENTRY_CORRUPT,`${n.kind} content mismatch for ${n.digest}`);return}await Lh(e,t)}function cN(e,t,n){let r=[...e],o=r.length-1;for(;;){if(n.objectBytes+Mt(Oh(r,o)).byteLength<=t.maxSessionBytes&&r.length<=t.maxEntries)return{entryIds:r,cursor:o};if(o<=0||r.length===0)throw new xe(he.CAPACITY_EXCEEDED,"history store exceeds capacity limits and the current entry cannot be trimmed");Ch(n,r.shift()),o-=1}}async function lN(e,t,n){Ku(t);let r=zu(e,t.stageId);if(n){await Ri(r,t);return}await xN(r,t)}async function Lu(e,t){let n=await $u(zu(e,t));if(n===null)return null;let r=wi(Buffer.from(n).toString("utf8"),`history stage ${t}`),o=Ku(r);if(o.stageId!==t)throw new xe(he.INVALID_SCHEMA,`history stage id mismatch: ${t}`);return o}async function Da(e){let t=[];for(let n of await La(Xu(e))){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);Mu(r);let o=await Lu(e,r);o&&t.push(o)}return t}async function yh(e,t,n,r,o){if(n.length===0&&r.length===0)return;let i=new Set(t.entries.keys()),s=new Set;for(let a of await Da(e))if(a.stageId!==o){i.add(a.entryId);for(let c of a.blobIds)s.add(c)}for(let a of new Set(n))i.has(a)||await xh(Hu(e,a),Gu(e,a));for(let a of new Set(r))!t.blobs.has(a)&&!s.has(a)&&await xh(Wu(e,a),Yu(e,a));await Vu(Oi(e)),await Vu(Fi(e))}async function Aa(e,t){await Du(zu(e,t)),await uN(e)}async function uN(e){try{await et.rmdir(Xu(e))}catch(t){if(Li(t)||gn(t)&&t.code==="ENOTEMPTY")return;throw t}}async function dN(e,t){for(let n of await Da(e))n.entryId===t&&await Aa(e,n.stageId)}async function Du(e){if(await et.rm(e,{force:!0}),await Dt(e))throw new xe(he.INDEX_CORRUPT,`unable to remove staged history object: ${e}`)}async function xh(e,t){await Du(e),await Du(t)}function Ku(e){if(!gn(e)||e.schemaVersion!==Fu||typeof e.stageId!="string"||!Ah(e.stageId)||!Ut(e.entryId))throw new xe(he.INVALID_SCHEMA,"history stage schema is invalid");let t=Dh(e.blobIds,"history stage blobIds");return{schemaVersion:Fu,stageId:e.stageId,entryId:e.entryId,blobIds:t}}function Mu(e){if(!Ah(e))throw new xe(he.INVALID_PATH,"history stageId must be a UUID")}function Ah(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 bh(e,t,n=Gn()){let r=new Set(t),o=new Set;for(let l of t){let u=await Ni(e,l,n);for(let d of u.blobs)o.add(d.digest)}for(let l of await Da(e)){r.add(l.entryId);for(let u of l.blobIds)o.add(u)}let i=Oi(e),s=await La(i);for(let l of s){if(!l.endsWith(".json"))continue;let u=vh(l.slice(0,-5));u&&!r.has(u)&&await Fa(rt.join(i,l))}let a=Fi(e),c=await La(a);for(let l of c){let u=vh(l);u&&!o.has(u)&&await Fa(rt.join(a,l))}}async function Ta(e,t=Gn()){let{index:n,sizeBytes:r}=await Ti(e),{totalBytes:o}=await Th(e,n.entryIds,t,r);return{...Ma(n),totalBytes:o}}async function Eh(e,t){let{index:n,sizeBytes:r}=await Ti(e);return{...Ma(n),totalBytes:t.objectBytes+r}}async function Ti(e){let t=Ju(e),n=await Pi(t,he.NOT_FOUND,"index"),r=wi(Buffer.from(n).toString("utf8"),"index");return{index:gN(r),sizeBytes:n.byteLength}}async function wa(e){return Ma((await Ti(e)).index)}function Ma(e){let t=[...e.entryIds],n=t.slice(0,e.cursor+1).reverse(),r=t.slice(e.cursor+1);return{schemaVersion:an,digest:e.digest,entryIds:t,cursor:e.cursor,currentId:t[e.cursor]??null,undoIds:n,redoIds:r}}async function Th(e,t,n,r){let o=0,i=new Set;o+=r??(await Ti(e)).sizeBytes;for(let s of new Set(t)){let a=await Ni(e,s,n);o+=n.entries.get(s).sizeBytes;for(let c of a.blobs)i.has(c.digest)||(i.add(c.digest),o+=n.blobSizes.get(c.digest))}return{totalBytes:o}}async function Ni(e,t,n=Gn()){let r=n.entries.get(t);if(r)return r.entry;let o=await vN(e,t),i=await Pi(o,he.NOT_FOUND,"entry"),s=wi(Buffer.from(i).toString("utf8"),`entry ${t}`),a=hN(s);if(a.id!==t)throw new xe(he.ENTRY_CORRUPT,`entry id mismatch for ${t}`);if(pr(Mt({schemaVersion:a.schemaVersion,kind:a.kind,manifest:a.manifest,blobs:a.blobs}))!==t)throw new xe(he.ENTRY_CORRUPT,`entry hash mismatch for ${t}`);let l=[...new Set(a.blobs.map(d=>d.digest))].filter(d=>!n.blobSizes.has(d)),u=async d=>{let f=await $h(e,d),g=await Pi(f,he.NOT_FOUND,"blob");return Mh(g,d,f),g.byteLength};if(l.length===1)n.blobSizes.set(l[0],await u(l[0]));else if(l.length>1){let d=new Array(l.length),f=[],g=0,p=Array.from({length:Math.min(4,l.length)},async()=>{for(;g<l.length&&f.length===0;){let x=g++;try{d[x]=await u(l[x])}catch(S){f.push({index:x,error:S})}}}),m=await Promise.allSettled(p),y=f.sort((x,S)=>x.index-S.index)[0];if(y)throw y.error;for(let x of m)if(x.status==="rejected")throw x.reason;for(let x=0;x<l.length;x++)n.blobSizes.set(l[x],d[x])}return n.entries.set(t,{entry:a,sizeBytes:i.byteLength}),a}async function wh(e,t,n){await Ri(Ju(e),Oh(t,n))}function Oh(e,t){return{schemaVersion:an,digest:pr(Mt({schemaVersion:an,entryIds:e,cursor:t})),entryIds:e,cursor:t}}function Fh(e,t){if(t!==void 0&&e.digest!==t)throw new xe(he.INVALID_SCHEMA,`history index changed concurrently (expected ${t}, current ${e.digest})`)}async function Sh(e){Fh(await wa(e.rootDir),e.previousDigest);let t=pr(Mt({schemaVersion:an,entryIds:e.entryIds,cursor:e.cursor}));try{await wh(e.rootDir,e.entryIds,e.cursor),await e.afterWrite?.();let n=await e.readback();if(n.digest!==t)throw new xe(he.INDEX_CORRUPT,"history index readback did not match the published transition");return n}catch(n){let r=await Ta(e.rootDir).catch(()=>null);if(r?.digest===t)return r;throw r?.digest===e.previousDigest?n:new xe(he.INDEX_CORRUPT,"history index publish outcome is ambiguous",{cause:n})}}async function fN(e){await et.mkdir(e,{recursive:!0}),await et.mkdir(Oi(e),{recursive:!0}),await et.mkdir(Fi(e),{recursive:!0}),await et.mkdir(Ai(e),{recursive:!0})}async function pN(e){await et.rm(Ai(e),{recursive:!0,force:!0}),await et.mkdir(Ai(e),{recursive:!0})}async function mN(e){let t=Ai(e);await et.mkdir(t,{recursive:!0});for(let n of await La(t))n!=="stages"&&await et.rm(rt.join(t,n),{recursive:!0,force:!0})}function gN(e){if(!gn(e))throw new xe(he.INDEX_CORRUPT,"index.json must be an object");if(e.schemaVersion!==an)throw new xe(he.INVALID_SCHEMA,`unsupported index schemaVersion: ${String(e.schemaVersion)}`);let t=Dh(e.entryIds,"index.entryIds"),n=e.cursor;if(!Number.isInteger(n)||n<-1||n>=t.length)throw new xe(he.INDEX_CORRUPT,"index cursor is out of bounds");let r=n,o=e.digest;if(!Ut(o))throw new xe(he.INDEX_CORRUPT,"index digest is invalid");let i=pr(Mt({schemaVersion:an,entryIds:t,cursor:r}));if(o!==i)throw new xe(he.INDEX_CORRUPT,"index digest mismatch");return{schemaVersion:an,digest:o,entryIds:t,cursor:r}}function hN(e){if(!gn(e))throw new xe(he.ENTRY_CORRUPT,"entry must be an object");if(e.schemaVersion!==an)throw new xe(he.INVALID_SCHEMA,`unsupported entry schemaVersion: ${String(e.schemaVersion)}`);let t=e.id;if(!Ut(t))throw new xe(he.ENTRY_CORRUPT,"entry id is invalid");let n=e.kind;if(typeof n!="string"||n.trim().length===0)throw new xe(he.ENTRY_CORRUPT,"entry kind is invalid");let r=ju(e.manifest,"entry.manifest"),o=yN(e.blobs);return{id:t,schemaVersion:an,kind:n,manifest:r,blobs:o}}function yN(e){if(!Array.isArray(e))throw new xe(he.ENTRY_CORRUPT,"entry blobs must be an array");return e.map((t,n)=>{if(!gn(t))throw new xe(he.ENTRY_CORRUPT,`entry blob ref ${n} must be an object`);let r=t.name;if(typeof r!="string"||r.trim().length===0)throw new xe(he.ENTRY_CORRUPT,`entry blob ref ${n} name is invalid`);let o=t.digest;if(!Ut(o))throw new xe(he.ENTRY_CORRUPT,`entry blob ref ${n} digest is invalid`);let i=t.sizeBytes;if(!Number.isInteger(i)||i<0)throw new xe(he.ENTRY_CORRUPT,`entry blob ref ${n} sizeBytes is invalid`);return{name:r,digest:o,sizeBytes:i}})}async function Ri(e,t){await Lh(e,Mt(t))}async function xN(e,t){let n=rt.dirname(e),r=rt.basename(e),o=rt.join(n,`.${r}.${process.pid}.${Uu()}.tmp`);await et.mkdir(n,{recursive:!0});try{await et.writeFile(o,Mt(t),{flag:"wx"}),await et.rename(o,e)}finally{await Fa(o)}}async function Lh(e,t){let n=rt.dirname(e),r=rt.basename(e),o=rt.join(n,`.${r}.${process.pid}.${Uu()}.tmp`);await et.mkdir(n,{recursive:!0});try{let i=await et.open(o,"wx");try{await i.writeFile(t),await i.sync()}finally{await i.close()}await et.rename(o,e),await Vu(n)}finally{await Fa(o)}}function Mt(e){return Buffer.from(JSON.stringify(Bu(e)),"utf8")}function Bu(e){if(Array.isArray(e))return e.map(t=>Bu(t));if(gn(e)){let t={};for(let n of Object.keys(e).sort())t[n]=Bu(e[n]);return t}return e}function wi(e,t){try{return JSON.parse(e)}catch(n){throw new xe(he.INVALID_JSON,`${t} is not valid JSON`,{cause:n})}}function ju(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=>ju(n,t));if(gn(e)){let n={};for(let[r,o]of Object.entries(e))n[r]=ju(o,t);return n}break}throw new xe(he.INVALID_JSON,`${t} must be JSON-serializable`)}function Dh(e,t){if(!Array.isArray(e))throw new xe(he.INDEX_CORRUPT,`${t} must be an array`);return e.map((n,r)=>{if(!Ut(n))throw new xe(he.INDEX_CORRUPT,`${t}[${r}] is invalid`);return n})}function Oa(e,t){if(!Ut(e))throw new xe(he.INVALID_PATH,`${t} must be a sha256 digest`)}function Ut(e){return typeof e=="string"&&/^sha256:[a-f0-9]{64}$/u.test(e)}function pr(e){return`sha256:${qR("sha256").update(e).digest("hex")}`}function bN(e){return typeof e=="string"?Buffer.from(e,"utf8"):Buffer.from(e)}async function Pi(e,t,n){try{return await et.readFile(e)}catch(r){throw new xe(t,`${n} not found: ${e}`,{cause:r})}}async function $u(e){try{return await et.readFile(e)}catch(t){if(Li(t))return null;throw t}}function Mh(e,t,n){if(pr(e)!==t)throw new xe(he.BLOB_CORRUPT,`blob hash mismatch for ${n}`)}async function Dt(e){try{return await et.access(e),!0}catch(t){if(Li(t))return!1;throw t}}async function Fa(e){try{await et.rm(e,{force:!0,recursive:!0})}catch{}}async function Vu(e){try{let t=await et.open(e,"r");try{await t.sync()}finally{await t.close()}}catch{}}async function La(e){try{return await et.readdir(e)}catch(t){if(Li(t))return[];throw t}}function EN(e){if(typeof e!="string"||e.trim().length===0)throw new xe(he.INVALID_ROOT,"history store rootDir must be a non-empty string");return rt.resolve(e)}function Ju(e){return rt.join(e,eN)}function Ou(e){return rt.join(e,tN)}function SN(e){return rt.join(e,nN)}function Bh(e){return rt.join(e,rN)}async function Ih(e){try{let t=await et.readFile(Bh(e),"utf8"),n=wi(t,"document version");if(!gn(n)||n.schemaVersion!==1||!Number.isInteger(n.version)||n.version<0)throw new xe(he.INVALID_SCHEMA,"document version schema is invalid");return n.version}catch(t){if(Li(t))return 0;throw t}}async function Na(e){let t=await Pi(e,he.RECOVERY_PENDING,"transaction journal"),n=wi(Buffer.from(t).toString("utf8"),"transaction journal");return jh(n),n}function jh(e){if(!gn(e)||e.schemaVersion!==QR||typeof e.transactionId!="string"||e.transactionId.length===0||typeof e.operationId!="string"||e.operationId.length===0||!["prepared","files-written","history-published"].includes(e.phase)||!iN(e.historyTransition)||!Array.isArray(e.files))throw new xe(he.INVALID_SCHEMA,"transaction journal schema is invalid");for(let t of e.files)if(!gn(t)||typeof t.path!="string"||t.path.length===0||t.preDigest!==null&&!Ut(t.preDigest)||t.postDigest!==null&&!Ut(t.postDigest))throw new xe(he.INVALID_SCHEMA,"transaction journal file digest is invalid")}function IN(e){return e.replace(/[\r\n]+/g," ").slice(0,512)}function Oi(e){return rt.join(e,"entries")}function Fi(e){return rt.join(e,"blobs")}function Ai(e){return rt.join(e,"tmp")}function Xu(e){return rt.join(Ai(e),"stages")}function zu(e,t){return rt.join(Xu(e),`${t}.json`)}function Hu(e,t){return rt.join(Oi(e),`${Uh(t)}.json`)}function Wu(e,t){return rt.join(Fi(e),Uh(t))}function Gu(e,t){return rt.join(Oi(e),`${t}.json`)}function Yu(e,t){return rt.join(Fi(e),t)}async function vN(e,t){return Vh(Hu(e,t),Gu(e,t))}async function $h(e,t){return Vh(Wu(e,t),Yu(e,t))}async function Vh(e,t){return await Dt(e)?e:await Dt(t)?t:e}function Uh(e){return e.slice(7)}function vh(e){let t=e.startsWith("sha256:")?e:`sha256:${e}`;return Ut(t)?t:null}function gn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Li(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function kN(e){return{maxEntries:e?.maxEntries??Pa.maxEntries,maxSessionBytes:e?.maxSessionBytes??Pa.maxSessionBytes,maxEntryBytes:e?.maxEntryBytes??Pa.maxEntryBytes}}async function _N(e){let t=Ju(e);await Dt(t)||await wh(e,[],-1)}var RN={affectedCompositions:[]};function Hh(e){let t=null,n=new WeakMap;async function r(){return t??=NN(e),t}async function o(i){if(!i)return null;let s=Zu(i);return s?PN(e,s):i}return{async prepareAppend(i){let s=await Ao(e),a=await e.stageAppend(Xh(i),{durableManifest:!1}),c;try{c=await e.previewStagedAppend(a.entryId,s.digest)}catch(u){throw await e.discardStage(a.stageId),u}let l={kind:"append",entry:i,historyTransition:c};return n.set(l,{expectedDigest:s.digest,stageId:a.stageId,entryId:a.entryId}),l},async prepareUndo(){let i=await r(),s=await o(i.undo.at(-1));if(!s?.historyId)return null;let a=await Ao(e),c=a.entryIds.indexOf(s.historyId);if(c<0)throw new Error("undo entry is missing from index");if(c!==a.cursor)throw new Error("undo state changed before prepare");let l=c-1,u=await e.previewCursor(l,a.digest),d={kind:"undo",entry:s,historyTransition:u};return n.set(d,{expectedDigest:a.digest,cursor:l}),d},async prepareRedo(){let i=await r(),s=await o(i.redo.at(-1));if(!s?.historyId)return null;let a=await Ao(e),c=a.entryIds.indexOf(s.historyId);if(c<0)throw new Error("redo entry is missing from index");if(c!==a.cursor+1)throw new Error("redo state changed before prepare");let l=c,u=await e.previewCursor(l,a.digest),d={kind:"redo",entry:s,historyTransition:u};return n.set(d,{expectedDigest:a.digest,cursor:l}),d},async publishPrepared(i){let s=n.get(i);if(!s)throw new Error("history mutation was not prepared");let a=await r();if(i.kind==="append"){if(!s.entryId)throw new Error("staged entry id is missing");let c=await e.publishStagedAppend(s.entryId,s.expectedDigest,s.stageId);Kh(c,i.historyTransition),i.entry.historyId=s.entryId,Object.assign(a,To(c))}else{if(s.cursor===void 0)throw new Error("prepared cursor is missing");let c=i.kind==="undo"?a.undo:a.redo;if(Zu(c.at(-1))!==Zu(i.entry))throw new Error("history state changed before publish");let l=await e.setCursor(s.cursor,s.expectedDigest);Kh(l,i.historyTransition),Object.assign(a,To(l))}n.delete(i)},async discardPrepared(i){let s=n.get(i);if(!s)return;let a=i.historyTransition;if(a){let c=await Ao(e);if(c.digest===a.publishedIndexDigest&&c.cursor===a.publishedCursor&&c.currentId===a.publishedCurrentId)throw new Error("cannot discard a history mutation whose index was published")}s.stageId&&await e.discardStage(s.stageId),n.delete(i)},async peekUndo(){return o((await r()).undo.at(-1))},async pushUndo(i){let s=await r(),a=i;if(a.historyId){let u=s.entryIds.indexOf(a.historyId);if(u>=0)try{let d=await e.setCursor(u);Object.assign(s,To(d));return}catch(d){throw s.redo.push(i),d}}let c=await e.append(Xh(i)),l=c.currentId;if(!l)throw new Error("history store did not publish an entry");i.historyId=l,Object.assign(s,To(c))},async popUndo(){let i=await r(),s=await o(i.undo.at(-1));return i.undo.pop(),s},async peekRedo(){return o((await r()).redo.at(-1))},async pushRedo(i){let s=await r(),a=i;if(!a.historyId)throw s.undo.push(i),new Error("cannot move an unpersisted history entry to redo");let c=s.entryIds.indexOf(a.historyId);if(c<0)throw s.undo.push(i),new Error("history entry is missing from the durable index");try{let l=await e.setCursor(c-1);Object.assign(s,To(l))}catch(l){throw s.undo.push(i),l}},async popRedo(){let i=await r(),s=await o(i.redo.at(-1));return i.redo.pop(),s},async clearRedo(){(await r()).redo.length=0},async getStatus(){let i=await e.readStatus();return{canUndo:i.canUndo,canRedo:i.canRedo,undoDepth:i.undoDepth,redoDepth:i.redoDepth,recoveryRequired:i.recoveryRequired}},async markRecoveryRequired(i){await e.markRecoveryRequired(i)}}}function Kh(e,t){if(!t)throw new Error("durable history transition is missing");if(e.digest!==t.publishedIndexDigest||e.cursor!==t.publishedCursor||e.currentId!==t.publishedCurrentId)throw new Error("durable history published an unexpected index state")}function Zu(e){return typeof e=="string"?e:e?.historyId}async function NN(e){let t=await Ao(e);return To(t)}function To(e){return{undo:[...e.undoIds].reverse(),redo:[...e.redoIds].reverse(),entryIds:[...e.entryIds],cursor:e.cursor}}async function PN(e,t){let n=await e.readEntry(t),r=AN(n),o=r.provenance??RN;return{historyId:t,...o.initiatingComposition?{composition:o.initiatingComposition}:{},operationId:r.operationId,kind:r.kind,target:r.target,provenance:o,...r.selectionRef?{selectionRef:r.selectionRef}:{},...r.output?{output:r.output}:{},preSnapshots:await Jh(e,n,r.preSnapshots),postSnapshots:await Jh(e,n,r.postSnapshots)}}async function Jh(e,t,n){let r=new Map(t.blobs.map(o=>[o.name,o.digest]));return Promise.all(n.map(async o=>{let i=o.exists&&o.blobName?Buffer.from(await e.readBlob(ON(r,o.blobName))).toString("utf8"):"";return{file:o.file,content:i,version:o.version,exists:o.exists,...o.sha256?{sha256:o.sha256}:{}}}))}function Xh(e){let t=[],n=(i,s)=>i.map((a,c)=>{let l={file:a.file,exists:a.exists!==!1,version:a.version,...a.sha256?{sha256:a.sha256}:{}};if(l.exists){let u=`${s}-${c}`;l.blobName=u,t.push({name:u,data:a.content})}return l}),r=TN(e),o={operationId:e.operationId,kind:e.kind,target:e.target,...r?{provenance:r}:{},...e.selectionRef?{selectionRef:e.selectionRef}:{},...e.output?{output:e.output}:{},preSnapshots:n(e.preSnapshots,"pre"),postSnapshots:n(e.postSnapshots,"post")};return{kind:"site-edit-operation",manifest:JSON.parse(JSON.stringify(o)),blobs:t}}function AN(e){if(!Gh(e.manifest))throw new Error("durable history manifest is not an object");let t=e.manifest,n=new Set(["operationId","kind","target","selectionRef","output","provenance","preSnapshots","postSnapshots"]);if(Object.keys(t).some(r=>!n.has(r)))throw new Error("durable history manifest contains unknown fields");if(typeof t.operationId!="string"||t.operationId.length===0||typeof t.kind!="string"||t.kind.length===0||!Array.isArray(t.preSnapshots)||!Array.isArray(t.postSnapshots))throw new Error("durable history manifest has an invalid shape");return{operationId:t.operationId,kind:t.kind,target:t.target,...t.selectionRef!==void 0?{selectionRef:t.selectionRef}:{},...t.output!==void 0?{output:t.output}:{},...t.provenance!==void 0?{provenance:Wh(t.provenance)}:{},preSnapshots:zh(t.preSnapshots,"preSnapshots"),postSnapshots:zh(t.postSnapshots,"postSnapshots")}}function TN(e){if(e.provenance!==void 0)return Wh(e.provenance);if(e.composition)return{initiatingComposition:e.composition,affectedCompositions:[]}}function Wh(e){let t=CN.safeParse(e);if(!t.success)throw new Error("durable history provenance is invalid");return{...t.data.initiatingComposition?{initiatingComposition:t.data.initiatingComposition}:{},affectedCompositions:t.data.affectedCompositions.map(n=>({routeId:n.routeId,...n.effectiveTemplateId?{effectiveTemplateId:n.effectiveTemplateId}:{}}))}}function zh(e,t){return e.map((n,r)=>{if(!Gh(n))throw new Error(`durable history ${t}[${r}] is invalid`);if(typeof n.file!="string"||n.file.length===0||!Number.isInteger(n.version)||n.exists!==void 0&&typeof n.exists!="boolean"||n.sha256!==void 0&&!wN(n.sha256)||n.blobName!==void 0&&typeof n.blobName!="string")throw new Error(`durable history ${t}[${r}] is invalid`);return{file:n.file,exists:n.exists!==!1,version:n.version,...n.sha256?{sha256:n.sha256}:{},...n.blobName?{blobName:n.blobName}:{}}})}function wN(e){return/^sha256:[0-9a-f]{64}$/.test(e)}function ON(e,t){let n=e.get(t);if(!n)throw new Error(`durable history blob is missing: ${t}`);return n}function Gh(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{GeneratedSiteCapabilitiesSchema as FN}from"@vcp-dev/contracts";var Yh={schema_version:1,policy_version:"starter-capabilities-v1",source:{starter_package_path:"templates/next-starter/package.json",components_catalog_path:"templates/next-starter/components.catalog.json",package_name:"vcp-next-starter",package_version:"0.0.0"},runtime_dependencies:[{name:"@gsap/react",version:"2.1.2"},{name:"@hookform/resolvers",version:"3.10.0"},{name:"@opennextjs/cloudflare",version:"1.19.11"},{name:"@radix-ui/react-accordion",version:"1.2.12"},{name:"@radix-ui/react-alert-dialog",version:"1.1.15"},{name:"@radix-ui/react-aspect-ratio",version:"1.1.8"},{name:"@radix-ui/react-avatar",version:"1.1.11"},{name:"@radix-ui/react-checkbox",version:"1.3.3"},{name:"@radix-ui/react-collapsible",version:"1.1.12"},{name:"@radix-ui/react-context-menu",version:"2.2.16"},{name:"@radix-ui/react-dialog",version:"1.1.15"},{name:"@radix-ui/react-dropdown-menu",version:"2.1.16"},{name:"@radix-ui/react-hover-card",version:"1.1.15"},{name:"@radix-ui/react-label",version:"2.1.8"},{name:"@radix-ui/react-menubar",version:"1.1.16"},{name:"@radix-ui/react-navigation-menu",version:"1.2.14"},{name:"@radix-ui/react-popover",version:"1.1.15"},{name:"@radix-ui/react-progress",version:"1.1.8"},{name:"@radix-ui/react-radio-group",version:"1.3.8"},{name:"@radix-ui/react-scroll-area",version:"1.2.10"},{name:"@radix-ui/react-select",version:"2.2.6"},{name:"@radix-ui/react-separator",version:"1.1.8"},{name:"@radix-ui/react-slider",version:"1.3.6"},{name:"@radix-ui/react-slot",version:"1.2.3"},{name:"@radix-ui/react-switch",version:"1.2.6"},{name:"@radix-ui/react-tabs",version:"1.1.13"},{name:"@radix-ui/react-toggle",version:"1.1.10"},{name:"@radix-ui/react-toggle-group",version:"1.1.11"},{name:"@radix-ui/react-tooltip",version:"1.2.8"},{name:"class-variance-authority",version:"0.7.1"},{name:"clsx",version:"2.1.1"},{name:"cmdk",version:"1.1.1"},{name:"date-fns",version:"4.3.0"},{name:"embla-carousel-react",version:"8.6.0"},{name:"gsap",version:"3.15.0"},{name:"i18next",version:"26.3.0"},{name:"input-otp",version:"1.4.2"},{name:"lucide-react",version:"0.525.0"},{name:"motion",version:"12.40.0"},{name:"next",version:"16.3.4"},{name:"react",version:"19.2.6"},{name:"react-day-picker",version:"9.14.0"},{name:"react-dom",version:"19.2.6"},{name:"react-hook-form",version:"7.76.1"},{name:"react-i18next",version:"17.0.8"},{name:"recharts",version:"2.15.4"},{name:"sonner",version:"2.0.7"},{name:"tailwind-merge",version:"3.6.0"},{name:"vaul",version:"1.1.2"},{name:"zod",version:"3.25.76"}],catalog_dependencies:["@hookform/resolvers","@radix-ui/react-accordion","@radix-ui/react-alert-dialog","@radix-ui/react-aspect-ratio","@radix-ui/react-avatar","@radix-ui/react-checkbox","@radix-ui/react-collapsible","@radix-ui/react-context-menu","@radix-ui/react-dialog","@radix-ui/react-dropdown-menu","@radix-ui/react-hover-card","@radix-ui/react-label","@radix-ui/react-menubar","@radix-ui/react-navigation-menu","@radix-ui/react-popover","@radix-ui/react-progress","@radix-ui/react-radio-group","@radix-ui/react-scroll-area","@radix-ui/react-select","@radix-ui/react-separator","@radix-ui/react-slider","@radix-ui/react-slot","@radix-ui/react-switch","@radix-ui/react-tabs","@radix-ui/react-toggle","@radix-ui/react-toggle-group","@radix-ui/react-tooltip","class-variance-authority","clsx","cmdk","date-fns","embla-carousel-react","input-otp","lucide-react","motion","react-day-picker","react-hook-form","recharts","sonner","tailwind-merge","vaul","zod"],public_paths:["components.json","components/site/generated/*","components/ui/*","components/ui/accordion.tsx","components/ui/alert-dialog.tsx","components/ui/alert.tsx","components/ui/aspect-ratio.tsx","components/ui/avatar.tsx","components/ui/badge.tsx","components/ui/border-beam.tsx","components/ui/breadcrumb.tsx","components/ui/button-group.tsx","components/ui/button.tsx","components/ui/calendar.tsx","components/ui/callout.tsx","components/ui/card.tsx","components/ui/carousel.tsx","components/ui/chart.tsx","components/ui/checkbox.tsx","components/ui/code-block.tsx","components/ui/collapsible.tsx","components/ui/command.tsx","components/ui/composite-carousel.tsx","components/ui/context-menu.tsx","components/ui/dialog.tsx","components/ui/drawer.tsx","components/ui/dropdown-menu.tsx","components/ui/empty.tsx","components/ui/field.tsx","components/ui/form.tsx","components/ui/hover-card.tsx","components/ui/input-group.tsx","components/ui/input-otp.tsx","components/ui/input.tsx","components/ui/item.tsx","components/ui/kbd.tsx","components/ui/label.tsx","components/ui/magic-card.tsx","components/ui/marquee.tsx","components/ui/menubar.tsx","components/ui/multi-step-form.tsx","components/ui/navigation-menu.tsx","components/ui/number-ticker.tsx","components/ui/pagination.tsx","components/ui/popover.tsx","components/ui/progress.tsx","components/ui/radio-group.tsx","components/ui/safe-image.tsx","components/ui/scroll-area.tsx","components/ui/scroll-choreographer.tsx","components/ui/select.tsx","components/ui/separator.tsx","components/ui/sheet.tsx","components/ui/site-footer-shell.tsx","components/ui/site-header.tsx","components/ui/skeleton.tsx","components/ui/slider.tsx","components/ui/sonner.tsx","components/ui/spinner.tsx","components/ui/stepper.tsx","components/ui/switch.tsx","components/ui/table.tsx","components/ui/tabs.tsx","components/ui/textarea.tsx","components/ui/toggle-group.tsx","components/ui/toggle.tsx","components/ui/tooltip.tsx","components/ui/video-frame.tsx","lib/cms","lib/utils.ts#cn"],generated_sections_path:"components/site/generated/*",ui_baseline:{kit:"shadcn-style",components_config:"components.json",class_name_helper:"lib/utils.ts#cn"},host_contract_digest:"03208e0d83ae2140368f162b6051dd45d4d6ac97f3652958b3ba24a6273d6eca"};function qu(){let e=FN.safeParse(Yh);return e.success?e.data:null}import{randomBytes as LN}from"node:crypto";import Ba from"node:path";import{parse as ry}from"@babel/parser";import DN from"@babel/traverse";import*as oy from"@babel/types";import{COMPONENT_I18N_FILE_SUFFIX as ed,PageResourceArtifactSchema as MN,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as BN,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as jN,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as $N,parseComponentI18nResourcesJson as VN}from"@vcp-dev/contracts";var td="{{$INSTANCE}}",UN=/\{\{\$PAGE_ROUTE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,KN=/\{\{\$PAGE_TITLE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,nd="components/site/generated",JN=/\.(?:tsx?|json)$/,XN=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,zN=["react","react/","next","next/","lucide-react","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],HN=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),Qu=DN,WN=typeof Qu=="function"?Qu:Qu.default;async function rd(e){let t=MN.safeParse(e.artifact);if(!t.success)return tt("Page resource artifact failed contract validation.");let n=t.data,r=e.randomHex??(()=>LN(4).toString("hex")),o=Math.max(1,Math.min(e.maxAttempts??5,5)),i=rP(r());if(!i)return tt("Random instance suffix must be 8 lowercase hex chars.");let s=`${oP(n.resource_id)}-${i}`,a=new Map,c=new Map,l=[];for(let b of n.pages){let E=b.final_route.slice(1);a.set(b.template_page_id,b.final_route),c.set(b.template_page_id,b.title),l.push({template_page_id:b.template_page_id,title:b.title,final_route:b.final_route,route_file_path:`app/${E}/page.tsx`})}let u=[],d=new Set,f=new Set,g=new Map,p=new Map,m=[],y=new Set(n.pages.flatMap(b=>b.components.map(E=>E.component_id)));for(let b of n.components){if(!y.has(b.component_id))continue;let E=Zh({materialization:b.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c});if(!E.ok)return E;for(let k of E.files){let I=Qh(k,d,u);if(I)return I}f.add(E.entry),p.set(E.entry,E.entryExport),g.set(b.component_id,E.entry)}for(let[b,E]of n.pages.entries()){let k=l[b],I=Zh({materialization:E.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c,pageEntryTarget:k.route_file_path,pageTitle:k.title});if(!I.ok)return I;for(let v of I.files){let N=Qh(v,d,u);if(N)return N}f.add(I.entry),p.set(I.entry,I.entryExport),m.push({entry:I.entry,declaredComponentIds:new Set(E.components.map(v=>v.component_id))})}let x=YN(u,f,s,g,m,p);if(!x.ok)return x;for(let b of u)if(await e.exists(b.file))return!b.file.startsWith("app/")&&o>1?rd({...e,randomHex:r,maxAttempts:o-1}):{ok:!1,code:"MATERIALIZATION_CONFLICT",message:`Page resource create-only target already exists: ${b.file}`,path:b.file};let S=ZN(u);return S||(u.sort((b,E)=>b.file.localeCompare(E.file)),{ok:!0,packageInstanceId:s,pages:l,files:u})}function Zh(e){let t=e.materialization.entry.pathTemplate,n=[];for(let o of e.materialization.files){let i=o.pathTemplate===t,s=i&&e.pageEntryTarget?e.pageEntryTarget:qh(o.pathTemplate,e.packageInstanceId);if(!s)return tt("Materialization path cannot be mapped into the package namespace.",o.pathTemplate);let a=GN(o.content,e.packageInstanceId,e.routeByPage,e.titleByPage);if(!a.ok)return a;let c=i&&e.pageTitle!==void 0?QN(a.data,e.pageTitle,s):a;if(!c.ok)return c;n.push({operation:"create-only",file:s,content:c.data})}let r=e.pageEntryTarget??qh(t,e.packageInstanceId);return!r||!n.some(o=>o.file===r)?tt("Materialization entry must match one controlled source file.",t):{ok:!0,files:n,entry:r,entryExport:e.materialization.entry.export}}function GN(e,t,n,r){let o,i=e.replace(UN,(c,l)=>{let u=n.get(l);return u||(o=l,c)});if(o)return tt(`Page route placeholder references unknown template page: ${o}`);let s=i.replace(KN,(c,l)=>{let u=r.get(l);return u?JSON.stringify(u):(o=l,c)});if(o)return tt(`Page title placeholder references unknown template page: ${o}`);let a=s.replaceAll(td,t);return a.includes("{{$PAGE_ROUTE:")||a.includes("{{$PAGE_TITLE:")||a.includes("{{$INSTANCE}}")?tt("Materialization contains an unresolved placeholder."):{ok:!0,data:a}}function qh(e,t){let n=`${nd}/${t}`;if(e.split(td).length>2)return null;let o=e.replace(td,t),i=`${nd}/${t}/`,s=o.startsWith(i)?o:`${n}/${o}`,a=Ba.posix.normalize(s);return a!==s||!a.startsWith(`${n}/`)||!JN.test(a)||XN.test(a)?null:a}function Qh(e,t,n){return t.has(e.file)?tt(`Page resource materializations resolve duplicate target: ${e.file}`,e.file):(t.add(e.file),n.push(e),null)}function YN(e,t,n,r,o,i){let s=new Set(e.map(g=>g.file)),a=`${nd}/${n}`,c=new Map(e.map(g=>[g.file,new Set])),l=new Map;for(let g of e){if(g.file.endsWith(".json")){try{JSON.parse(g.content)}catch{return tt("Materialization JSON file must contain valid JSON.",g.file)}if(g.file.endsWith(ed)&&!VN(g.content).success)return tt("Materialization component i18n resources are invalid.",g.file);continue}try{let p=ry(g.content,{sourceType:"module",plugins:["jsx","typescript"]});l.set(g.file,p);for(let y of p.program.body)if((y.type==="ImportDeclaration"||y.type==="ExportAllDeclaration"||y.type==="ExportNamedDeclaration"&&y.source)&&y.source){let x=y.source.value,S=tP(g.file,x,s,a);if(!S.allowed)return tt(`Materialization import is outside the controlled package: ${x}`,g.file);S.internalPath&&c.get(g.file).add(S.internalPath)}let m;if(WN(p,{Identifier(y){y.isReferencedIdentifier()&&HN.has(y.node.name)&&(m??=y.node.name,y.stop())},JSXOpeningElement(y){y.node.name.type==="JSXIdentifier"&&y.node.name.name.toLowerCase()==="style"&&(m??="style element",y.stop())}}),m)return tt(`Materialization source uses forbidden capability: ${m}`,g.file)}catch{return tt("Materialization source must parse as TS/TSX.",g.file)}}if([...t].some(g=>!s.has(g)))return tt("Materialization entry is outside the controlled package.");for(let g of t)if(g.endsWith(".json"))return tt("Materialization JSON files cannot be package entries.");for(let[g,p]of i){let m=l.get(g);if(!m||!qN(m,p))return tt("Materialization entry does not declare its contracted export.",g)}let u=new Map([...r].map(([g,p])=>[p,g]));for(let g of o){let p=ny(g.entry,c);for(let m of g.declaredComponentIds){let y=r.get(m);if(!y||!p.has(y))return tt(`Page entry does not reach declared component: ${m}`,g.entry)}for(let m of p){let y=u.get(m);if(y&&!g.declaredComponentIds.has(y))return tt(`Page entry imports undeclared component: ${y}`,g.entry)}}let d=new Set;for(let g of t)for(let p of ny(g,c))d.add(p);if(d.size!==e.length)return tt("Every materialization file must be reachable from a package entry.");let f=nP(e,l,c);return f||{ok:!0}}function ZN(e){if(e.length>BN)return tt("Page resource exceeds the aggregate source file limit.");let t=0;for(let n of e){let r=Buffer.byteLength(n.content,"utf8");if(r>jN)return tt("Page resource file exceeds the content byte limit.",n.file);t+=r}return t>$N?tt("Page resource exceeds the aggregate content byte limit."):null}function qN(e,t){for(let n of e.program.body){if(t.kind==="default"){if(n.type==="ExportDefaultDeclaration")return!0;continue}if(n.type==="ExportNamedDeclaration"&&(n.declaration?.type==="VariableDeclaration"&&n.declaration.declarations.some(r=>r.id.type==="Identifier"&&r.id.name===t.name)||(n.declaration?.type==="FunctionDeclaration"||n.declaration?.type==="ClassDeclaration")&&n.declaration.id?.name===t.name||n.specifiers.some(r=>r.exported.type==="Identifier"&&r.exported.name===t.name)))return!0}return!1}function QN(e,t,n){let r;try{r=ry(e,{sourceType:"module",sourceFilename:n,plugins:["jsx","typescript"]})}catch{return tt("Page materialization PAGE_SEO must parse as TS/TSX.",n)}for(let o of r.program.body){let i=o.type==="VariableDeclaration"?o:o.type==="ExportNamedDeclaration"&&o.declaration?.type==="VariableDeclaration"?o.declaration:null;if(i)for(let s of i.declarations){if(s.id.type!=="Identifier"||s.id.name!=="PAGE_SEO")continue;let a=ey(s.init);if(a?.type!=="ObjectExpression")return{ok:!0,data:e};let c=a.properties.find(u=>u.type==="ObjectProperty"&&!u.computed&&eP(u.key));if(!c||c.type!=="ObjectProperty")return{ok:!0,data:e};let l=ey(c.value);return l?l.type!=="StringLiteral"&&l.type!=="TemplateLiteral"||l.type==="TemplateLiteral"&&l.expressions.length>0||typeof l.start!="number"||typeof l.end!="number"?{ok:!0,data:e}:{ok:!0,data:e.slice(0,l.start)+JSON.stringify(t)+e.slice(l.end)}:{ok:!0,data:e}}}return{ok:!0,data:e}}function ey(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression"||t?.type==="TSNonNullExpression";)t=t.expression;return t&&oy.isExpression(t)?t:null}function eP(e){return e.type==="Identifier"&&e.name==="title"||e.type==="StringLiteral"&&e.value==="title"}function tP(e,t,n,r){if(t.startsWith(`@/${r}/`)){let s=t.slice(2),a=ty(s,n);return a?{allowed:!0,internalPath:a}:{allowed:!1}}if(!t.startsWith("."))return{allowed:zN.some(s=>s.endsWith("/")?t.startsWith(s):t===s)};if(t.includes("\\")||t.includes("\0"))return{allowed:!1};let o=Ba.posix.normalize(Ba.posix.join(Ba.posix.dirname(e),t)),i=ty(o,n);return i&&(i.startsWith(`${r}/`)||i.startsWith("app/"))?{allowed:!0,internalPath:i}:{allowed:!1}}function ty(e,t){return[e,`${e}.ts`,`${e}.tsx`,`${e}.json`,`${e}/index.ts`,`${e}/index.tsx`,`${e}/index.json`].find(n=>t.has(n))}function nP(e,t,n){let r=new Set(e.map(o=>o.file));for(let o of e){if(!o.file.endsWith(ed))continue;let i=o.file.slice(0,-ed.length),s=[`${i}.tsx`,`${i}.ts`].find(u=>r.has(u));if(!s)return tt("Component i18n resources require a same-name TS/TSX companion.",o.file);let c=t.get(s)?.program.directives.some(u=>u.value.value==="use client"),l=[...n].filter(([,u])=>u.has(o.file));if(!c||l.length!==1||l[0]?.[0]!==s)return tt("Component i18n resources must have exactly one same-name Client Component static importer.",s)}return null}function ny(e,t){let n=new Set,r=[e];for(;r.length>0;){let o=r.pop();if(!n.has(o)){n.add(o);for(let i of t.get(o)??[])r.push(i)}}return n}function rP(e){return/^[a-f0-9]{8}$/.test(e)?e:null}function oP(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"page-resource"}function tt(e,t){return{ok:!1,code:"MATERIALIZATION_REJECTED",message:e,...t?{path:t}:{}}}import{randomBytes as AP}from"node:crypto";import Zn from"node:path";import{parse as TP}from"@babel/parser";import wP from"@babel/traverse";import{COMPONENT_I18N_FILE_SUFFIX as $a,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as dy,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as OP,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as FP,SiteEditMaterializationSchema as LP,parseComponentI18nResourcesJson as DP}from"@vcp-dev/contracts";import{parse as EP}from"@babel/parser";import SP from"@babel/traverse";import{GeneratedSiteCapabilitiesSchema as IP,FormDefinitionIdSchema as vP}from"@vcp-dev/contracts";var sy={colorMixPolicy:"always",includeExtendedColorFunctions:!0},ay=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\(/i,cy=/\b(?:bg-black|bg-white|text-white|text-black)(?:\b|\/)/g,iP=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke)-\[#(?:[0-9a-fA-F]{3,8})\](?:\/\d+)?/g,sP=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*#[0-9a-fA-F]{3,8}[^'"]*['"]/g,aP=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*rgba?\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,cP=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,lP=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,uP=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*(?:oklch|lab|lch|hsla?)\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,dP=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*(?:oklch|lab|lch|hsla?)\([^)]+\)[^'"]*['"]/gi,fP=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*color-mix\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,pP=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*color-mix\([^'"]*['"]/gi,mP=/\b(?:bg|text|border|ring|outline|fill|stroke)-(?:black|white|slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)(?:-\d{2,3})?(?:\b|\/)/g,gP=/var\(\s*--(?:_|private-|vcp-)[^)]+\)/gi,hP=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\([^)]*\)/gi;function od(e,t){let n=ja([...cn(e,iP),...cn(e,sP),...cn(e,aP),...cn(e,t.includeRgbBackgroundImage?cP:lP),...t.includeExtendedColorFunctions?[...cn(e,uP),...cn(e,dP)]:[]]),r=ja([...cn(e,fP),...cn(e,pP)]).filter(o=>t.colorMixPolicy==="always"||ay.test(o));return n.push(...r.filter(o=>!n.includes(o))),t.rejectTailwindPalette&&n.push(...cn(e,mP).filter(o=>!n.includes(o))),t.rejectAnyRawColorLiteral&&n.push(...cn(e,hP).filter(o=>!n.includes(o))),{hardCodedSurfaceHits:ja(cn(e,cy)),hardCodedSurfaceOccurrences:bP(e),rawColorHits:n,privateTokenHits:t.rejectPrivateTokens?yP(e):[]}}function yP(e){return ja(cn(e,gP))}function cn(e,t){return e.match(new RegExp(t.source,t.flags))??[]}var iy=160,xP=/((?:[a-z][a-z0-9-]*(?:\[[^\]]*\])?:)+)$/;function bP(e){let t=new RegExp(cy.source,"g"),n=[0];for(let s=0;s<e.length;s+=1)e[s]===`
4
+ `)}function ea(e){let{ast:t,source:n}=e;try{let r=z_(n),i=X_(t,{comments:!0,jsescOption:{minimal:!0,quotes:"single"}},n).code;return r!=="2"&&(i=W_(i,r)),{ok:!0,source:i}}catch(r){return ee(n,"printer-failed",`AST print failed: ${r instanceof Error?r.message:String(r)}`)}}function Ng(e){let t=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);t=(t<<5)-t+r,t|=0}return`0x${Math.abs(t).toString(16)}`}function xi(e,t,n){return{ok:!0,source:t,operation:{type:n.kind,nodeId:n.target,kind:n.kind,target:n.target,beforeSourceHash:Ng(e),afterSourceHash:Ng(t),inverse:n.inverse}}}function Me(e,t,n){let r=ea({ast:e,source:t});return r.ok?xi(t,r.source,n):r}function We(e,t){let n=pi(e,t);return n.ok?{ok:!0,ast:n.ast}:{ok:!1,result:{ok:!1,source:e,diagnostic:n.diagnostic}}}function ta(e,t){return ea({ast:e,source:t})}function iC(e,t,n){let r=Ie(e,t);return r.ok?{ok:!0,match:r.match}:{ok:!1,result:{ok:!1,source:n,diagnostic:r.diagnostic}}}function vo(e,t,n){let r=iC(e,t,n);return r.ok?r.match.path.isJSXElement()?r:{ok:!1,result:ee(n,"unsupported-syntax","JSX locator must resolve to JSXElement","jsx-node")}:r}function lr(e){return typeof e=="string"?uu(e):typeof e=="number"?nC(e):typeof e=="boolean"?Y_(e):e===null?tC():Array.isArray(e)?G_(e.map(t=>lr(t))):rC(Object.entries(e).map(([t,n])=>{let r=oC(du(t),lr(n));return t==="__proto__"&&(r.computed=!0),r}))}function sC(e){return typeof e=="string"?uu(e):Q_(lr(e))}function bi(e,t){return q_(eC(e),sC(t))}function na(e,t){try{let r=Pg.parse(`const __VD_NODE__ = (${t});`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0];return r?.type!=="VariableDeclaration"||r.declarations[0]?.type!=="VariableDeclarator"||!r.declarations[0].init||r.declarations[0].init.type!=="JSXElement"&&r.declarations[0].init.type!=="JSXFragment"?{ok:!1,result:ee(e,"unsupported-syntax","Provided JSX source does not resolve to a JSX node","jsx-node")}:{ok:!0,node:r.declarations[0].init}}catch(n){return{ok:!1,result:ee(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function du(e){return/^[$A-Z_][0-9A-Z_$]*$/i.test(e)?Z_(e):uu(e)}function ra(e){let{source:t,locator:n,segmentIndex:r,newText:o}=e,i=We(t,"jsx-node");if(!i.ok)return i.result;let s=Ie(i.ast,n);if(!s.ok)return{ok:!1,source:t,diagnostic:s.diagnostic};let c=aC(s.match.path)[r];if(!c)return ee(t,"locator-miss",`Text segment ${r} not found`,"jsx-node");switch(c.kind){case"jsx-text":{let l=c.path.node.value;if(o.trim().length===0){let d=l.match(/^\s*/)?.[0]??"",f=l.match(/\s*$/)?.[0]??"";c.path.replaceWithMultiple([...d?[Zr.jsxText(d)]:[],Zr.jsxExpressionContainer(Zr.stringLiteral("")),...f?[Zr.jsxText(f)]:[]]);break}let u=cC(l,o);c.path.node.value=u,c.path.node.extra={rawValue:u,raw:u.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/{/g,"&#123;").replace(/}/g,"&#125;")};break}case"string-literal":c.path.node.value=o;break;case"template-literal":{let l=c.quasiIndex;c.path.node.quasis[l].value.raw=o.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\$\{/g,"\\${").replace(/\r/g,"\\r"),c.path.node.quasis[l].value.cooked=o;break}}return Me(i.ast,t,{kind:"update-text",target:"jsx-node",inverse:"restore-text"})}function aC(e){let t=[],n=e.isJSXElement()||e.isJSXFragment()?e.get("children"):[];for(let r of n){if(r.isJSXText()){r.node.value.trim().length>0&&t.push({kind:"jsx-text",path:r});continue}if(r.isJSXExpressionContainer()){let o=lC(r.get("expression"));o.length>0&&t.push(...o)}}return t}function cC(e,t){let n=e.match(/^\s*/)?.[0]??"",r=e.match(/\s*$/)?.[0]??"";return`${n}${t.trim()}${r}`}function lC(e){if(e.isStringLiteral())return[{kind:"string-literal",path:e}];if(e.isTemplateLiteral()){let t=[],n=e.node.quasis;for(let r=0;r<n.length;r++)(n[r].value.raw.trim().length>0||n.length===1&&e.node.expressions.length===0)&&t.push({kind:"template-literal",path:e,quasiIndex:r});if(t.length>0)return t}return e.isCallExpression()?[]:[]}import{nullLiteral as fu}from"@babel/types";function qr(e){let{source:t,locator:n}=e,r=We(t,"jsx-node");if(!r.ok)return r.result;let o=Ie(r.ast,n);return o.ok?(uC(o.match.path),Me(r.ast,t,{kind:"remove-node",target:"jsx-node",inverse:"insert-child"})):{ok:!1,source:t,diagnostic:o.diagnostic}}function uC(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(fu());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(fu());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(fu());return}e.remove()}import{cloneNode as dC}from"@babel/types";function ko(e){let t=We(e.source,"jsx-node");if(!t.ok)return t.result;let n=Ie(t.ast,e.locator);if(!n.ok)return{ok:!1,source:e.source,diagnostic:n.diagnostic};let r=na(e.source,e.node.jsx);return r.ok?(n.match.path.replaceWith(dC(r.node,!0)),Me(t.ast,e.source,{kind:"replace-node",target:"jsx-node",inverse:"replace-node"})):r.result}import{cloneNode as IC}from"@babel/types";import pu from"@babel/traverse";import*as me from"@babel/types";function Ei(e,t,n){return`${e}::${t}::${n}`}var U={NODE_NOT_FOUND:"NODE_NOT_FOUND",HOME_PAGE_LOCKED:"HOME_PAGE_LOCKED",ROUTE_NOT_FOUND:"ROUTE_NOT_FOUND",CAPABILITY_REJECTED:"CAPABILITY_REJECTED",CONSTRAINT_VIOLATED:"CONSTRAINT_VIOLATED",INVALID_PARAMS:"INVALID_PARAMS",PLAN_FAILED:"PLAN_FAILED",TRANSACTION_PREFLIGHT_FAILED:"TRANSACTION_PREFLIGHT_FAILED",ROUTE_REBUILD_FAILED:"ROUTE_REBUILD_FAILED",HISTORY_COMMIT_FAILED:"HISTORY_COMMIT_FAILED",MATERIALIZATION_CONFLICT:"MATERIALIZATION_CONFLICT",MATERIALIZATION_REJECTED:"MATERIALIZATION_REJECTED",MUTATION_ASSERTION_REQUIRED:"MUTATION_ASSERTION_REQUIRED",MUTATION_ASSERTION_INVALID:"MUTATION_ASSERTION_INVALID",VERSION_STALE:"VERSION_STALE",AST_PARSE_ERROR:"AST_PARSE_ERROR",UNSUPPORTED_OPERATION:"UNSUPPORTED_OPERATION",LOCATOR_FAILED:"LOCATOR_FAILED",INVALID_TARGET:"INVALID_TARGET",WRITE_IO_ERROR:"WRITE_IO_ERROR",CONCURRENT_MODIFIED:"CONCURRENT_MODIFIED",ROLLBACK_FAILED:"ROLLBACK_FAILED",RECOVERY_REQUIRED:"RECOVERY_REQUIRED",RECOVERY_PERSIST_FAILED:"RECOVERY_PERSIST_FAILED",MUTATION_SESSION_REQUIRED:"MUTATION_SESSION_REQUIRED",LEASE_ASSERTION_INVALID:"LEASE_ASSERTION_INVALID",LEASE_ASSERTION_EXPIRED:"LEASE_ASSERTION_EXPIRED",LEASE_ASSERTION_SCOPE_MISMATCH:"LEASE_ASSERTION_SCOPE_MISMATCH",CROSS_PAGE_MOVE_UNSUPPORTED:"CROSS_PAGE_MOVE_UNSUPPORTED",INTERNAL_ERROR:"INTERNAL_ERROR"};var fC=typeof pu=="function"?pu:pu.default;function rn(e,t,n,r){if(!e.ok)return e;let o=nn(n,t);if(!o)return e;let i=pC(t,o,r);return i?{...e,selectionRef:i}:e}function pC(e,t,n){let r=mC(e,t);if(!r)return;let o=n.sourceLocator?Ag(n.sourceLocator):void 0,i=n.targetParentLocator?Ag(n.targetParentLocator):void 0,s=n.file??i?.file??o?.file,a=n.component??hC(r)??i?.component??o?.component;if(!(!s||!a))return{key:Ei(s,a,yC(r))}}function Ag(e){return e.strategy==="structural-path"?{file:e.file,component:e.component,structuralPath:e.structuralPath}:e.expectedIdentity}function mC(e,t){let n=Mg(e,t);return!n||n.node.type!=="JSXElement"?null:n}function Mg(e,t){let n=null;return fC(e,{JSXElement(r){r.node===t&&(n=r,r.stop())},JSXFragment(r){r.node===t&&(n=r,r.stop())}}),n}function nn(e,t){if(!e)return null;if(me.isJSXElement(e))return SC(t,e)?Tg(e.children,t):e;if(me.isJSXFragment(e))return Tg(e.children,t);if(me.isJSXExpressionContainer(e)||me.isParenthesizedExpression(e)||me.isTSAsExpression(e)||me.isTSSatisfiesExpression(e)||me.isTSTypeAssertion(e)||me.isTSNonNullExpression(e))return nn(e.expression,t);if(me.isLogicalExpression(e))return nn(e.right,t);if(me.isConditionalExpression(e))return nn(e.consequent,t)??nn(e.alternate,t);if(me.isCallExpression(e)||me.isOptionalCallExpression(e))return Dg(e)?gC(e.arguments[0],t):null;if(me.isArrayExpression(e))for(let n of e.elements){if(!n)continue;let r=nn(n,t);if(r)return r}return null}function Tg(e,t){for(let n of e){let r=nn(n,t);if(r)return r}return null}function gC(e,t){return!e||!me.isArrowFunctionExpression(e)&&!me.isFunctionExpression(e)?null:me.isBlockStatement(e.body)?Si(e.body.body,t):nn(e.body,t)}function Si(e,t){for(let n of e){if(me.isReturnStatement(n)){let r=nn(n.argument,t);if(r)return r;continue}if(me.isBlockStatement(n)){let r=Si(n.body,t);if(r)return r;continue}if(me.isIfStatement(n)){let r=wg(n.consequent,t);if(r)return r;let o=n.alternate?wg(n.alternate,t):null;if(o)return o;continue}if(me.isSwitchStatement(n))for(let r of n.cases){let o=Si(r.consequent,t);if(o)return o}}return null}function wg(e,t){return me.isBlockStatement(e)?Si(e.body,t):Si([e],t)}function hC(e){let t=e;for(;t;){if(t.isFunctionDeclaration()||t.isClassDeclaration())return t.node.id?.name??null;if(t.isExportDefaultDeclaration()){let n=t.node.declaration;if(me.isFunctionDeclaration(n))return n.id?.name??"default"}if(t.isVariableDeclarator()&&me.isIdentifier(t.node.id)){let n=t.get("init");if(!Array.isArray(n)&&(n.isArrowFunctionExpression()||n.isFunctionExpression()))return t.node.id.name}t=t.parentPath}return null}var Og=new WeakMap,Fg=new WeakMap,mu=new WeakMap;function yC(e){let t=Og.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=xC(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return Og.set(e.node,o),o}function xC(e){let t=Bg(e.node.openingElement.name);return!t||Ye(e)?null:/^[A-Z]/.test(t)?`component:${t}#${Lg(e,t)}`:`${t}#${Lg(e,t)}`}function Lg(e,t){let n=bC(e);if(!n)return 0;let r=mu.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=mu.get(n.node);o||(o=new Map,mu.set(n.node,o));let i=o.get(t);i||(i=new WeakMap,o.set(t,i));let s=0;for(let a of Qr(n))if(Bg(a.node.openingElement.name)===t){if(i.set(a.node,s),a.node===e.node)return s;s+=1}return i.get(e.node)??0}function bC(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(Ye(t)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function Qr(e){let t=Fg.get(e.node);if(t)return t;let n=[],r=e.get("children");for(let o of r)if(!Array.isArray(o)){if(o.isJSXElement()){if(Ye(o)){n.push(...Qr(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...Qr(o));continue}o.isJSXExpressionContainer()&&n.push(...An(o.get("expression")))}return Fg.set(e.node,n),n}function An(e){if(e.isJSXElement())return Ye(e)?Qr(e):[e];if(e.isJSXFragment())return Qr(e);if(e.isParenthesizedExpression())return An(e.get("expression"));if(e.isLogicalExpression())return An(e.get("right"));if(e.isConditionalExpression())return[...An(e.get("consequent")),...An(e.get("alternate"))];if(e.isArrayExpression())return e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:An(t));if((e.isCallExpression()||e.isOptionalCallExpression())&&Dg(e.node)){let t=e.get("arguments"),n=Array.isArray(t)?t[0]:void 0;return n?EC(n):[]}return[]}function EC(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return Ye(t)?Qr(t):[t];if(t.isJSXFragment())return Qr(t);if(t.isParenthesizedExpression())return An(t.get("expression"));if(t.isLogicalExpression()||t.isConditionalExpression())return An(t);if(!t.isBlockStatement())return[];let n=[];for(let r of t.get("body")){if(r.isVariableDeclaration())for(let i of r.get("declarations")){let s=i.get("init");(s.isJSXElement()||s.isJSXFragment())&&n.push(...An(s))}if(!r.isReturnStatement())continue;let o=r.get("argument");return o.node&&n.push(...An(o)),n}return n}function Dg(e){let t=e.callee;return(me.isMemberExpression(t)||me.isOptionalMemberExpression(t))&&me.isIdentifier(t.property)&&t.property.name==="map"&&!t.computed}function SC(e,t){let n=Mg(e,t);return n?Ye(n):!1}function Bg(e){return me.isJSXIdentifier(e)?e.name:me.isJSXMemberExpression(e)?jg(e):me.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function jg(e){return`${me.isJSXIdentifier(e.object)?e.object.name:jg(e.object)}.${e.property.name}`}function ur(e,t){if(t.parentPath===e&&t.listKey==="children"&&gu(e))return e;if(!t.parentPath||t.listKey!=="children")return null;let n=t.parentPath;if(!gu(n))return null;let r=n;for(;r&&r!==e;){if(!gu(r)||!Ye(r)||r.listKey!=="children")return null;r=r.parentPath}return r===e?n:null}function gu(e){return e.isJSXElement()||e.isJSXFragment()}function on(e){let{source:t,locator:n,node:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=We(t,"jsx-node");if(!a.ok)return a.result;let c=Ie(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};if(!c.match.path.isJSXElement()&&!c.match.path.isJSXFragment())return ee(t,"unsupported-syntax","insert-child target must be a JSXElement or JSXFragment","jsx-node");let l=c.match.path;if(c.match.path.isJSXElement()){let b=c.match.path.node;if(!b.closingElement||b.openingElement.selfClosing)return ee(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=na(t,r.jsx);if(!u.ok)return u.result;let d=IC(u.node,!0),f=l.node.children,g={...s,targetParentLocator:n},p=b=>s?rn(b,a.ast,d,g):b;if(o==="append")return f.push(d),p(Me(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return f.unshift(d),p(Me(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(!i)return ee(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let m=Ie(a.ast,i);if(!m.ok)return{ok:!1,source:t,diagnostic:m.diagnostic};let y=ur(c.match.path,m.match.path);if(!y)return ee(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");l=y;let x=l.node.children,S=x.findIndex(b=>b===m.match.path.node);return S===-1?ee(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(x.splice(o==="before"?S:S+1,0,d),p(Me(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"})))}import*as $g from"@babel/parser";import{cloneNode as vC}from"@babel/types";function oa(e){let{source:t,locator:n,expression:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=We(t,"jsx-node");if(!a.ok)return a.result;let c=kC(t,r);if(!c.ok)return c.result;let l=Ie(a.ast,n);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return ee(t,"unsupported-syntax","insert-jsx-expression-child target must be a JSXElement or JSXFragment","jsx-node");if(l.match.path.isJSXElement()){let x=l.match.path.node;if(!x.closingElement||x.openingElement.selfClosing)return ee(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=l.match.path,d=null;if(i){let x=Ie(a.ast,i);if(!x.ok)return{ok:!1,source:t,diagnostic:x.diagnostic};let S=ur(l.match.path,x.match.path);if(!S)return ee(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=S,d=x.match.path.node}else if(o==="before"||o==="after")return ee(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let f=vC(c.node,!0),g=u.node.children,p={...s,targetParentLocator:n},m=x=>s?rn(x,a.ast,f,p):x;if(o==="append")return g.push(f),m(Me(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return g.unshift(f),m(Me(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));let y=g.findIndex(x=>x===d);return y===-1?ee(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(g.splice(o==="before"?y:y+1,0,f),m(Me(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"})))}function kC(e,t){try{let r=$g.parse(`const __VD_EXPR__ = <>{${t}}</>;`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0],o=r?.type==="VariableDeclaration"?r.declarations[0]?.init:null,i=o?.type==="JSXFragment"?o.children[0]:void 0;return i?.type!=="JSXExpressionContainer"?{ok:!1,result:ee(e,"unsupported-syntax","Expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:ee(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}import{cloneNode as _C,nullLiteral as hu}from"@babel/types";import*as dr from"@babel/types";import*as Vg from"@babel/types";function Ii(e,t){let n=e.parentPath;if(!n?.isConditionalExpression()||e.key!=="consequent"||!Vg.isNullLiteral(n.node.alternate))return e;let r=n.parentPath;return!r?.isJSXExpressionContainer()||r.parentPath?.node!==t.node||r.listKey!=="children"?e:r}function eo(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=We(t,"jsx-node");if(!a.ok)return a.result;let c=Ie(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};let l=Ie(a.ast,r);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return ee(t,"unsupported-syntax","move-node target parent must be a JSXElement or JSXFragment","jsx-node");let u=l.match.path;if(l.match.path.isJSXElement()){let b=l.match.path.node;if(!b.closingElement||b.openingElement.selfClosing)return ee(t,"self-closing-element","Cannot move child into self-closing element","jsx-node")}let d=null;if(i){let b=Ie(a.ast,i);if(!b.ok)return{ok:!1,source:t,diagnostic:b.diagnostic};let E=b.match.path.isJSXElement()?Ii(b.match.path,l.match.path):b.match.path,k=ur(l.match.path,E);if(!k)return ee(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=k,d=E}else if(o==="before"||o==="after")return ee(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let f=d&&typeof d.key=="number"?d.key:-1;if(d&&f===-1)return ee(t,"locator-miss","Anchor node does not exist in target parent","jsx-node");let g=c.match.path.isJSXElement()?Ii(c.match.path,l.match.path):c.match.path,p=_C(g.node,!0);if(!dr.isJSXElement(p)&&!dr.isJSXExpressionContainer(p)&&!dr.isJSXFragment(p)&&!dr.isJSXText(p))return ee(t,"unsupported-syntax","move-node source must resolve to a JSX child","jsx-node");let m=g.parentPath?.node===u.node&&typeof g.key=="number"?g.key:-1;if(d&&g.parentPath?.node===d.parentPath?.node&&g.key===d.key)return ee(t,"invalid-parent-child-relation","Cannot move a node relative to itself","jsx-node");CC(g);let y=u.node.children,x={...s,sourceLocator:n,targetParentLocator:r};if(o==="append")return y.push(p),rn(ta(a.ast,t),a.ast,p,x);if(o==="prepend")return y.unshift(p),rn(ta(a.ast,t),a.ast,p,x);let S=f-(m!==-1&&m<f?1:0);return y.splice(o==="before"?S:S+1,0,p),rn(ta(a.ast,t),a.ast,p,x)}function CC(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(hu());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(hu());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(hu());return}e.remove()}import*as Ug from"@babel/parser";import{cloneNode as RC,nullLiteral as yu}from"@babel/types";function ia(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,repeatExpression:s,selectionContext:a}=e,c=We(t,"jsx-node");if(!c.ok)return c.result;let l=NC(t,s);if(!l.ok)return l.result;let u=Ie(c.ast,n);if(!u.ok)return{ok:!1,source:t,diagnostic:u.diagnostic};let d=Ie(c.ast,r);if(!d.ok)return{ok:!1,source:t,diagnostic:d.diagnostic};if(!d.match.path.isJSXElement()&&!d.match.path.isJSXFragment())return ee(t,"unsupported-syntax","move-repeat-template-child target parent must be a JSXElement or JSXFragment","jsx-node");if(d.match.path.isJSXElement()){let b=d.match.path.node;if(!b.closingElement||b.openingElement.selfClosing)return ee(t,"self-closing-element","Cannot move repeat child into self-closing element","jsx-node")}let f=d.match.path,g=null;if(i){let b=Ie(c.ast,i);if(!b.ok)return{ok:!1,source:t,diagnostic:b.diagnostic};let E=ur(d.match.path,b.match.path);if(!E)return ee(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");f=E,g=b.match.path.node}else if(o==="before"||o==="after")return ee(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");if(!u.match.path.isJSXElement())return ee(t,"unsupported-syntax","move-repeat-template-child source must be a JSXElement","jsx-node");let p=f.node,m=RC(l.node,!0);PC(u.match.path);let y={...a,sourceLocator:n,targetParentLocator:r},x=p.children;if(o==="append")return x.push(m),rn(Me(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,m,y);if(o==="prepend")return x.unshift(m),rn(Me(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,m,y);let S=x.findIndex(b=>b===g);return S===-1?ee(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(x.splice(o==="before"?S:S+1,0,m),rn(Me(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,m,y))}function NC(e,t){try{let r=Ug.parse(`const __VD_EXPR__ = <>{${t}}</>;`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0],o=r?.type==="VariableDeclaration"?r.declarations[0]?.init:null,i=o?.type==="JSXFragment"?o.children[0]:void 0;return i?.type!=="JSXExpressionContainer"?{ok:!1,result:ee(e,"unsupported-syntax","Repeat expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:ee(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function PC(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(yu());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(yu());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(yu());return}e.remove()}import{SiteEditSetPropsParamsSchema as AC,classifySiteEditPropertyName as TC}from"@vcp-dev/contracts";import*as _o from"@babel/types";function sa(e){let t=AC.safeParse({kind:"set-props",scope:"selection",changes:e.changes});if(!t.success)return ee(e.source,"unsupported-syntax","Invalid typed JSX property changes","jsx-node",{issues:t.error.issues});let n=We(e.source,"jsx-node");if(!n.ok)return n.result;let r=vo(n.ast,e.locator,e.source);if(!r.ok)return r.result;for(let a of t.data.changes){let c=TC(a.name);if(c.owner!=="generic")return ee(e.source,"unsupported-syntax",c.diagnostic?.message??`Property '${a.name}' is not owned by the generic JSX primitive`,"jsx-node")}let o=r.match.path.node.openingElement,i=o.attributes.filter(_o.isJSXAttribute),s=new Map;for(let a of i){let c=wC(a);if(!c)continue;let l=s.get(c)??[];l.push(a),s.set(c,l)}for(let a of t.data.changes)if((s.get(a.name)??[]).length>1)return ee(e.source,"unsupported-syntax",`JSX attribute '${a.name}' has multiple sources`,"jsx-node");for(let a of t.data.changes){let c=s.get(a.name)?.[0];if(a.operation==="remove"){c&&(o.attributes=o.attributes.filter(u=>u!==c));continue}let l=bi(a.name,a.value).value;c?c.value=l:o.attributes.push(bi(a.name,a.value))}return Me(n.ast,e.source,{kind:"set-props",target:"jsx-node",inverse:"set-props"})}function wC(e){return _o.isJSXIdentifier(e.name)?e.name.name:_o.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:null}import{SiteEditOperationParamsSchema as OC}from"@vcp-dev/contracts";import*as re from"@babel/types";var Kg=["prefetch","replace","scroll","locale","onNavigate"],FC=/^on(?:Click|DoubleClick|AuxClick|MouseDown|MouseUp|PointerDown|PointerUp|TouchStart|TouchEnd|KeyDown|KeyUp|ContextMenu)(?:Capture)?$/;function LC(e){let t=e;for(;t;){if(t.isJSXElement()&&t.node.openingElement.attributes.some(n=>re.isJSXAttribute(n)&&re.isJSXIdentifier(n.name)&&FC.test(n.name.name)))return!0;t=t.parentPath}return!1}function aa(e){let t=We(e.source,"jsx-node");if(!t.ok)return t.result;let n=vo(t.ast,e.locator,e.source);if(!n.ok)return n.result;let r=OC.safeParse({kind:"set-link-target",scope:"selection",link:e.link,changes:e.changes});if(!r.success||r.data.kind!=="set-link-target")return zn(e.source,"Invalid typed link-target changes");let o=n.match.path,i=o.node,s=i.openingElement,a=UC(s.name);if(!a)return zn(e.source,"Unsupported JSX link tag");if(s.attributes.some(re.isJSXSpreadAttribute))return zn(e.source,"Link elements with spread props cannot be transformed safely");let c=new Map;for(let p of s.attributes){if(!re.isJSXAttribute(p))continue;let m=bu(p);if(!m)return zn(e.source,"Unsupported JSX attribute name");let y=c.get(m)??[];y.push(p),c.set(m,y)}if([...c.values()].some(p=>p.length>1))return zn(e.source,"Duplicate JSX attributes cannot be transformed safely");let l=c.get("href")?.[0];if(l&&!VC(l))return zn(e.source,"Dynamic link href cannot be transformed safely");let u=a==="a",d=u?null:BC(o,s.name);if(!u&&!d)return zn(e.source,"Only native anchors and imported next/link components are supported");if(e.link.kind==="none"&&LC(o))return zn(e.source,"A link with an active event handler in its JSX ancestry cannot become an inert anchor");let f=null;if(e.link.kind==="internal-route")if(d)f=a;else{let p=jC(t.ast,o);if(!p.ok)return zn(e.source,p.reason);f=p.localName}if(d&&e.link.kind!=="internal-route"){let p=re.jsxIdentifier("a");s.name=p,i.closingElement&&(i.closingElement.name=re.jsxIdentifier("a")),$C(t.ast,d,o)}else f&&u&&(s.name=re.jsxIdentifier(f),i.closingElement&&(i.closingElement.name=re.jsxIdentifier(f)));let g=new Set;return e.link.kind==="none"?(g.add("href"),g.add("target"),g.add("rel"),Kg.forEach(p=>g.add(p))):(g.add("href"),e.link.kind==="native-link"&&Kg.forEach(p=>g.add(p))),s.attributes=s.attributes.filter(p=>{if(!re.isJSXAttribute(p))return!0;let m=bu(p);return!m||!g.has(m)}),e.link.kind!=="none"&&s.attributes.push(re.jsxAttribute(re.jsxIdentifier("href"),re.stringLiteral(e.link.href))),MC(s,e.changes),Me(t.ast,e.source,{kind:"set-link-target",target:"jsx-node",inverse:"set-link-target"})}function MC(e,t){for(let n of t){let r=e.attributes.find(s=>re.isJSXAttribute(s)&&bu(s)===n.name);if(n.operation==="remove"){e.attributes=e.attributes.filter(s=>s!==r);continue}let o=typeof n.value=="string"?re.stringLiteral(n.value):re.jsxExpressionContainer(xu(n.value)),i=re.jsxAttribute(re.jsxIdentifier(n.name),o);r&&re.isJSXAttribute(r)?r.value=i.value:e.attributes.push(i)}}function xu(e){return e===null?re.nullLiteral():typeof e=="string"?re.stringLiteral(e):typeof e=="number"?re.numericLiteral(e):typeof e=="boolean"?re.booleanLiteral(e):Array.isArray(e)?re.arrayExpression(e.map(t=>xu(t))):typeof e=="object"?re.objectExpression(Object.entries(e).map(([t,n])=>re.objectProperty(re.isValidIdentifier(t)?re.identifier(t):re.stringLiteral(t),xu(n)))):re.nullLiteral()}function DC(e){return re.isImportDefaultSpecifier(e)||re.isImportSpecifier(e)&&e.importKind!=="type"&&(re.isIdentifier(e.imported,{name:"default"})||re.isStringLiteral(e.imported,{value:"default"}))}function Jg(e){return!e.parentPath?.isImportDeclaration()||e.parentPath.node.importKind==="type"?!1:e.isImportDefaultSpecifier()||e.isImportSpecifier()&&e.node.importKind!=="type"&&(re.isIdentifier(e.node.imported,{name:"default"})||re.isStringLiteral(e.node.imported,{value:"default"}))}function BC(e,t){if(!re.isJSXIdentifier(t))return null;let n=e.scope.getBinding(t.name);if(!n||!Jg(n.path))return null;let r=n.path.parentPath;return!r?.isImportDeclaration()||r.node.source.value!=="next/link"?null:t.name}function jC(e,t){let n=e.program.body.filter(c=>re.isImportDeclaration(c)&&c.source.value==="next/link"&&c.importKind!=="type"),r=n[0],o=n.flatMap(c=>c.specifiers).find(DC);if(o)return t.scope.getBinding(o.local.name)?.path.node!==o?{ok:!1,reason:"The next/link import is shadowed at the selected element"}:{ok:!0,localName:o.local.name};let i=t.scope.getProgramParent(),s=["Link","NextLink",...Array.from({length:20},(c,l)=>`NextLink${l+2}`)].find(c=>!i.hasBinding(c)&&!t.scope.hasBinding(c));if(!s)return{ok:!1,reason:"Cannot create an unshadowed runtime next/link import"};let a=re.importDefaultSpecifier(re.identifier(s));if(r)r.specifiers.unshift(a);else{let c=re.importDeclaration([a],re.stringLiteral("next/link")),l=0;for(;l<e.program.body.length&&re.isImportDeclaration(e.program.body[l]);)l+=1;e.program.body.splice(l,0,c)}return{ok:!0,localName:s}}function $C(e,t,n){let r=n.scope.getProgramParent();r.crawl();let o=r.getBinding(t);if(!o||!Jg(o.path)||o.referenced)return;let i=o.path.parentPath;if(!(!i?.isImportDeclaration()||i.node.source.value!=="next/link")&&(i.node.specifiers=i.node.specifiers.filter(s=>s!==o.path.node),i.node.specifiers.length===0)){let s=e.program.body.indexOf(i.node);s>=0&&e.program.body.splice(s,1)}}function VC(e){return!e.value||re.isStringLiteral(e.value)}function UC(e){return re.isJSXIdentifier(e)?e.name:null}function bu(e){return re.isJSXIdentifier(e.name)?e.name.name:null}function zn(e,t){return ee(e,"unsupported-syntax",t,"jsx-node")}import*as ht from"@babel/types";import{classifySiteEditPropertyName as Xg}from"@vcp-dev/contracts";function ca(e){let t=Xg(e.name),n=Xg(e.property);if(t.owner!=="generic"||n.owner!=="generic")return ee(e.source,"unsupported-syntax","Property binding is only available for generic properties","jsx-node");if(!zg(e.object))return ee(e.source,"unsupported-syntax","Property binding object must be a single identifier","jsx-node");if(e.property.length===0)return ee(e.source,"unsupported-syntax","Property binding requires a non-empty property name","jsx-node");let r=We(e.source,"jsx-node");if(!r.ok)return r.result;let o=vo(r.ast,e.locator,e.source);if(!o.ok)return o.result;let i=o.match.path.node.openingElement,s=i.attributes.filter(l=>ht.isJSXAttribute(l)&&JC(l)===e.name);if(s.length>1)return ee(e.source,"unsupported-syntax",`JSX attribute '${e.name}' has multiple sources`,"jsx-node");let a=KC(e.object,e.property),c=s[0];if(c)c.value=ht.jsxExpressionContainer(a);else{let l=bi(e.name,"");l.value=ht.jsxExpressionContainer(a),i.attributes.push(l)}return Me(r.ast,e.source,{kind:"set-property-binding",target:"jsx-node",inverse:"restore-property-binding"})}function KC(e,t){return zg(t)?ht.memberExpression(ht.identifier(e),ht.identifier(t)):ht.memberExpression(ht.identifier(e),ht.stringLiteral(t),!0)}function zg(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(e)}function JC(e){return ht.isJSXIdentifier(e.name)?e.name.name:ht.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:null}import{getBindingIdentifiers as zC,identifier as vi,importDeclaration as HC,importDefaultSpecifier as WC,importNamespaceSpecifier as GC,importSpecifier as YC,isImportDefaultSpecifier as Hg,isImportNamespaceSpecifier as Wg,isImportSpecifier as Gg,stringLiteral as ZC}from"@babel/types";function sn(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(y=>!sR(y));if(o!==-1){let y=r[o],x=y&&typeof y=="object"&&"kind"in y?y.kind:void 0;return ee(t,"unsupported-syntax",`Unsupported import spec kind: ${String(x)}`)}let i=rR(r);if(!i.ok)return ee(t,"unsupported-syntax",i.message);let s=We(t);if(!s.ok)return s.result;let{ast:a}=s,c=a.program,l=c.body.filter(y=>y.type==="ImportDeclaration"&&y.source.value===n),u=new Set(l.flatMap(y=>y.specifiers.flatMap(x=>{let S=aR(y,x);return S?[S]:[]}))),d=i.imports.filter(y=>!u.has(th(y)));if(d.length===0)return xi(t,t,{kind:"add-import",target:"import",inverse:"remove-import"});let f=oR(c.body),g=d.find(y=>f.has(Eu(y)));if(g)return ee(t,"unsupported-syntax",`Import local binding already exists: ${Eu(g)}`);let p=nR(d);if(p.reduce((y,x)=>y+x.length,0)!==d.length)return ee(t,"unsupported-syntax","Unsupported import specifier grouping");for(let y of p){if(!Qg(Zg(y)))return ee(t,"unsupported-syntax","Unsupported import specifier combination");let x=l.find(S=>qC(S,y));if(x)QC(x,y);else{let S=HC(Yg(y),ZC(n));iR(c.body,S),l.push(S)}}return Me(a,t,{kind:"add-import",target:"import",inverse:"remove-import"})}function qC(e,t){return e.importKind==="type"?!1:Qg(tR(eR(e),Zg(t)))}function QC(e,t){let n=!1,r=new Set(e.specifiers.map(o=>Su(o)));for(let o of Yg(t)){let i=Su(o);r.has(i)||(e.specifiers.push(o),r.add(i),n=!0)}return eh(e.specifiers),{changed:n}}function Yg(e){let t=e.map(n=>{switch(n.kind){case"named":return YC(n.local?vi(n.local):vi(n.imported),vi(n.imported));case"default":return WC(vi(n.local));case"namespace":return GC(vi(n.local));default:return n}});return eh(t),t}function Zg(e){let t=qg();for(let n of e)n.kind==="default"?t.defaultLocals.add(n.local):n.kind==="named"?t.hasNamed=!0:t.namespaceLocals.add(n.local);return t}function eR(e){let t=qg();for(let n of e.specifiers)Hg(n)?t.defaultLocals.add(n.local.name):Wg(n)?t.namespaceLocals.add(n.local.name):t.hasNamed=!0;return t}function qg(){return{defaultLocals:new Set,hasNamed:!1,namespaceLocals:new Set}}function tR(e,t){return{defaultLocals:new Set([...e.defaultLocals,...t.defaultLocals]),hasNamed:e.hasNamed||t.hasNamed,namespaceLocals:new Set([...e.namespaceLocals,...t.namespaceLocals])}}function Qg(e){return e.defaultLocals.size>1||e.namespaceLocals.size>1?!1:!(e.hasNamed&&e.namespaceLocals.size>0)}function eh(e){let t=[...e.filter(n=>Hg(n)),...e.filter(n=>Wg(n)),...e.filter(n=>Gg(n))];e.splice(0,e.length,...t)}function nR(e){let t=e.filter(i=>i.kind==="default"),n=e.filter(i=>i.kind==="namespace"),r=e.filter(i=>i.kind==="named"),o=[];if(n.length>0){let i=Math.max(t.length,n.length);for(let s=0;s<i;s+=1){let a=[],c=t[s],l=n[s];c&&a.push(c),l&&a.push(l),o.push(a)}return r.length>0&&o.push(r),o}if(t.length>0){o.push([t[0],...r]);for(let i of t.slice(1))o.push([i])}else r.length>0&&o.push(r);return o}function rR(e){let t=new Map,n=new Map;for(let r of e){let o=th(r);if(t.has(o))continue;let i=Eu(r),s=n.get(i);if(s&&s!==o)return{ok:!1,message:`Import local binding is requested more than once: ${i}`};t.set(o,r),n.set(i,o)}return{ok:!0,imports:[...t.values()]}}function oR(e){let t=new Set;for(let n of e){if(n.type==="ImportDeclaration"){for(let o of n.specifiers)t.add(o.local.name);continue}let r=(n.type==="ExportNamedDeclaration"||n.type==="ExportDefaultDeclaration")&&n.declaration?n.declaration:n;if(r.type==="VariableDeclaration")for(let o of r.declarations)for(let i of Object.keys(zC(o.id)))t.add(i);else(r.type==="FunctionDeclaration"||r.type==="ClassDeclaration"||r.type==="TSEnumDeclaration")&&r.id&&t.add(r.id.name)}return t}function iR(e,t){let n=[...e].reverse().findIndex(r=>r.type==="ImportDeclaration");if(n===-1)e.unshift(t);else{let r=e.length-n;e.splice(r,0,t)}}function sR(e){if(!e||typeof e!="object"||!("kind"in e))return!1;let t=e.kind;return t==="named"?typeof e.imported=="string"&&(e.local===void 0||typeof e.local=="string"):t==="default"||t==="namespace"?typeof e.local=="string":!1}function th(e){switch(e.kind){case"default":return`default:${e.local}`;case"namespace":return`namespace:${e.local}`;case"named":return`named:${e.imported}:${e.local??e.imported}`;default:return e}}function Eu(e){return e.kind==="named"?e.local??e.imported:e.local}function aR(e,t){return e.importKind==="type"||Gg(t)&&t.importKind==="type"?null:Su(t)}function Su(e){if(e.type==="ImportDefaultSpecifier")return`default:${e.local.name}`;if(e.type==="ImportNamespaceSpecifier")return`namespace:${e.local.name}`;let t=e.imported.type==="Identifier"?e.imported.name:e.imported.value,n=e.local.name;return`named:${t}:${n}`}function Co(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(u=>!lR(u));if(o!==-1){let u=r[o],d=u&&typeof u=="object"&&"kind"in u?u.kind:void 0;return ee(t,"unsupported-syntax",`Unsupported remove import spec kind: ${String(d)}`)}let i=We(t);if(!i.ok)return i.result;let{ast:s}=i,a=s.program,c=a.body.findIndex(u=>u.type==="ImportDeclaration"&&u.source.value===n);if(c===-1)return xi(t,t,{kind:"remove-import",target:"import",inverse:"add-import"});let l=a.body[c];return r.length===0?(a.body.splice(c,1),Me(s,t,{kind:"remove-import",target:"import",inverse:"add-import"})):(l.specifiers=l.specifiers.filter(u=>!r.some(d=>cR(u,d))),l.specifiers.length===0&&a.body.splice(c,1),Me(s,t,{kind:"remove-import",target:"import",inverse:"add-import"}))}function cR(e,t){return t.kind==="default"?e.type==="ImportDefaultSpecifier":t.kind==="namespace"?e.type==="ImportNamespaceSpecifier":e.type!=="ImportSpecifier"?!1:(e.imported.type==="Identifier"?e.imported.name:e.imported.value)===t.imported}function lR(e){if(!e||typeof e!="object"||!("kind"in e))return!1;let t=e.kind;return t==="named"?typeof e.imported=="string":t==="default"||t==="namespace"}function ki(e){let{source:t,locator:n,next:r}=e,o=fa(t,n);return o.ok?(o.path.replaceWith(lr(r)),Me(o.ast,t,{kind:"update-value",target:"value",inverse:"restore-value"})):o.result}function la(e){let{source:t,locator:n,index:r,value:o}=e,i=fa(t,n);return i.ok?i.path.isArrayExpression()?i.path.node.elements.some(s=>s?.type==="SpreadElement")?ee(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>i.path.node.elements.length?ee(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(i.path.node.elements.splice(r,0,lr(o)),Me(i.ast,t,{kind:"insert-array-element",target:"value",inverse:"remove-array-element"})):ee(t,"unsupported-syntax","Array operations require array expression target","value"):i.result}function ua(e){let{source:t,locator:n,index:r}=e,o=fa(t,n);return o.ok?o.path.isArrayExpression()?o.path.node.elements.some(i=>i?.type==="SpreadElement")?ee(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>=o.path.node.elements.length?ee(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(o.path.node.elements.splice(r,1),Me(o.ast,t,{kind:"remove-array-element",target:"value",inverse:"insert-array-element"})):ee(t,"unsupported-syntax","Array operations require array expression target","value"):o.result}function da(e){let{source:t,locator:n,fromIndex:r,toIndex:o}=e,i=fa(t,n);if(!i.ok)return i.result;if(!i.path.isArrayExpression())return ee(t,"unsupported-syntax","Array operations require array expression target","value");if(i.path.node.elements.some(c=>c?.type==="SpreadElement"))return ee(t,"unsupported-syntax","Spread array elements are not supported","value");if(r<0||r>=i.path.node.elements.length||o<0||o>i.path.node.elements.length)return ee(t,"array-index-out-of-range","Array move indices are out of range","value");let[s]=i.path.node.elements.splice(r,1),a=Math.min(o,i.path.node.elements.length);return i.path.node.elements.splice(a,0,s),Me(i.ast,t,{kind:"move-array-element",target:"value",inverse:"move-array-element-back"})}function fa(e,t){let n=We(e,"value");if(!n.ok)return{ok:!1,result:n.result};let r=Ie(n.ast,t);return r.ok?{ok:!0,ast:n.ast,path:r.match.path}:{ok:!1,result:{ok:!1,source:e,diagnostic:r.diagnostic}}}import*as Et from"@babel/types";function pa(e){let t=We(e.source,"value");if(!t.ok)return t.result;let n=Ie(t.ast,e.objectLocator);if(!n.ok)return{ok:!1,source:e.source,diagnostic:n.diagnostic};if(!n.match.path.isObjectExpression())return ee(e.source,"unsupported-syntax","Object property upsert requires an ObjectExpression parent","value");let r=n.match.path.node;if(r.properties.some(a=>Et.isSpreadElement(a)||Et.isObjectProperty(a)&&a.computed))return ee(e.source,"unsupported-syntax","Object property upsert does not support spreads or computed keys","value");let o=r.properties.filter(a=>Et.isObjectProperty(a)&&uR(a.key)===e.name);if(o.length>1)return ee(e.source,"unsupported-syntax",`Object property '${e.name}' has multiple sources`,"value");let i=e.value.kind==="undefined"?Et.unaryExpression("void",Et.numericLiteral(0)):lr(e.value.value),s=o[0];if(s)s.value=i,s.shorthand=!1;else{let a=Et.objectProperty(du(e.name),i);e.name==="__proto__"&&(a.computed=!0),r.properties.push(a)}return Me(t.ast,e.source,{kind:"upsert-object-property",target:"value",inverse:"restore-object-property"})}function uR(e){return Et.isIdentifier(e)?e.name:Et.isStringLiteral(e)?e.value:Et.isNumericLiteral(e)?String(e.value):null}import{isSiteEditRuntimeContainerTag as dR,isSiteEditRuntimeVoidElementTag as fR}from"@vcp-dev/contracts/site-edit-runtime-capability";function Ro(e){if(!e.composition)throw new Error("Composition unavailable for render source graph.");return e.composition}function pR(e,t,n){let r=Ro(n),o=t.nodes.get(e),i=n.elements.get(e);if(!o||!i)return{composition:r,key:e,canUpdateText:!1,canInsertChild:!1,canMove:!1,canRemove:!1,constraints:[{kind:"opaque-region",message:"Node not found in graph"}]};let s=o.constraints.map(E=>({kind:E.kind,message:E.reason})),a=i.isOpaque,l=o.parentKey===null&&i.componentName==="Page",u=i.tag.toLowerCase(),d=i.tag!==u,f=!d&&fR(u),g=d||dR(u),p=d&&i.childKeys.length>0&&!i.isPublicUiComponent,m=i.textSegments.length>0&&i.textSegments.some(E=>E.editable);f&&!s.some(E=>E.kind==="void-element")&&s.push({kind:"void-element",message:`Element '${i.tag}' is void: children cannot be inserted`}),!f&&!g&&!s.some(E=>E.kind==="void-element")&&s.push({kind:"void-element",message:`Element '${i.tag}' cannot contain structured children`});let y=m&&(!a||i.importedFrom==="next/link"),x=!i.isPublicUiComponent&&!f&&g&&(!a||p);return{composition:r,key:e,canUpdateText:y,canInsertChild:x,canMove:!l,canRemove:!l,constraints:s}}function ma(e,t){let n=new Map;for(let r of e.nodes.keys())n.set(r,pR(r,e,t));return n}function Iu(e){let t=e.route.graph.elements.get(e.key);if(!t)return{key:e.key,composition:e.route.composition,filePath:"",componentName:"",sourceKind:"missing",attrRaw:null,valueRaw:null,attrRange:null,openingElementRange:{start:0,end:0},version:{documentVersion:e.route.graph.version,contentHash:ke(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Key not found: ${e.key}`}]};let n=mR(e.route.source,t);if(!n)return{key:e.key,composition:e.route.composition,filePath:t.sourceFile,componentName:t.componentName,sourceKind:"missing",attrRaw:null,valueRaw:null,attrRange:null,openingElementRange:{start:0,end:0},version:{documentVersion:e.route.graph.version,contentHash:ke(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Unable to locate JSX element for key ${t.identity.key}`}]};let r=n.node.openingElement,o=r.attributes.find(d=>d.type==="JSXAttribute"&&d.name.type==="JSXIdentifier"&&d.name.name==="className"),i={key:e.key,composition:e.route.composition,filePath:t.sourceFile,componentName:t.componentName,openingElementRange:rh(r),version:{documentVersion:e.route.graph.version,contentHash:ke(e.route.source)}};if(!o)return{...i,sourceKind:"missing",attrRaw:null,valueRaw:null,attrRange:null,diagnostics:[{code:"missing-class-name",message:"No className attribute is present on this element."}]};let s=o.value,a=s?.type==="StringLiteral"?"stringLiteral":"expression",c=n.get("openingElement").get("attributes").find(d=>d.node===o),l=c?.isJSXAttribute()?c.get("value"):null,u=l?.isJSXExpressionContainer()?gR(l.get("expression")):void 0;return{...i,sourceKind:a,attrRaw:nh(e.route.source,o),valueRaw:s?nh(e.route.source,s):null,...u===void 0?{}:{resolvedClassName:u},attrRange:rh(o),diagnostics:[]}}function oh(e){let{source:t,oldAttrRange:n,openingElementRange:r,newAttrRaw:o}=e;if(n){let a=n.start>0&&/\s/.test(t[n.start-1]??"")?n.start-1:n.start,c=o?`${a<n.start?" ":""}${o}`:"";return t.slice(0,a)+c+t.slice(n.end)}if(!o)return t;let i=r.end,s=t.slice(Math.max(0,i-2),i)==="/>"?i-2:i-1;return t.slice(0,s)+` ${o}`+t.slice(s)}function mR(e,t){let n=Rn({source:e,profile:zr({filePath:t.sourceFile,source:e})});if(!n.ok)return null;let r=Ie(n.ast,{kind:"jsx-node",strategy:"structural-path",file:t.identity.file,component:t.identity.component,structuralPath:t.identity.structuralPath,expectedRange:hR(t.sourceRange)});return!r.ok||!r.match.path.isJSXElement()?null:r.match.path}function gR(e){let t=new Set,n=e;if(n.isIdentifier()){for(;n.isIdentifier();){let r=n.scope.getBinding(n.node.name);if(!r?.constant||!r.path.isVariableDeclarator()||!r.path.get("id").isIdentifier({name:n.node.name})||!r.path.parentPath.isVariableDeclaration({kind:"const"})||t.has(r.path.node))return;t.add(r.path.node);let o=r.path.get("init");if(!o.isExpression())return;n=o}if(n.isStringLiteral())return n.node.value;if(n.isTemplateLiteral()&&n.node.expressions.length===0)return n.node.quasis.map(r=>r.value.cooked??r.value.raw).join("")}}function ih(e){let t=Rn({source:`const __v = <div ${e} />;`,profile:"tsx-module"});if(!t.ok)return!1;let n=t.ast.program.body[0],o=(n?.type==="VariableDeclaration"?n.declarations[0]:null)?.init;if(o?.type!=="JSXElement")return!1;let i=o.openingElement.attributes;return i.length===1&&i[0]?.type==="JSXAttribute"&&i[0].name.type==="JSXIdentifier"&&i[0].name.name==="className"}function nh(e,t){return t.start==null||t.end==null?"":e.slice(t.start,t.end)}function rh(e){if(e.start==null||e.end==null)throw new Error("AST node does not include offsets.");return{start:e.start,end:e.end}}function hR(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function sh(){let e=new Set;return{emit(t){for(let n of Array.from(e))try{n(t)}catch{}},subscribe(t){return e.add(t),()=>{e.delete(t)}}}}import{randomUUID as yR}from"node:crypto";import ga from"node:fs/promises";import vu from"node:path";import{setTimeout as xR}from"node:timers/promises";var bR={async mkdir(e,t){await ga.mkdir(e,t)},async writeFile(e,t,n){await ga.writeFile(e,t,n)},async rename(e,t){await ga.rename(e,t)},async rm(e,t){await ga.rm(e,t)}},ER=new Set(["EACCES","EBUSY","EPERM"]),SR=[10,20,40,80,160];async function IR(e,t,n){for(let r of SR)try{await e.rename(t,n);return}catch(o){if(!vR(o))throw o;await xR(r)}await e.rename(t,n)}function vR(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&ER.has(e.code)}async function ha(e,t,n=bR){let r=vu.dirname(e),o=vu.basename(e),i=vu.join(r,`.${o}.${process.pid}.${yR()}.tmp`),s=!1;try{await n.mkdir(r,{recursive:!0}),await n.writeFile(i,t,"utf8"),await IR(n,i,e),s=!0}finally{if(!s)try{await n.rm(i,{force:!0})}catch{}}}import ku from"@babel/traverse";import*as P from"@babel/types";import*as we from"@babel/types";function Tn(e,t={}){if(we.isTSAsExpression(e)||we.isTSSatisfiesExpression(e)||we.isTSNonNullExpression(e)||we.isTypeCastExpression(e)||we.isParenthesizedExpression(e))return Tn(e.expression,t);if(we.isStringLiteral(e))return{status:"resolved",value:e.value};if(we.isNumericLiteral(e))return Number.isFinite(e.value)?{status:"resolved",value:e.value}:{status:"unresolved"};if(we.isBooleanLiteral(e))return{status:"resolved",value:e.value};if(we.isNullLiteral(e))return{status:"resolved",value:null};if(we.isTemplateLiteral(e))return e.expressions.length===0&&e.quasis.length===1?{status:"resolved",value:e.quasis[0].value.cooked??e.quasis[0].value.raw}:{status:"unresolved"};if(we.isIdentifier(e))return e.name==="undefined"&&!t.resolveIdentifier?{status:"undefined"}:t.resolveIdentifier?.(e.name)??{status:"unresolved"};if(we.isUnaryExpression(e)&&e.operator==="void"&&we.isNumericLiteral(e.argument)&&e.argument.value===0)return{status:"undefined"};if(we.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||we.isSpreadElement(r))return{status:"unresolved"};let o=Tn(r,t);if(o.status!=="resolved")return{status:"unresolved"};n.push(o.value)}return{status:"resolved",value:n}}if(we.isObjectExpression(e)){let n=Object.create(null);for(let r of e.properties){if(!we.isObjectProperty(r)||r.computed||!we.isExpression(r.value))return{status:"unresolved"};let o=kR(r.key);if(o===null)return{status:"unresolved"};let i=Tn(r.value,t);if(i.status!=="resolved")return{status:"unresolved"};Object.defineProperty(n,o,{configurable:!0,enumerable:!0,value:i.value,writable:!0})}return{status:"resolved",value:n}}return we.isMemberExpression(e)||we.isOptionalMemberExpression(e)?t.resolveMember?.(e)??{status:"unresolved"}:{status:"unresolved"}}function kR(e){return we.isIdentifier(e)?e.name:we.isStringLiteral(e)?e.value:we.isNumericLiteral(e)?String(e.value):null}var _R=typeof ku=="function"?ku:ku.default;function Rt(e){return{startLine:e.loc?.start.line??0,startColumn:e.loc?.start.column??0,endLine:e.loc?.end.line??0,endColumn:e.loc?.end.column??0}}function CR(e){return/^[A-Z]/.test(e)}function Pu(e){let t=e.openingElement;return P.isJSXIdentifier(t.name)?t.name.name==="Fragment":P.isJSXMemberExpression(t.name)?t.name.property.name==="Fragment":!1}function Po(e){return P.isJSXFragment(e)}function ch(e){return P.isJSXIdentifier(e.name)?e.name.name:P.isJSXMemberExpression(e.name)?lh(e.name):P.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:"unknown"}function lh(e){return P.isJSXIdentifier(e.object)?`${e.object.name}.${e.property.name}`:P.isJSXMemberExpression(e.object)?`${lh(e.object)}.${e.property.name}`:e.property.name}function RR(e){return e.split(".")[0]??e}function NR(e){let t=e;for(;t;){let n=t.node;if(P.isFunctionDeclaration(n)&&n.id||P.isVariableDeclarator(n)&&P.isIdentifier(n.id))return n.id.name;if(P.isExportDefaultDeclaration(n)){let r=n.declaration;if(P.isFunctionDeclaration(r)&&r.id)return r.id.name;if(P.isFunctionDeclaration(r)&&!r.id)return"default"}t=t.parentPath}return null}function PR(){let e=new Map;return{getOrdinal(t,n){let r=t??"__root__";e.has(r)||e.set(r,new Map);let o=e.get(r),i=o.get(n)??0;return o.set(n,i+1),i}}}function AR(e){let t=new Map;for(let n of e.program.body){if(!P.isImportDeclaration(n))continue;let r=n.source.value;for(let o of n.specifiers)if(P.isImportDefaultSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"default"});else if(P.isImportNamespaceSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"*"});else if(P.isImportSpecifier(o)){let i=P.isIdentifier(o.imported)?o.imported.name:o.imported.value;t.set(o.local.name,{specifier:r,exportName:i})}}return t}function Hn(e,t=[]){if(P.isIdentifier(e))return t.push(e.name),t;if(P.isObjectPattern(e)){for(let n of e.properties)P.isObjectProperty(n)?Hn(n.value,t):P.isRestElement(n)&&Hn(n.argument,t);return t}if(P.isArrayPattern(e)){for(let n of e.elements)n&&(P.isRestElement(n)?Hn(n.argument,t):Hn(n,t));return t}return P.isAssignmentPattern(e)?(Hn(e.left,t),t):(P.isRestElement(e)&&Hn(e.argument,t),t)}function mn(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function _i(e,t){for(let n=t.length-1;n>=0;n-=1){let r=t[n].get(e);if(r)return r.resolved?{kind:"resolved",value:r.value}:{kind:"unresolved"}}return{kind:"unresolved"}}function TR(e,t,n){e.set(t,{resolved:!0,value:n})}function Au(e,t){e.set(t,{resolved:!1})}function uh(e,t){let n=e;for(let r of t){if(r.kind==="property"){if(n==null||Array.isArray(n)||typeof n!="object"||!(r.name in n))return{kind:"known-empty"};n=n[r.name];continue}if(!Array.isArray(n)||r.index<0||r.index>=n.length)return{kind:"known-empty"};n=n[r.index]}return{kind:"resolved",value:n}}function pt(e,t,n){if(P.isTSAsExpression(e)||P.isTSSatisfiesExpression(e)||P.isTSNonNullExpression(e)||P.isTypeCastExpression(e)||P.isParenthesizedExpression(e))return pt(e.expression,t,n);if(P.isLogicalExpression(e))return ya([pt(e.left,t,n),pt(e.right,t,n)]);if(P.isBinaryExpression(e))return ya([P.isExpression(e.left)?pt(e.left,t,n):null,P.isExpression(e.right)?pt(e.right,t,n):null]);if(P.isConditionalExpression(e))return ya([pt(e.consequent,t,n),pt(e.alternate,t,n)]);if(P.isTemplateLiteral(e))return ya(e.expressions.filter(P.isExpression).map(i=>pt(i,t,n)));if(P.isIdentifier(e))return{kind:"identifier",expression:e.name,base:e.name,path:[]};if(!P.isMemberExpression(e)&&!P.isOptionalMemberExpression(e))return null;let r=[],o=e;for(;P.isMemberExpression(o)||P.isOptionalMemberExpression(o);){if(o.computed)if(P.isNumericLiteral(o.property))r.unshift({kind:"index",index:o.property.value});else if(P.isStringLiteral(o.property))r.unshift({kind:"property",name:o.property.value});else if(n&&P.isExpression(o.property)){let i=fr(o.property,n);if(typeof i=="string")r.unshift({kind:"property",name:i});else if(Number.isInteger(i))r.unshift({kind:"index",index:i});else return null}else return null;else{if(!P.isIdentifier(o.property))return null;r.unshift({kind:"property",name:o.property.name})}o=o.object}return P.isIdentifier(o)?{kind:r.some(i=>i.kind==="index")?"index-expression":"member-expression",expression:mn(e,t),base:o.name,path:r}:null}function ya(e){let t=e.filter(r=>r!==null);if(t.length===0)return null;let n=t[0];return t.some(r=>r.base!==n.base||JSON.stringify(r.path)!==JSON.stringify(n.path))?null:{...n}}function Tu(e,t,n){if(P.isArrayExpression(e)){let r=e.elements[0];return e.elements.length===1&&P.isExpression(r)?pt(r,t,n):null}return P.isCallExpression(e)&&P.isMemberExpression(e.callee)&&!e.callee.computed&&P.isIdentifier(e.callee.property)&&["filter","slice","sort","toSorted","reverse","toReversed"].includes(e.callee.property.name)&&P.isExpression(e.callee.object)?Tu(e.callee.object,t,n):pt(e,t,n)}function fr(e,t){if(P.isStringLiteral(e)||P.isNumericLiteral(e)||P.isBooleanLiteral(e))return e.value;if(P.isNullLiteral(e))return null;if(P.isTemplateLiteral(e))return e.expressions.length===0&&e.quasis.length===1?e.quasis[0].value.cooked??e.quasis[0].value.raw:void 0;if(P.isIdentifier(e)){let n=_i(e.name,t.valueScopes);return n.kind==="resolved"?n.value:void 0}if(P.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||P.isSpreadElement(r))return;let o=fr(r,t);if(o===void 0)return;n.push(o)}return n}if(P.isObjectExpression(e)){let n={};for(let r of e.properties){if(!P.isObjectProperty(r)||r.computed||!P.isExpression(r.value))return;let o=null;if(P.isIdentifier(r.key)?o=r.key.name:P.isStringLiteral(r.key)&&(o=r.key.value),!o)return;let i;if(r.shorthand){if(!P.isIdentifier(r.value))return;let s=_i(r.value.name,t.valueScopes);if(s.kind!=="resolved")return;i=s.value}else i=fr(r.value,t);if(i===void 0)return;n[o]=i}return n}if(P.isMemberExpression(e)){let n=pt(e,"",t);if(!n)return;let r=_i(n.base,t.valueScopes);if(r.kind!=="resolved")return;let o=uh(r.value,n.path);return o.kind==="resolved"?o.value:void 0}if(P.isCallExpression(e))return fh(e,t)??void 0}function dh(e,t,n){let r=pt(e,n,t);if(!r)return P.isMemberExpression(e)||P.isBinaryExpression(e)||P.isLogicalExpression(e)||P.isConditionalExpression(e)||P.isCallExpression(e)?{value:mn(e,n),source:null}:null;let o=_i(r.base,t.valueScopes),i=r.kind==="identifier"?o:o.kind==="resolved"?uh(o.value,r.path):o;return i.kind==="resolved"&&(typeof i.value=="string"||typeof i.value=="number")?{value:String(i.value),source:r}:i.kind==="resolved"&&(typeof i.value=="boolean"||i.value===null)||i.kind==="known-empty"?null:{value:r.expression,source:r}}function _u(e,t,n,r,o,i){return{file:e,componentName:t,elements:n,regions:r,ordinalTracker:PR(),parentStack:[],valueScopes:i,importMap:o}}function Ru(e,t,n){for(let r of e)for(let o of r.declarations){for(let s of Hn(o.id))Au(n,s);if(!P.isIdentifier(o.id)||!o.init||!P.isExpression(o.init))continue;let i=fr(o.init,t);i!==void 0&&TR(n,o.id.name,i)}}function wR(e){let t=[];for(let n of e){if(P.isVariableDeclaration(n)){t.push(n);continue}P.isExportNamedDeclaration(n)&&n.declaration&&P.isVariableDeclaration(n.declaration)&&t.push(n.declaration)}return t}function OR(e,t,n){let r=[],o=0;for(let i of e)if(P.isJSXText(i)){let s=i.value.trim();s&&r.push({index:o++,value:s,sourceRange:Rt(i),editable:!0,source:null})}else if(P.isJSXExpressionContainer(i)&&P.isStringLiteral(i.expression))r.push({index:o++,value:i.expression.value,sourceRange:Rt(i),editable:!0,source:null});else if(P.isJSXExpressionContainer(i)&&P.isTemplateLiteral(i.expression)){let s=i.expression;s.expressions.length===0&&s.quasis.length===1?r.push({index:o++,value:s.quasis[0].value.cooked??s.quasis[0].value.raw,sourceRange:Rt(i),editable:!0,source:null}):r.push({index:o++,value:mn(s,n),sourceRange:Rt(i),editable:!0,source:pt(s,n,t)})}else if(P.isJSXExpressionContainer(i)&&P.isExpression(i.expression)){let s=dh(i.expression,t,n);s&&r.push({index:o++,value:s.value,sourceRange:Rt(i),editable:!0,source:s.source})}return r}function FR(e,t,n){let r=[];for(let[o,i]of e.attributes.entries()){if(!P.isJSXAttribute(i))continue;let s=MR(i.name);if(!s)continue;let a=mn(i,n);if(P.isStringLiteral(i.value)){r.push({name:s,value:i.value.value,sourceRange:Rt(i),source:null,syntaxKind:"literal",raw:a,order:o,resolution:{status:"resolved",value:i.value.value}});continue}if(i.value===null){r.push({name:s,value:"true",sourceRange:Rt(i),source:null,syntaxKind:"boolean-shorthand",raw:a,order:o,resolution:{status:"resolved",value:!0},resolvedValue:!0});continue}if(P.isJSXExpressionContainer(i.value)&&P.isExpression(i.value.expression)){let c=fr(i.value.expression,t);if(s==="className"){let g=typeof c=="string"?c:c===void 0?fh(i.value.expression,t):null;if(g){r.push({name:s,value:g,sourceRange:Rt(i),source:null,resolvedValue:g,syntaxKind:"expression",raw:a,order:o,resolution:{status:"resolved",value:g}});continue}}let l=dh(i.value.expression,t,n);if(c!==void 0){r.push({name:s,value:KR(c),sourceRange:Rt(i),source:pt(i.value.expression,n,t),resolvedValue:c,syntaxKind:"expression",raw:a,order:o,resolution:{status:"resolved",value:c}});continue}let u=DR(i.value.expression,t),d=pt(i.value.expression,n,t),f=l?.value??mn(i.value.expression,n);r.push({name:s,value:u.status==="undefined"?"undefined":f,sourceRange:Rt(i),source:l?.source??d,syntaxKind:"expression",raw:a,order:o,resolution:u})}}return r}function LR(e,t,n){return e.attributes.flatMap((r,o)=>!P.isJSXSpreadAttribute(r)||!P.isExpression(r.argument)?[]:[{raw:mn(r.argument,n),sourceRange:Rt(r),order:o,source:pt(r.argument,n,t)}])}function MR(e){return P.isJSXIdentifier(e)?e.name:P.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function DR(e,t){return Tn(e,{resolveIdentifier(n){let r=_i(n,t.valueScopes);return r.kind==="resolved"?{status:"resolved",value:r.value}:n==="undefined"&&!t.valueScopes.some(o=>o.has(n))?{status:"undefined"}:{status:"unresolved"}},resolveMember(n){let r=fr(n,t);return r===void 0?{status:"unresolved"}:{status:"resolved",value:r}}})}function fh(e,t){let n=No(e,t);return n&&n.map(o=>o.trim()).filter(Boolean).join(" ")||null}function No(e,t){if(P.isStringLiteral(e))return[e.value];if(P.isTemplateLiteral(e))return e.expressions.length>0?null:[e.quasis.map(n=>n.value.cooked??"").join("")];if(P.isNullLiteral(e))return[];if(P.isBooleanLiteral(e))return e.value?null:[];if(P.isIdentifier(e)||P.isMemberExpression(e)){if(P.isIdentifier(e)&&e.name==="undefined")return[];let n=fr(e,t);return typeof n=="string"?[n]:null}if(P.isConditionalExpression(e)){let n=No(e.consequent,t),r=No(e.alternate,t);return!n||!r?null:[...n,...r]}if(P.isLogicalExpression(e)){if(e.operator!=="&&")return null;let n=fr(e.left,t);return n===!1||n===null?[]:No(e.right,t)}if(P.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||P.isSpreadElement(r))return null;let o=No(r,t);if(!o)return null;n.push(...o)}return n}if(P.isObjectExpression(e)){let n=[];for(let r of e.properties){if(!P.isObjectProperty(r))return null;let o=jR(r.key);if(!o)return null;n.push(o)}return n}if(P.isCallExpression(e)){let n=BR(e.callee);if(!n||!["cn","clsx","twMerge"].includes(n))return null;let r=[];for(let o of e.arguments){if(!P.isExpression(o))return null;let i=No(o,t);if(!i)return null;r.push(...i)}return r}return null}function BR(e){return P.isIdentifier(e)?e.name:P.isMemberExpression(e)&&P.isIdentifier(e.property)?e.property.name:null}function jR(e){return P.isIdentifier(e)?e.name:P.isStringLiteral(e)?e.value:null}function $R(e,t){let n=e.attributes.find(r=>P.isJSXAttribute(r)&&P.isJSXIdentifier(r.name)&&r.name.name===t);return!n||!P.isJSXAttribute(n)||!P.isJSXExpressionContainer(n.value)?null:n.value.expression}function VR(e,t){for(let n of t){let r=$R(e,n);if(r)return r}return null}function UR(e){return P.isJSXIdentifier(e.name)?e.name.name:null}function KR(e){return e===null?"null":typeof e=="boolean"?e?"true":"false":JSON.stringify(e)}function JR(e){if(!P.isCallExpression(e)&&!P.isOptionalCallExpression(e))return null;let t=e.callee;return!P.isMemberExpression(t)&&!P.isOptionalMemberExpression(t)||!P.isIdentifier(t.property)||t.property.name!=="map"||t.computed||!P.isExpression(t.object)?null:{call:e,collection:t.object,callback:e.arguments[0]}}function Cu(e){return P.isArrowFunctionExpression(e)||P.isFunctionExpression(e)}function XR(e){return e==="render"||e==="itemRender"||e==="rowRender"||e==="children"}function zR(e){return e==="empty"||e==="emptyRender"||e==="loading"||e==="loadingRender"||e==="error"||e==="errorRender"||e==="fallback"||e==="headerRender"||e==="footerRender"}function ah(e,t,n,r){if(!e||!P.isExpression(e))return null;let o={kind:"repeat-template",collectionExpression:mn(e,n),collectionSource:Tu(e,n,r)};if(t){let i=t.params[0],s=t.params[1];P.isIdentifier(i)&&(o.itemParamName=i.name),P.isIdentifier(s)&&(o.indexParamName=s.name)}return o}function Wn(e,t,n){if(!e)return[];if(P.isJSXElement(e)){if(Pu(e))return Ia(e.children,t,n);let r=Ea(e,t,n);return r?[r]:[]}return Po(e)?Sa(e,t,n):P.isParenthesizedExpression(e)?Wn(e.expression,t,n):P.isExpression(e)?va(e,t,n):[]}function xa(e,t,n){let r=new Map;for(let o of e.params)for(let i of Hn(o))Au(r,i);t.valueScopes.push(r);try{if(!P.isBlockStatement(e.body))return Wn(e.body,t,n);let o=new Map;t.valueScopes.push(o);try{return ph(e.body.body,t,n)}finally{t.valueScopes.pop()}}finally{t.valueScopes.pop()}}function ph(e,t,n){let r=[];for(let o of e){if(P.isVariableDeclaration(o)){let i=t.valueScopes[t.valueScopes.length-1];if(i){Ru([o],t,i);for(let s of o.declarations)P.isIdentifier(s.id)&&(P.isJSXElement(s.init)||P.isJSXFragment(s.init))&&r.push(...Wn(s.init,t,n))}continue}r.push(...Nu(o,t,n))}return r}function Nu(e,t,n){if(P.isReturnStatement(e))return e.argument?Wn(e.argument,t,n):[];if(P.isBlockStatement(e))return to(e.body,t,n);if(P.isIfStatement(e)){let r=P.isBlockStatement(e.consequent)?to(e.consequent.body,t,n):Nu(e.consequent,t,n),o=e.alternate?P.isBlockStatement(e.alternate)?to(e.alternate.body,t,n):Nu(e.alternate,t,n):[];return[...r,...o]}if(P.isSwitchStatement(e))return to(e.cases.flatMap(r=>r.consequent),t,n);if(P.isTryStatement(e)){let r=to(e.block.body,t,n);return e.handler&&r.push(...to(e.handler.body.body,t,n)),e.finalizer&&r.push(...to(e.finalizer.body,t,n)),r}return[]}function to(e,t,n){let r=new Map;t.valueScopes.push(r);try{return ph(e,t,n)}finally{t.valueScopes.pop()}}function ba(e,t,n,r,o,i){o.length!==0&&e.regions.push({kind:t,ownerKey:n,childKeys:o,sourceRange:Rt(r),sourceCandidates:i&&i.length>0?i:void 0})}function HR(e,t,n,r){let o=VR(e.openingElement,["items","dataSource","data"]),i={key:t,tag:ch(e.openingElement)};n.parentStack.push(i);try{for(let s of e.openingElement.attributes){if(!P.isJSXAttribute(s))continue;let a=UR(s);if(!a||!P.isJSXExpressionContainer(s.value))continue;let c=s.value.expression;if(!P.isJSXEmptyExpression(c)){if(XR(a)&&Cu(c)){let l=xa(c,n,r),u=ah(o,c,r,n);ba(n,"repeat-region",t,s,l,u?[u]:void 0);continue}if(zR(a)){let l=Cu(c)?xa(c,n,r):Wn(c,n,r);ba(n,"conditional-region",t,s,l)}}}if(o)for(let s of e.children){if(!P.isJSXExpressionContainer(s)||!Cu(s.expression))continue;let a=xa(s.expression,n,r),c=ah(o,s.expression,r,n);ba(n,"repeat-region",t,s,a,c?[c]:void 0)}}finally{n.parentStack.pop()}}function Ea(e,t,n){let r=ch(e.openingElement);if(r==="Fragment"||Pu(e))return Ia(e.children,t,n),null;let o=t.parentStack[t.parentStack.length-1]??null,i=o?.key??null,s=CR(r),a;if(s){let E=t.ordinalTracker.getOrdinal(i,r);a=`component:${r}#${E}`}else{let E=t.ordinalTracker.getOrdinal(i,r);a=`${r}#${E}`}let c=o?t.elements.get(o.key)?.identity.structuralPath:void 0,l=c?`${c}/${a}`:a,u=Ei(t.file,t.componentName,l),d={file:t.file,component:t.componentName,structuralPath:l,key:u},f=s?"component-boundary":null,g=OR(e.children,t,n),p=FR(e.openingElement,t,n),m=LR(e.openingElement,t,n),y,x,S=!1;if(s){let E=t.importMap.get(r)??t.importMap.get(RR(r));E&&(y=E.specifier,x=E.exportName,S=Hr(E.specifier,t.file))}let b={identity:d,tag:r,componentName:t.componentName,sourceFile:t.file,sourceRange:Rt(e),parentKey:i,childKeys:[],textSegments:g,attributes:p.length>0?p:void 0,attributeSpreads:m.length>0?m:void 0,boundaryKind:f,isOpaque:s,...S?{isPublicUiComponent:!0}:{},importedFrom:y,exportName:x};return t.elements.set(u,b),i&&t.elements.has(i)&&t.elements.get(i).childKeys.push(u),HR(e,u,t,n),(!s||e.children.length>0)&&(t.parentStack.push({key:u,tag:r}),WR(e.children,t,n),t.parentStack.pop()),u}function Sa(e,t,n){return Ia(e.children,t,n)}function Ia(e,t,n){let r=[];for(let o of e)if(P.isJSXElement(o))if(Pu(o))r.push(...Ia(o.children,t,n));else{let i=Ea(o,t,n);i&&r.push(i)}else Po(o)?r.push(...Sa(o,t,n)):P.isJSXExpressionContainer(o)&&r.push(...va(o.expression,t,n));return r}function WR(e,t,n){for(let r of e)P.isJSXElement(r)?Ea(r,t,n):Po(r)?Sa(r,t,n):P.isJSXExpressionContainer(r)&&va(r.expression,t,n)}function GR(e){return e==="&&"||e==="||"||e==="??"}function va(e,t,n){if(P.isJSXEmptyExpression(e))return[];let r=JR(e);if(r){let o=r.call,i=t.parentStack[t.parentStack.length-1]??null,s=[],a=r.callback,c={kind:"repeat-template",collectionExpression:mn(r.collection,n),collectionSource:Tu(r.collection,n,t)};if(P.isArrowFunctionExpression(a)||P.isFunctionExpression(a)){let u=a.params[0],d=a.params[1];P.isIdentifier(u)&&(c.itemParamName=u.name),P.isIdentifier(d)&&(c.indexParamName=d.name)}s.push(c);let l={kind:"repeat-region",ownerKey:i?.key??"",childKeys:[],sourceRange:Rt(o),sourceCandidates:s.length>0?s:void 0};return t.regions.push(l),(P.isArrowFunctionExpression(a)||P.isFunctionExpression(a))&&l.childKeys.push(...xa(a,t,n)),l.childKeys}if(P.isConditionalExpression(e)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:mn(e.test,n),conditionSource:pt(e.test,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:Rt(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...Wn(e.consequent,t,n)),s.childKeys.push(...Wn(e.alternate,t,n)),s.childKeys}if(P.isLogicalExpression(e)&&GR(e.operator)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:mn(e.left,n),conditionSource:pt(e.left,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:Rt(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...Wn(e.right,t,n)),s.childKeys}if(P.isParenthesizedExpression(e))return va(e.expression,t,n);if(P.isJSXElement(e)){let o=Ea(e,t,n);return o?[o]:[]}return Po(e)?Sa(e,t,n):[]}function YR(e){let t=e.argument;return t&&(P.isExpression(t)||Po(t))?t:null}function Ci(e,t){let n=[];for(let r of e){if(P.isReturnStatement(r)){let o=YR(r);o&&n.push({argument:o,statement:r,condition:t});continue}if(P.isIfStatement(r)){let o=P.isBlockStatement(r.consequent)?r.consequent.body:[r.consequent];if(n.push(...Ci(o,r.test)),r.alternate){let i=P.isBlockStatement(r.alternate)?r.alternate.body:[r.alternate];n.push(...Ci(i,r.test))}continue}if(P.isSwitchStatement(r))for(let o of r.cases){let i=o.test?P.binaryExpression("===",r.discriminant,o.test):r.discriminant;n.push(...Ci(o.consequent,i))}}return n}function ka(e){return{routeId:e,rootKeys:[],elements:new Map,regions:[],fileIndex:new Map,version:1,diagnostics:[]}}function mh(e){let{file:t,source:n,ast:r}=e,o=e.imports.map(f=>f.specifier);if(!P.traverseFast(r,f=>{if(P.isJSXElement(f)||P.isJSXFragment(f))return P.traverseFast.stop}))return{graph:ka(t),localImports:o};let s=new Map,a=[],c=[],l=new Map,u=AR(r);_R(r,{"FunctionDeclaration|FunctionExpression|ArrowFunctionExpression"(f){let g=NR(f);if(!g)return;let p=f.node,m=[];if(P.isArrowFunctionExpression(p))P.isExpression(p.body)||Po(p.body)?m=[{argument:p.body,statement:P.returnStatement(P.isExpression(p.body)?p.body:null)}]:P.isBlockStatement(p.body)&&(m=Ci(p.body.body));else{let k=p.body;P.isBlockStatement(k)&&(m=Ci(k.body))}if(m.length===0){f.skip();return}let y=new Map;Ru(wR(r.program.body),_u(t,g,s,a,u,[y]),y);let x=new Map;for(let k of p.params)for(let I of Hn(k))Au(x,I);let S=P.isBlockStatement(p.body)?p.body.body:[],b=m[0]?.statement??null;for(let k of S){if(b&&k===b)break;P.isVariableDeclaration(k)&&Ru([k],_u(t,g,s,a,u,[y,x]),x)}let E=_u(t,g,s,a,u,[y,x]);for(let k of m){let I=Wn(k.argument,E,n);for(let v of I)c.includes(v)||c.push(v);if(k.condition){let v={kind:"conditional-branch",conditionExpression:mn(k.condition,n),conditionSource:pt(k.condition,n,E)};ba(E,"conditional-region","",k.statement,I,[v])}}f.skip()}});let d=[...s.keys()];return d.length>0&&l.set(t,d),{graph:{routeId:t,rootKeys:c,elements:s,regions:a,fileIndex:l,version:1,diagnostics:[]},localImports:o}}function wu(e,t,n,r){return[...e.map(o=>({...o})),{fromFile:t,specifier:n,targetPath:r}]}function _a(e,t,n){return{...e,details:{...e.details??{},entryFile:t,importStack:n.map(r=>({...r}))}}}async function gh(e,t){if(e.length===0)return[];if(e.length===1)return[await t(e[0])];let n=new Array(e.length),r=0,o=Array.from({length:Math.min(8,e.length)},async()=>{for(;r<e.length;){let s=r++;n[s]=await t(e[s])}}),i=await Promise.allSettled(o);for(let s of i)if(s.status==="rejected")throw s.reason;return n}async function Ca(e,t,n,r,o={}){let i=o.maxDepth??10,s=o.version??1,a=o.parseModule??je,c=new Map,l=new Map,u=new Map,d=[],f=new Set,g=x=>{let S=`${x.path}\0${x.code}\0${x.message}\0${JSON.stringify(x.details??{})}`;f.has(S)||(f.add(S),d.push(x))},p=[{file:e,source:t,depth:0,diagnosticEntryFile:e,importStack:[]},...(o.additionalEntries??[]).map(x=>({file:x.file,source:x.source,depth:0,diagnosticEntryFile:x.file,importStack:[]}))],m=new Set;for(;p.length>0;){let x=p.shift(),{file:S,source:b,depth:E,diagnosticEntryFile:k,importStack:I}=x;if(m.has(S))continue;m.add(S),c.set(S,b);let v=o.validationOnly&&E<i?o.validatedImports?.(S,b):void 0,N,A;if(v)N=ka(S),A=v;else{let $=a(S,b);if(!$.ok){g(_a($.diagnostic,k,I));continue}u.set(S,$.module);let G=o.validationOnly&&E<i?{graph:ka(S),localImports:$.module.imports.map(D=>D.specifier)}:mh($.module);N=G.graph,A=G.localImports}let w=[...new Set([...N.elements.values()].map($=>$.importedFrom).filter($=>typeof $=="string"&&nt($)))],F=w.length?await gh(w,$=>js(S,$,r)):[],B=new Map(w.map(($,G)=>[$,F[G]]));for(let $ of N.elements.values())if($.importedFrom&&nt($.importedFrom)){let G=$.importedFrom,D=B.get(G);D.ok?($.importedFrom=D.path,Kn(D.path)&&($.isPublicUiComponent=!0)):Hr(G,S)||g(_a(D.diagnostic,k,wu(I,S,G,D.diagnostic.path)))}if(l.set(S,N),E>=i)continue;let X=await gh(A,async $=>{if(Gm($))return null;let G=B.get($)??await js(S,$,r);if(!G.ok)return Hr($,S)?null:{diagnostic:_a(G.diagnostic,k,wu(I,S,$,G.diagnostic.path))};let D=G.path;if(m.has(D)||Kn(D))return null;let fe=wu(I,S,$,D);try{let Fe=await n(D);return{entry:{file:D,source:Fe,depth:E+1,diagnosticEntryFile:k,importStack:fe}}}catch(Fe){return{diagnostic:_a({path:D,code:"import-read-failed",message:`Failed to read imported file: ${D}`,details:{fromFile:S,specifier:$,reason:Fe instanceof Error?Fe.message:String(Fe)}},k,fe)}}});for(let $ of X)$&&"entry"in $?p.push($.entry):$&&g($.diagnostic)}let y=ZR(e,l,s,(o.additionalEntries??[]).map(x=>x.file));return y.diagnostics=d,{graph:y,allSources:c,diagnostics:d,parsedModules:u,entryModule:u.get(e)??null}}function ZR(e,t,n,r=[]){let o=new Map,i=[],s=new Map,a=[];for(let[c,l]of t){for(let[u,d]of l.elements)o.set(u,d);for(let u of l.regions)i.push(u);for(let[u,d]of l.fileIndex){let f=s.get(u)??[];s.set(u,[...f,...d])}if(c===e){a=l.rootKeys;continue}r.includes(c)&&(a=[...a,...l.rootKeys])}return{routeId:e,rootKeys:a,elements:o,regions:i,fileIndex:s,version:n}}function hh(e=256){if(!Number.isSafeInteger(e)||e<1)throw new RangeError("Validated syntax capacity must be positive.");let t=new Map;return{remember(n){for(let r of n)t.get(r.file)?.source!==r.source&&(t.delete(r.file),t.size>=e&&t.delete(t.keys().next().value),t.set(r.file,{source:r.source,imports:Object.freeze(r.imports.map(o=>o.specifier))}))},getImports(n,r){let o=t.get(n);return o?.source===r?o.imports:void 0},clear(){t.clear()}}}import{SiteEditHistoryProvenanceSchema as CN}from"@vcp-dev/contracts";import{createHash as qR,randomUUID as Uu}from"node:crypto";import et from"node:fs/promises";import rt from"node:path";var Ch=new WeakMap;function Ao(e){return Ch.get(e)?.()??e.readIndex()}var an=1,Fu=1,QR=2,eN="index.json",tN="recovery.json",nN="transaction-journal.json",rN="document-version.json",Pa={maxEntries:100,maxSessionBytes:512*1024*1024,maxEntryBytes:128*1024*1024},he={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"},xe=class extends Error{constructor(t,n,r){super(n),this.name="FileHistoryStoreError",this.code=t,r?.cause!==void 0&&(this.cause=r.cause)}};function Gn(){return{entries:new Map,blobSizes:new Map}}function Ra(e,t){let n={entries:new Map,blobs:new Map,objectBytes:0};for(let r of e)Rh(n,r,t);return n}function Rh(e,t,n){let r=e.entries.get(t);if(r){e.entries.set(t,{...r,references:r.references+1});return}let o=n.entries.get(t),i=new Map(o.entry.blobs.map(s=>[s.digest,n.blobSizes.get(s.digest)]));e.entries.set(t,{sizeBytes:o.sizeBytes,references:1,blobs:i}),e.objectBytes+=o.sizeBytes;for(let[s,a]of i){let c=e.blobs.get(s);e.blobs.set(s,{sizeBytes:a,references:(c?.references??0)+1}),c||(e.objectBytes+=a)}}function Nh(e,t){let n=e.entries.get(t);if(n.references>1){e.entries.set(t,{...n,references:n.references-1});return}e.entries.delete(t),e.objectBytes-=n.sizeBytes;for(let r of n.blobs.keys()){let o=e.blobs.get(r);o.references>1?e.blobs.set(r,{...o,references:o.references-1}):(e.blobs.delete(r),e.objectBytes-=o.sizeBytes)}}async function Ph(e,t={}){let n=EN(e),r=kN(t.limits),o=Ou(n),i=SN(n),s=await Mt(i),a=await Mt(o)||s;a||(await fN(n),await pN(n)),a||await _N(n);let c=Gn(),l=await Ta(n,c),u=new Set(a?(await Ma(n)).map(S=>S.stageId):[]);a||await Sh(n,l.entryIds,c);let d=l.digest,f=Ra(l.entryIds,c),g=async S=>{let{index:b,sizeBytes:E}=await Ti(n);if(Mh(b,S),b.digest!==d){let k=Gn();await Oh(n,b.entryIds,k,E),f=Ra(b.entryIds,k),d=b.digest}return{...Da(b),totalBytes:f.objectBytes+E}},p=async S=>{Ku(S),await g(),await bh(n,f,[S.entryId],S.blobIds,S.stageId),await Aa(n,S.stageId)},m=async(S,b)=>{let E=await g(b);Th(S,E.entryIds.length);let k=Gn();for(let I of E.entryIds.slice(Math.min(E.cursor,S)+1,Math.max(E.cursor,S)+1))await Ni(n,I,k);return E},y=async()=>{if(await Mt(o)||s)throw new xe(he.RECOVERY_PENDING,"history store requires explicit recovery before accepting writes")},x={rootDir:n,recoveryRequired:a,async readDocumentVersion(){return kh(n)},async writeDocumentVersion(S){if(await y(),!Number.isInteger(S)||S<0)throw new xe(he.INVALID_SCHEMA,"document version must be a non-negative integer");let b=await kh(n);S<=b||await Ri($h(n),{schemaVersion:1,version:Math.max(b,S)})},async stageAppend(S,b={}){await y();let E=await sN(S,r),k={schemaVersion:Fu,stageId:Uu(),entryId:E.entryId,blobIds:E.blobs.map(I=>I.digest)};try{await aN(n,E),await lN(n,k,b.durableManifest!==!1)}catch(I){try{await p(k)}catch(v){throw new xe(he.INDEX_CORRUPT,"staged history cleanup failed after preparation error",{cause:v})}throw I}return{stageId:k.stageId,entryId:k.entryId,blobIds:k.blobIds}},async discardStage(S){await y(),Du(S);let b=await Lu(n,S);b&&await p(b)},async previewStagedAppend(S,b){await y();let E=await g(b);return(await yh(n,r,S,E,f)).transition},async previewCursor(S,b){await y();let E=await m(S,b);return Ah(E,E.entryIds,S)},async publishStagedAppend(S,b,E){if(await y(),Oa(S,"entryId"),E){Du(E);let A=await Lu(n,E);if(!A||A.entryId!==S)throw new xe(he.INVALID_SCHEMA,"history stage does not match the published entry")}let k=await g(b),I=f,v=await yh(n,r,S,k,I),N=await vh({rootDir:n,previousDigest:v.current.digest,entryIds:v.entryIds,cursor:v.cursor,readback:async()=>Ih(n,v.usage),afterWrite:async()=>{E?await Aa(n,E):await dN(n,S),await bh(n,v.usage,[...I.entries.keys()].filter(A=>!v.usage.entries.has(A)),[...I.blobs.keys()].filter(A=>!v.usage.blobs.has(A)))}});return f=v.usage,d=N.digest,N},async append(S){await y();let b=await g(),E=await x.stageAppend(S);try{return await x.publishStagedAppend(E.entryId,b.digest,E.stageId)}catch(k){throw await x.discardStage(E.stageId),k}},async readEntry(S){return Oa(S,"entryId"),Ni(n,S)},async readBlob(S){Oa(S,"blobId");let b=await Uh(n,S),E=await Pi(b,he.NOT_FOUND,"blob");return jh(E,S,b),E},async readIndex(){let S=Gn(),b=await Ta(n,S);return f=Ra(b.entryIds,S),d=b.digest,b},async readStatus(){let S=await wa(n);return{canUndo:S.undoIds.length>0,canRedo:S.redoIds.length>0,undoDepth:S.undoIds.length,redoDepth:S.redoIds.length,cursor:S.cursor,recoveryRequired:await Mt(o)||await Mt(i)}},async readUndoRedoIds(){let S=await wa(n);return{undoIds:S.undoIds,redoIds:S.redoIds,currentId:S.currentId}},async setCursor(S,b){await y();let E=await m(S,b),k=await vh({rootDir:n,previousDigest:E.digest,entryIds:E.entryIds,cursor:S,readback:async()=>Ih(n,f)});return d=k.digest,k},async markRecoveryRequired(S){await Mt(o)||await Ri(Ou(n),{schemaVersion:an,reason:IN(S),createdAt:new Date().toISOString()})},async clearRecoveryRequired(){await et.rm(Ou(n),{force:!0})},async readTransactionJournal(){return await Mt(i)?Na(i):null},async writeTransactionJournal(S){await y(),Vh(S);try{await Ri(i,S)}catch(E){let k=await Na(i).catch(()=>null);if(k&&Buffer.from(Dt(k)).equals(Buffer.from(Dt(S))))return;throw k?new xe(he.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous",{cause:E}):E}let b=await Na(i);if(!Buffer.from(Dt(b)).equals(Buffer.from(Dt(S))))throw new xe(he.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous")},async clearTransactionJournal(S){let b=await Mt(i)?await Na(i):null;if(b&&b.transactionId!==S)throw new xe(he.INVALID_SCHEMA,"transaction journal changed concurrently");try{await et.rm(i,{force:!0})}catch(E){if(!await Mt(i))return;throw E}if(await Mt(i))throw new xe(he.INDEX_CORRUPT,"transaction journal clear outcome is ambiguous");s=!1},async cleanupTmp(){await y();for(let E of u)await Aa(n,E),u.delete(E);await mN(n);let S=Gn(),b=await Ta(n,S);await Sh(n,b.entryIds,S),f=Ra(b.entryIds,S),d=b.digest}};return Ch.set(x,()=>wa(n)),x}async function yh(e,t,n,r,o){Oa(n,"entryId");let i=Gn(),s=await Ni(e,n,i),a={entries:new Map(o.entries),blobs:new Map(o.blobs),objectBytes:o.objectBytes},c=r.entryIds.slice(0,r.cursor+1);for(let u of r.entryIds.slice(r.cursor+1))Nh(a,u);Rh(a,s.id,i),c.push(s.id);let l=cN(c,t,a);return{current:r,entryIds:l.entryIds,cursor:l.cursor,usage:a,transition:Ah(r,l.entryIds,l.cursor)}}function Ah(e,t,n){return Th(n,t.length),{expectedIndexDigest:e.digest,publishedIndexDigest:oN(t,n),publishedCursor:n,publishedCurrentId:t[n]??null}}function oN(e,t){return pr(Dt({schemaVersion:an,entryIds:e,cursor:t}))}function Th(e,t){if(!Number.isInteger(e)||e<-1||e>=t)throw new xe(he.INVALID_SCHEMA,`history cursor is out of bounds: ${e}`)}function iN(e){if(!gn(e))return!1;let t=e.publishedCursor,n=e.publishedCurrentId;return!Ut(e.expectedIndexDigest)||!Ut(e.publishedIndexDigest)||!Number.isInteger(t)||t<-1||n!==null&&!Ut(n)?!1:t===-1?n===null:Ut(n)}async function sN(e,t){if(!e.kind.trim())throw new xe(he.INVALID_JSON,"history entry kind must not be empty");let n=[],r=[];for(let c of e.blobs??[]){if(!c.name.trim())throw new xe(he.INVALID_JSON,"history blob name must not be empty");let l=bN(c.data),u=pr(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:an,kind:e.kind,manifest:e.manifest,blobs:r},i=Dt({...o}),s=pr(i),a=i.byteLength+n.reduce((c,l)=>c+l.sizeBytes,0);if(a>t.maxEntryBytes)throw new xe(he.CAPACITY_EXCEEDED,`history entry exceeds maxEntryBytes (${a} > ${t.maxEntryBytes})`);return{entryBody:o,entryId:s,blobs:n}}async function aN(e,t){let n=Hu(e,t.entryId),r={id:t.entryId,...t.entryBody},o=new Map(t.blobs.map(c=>[c.digest,c])),i=[...Array.from(o.values(),c=>xh(Wu(e,c.digest),c.bytes,{kind:"blob",digest:c.digest},Yu(e,c.digest))),xh(n,Dt(r),{kind:"entry",digest:t.entryId},Gu(e,t.entryId))],a=(await Promise.allSettled(i)).find(c=>c.status==="rejected");if(a)throw a.reason}async function xh(e,t,n,r){let o=await $u(e)??(r?await $u(r):null);if(o!==null){if(Buffer.compare(o,t)!==0)throw new xe(n.kind==="blob"?he.BLOB_CORRUPT:he.ENTRY_CORRUPT,`${n.kind} content mismatch for ${n.digest}`);return}await Dh(e,t)}function cN(e,t,n){let r=[...e],o=r.length-1;for(;;){if(n.objectBytes+Dt(Lh(r,o)).byteLength<=t.maxSessionBytes&&r.length<=t.maxEntries)return{entryIds:r,cursor:o};if(o<=0||r.length===0)throw new xe(he.CAPACITY_EXCEEDED,"history store exceeds capacity limits and the current entry cannot be trimmed");Nh(n,r.shift()),o-=1}}async function lN(e,t,n){Ku(t);let r=zu(e,t.stageId);if(n){await Ri(r,t);return}await xN(r,t)}async function Lu(e,t){let n=await $u(zu(e,t));if(n===null)return null;let r=wi(Buffer.from(n).toString("utf8"),`history stage ${t}`),o=Ku(r);if(o.stageId!==t)throw new xe(he.INVALID_SCHEMA,`history stage id mismatch: ${t}`);return o}async function Ma(e){let t=[];for(let n of await La(Xu(e))){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);Du(r);let o=await Lu(e,r);o&&t.push(o)}return t}async function bh(e,t,n,r,o){if(n.length===0&&r.length===0)return;let i=new Set(t.entries.keys()),s=new Set;for(let a of await Ma(e))if(a.stageId!==o){i.add(a.entryId);for(let c of a.blobIds)s.add(c)}for(let a of new Set(n))i.has(a)||await Eh(Hu(e,a),Gu(e,a));for(let a of new Set(r))!t.blobs.has(a)&&!s.has(a)&&await Eh(Wu(e,a),Yu(e,a));await Vu(Oi(e)),await Vu(Fi(e))}async function Aa(e,t){await Mu(zu(e,t)),await uN(e)}async function uN(e){try{await et.rmdir(Xu(e))}catch(t){if(Li(t)||gn(t)&&t.code==="ENOTEMPTY")return;throw t}}async function dN(e,t){for(let n of await Ma(e))n.entryId===t&&await Aa(e,n.stageId)}async function Mu(e){if(await et.rm(e,{force:!0}),await Mt(e))throw new xe(he.INDEX_CORRUPT,`unable to remove staged history object: ${e}`)}async function Eh(e,t){await Mu(e),await Mu(t)}function Ku(e){if(!gn(e)||e.schemaVersion!==Fu||typeof e.stageId!="string"||!wh(e.stageId)||!Ut(e.entryId))throw new xe(he.INVALID_SCHEMA,"history stage schema is invalid");let t=Bh(e.blobIds,"history stage blobIds");return{schemaVersion:Fu,stageId:e.stageId,entryId:e.entryId,blobIds:t}}function Du(e){if(!wh(e))throw new xe(he.INVALID_PATH,"history stageId must be a UUID")}function wh(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 Sh(e,t,n=Gn()){let r=new Set(t),o=new Set;for(let l of t){let u=await Ni(e,l,n);for(let d of u.blobs)o.add(d.digest)}for(let l of await Ma(e)){r.add(l.entryId);for(let u of l.blobIds)o.add(u)}let i=Oi(e),s=await La(i);for(let l of s){if(!l.endsWith(".json"))continue;let u=_h(l.slice(0,-5));u&&!r.has(u)&&await Fa(rt.join(i,l))}let a=Fi(e),c=await La(a);for(let l of c){let u=_h(l);u&&!o.has(u)&&await Fa(rt.join(a,l))}}async function Ta(e,t=Gn()){let{index:n,sizeBytes:r}=await Ti(e),{totalBytes:o}=await Oh(e,n.entryIds,t,r);return{...Da(n),totalBytes:o}}async function Ih(e,t){let{index:n,sizeBytes:r}=await Ti(e);return{...Da(n),totalBytes:t.objectBytes+r}}async function Ti(e){let t=Ju(e),n=await Pi(t,he.NOT_FOUND,"index"),r=wi(Buffer.from(n).toString("utf8"),"index");return{index:gN(r),sizeBytes:n.byteLength}}async function wa(e){return Da((await Ti(e)).index)}function Da(e){let t=[...e.entryIds],n=t.slice(0,e.cursor+1).reverse(),r=t.slice(e.cursor+1);return{schemaVersion:an,digest:e.digest,entryIds:t,cursor:e.cursor,currentId:t[e.cursor]??null,undoIds:n,redoIds:r}}async function Oh(e,t,n,r){let o=0,i=new Set;o+=r??(await Ti(e)).sizeBytes;for(let s of new Set(t)){let a=await Ni(e,s,n);o+=n.entries.get(s).sizeBytes;for(let c of a.blobs)i.has(c.digest)||(i.add(c.digest),o+=n.blobSizes.get(c.digest))}return{totalBytes:o}}async function Ni(e,t,n=Gn()){let r=n.entries.get(t);if(r)return r.entry;let o=await vN(e,t),i=await Pi(o,he.NOT_FOUND,"entry"),s=wi(Buffer.from(i).toString("utf8"),`entry ${t}`),a=hN(s);if(a.id!==t)throw new xe(he.ENTRY_CORRUPT,`entry id mismatch for ${t}`);if(pr(Dt({schemaVersion:a.schemaVersion,kind:a.kind,manifest:a.manifest,blobs:a.blobs}))!==t)throw new xe(he.ENTRY_CORRUPT,`entry hash mismatch for ${t}`);let l=[...new Set(a.blobs.map(d=>d.digest))].filter(d=>!n.blobSizes.has(d)),u=async d=>{let f=await Uh(e,d),g=await Pi(f,he.NOT_FOUND,"blob");return jh(g,d,f),g.byteLength};if(l.length===1)n.blobSizes.set(l[0],await u(l[0]));else if(l.length>1){let d=new Array(l.length),f=[],g=0,p=Array.from({length:Math.min(4,l.length)},async()=>{for(;g<l.length&&f.length===0;){let x=g++;try{d[x]=await u(l[x])}catch(S){f.push({index:x,error:S})}}}),m=await Promise.allSettled(p),y=f.sort((x,S)=>x.index-S.index)[0];if(y)throw y.error;for(let x of m)if(x.status==="rejected")throw x.reason;for(let x=0;x<l.length;x++)n.blobSizes.set(l[x],d[x])}return n.entries.set(t,{entry:a,sizeBytes:i.byteLength}),a}async function Fh(e,t,n){await Ri(Ju(e),Lh(t,n))}function Lh(e,t){return{schemaVersion:an,digest:pr(Dt({schemaVersion:an,entryIds:e,cursor:t})),entryIds:e,cursor:t}}function Mh(e,t){if(t!==void 0&&e.digest!==t)throw new xe(he.INVALID_SCHEMA,`history index changed concurrently (expected ${t}, current ${e.digest})`)}async function vh(e){Mh(await wa(e.rootDir),e.previousDigest);let t=pr(Dt({schemaVersion:an,entryIds:e.entryIds,cursor:e.cursor}));try{await Fh(e.rootDir,e.entryIds,e.cursor),await e.afterWrite?.();let n=await e.readback();if(n.digest!==t)throw new xe(he.INDEX_CORRUPT,"history index readback did not match the published transition");return n}catch(n){let r=await Ta(e.rootDir).catch(()=>null);if(r?.digest===t)return r;throw r?.digest===e.previousDigest?n:new xe(he.INDEX_CORRUPT,"history index publish outcome is ambiguous",{cause:n})}}async function fN(e){await et.mkdir(e,{recursive:!0}),await et.mkdir(Oi(e),{recursive:!0}),await et.mkdir(Fi(e),{recursive:!0}),await et.mkdir(Ai(e),{recursive:!0})}async function pN(e){await et.rm(Ai(e),{recursive:!0,force:!0}),await et.mkdir(Ai(e),{recursive:!0})}async function mN(e){let t=Ai(e);await et.mkdir(t,{recursive:!0});for(let n of await La(t))n!=="stages"&&await et.rm(rt.join(t,n),{recursive:!0,force:!0})}function gN(e){if(!gn(e))throw new xe(he.INDEX_CORRUPT,"index.json must be an object");if(e.schemaVersion!==an)throw new xe(he.INVALID_SCHEMA,`unsupported index schemaVersion: ${String(e.schemaVersion)}`);let t=Bh(e.entryIds,"index.entryIds"),n=e.cursor;if(!Number.isInteger(n)||n<-1||n>=t.length)throw new xe(he.INDEX_CORRUPT,"index cursor is out of bounds");let r=n,o=e.digest;if(!Ut(o))throw new xe(he.INDEX_CORRUPT,"index digest is invalid");let i=pr(Dt({schemaVersion:an,entryIds:t,cursor:r}));if(o!==i)throw new xe(he.INDEX_CORRUPT,"index digest mismatch");return{schemaVersion:an,digest:o,entryIds:t,cursor:r}}function hN(e){if(!gn(e))throw new xe(he.ENTRY_CORRUPT,"entry must be an object");if(e.schemaVersion!==an)throw new xe(he.INVALID_SCHEMA,`unsupported entry schemaVersion: ${String(e.schemaVersion)}`);let t=e.id;if(!Ut(t))throw new xe(he.ENTRY_CORRUPT,"entry id is invalid");let n=e.kind;if(typeof n!="string"||n.trim().length===0)throw new xe(he.ENTRY_CORRUPT,"entry kind is invalid");let r=ju(e.manifest,"entry.manifest"),o=yN(e.blobs);return{id:t,schemaVersion:an,kind:n,manifest:r,blobs:o}}function yN(e){if(!Array.isArray(e))throw new xe(he.ENTRY_CORRUPT,"entry blobs must be an array");return e.map((t,n)=>{if(!gn(t))throw new xe(he.ENTRY_CORRUPT,`entry blob ref ${n} must be an object`);let r=t.name;if(typeof r!="string"||r.trim().length===0)throw new xe(he.ENTRY_CORRUPT,`entry blob ref ${n} name is invalid`);let o=t.digest;if(!Ut(o))throw new xe(he.ENTRY_CORRUPT,`entry blob ref ${n} digest is invalid`);let i=t.sizeBytes;if(!Number.isInteger(i)||i<0)throw new xe(he.ENTRY_CORRUPT,`entry blob ref ${n} sizeBytes is invalid`);return{name:r,digest:o,sizeBytes:i}})}async function Ri(e,t){await Dh(e,Dt(t))}async function xN(e,t){let n=rt.dirname(e),r=rt.basename(e),o=rt.join(n,`.${r}.${process.pid}.${Uu()}.tmp`);await et.mkdir(n,{recursive:!0});try{await et.writeFile(o,Dt(t),{flag:"wx"}),await et.rename(o,e)}finally{await Fa(o)}}async function Dh(e,t){let n=rt.dirname(e),r=rt.basename(e),o=rt.join(n,`.${r}.${process.pid}.${Uu()}.tmp`);await et.mkdir(n,{recursive:!0});try{let i=await et.open(o,"wx");try{await i.writeFile(t),await i.sync()}finally{await i.close()}await et.rename(o,e),await Vu(n)}finally{await Fa(o)}}function Dt(e){return Buffer.from(JSON.stringify(Bu(e)),"utf8")}function Bu(e){if(Array.isArray(e))return e.map(t=>Bu(t));if(gn(e)){let t={};for(let n of Object.keys(e).sort())t[n]=Bu(e[n]);return t}return e}function wi(e,t){try{return JSON.parse(e)}catch(n){throw new xe(he.INVALID_JSON,`${t} is not valid JSON`,{cause:n})}}function ju(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=>ju(n,t));if(gn(e)){let n={};for(let[r,o]of Object.entries(e))n[r]=ju(o,t);return n}break}throw new xe(he.INVALID_JSON,`${t} must be JSON-serializable`)}function Bh(e,t){if(!Array.isArray(e))throw new xe(he.INDEX_CORRUPT,`${t} must be an array`);return e.map((n,r)=>{if(!Ut(n))throw new xe(he.INDEX_CORRUPT,`${t}[${r}] is invalid`);return n})}function Oa(e,t){if(!Ut(e))throw new xe(he.INVALID_PATH,`${t} must be a sha256 digest`)}function Ut(e){return typeof e=="string"&&/^sha256:[a-f0-9]{64}$/u.test(e)}function pr(e){return`sha256:${qR("sha256").update(e).digest("hex")}`}function bN(e){return typeof e=="string"?Buffer.from(e,"utf8"):Buffer.from(e)}async function Pi(e,t,n){try{return await et.readFile(e)}catch(r){throw new xe(t,`${n} not found: ${e}`,{cause:r})}}async function $u(e){try{return await et.readFile(e)}catch(t){if(Li(t))return null;throw t}}function jh(e,t,n){if(pr(e)!==t)throw new xe(he.BLOB_CORRUPT,`blob hash mismatch for ${n}`)}async function Mt(e){try{return await et.access(e),!0}catch(t){if(Li(t))return!1;throw t}}async function Fa(e){try{await et.rm(e,{force:!0,recursive:!0})}catch{}}async function Vu(e){try{let t=await et.open(e,"r");try{await t.sync()}finally{await t.close()}}catch{}}async function La(e){try{return await et.readdir(e)}catch(t){if(Li(t))return[];throw t}}function EN(e){if(typeof e!="string"||e.trim().length===0)throw new xe(he.INVALID_ROOT,"history store rootDir must be a non-empty string");return rt.resolve(e)}function Ju(e){return rt.join(e,eN)}function Ou(e){return rt.join(e,tN)}function SN(e){return rt.join(e,nN)}function $h(e){return rt.join(e,rN)}async function kh(e){try{let t=await et.readFile($h(e),"utf8"),n=wi(t,"document version");if(!gn(n)||n.schemaVersion!==1||!Number.isInteger(n.version)||n.version<0)throw new xe(he.INVALID_SCHEMA,"document version schema is invalid");return n.version}catch(t){if(Li(t))return 0;throw t}}async function Na(e){let t=await Pi(e,he.RECOVERY_PENDING,"transaction journal"),n=wi(Buffer.from(t).toString("utf8"),"transaction journal");return Vh(n),n}function Vh(e){if(!gn(e)||e.schemaVersion!==QR||typeof e.transactionId!="string"||e.transactionId.length===0||typeof e.operationId!="string"||e.operationId.length===0||!["prepared","files-written","history-published"].includes(e.phase)||!iN(e.historyTransition)||!Array.isArray(e.files))throw new xe(he.INVALID_SCHEMA,"transaction journal schema is invalid");for(let t of e.files)if(!gn(t)||typeof t.path!="string"||t.path.length===0||t.preDigest!==null&&!Ut(t.preDigest)||t.postDigest!==null&&!Ut(t.postDigest))throw new xe(he.INVALID_SCHEMA,"transaction journal file digest is invalid")}function IN(e){return e.replace(/[\r\n]+/g," ").slice(0,512)}function Oi(e){return rt.join(e,"entries")}function Fi(e){return rt.join(e,"blobs")}function Ai(e){return rt.join(e,"tmp")}function Xu(e){return rt.join(Ai(e),"stages")}function zu(e,t){return rt.join(Xu(e),`${t}.json`)}function Hu(e,t){return rt.join(Oi(e),`${Jh(t)}.json`)}function Wu(e,t){return rt.join(Fi(e),Jh(t))}function Gu(e,t){return rt.join(Oi(e),`${t}.json`)}function Yu(e,t){return rt.join(Fi(e),t)}async function vN(e,t){return Kh(Hu(e,t),Gu(e,t))}async function Uh(e,t){return Kh(Wu(e,t),Yu(e,t))}async function Kh(e,t){return await Mt(e)?e:await Mt(t)?t:e}function Jh(e){return e.slice(7)}function _h(e){let t=e.startsWith("sha256:")?e:`sha256:${e}`;return Ut(t)?t:null}function gn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Li(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function kN(e){return{maxEntries:e?.maxEntries??Pa.maxEntries,maxSessionBytes:e?.maxSessionBytes??Pa.maxSessionBytes,maxEntryBytes:e?.maxEntryBytes??Pa.maxEntryBytes}}async function _N(e){let t=Ju(e);await Mt(t)||await Fh(e,[],-1)}var RN={affectedCompositions:[]};function Gh(e){let t=null,n=new WeakMap;async function r(){return t??=NN(e),t}async function o(i){if(!i)return null;let s=Zu(i);return s?PN(e,s):i}return{async prepareAppend(i){let s=await Ao(e),a=await e.stageAppend(Hh(i),{durableManifest:!1}),c;try{c=await e.previewStagedAppend(a.entryId,s.digest)}catch(u){throw await e.discardStage(a.stageId),u}let l={kind:"append",entry:i,historyTransition:c};return n.set(l,{expectedDigest:s.digest,stageId:a.stageId,entryId:a.entryId}),l},async prepareUndo(){let i=await r(),s=await o(i.undo.at(-1));if(!s?.historyId)return null;let a=await Ao(e),c=a.entryIds.indexOf(s.historyId);if(c<0)throw new Error("undo entry is missing from index");if(c!==a.cursor)throw new Error("undo state changed before prepare");let l=c-1,u=await e.previewCursor(l,a.digest),d={kind:"undo",entry:s,historyTransition:u};return n.set(d,{expectedDigest:a.digest,cursor:l}),d},async prepareRedo(){let i=await r(),s=await o(i.redo.at(-1));if(!s?.historyId)return null;let a=await Ao(e),c=a.entryIds.indexOf(s.historyId);if(c<0)throw new Error("redo entry is missing from index");if(c!==a.cursor+1)throw new Error("redo state changed before prepare");let l=c,u=await e.previewCursor(l,a.digest),d={kind:"redo",entry:s,historyTransition:u};return n.set(d,{expectedDigest:a.digest,cursor:l}),d},async publishPrepared(i){let s=n.get(i);if(!s)throw new Error("history mutation was not prepared");let a=await r();if(i.kind==="append"){if(!s.entryId)throw new Error("staged entry id is missing");let c=await e.publishStagedAppend(s.entryId,s.expectedDigest,s.stageId);Xh(c,i.historyTransition),i.entry.historyId=s.entryId,Object.assign(a,To(c))}else{if(s.cursor===void 0)throw new Error("prepared cursor is missing");let c=i.kind==="undo"?a.undo:a.redo;if(Zu(c.at(-1))!==Zu(i.entry))throw new Error("history state changed before publish");let l=await e.setCursor(s.cursor,s.expectedDigest);Xh(l,i.historyTransition),Object.assign(a,To(l))}n.delete(i)},async discardPrepared(i){let s=n.get(i);if(!s)return;let a=i.historyTransition;if(a){let c=await Ao(e);if(c.digest===a.publishedIndexDigest&&c.cursor===a.publishedCursor&&c.currentId===a.publishedCurrentId)throw new Error("cannot discard a history mutation whose index was published")}s.stageId&&await e.discardStage(s.stageId),n.delete(i)},async peekUndo(){return o((await r()).undo.at(-1))},async pushUndo(i){let s=await r(),a=i;if(a.historyId){let u=s.entryIds.indexOf(a.historyId);if(u>=0)try{let d=await e.setCursor(u);Object.assign(s,To(d));return}catch(d){throw s.redo.push(i),d}}let c=await e.append(Hh(i)),l=c.currentId;if(!l)throw new Error("history store did not publish an entry");i.historyId=l,Object.assign(s,To(c))},async popUndo(){let i=await r(),s=await o(i.undo.at(-1));return i.undo.pop(),s},async peekRedo(){return o((await r()).redo.at(-1))},async pushRedo(i){let s=await r(),a=i;if(!a.historyId)throw s.undo.push(i),new Error("cannot move an unpersisted history entry to redo");let c=s.entryIds.indexOf(a.historyId);if(c<0)throw s.undo.push(i),new Error("history entry is missing from the durable index");try{let l=await e.setCursor(c-1);Object.assign(s,To(l))}catch(l){throw s.undo.push(i),l}},async popRedo(){let i=await r(),s=await o(i.redo.at(-1));return i.redo.pop(),s},async clearRedo(){(await r()).redo.length=0},async getStatus(){let i=await e.readStatus();return{canUndo:i.canUndo,canRedo:i.canRedo,undoDepth:i.undoDepth,redoDepth:i.redoDepth,recoveryRequired:i.recoveryRequired}},async markRecoveryRequired(i){await e.markRecoveryRequired(i)}}}function Xh(e,t){if(!t)throw new Error("durable history transition is missing");if(e.digest!==t.publishedIndexDigest||e.cursor!==t.publishedCursor||e.currentId!==t.publishedCurrentId)throw new Error("durable history published an unexpected index state")}function Zu(e){return typeof e=="string"?e:e?.historyId}async function NN(e){let t=await Ao(e);return To(t)}function To(e){return{undo:[...e.undoIds].reverse(),redo:[...e.redoIds].reverse(),entryIds:[...e.entryIds],cursor:e.cursor}}async function PN(e,t){let n=await e.readEntry(t),r=AN(n),o=r.provenance??RN;return{historyId:t,...o.initiatingComposition?{composition:o.initiatingComposition}:{},operationId:r.operationId,kind:r.kind,target:r.target,provenance:o,...r.selectionRef?{selectionRef:r.selectionRef}:{},...r.output?{output:r.output}:{},preSnapshots:await zh(e,n,r.preSnapshots),postSnapshots:await zh(e,n,r.postSnapshots)}}async function zh(e,t,n){let r=new Map(t.blobs.map(o=>[o.name,o.digest]));return Promise.all(n.map(async o=>{let i=o.exists&&o.blobName?Buffer.from(await e.readBlob(ON(r,o.blobName))).toString("utf8"):"";return{file:o.file,content:i,version:o.version,exists:o.exists,...o.sha256?{sha256:o.sha256}:{}}}))}function Hh(e){let t=[],n=(i,s)=>i.map((a,c)=>{let l={file:a.file,exists:a.exists!==!1,version:a.version,...a.sha256?{sha256:a.sha256}:{}};if(l.exists){let u=`${s}-${c}`;l.blobName=u,t.push({name:u,data:a.content})}return l}),r=TN(e),o={operationId:e.operationId,kind:e.kind,target:e.target,...r?{provenance:r}:{},...e.selectionRef?{selectionRef:e.selectionRef}:{},...e.output?{output:e.output}:{},preSnapshots:n(e.preSnapshots,"pre"),postSnapshots:n(e.postSnapshots,"post")};return{kind:"site-edit-operation",manifest:JSON.parse(JSON.stringify(o)),blobs:t}}function AN(e){if(!Zh(e.manifest))throw new Error("durable history manifest is not an object");let t=e.manifest,n=new Set(["operationId","kind","target","selectionRef","output","provenance","preSnapshots","postSnapshots"]);if(Object.keys(t).some(r=>!n.has(r)))throw new Error("durable history manifest contains unknown fields");if(typeof t.operationId!="string"||t.operationId.length===0||typeof t.kind!="string"||t.kind.length===0||!Array.isArray(t.preSnapshots)||!Array.isArray(t.postSnapshots))throw new Error("durable history manifest has an invalid shape");return{operationId:t.operationId,kind:t.kind,target:t.target,...t.selectionRef!==void 0?{selectionRef:t.selectionRef}:{},...t.output!==void 0?{output:t.output}:{},...t.provenance!==void 0?{provenance:Yh(t.provenance)}:{},preSnapshots:Wh(t.preSnapshots,"preSnapshots"),postSnapshots:Wh(t.postSnapshots,"postSnapshots")}}function TN(e){if(e.provenance!==void 0)return Yh(e.provenance);if(e.composition)return{initiatingComposition:e.composition,affectedCompositions:[]}}function Yh(e){let t=CN.safeParse(e);if(!t.success)throw new Error("durable history provenance is invalid");return{...t.data.initiatingComposition?{initiatingComposition:t.data.initiatingComposition}:{},affectedCompositions:t.data.affectedCompositions.map(n=>({routeId:n.routeId,...n.effectiveTemplateId?{effectiveTemplateId:n.effectiveTemplateId}:{}}))}}function Wh(e,t){return e.map((n,r)=>{if(!Zh(n))throw new Error(`durable history ${t}[${r}] is invalid`);if(typeof n.file!="string"||n.file.length===0||!Number.isInteger(n.version)||n.exists!==void 0&&typeof n.exists!="boolean"||n.sha256!==void 0&&!wN(n.sha256)||n.blobName!==void 0&&typeof n.blobName!="string")throw new Error(`durable history ${t}[${r}] is invalid`);return{file:n.file,exists:n.exists!==!1,version:n.version,...n.sha256?{sha256:n.sha256}:{},...n.blobName?{blobName:n.blobName}:{}}})}function wN(e){return/^sha256:[0-9a-f]{64}$/.test(e)}function ON(e,t){let n=e.get(t);if(!n)throw new Error(`durable history blob is missing: ${t}`);return n}function Zh(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{GeneratedSiteCapabilitiesSchema as FN}from"@vcp-dev/contracts";var qh={schema_version:1,policy_version:"starter-capabilities-v1",source:{starter_package_path:"templates/next-starter/package.json",components_catalog_path:"templates/next-starter/components.catalog.json",package_name:"vcp-next-starter",package_version:"0.0.0"},runtime_dependencies:[{name:"@gsap/react",version:"2.1.2"},{name:"@hookform/resolvers",version:"3.10.0"},{name:"@opennextjs/cloudflare",version:"1.19.11"},{name:"@radix-ui/react-accordion",version:"1.2.12"},{name:"@radix-ui/react-alert-dialog",version:"1.1.15"},{name:"@radix-ui/react-aspect-ratio",version:"1.1.8"},{name:"@radix-ui/react-avatar",version:"1.1.11"},{name:"@radix-ui/react-checkbox",version:"1.3.3"},{name:"@radix-ui/react-collapsible",version:"1.1.12"},{name:"@radix-ui/react-context-menu",version:"2.2.16"},{name:"@radix-ui/react-dialog",version:"1.1.15"},{name:"@radix-ui/react-dropdown-menu",version:"2.1.16"},{name:"@radix-ui/react-hover-card",version:"1.1.15"},{name:"@radix-ui/react-label",version:"2.1.8"},{name:"@radix-ui/react-menubar",version:"1.1.16"},{name:"@radix-ui/react-navigation-menu",version:"1.2.14"},{name:"@radix-ui/react-popover",version:"1.1.15"},{name:"@radix-ui/react-progress",version:"1.1.8"},{name:"@radix-ui/react-radio-group",version:"1.3.8"},{name:"@radix-ui/react-scroll-area",version:"1.2.10"},{name:"@radix-ui/react-select",version:"2.2.6"},{name:"@radix-ui/react-separator",version:"1.1.8"},{name:"@radix-ui/react-slider",version:"1.3.6"},{name:"@radix-ui/react-slot",version:"1.2.3"},{name:"@radix-ui/react-switch",version:"1.2.6"},{name:"@radix-ui/react-tabs",version:"1.1.13"},{name:"@radix-ui/react-toggle",version:"1.1.10"},{name:"@radix-ui/react-toggle-group",version:"1.1.11"},{name:"@radix-ui/react-tooltip",version:"1.2.8"},{name:"class-variance-authority",version:"0.7.1"},{name:"clsx",version:"2.1.1"},{name:"cmdk",version:"1.1.1"},{name:"date-fns",version:"4.3.0"},{name:"embla-carousel-react",version:"8.6.0"},{name:"gsap",version:"3.15.0"},{name:"i18next",version:"26.3.0"},{name:"input-otp",version:"1.4.2"},{name:"lucide-react",version:"0.525.0"},{name:"motion",version:"12.40.0"},{name:"next",version:"16.3.4"},{name:"react",version:"19.2.6"},{name:"react-day-picker",version:"9.14.0"},{name:"react-dom",version:"19.2.6"},{name:"react-hook-form",version:"7.76.1"},{name:"react-i18next",version:"17.0.8"},{name:"recharts",version:"2.15.4"},{name:"sonner",version:"2.0.7"},{name:"tailwind-merge",version:"3.6.0"},{name:"vaul",version:"1.1.2"},{name:"zod",version:"3.25.76"}],catalog_dependencies:["@hookform/resolvers","@radix-ui/react-accordion","@radix-ui/react-alert-dialog","@radix-ui/react-aspect-ratio","@radix-ui/react-avatar","@radix-ui/react-checkbox","@radix-ui/react-collapsible","@radix-ui/react-context-menu","@radix-ui/react-dialog","@radix-ui/react-dropdown-menu","@radix-ui/react-hover-card","@radix-ui/react-label","@radix-ui/react-menubar","@radix-ui/react-navigation-menu","@radix-ui/react-popover","@radix-ui/react-progress","@radix-ui/react-radio-group","@radix-ui/react-scroll-area","@radix-ui/react-select","@radix-ui/react-separator","@radix-ui/react-slider","@radix-ui/react-slot","@radix-ui/react-switch","@radix-ui/react-tabs","@radix-ui/react-toggle","@radix-ui/react-toggle-group","@radix-ui/react-tooltip","class-variance-authority","clsx","cmdk","date-fns","embla-carousel-react","input-otp","lucide-react","motion","react-day-picker","react-hook-form","recharts","sonner","tailwind-merge","vaul","zod"],public_paths:["components.json","components/site/generated/*","components/ui/*","components/ui/accordion.tsx","components/ui/alert-dialog.tsx","components/ui/alert.tsx","components/ui/aspect-ratio.tsx","components/ui/avatar.tsx","components/ui/badge.tsx","components/ui/border-beam.tsx","components/ui/breadcrumb.tsx","components/ui/button-group.tsx","components/ui/button.tsx","components/ui/calendar.tsx","components/ui/callout.tsx","components/ui/card.tsx","components/ui/carousel.tsx","components/ui/chart.tsx","components/ui/checkbox.tsx","components/ui/code-block.tsx","components/ui/collapsible.tsx","components/ui/command.tsx","components/ui/composite-carousel.tsx","components/ui/context-menu.tsx","components/ui/dialog.tsx","components/ui/drawer.tsx","components/ui/dropdown-menu.tsx","components/ui/empty.tsx","components/ui/field.tsx","components/ui/form.tsx","components/ui/hover-card.tsx","components/ui/input-group.tsx","components/ui/input-otp.tsx","components/ui/input.tsx","components/ui/item.tsx","components/ui/kbd.tsx","components/ui/label.tsx","components/ui/magic-card.tsx","components/ui/marquee.tsx","components/ui/menubar.tsx","components/ui/multi-step-form.tsx","components/ui/navigation-menu.tsx","components/ui/number-ticker.tsx","components/ui/pagination.tsx","components/ui/popover.tsx","components/ui/progress.tsx","components/ui/radio-group.tsx","components/ui/safe-image.tsx","components/ui/scroll-area.tsx","components/ui/scroll-choreographer.tsx","components/ui/select.tsx","components/ui/separator.tsx","components/ui/sheet.tsx","components/ui/site-footer-shell.tsx","components/ui/site-header.tsx","components/ui/skeleton.tsx","components/ui/slider.tsx","components/ui/sonner.tsx","components/ui/spinner.tsx","components/ui/stepper.tsx","components/ui/switch.tsx","components/ui/table.tsx","components/ui/tabs.tsx","components/ui/textarea.tsx","components/ui/toggle-group.tsx","components/ui/toggle.tsx","components/ui/tooltip.tsx","components/ui/video-frame.tsx","lib/cms","lib/utils.ts#cn"],generated_sections_path:"components/site/generated/*",ui_baseline:{kit:"shadcn-style",components_config:"components.json",class_name_helper:"lib/utils.ts#cn"},host_contract_digest:"03208e0d83ae2140368f162b6051dd45d4d6ac97f3652958b3ba24a6273d6eca"};function qu(){let e=FN.safeParse(qh);return e.success?e.data:null}import{randomBytes as LN}from"node:crypto";import Ba from"node:path";import{parse as iy}from"@babel/parser";import MN from"@babel/traverse";import*as sy from"@babel/types";import{COMPONENT_I18N_FILE_SUFFIX as ed,PageResourceArtifactSchema as DN,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as BN,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as jN,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as $N,parseComponentI18nResourcesJson as VN}from"@vcp-dev/contracts";var td="{{$INSTANCE}}",UN=/\{\{\$PAGE_ROUTE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,KN=/\{\{\$PAGE_TITLE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,nd="components/site/generated",JN=/\.(?:tsx?|json)$/,XN=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,zN=["react","react/","next","next/","lucide-react","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],HN=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),Qu=MN,WN=typeof Qu=="function"?Qu:Qu.default;async function rd(e){let t=DN.safeParse(e.artifact);if(!t.success)return tt("Page resource artifact failed contract validation.");let n=t.data,r=e.randomHex??(()=>LN(4).toString("hex")),o=Math.max(1,Math.min(e.maxAttempts??5,5)),i=rP(r());if(!i)return tt("Random instance suffix must be 8 lowercase hex chars.");let s=`${oP(n.resource_id)}-${i}`,a=new Map,c=new Map,l=[];for(let b of n.pages){let E=b.final_route.slice(1);a.set(b.template_page_id,b.final_route),c.set(b.template_page_id,b.title),l.push({template_page_id:b.template_page_id,title:b.title,final_route:b.final_route,route_file_path:`app/${E}/page.tsx`})}let u=[],d=new Set,f=new Set,g=new Map,p=new Map,m=[],y=new Set(n.pages.flatMap(b=>b.components.map(E=>E.component_id)));for(let b of n.components){if(!y.has(b.component_id))continue;let E=Qh({materialization:b.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c});if(!E.ok)return E;for(let k of E.files){let I=ty(k,d,u);if(I)return I}f.add(E.entry),p.set(E.entry,E.entryExport),g.set(b.component_id,E.entry)}for(let[b,E]of n.pages.entries()){let k=l[b],I=Qh({materialization:E.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c,pageEntryTarget:k.route_file_path,pageTitle:k.title});if(!I.ok)return I;for(let v of I.files){let N=ty(v,d,u);if(N)return N}f.add(I.entry),p.set(I.entry,I.entryExport),m.push({entry:I.entry,declaredComponentIds:new Set(E.components.map(v=>v.component_id))})}let x=YN(u,f,s,g,m,p);if(!x.ok)return x;for(let b of u)if(await e.exists(b.file))return!b.file.startsWith("app/")&&o>1?rd({...e,randomHex:r,maxAttempts:o-1}):{ok:!1,code:"MATERIALIZATION_CONFLICT",message:`Page resource create-only target already exists: ${b.file}`,path:b.file};let S=ZN(u);return S||(u.sort((b,E)=>b.file.localeCompare(E.file)),{ok:!0,packageInstanceId:s,pages:l,files:u})}function Qh(e){let t=e.materialization.entry.pathTemplate,n=[];for(let o of e.materialization.files){let i=o.pathTemplate===t,s=i&&e.pageEntryTarget?e.pageEntryTarget:ey(o.pathTemplate,e.packageInstanceId);if(!s)return tt("Materialization path cannot be mapped into the package namespace.",o.pathTemplate);let a=GN(o.content,e.packageInstanceId,e.routeByPage,e.titleByPage);if(!a.ok)return a;let c=i&&e.pageTitle!==void 0?QN(a.data,e.pageTitle,s):a;if(!c.ok)return c;n.push({operation:"create-only",file:s,content:c.data})}let r=e.pageEntryTarget??ey(t,e.packageInstanceId);return!r||!n.some(o=>o.file===r)?tt("Materialization entry must match one controlled source file.",t):{ok:!0,files:n,entry:r,entryExport:e.materialization.entry.export}}function GN(e,t,n,r){let o,i=e.replace(UN,(c,l)=>{let u=n.get(l);return u||(o=l,c)});if(o)return tt(`Page route placeholder references unknown template page: ${o}`);let s=i.replace(KN,(c,l)=>{let u=r.get(l);return u?JSON.stringify(u):(o=l,c)});if(o)return tt(`Page title placeholder references unknown template page: ${o}`);let a=s.replaceAll(td,t);return a.includes("{{$PAGE_ROUTE:")||a.includes("{{$PAGE_TITLE:")||a.includes("{{$INSTANCE}}")?tt("Materialization contains an unresolved placeholder."):{ok:!0,data:a}}function ey(e,t){let n=`${nd}/${t}`;if(e.split(td).length>2)return null;let o=e.replace(td,t),i=`${nd}/${t}/`,s=o.startsWith(i)?o:`${n}/${o}`,a=Ba.posix.normalize(s);return a!==s||!a.startsWith(`${n}/`)||!JN.test(a)||XN.test(a)?null:a}function ty(e,t,n){return t.has(e.file)?tt(`Page resource materializations resolve duplicate target: ${e.file}`,e.file):(t.add(e.file),n.push(e),null)}function YN(e,t,n,r,o,i){let s=new Set(e.map(g=>g.file)),a=`${nd}/${n}`,c=new Map(e.map(g=>[g.file,new Set])),l=new Map;for(let g of e){if(g.file.endsWith(".json")){try{JSON.parse(g.content)}catch{return tt("Materialization JSON file must contain valid JSON.",g.file)}if(g.file.endsWith(ed)&&!VN(g.content).success)return tt("Materialization component i18n resources are invalid.",g.file);continue}try{let p=iy(g.content,{sourceType:"module",plugins:["jsx","typescript"]});l.set(g.file,p);for(let y of p.program.body)if((y.type==="ImportDeclaration"||y.type==="ExportAllDeclaration"||y.type==="ExportNamedDeclaration"&&y.source)&&y.source){let x=y.source.value,S=tP(g.file,x,s,a);if(!S.allowed)return tt(`Materialization import is outside the controlled package: ${x}`,g.file);S.internalPath&&c.get(g.file).add(S.internalPath)}let m;if(WN(p,{Identifier(y){y.isReferencedIdentifier()&&HN.has(y.node.name)&&(m??=y.node.name,y.stop())},JSXOpeningElement(y){y.node.name.type==="JSXIdentifier"&&y.node.name.name.toLowerCase()==="style"&&(m??="style element",y.stop())}}),m)return tt(`Materialization source uses forbidden capability: ${m}`,g.file)}catch{return tt("Materialization source must parse as TS/TSX.",g.file)}}if([...t].some(g=>!s.has(g)))return tt("Materialization entry is outside the controlled package.");for(let g of t)if(g.endsWith(".json"))return tt("Materialization JSON files cannot be package entries.");for(let[g,p]of i){let m=l.get(g);if(!m||!qN(m,p))return tt("Materialization entry does not declare its contracted export.",g)}let u=new Map([...r].map(([g,p])=>[p,g]));for(let g of o){let p=oy(g.entry,c);for(let m of g.declaredComponentIds){let y=r.get(m);if(!y||!p.has(y))return tt(`Page entry does not reach declared component: ${m}`,g.entry)}for(let m of p){let y=u.get(m);if(y&&!g.declaredComponentIds.has(y))return tt(`Page entry imports undeclared component: ${y}`,g.entry)}}let d=new Set;for(let g of t)for(let p of oy(g,c))d.add(p);if(d.size!==e.length)return tt("Every materialization file must be reachable from a package entry.");let f=nP(e,l,c);return f||{ok:!0}}function ZN(e){if(e.length>BN)return tt("Page resource exceeds the aggregate source file limit.");let t=0;for(let n of e){let r=Buffer.byteLength(n.content,"utf8");if(r>jN)return tt("Page resource file exceeds the content byte limit.",n.file);t+=r}return t>$N?tt("Page resource exceeds the aggregate content byte limit."):null}function qN(e,t){for(let n of e.program.body){if(t.kind==="default"){if(n.type==="ExportDefaultDeclaration")return!0;continue}if(n.type==="ExportNamedDeclaration"&&(n.declaration?.type==="VariableDeclaration"&&n.declaration.declarations.some(r=>r.id.type==="Identifier"&&r.id.name===t.name)||(n.declaration?.type==="FunctionDeclaration"||n.declaration?.type==="ClassDeclaration")&&n.declaration.id?.name===t.name||n.specifiers.some(r=>r.exported.type==="Identifier"&&r.exported.name===t.name)))return!0}return!1}function QN(e,t,n){let r;try{r=iy(e,{sourceType:"module",sourceFilename:n,plugins:["jsx","typescript"]})}catch{return tt("Page materialization PAGE_SEO must parse as TS/TSX.",n)}for(let o of r.program.body){let i=o.type==="VariableDeclaration"?o:o.type==="ExportNamedDeclaration"&&o.declaration?.type==="VariableDeclaration"?o.declaration:null;if(i)for(let s of i.declarations){if(s.id.type!=="Identifier"||s.id.name!=="PAGE_SEO")continue;let a=ny(s.init);if(a?.type!=="ObjectExpression")return{ok:!0,data:e};let c=a.properties.find(u=>u.type==="ObjectProperty"&&!u.computed&&eP(u.key));if(!c||c.type!=="ObjectProperty")return{ok:!0,data:e};let l=ny(c.value);return l?l.type!=="StringLiteral"&&l.type!=="TemplateLiteral"||l.type==="TemplateLiteral"&&l.expressions.length>0||typeof l.start!="number"||typeof l.end!="number"?{ok:!0,data:e}:{ok:!0,data:e.slice(0,l.start)+JSON.stringify(t)+e.slice(l.end)}:{ok:!0,data:e}}}return{ok:!0,data:e}}function ny(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression"||t?.type==="TSNonNullExpression";)t=t.expression;return t&&sy.isExpression(t)?t:null}function eP(e){return e.type==="Identifier"&&e.name==="title"||e.type==="StringLiteral"&&e.value==="title"}function tP(e,t,n,r){if(t.startsWith(`@/${r}/`)){let s=t.slice(2),a=ry(s,n);return a?{allowed:!0,internalPath:a}:{allowed:!1}}if(!t.startsWith("."))return{allowed:zN.some(s=>s.endsWith("/")?t.startsWith(s):t===s)};if(t.includes("\\")||t.includes("\0"))return{allowed:!1};let o=Ba.posix.normalize(Ba.posix.join(Ba.posix.dirname(e),t)),i=ry(o,n);return i&&(i.startsWith(`${r}/`)||i.startsWith("app/"))?{allowed:!0,internalPath:i}:{allowed:!1}}function ry(e,t){return[e,`${e}.ts`,`${e}.tsx`,`${e}.json`,`${e}/index.ts`,`${e}/index.tsx`,`${e}/index.json`].find(n=>t.has(n))}function nP(e,t,n){let r=new Set(e.map(o=>o.file));for(let o of e){if(!o.file.endsWith(ed))continue;let i=o.file.slice(0,-ed.length),s=[`${i}.tsx`,`${i}.ts`].find(u=>r.has(u));if(!s)return tt("Component i18n resources require a same-name TS/TSX companion.",o.file);let c=t.get(s)?.program.directives.some(u=>u.value.value==="use client"),l=[...n].filter(([,u])=>u.has(o.file));if(!c||l.length!==1||l[0]?.[0]!==s)return tt("Component i18n resources must have exactly one same-name Client Component static importer.",s)}return null}function oy(e,t){let n=new Set,r=[e];for(;r.length>0;){let o=r.pop();if(!n.has(o)){n.add(o);for(let i of t.get(o)??[])r.push(i)}}return n}function rP(e){return/^[a-f0-9]{8}$/.test(e)?e:null}function oP(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"page-resource"}function tt(e,t){return{ok:!1,code:"MATERIALIZATION_REJECTED",message:e,...t?{path:t}:{}}}import{randomBytes as AP}from"node:crypto";import Zn from"node:path";import{parse as TP}from"@babel/parser";import wP from"@babel/traverse";import{COMPONENT_I18N_FILE_SUFFIX as $a,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as py,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as OP,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as FP,SiteEditMaterializationSchema as LP,parseComponentI18nResourcesJson as MP}from"@vcp-dev/contracts";import{parse as EP}from"@babel/parser";import SP from"@babel/traverse";import{GeneratedSiteCapabilitiesSchema as IP,FormDefinitionIdSchema as vP}from"@vcp-dev/contracts";var cy={colorMixPolicy:"always",includeExtendedColorFunctions:!0},ly=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\(/i,uy=/\b(?:bg-black|bg-white|text-white|text-black)(?:\b|\/)/g,iP=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke)-\[#(?:[0-9a-fA-F]{3,8})\](?:\/\d+)?/g,sP=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*#[0-9a-fA-F]{3,8}[^'"]*['"]/g,aP=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*rgba?\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,cP=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,lP=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,uP=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*(?:oklch|lab|lch|hsla?)\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,dP=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*(?:oklch|lab|lch|hsla?)\([^)]+\)[^'"]*['"]/gi,fP=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*color-mix\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,pP=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*color-mix\([^'"]*['"]/gi,mP=/\b(?:bg|text|border|ring|outline|fill|stroke)-(?:black|white|slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)(?:-\d{2,3})?(?:\b|\/)/g,gP=/var\(\s*--(?:_|private-|vcp-)[^)]+\)/gi,hP=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\([^)]*\)/gi;function od(e,t){let n=ja([...cn(e,iP),...cn(e,sP),...cn(e,aP),...cn(e,t.includeRgbBackgroundImage?cP:lP),...t.includeExtendedColorFunctions?[...cn(e,uP),...cn(e,dP)]:[]]),r=ja([...cn(e,fP),...cn(e,pP)]).filter(o=>t.colorMixPolicy==="always"||ly.test(o));return n.push(...r.filter(o=>!n.includes(o))),t.rejectTailwindPalette&&n.push(...cn(e,mP).filter(o=>!n.includes(o))),t.rejectAnyRawColorLiteral&&n.push(...cn(e,hP).filter(o=>!n.includes(o))),{hardCodedSurfaceHits:ja(cn(e,uy)),hardCodedSurfaceOccurrences:bP(e),rawColorHits:n,privateTokenHits:t.rejectPrivateTokens?yP(e):[]}}function yP(e){return ja(cn(e,gP))}function cn(e,t){return e.match(new RegExp(t.source,t.flags))??[]}var ay=160,xP=/((?:[a-z][a-z0-9-]*(?:\[[^\]]*\])?:)+)$/;function bP(e){let t=new RegExp(uy.source,"g"),n=[0];for(let s=0;s<e.length;s+=1)e[s]===`
5
5
  `&&n.push(s+1);let r=s=>{let a=0,c=n.length-1;for(;a<c;){let l=Math.ceil((a+c)/2);(n[l]??0)<=s?a=l:c=l-1}return a},o=[],i;for(;(i=t.exec(e))!==null;){let s=i[0],a=s.endsWith("/")?s.slice(0,-1):s,c=/^\/(\d+)/.exec(e.slice(i.index+a.length)),l=e.slice(Math.max(0,i.index-64),i.index),u=xP.exec(l),d=r(i.index),f=e.indexOf(`
6
- `,i.index),g=e.slice(n[d]??0,f===-1?void 0:f).trim();o.push({token:a,variant:u?.[1]??"",alpha:c?Number(c[1]):null,line:d+1,snippet:g.length>iy?`${g.slice(0,iy-1)}\u2026`:g})}return o}function ja(e){return[...new Set(e)]}var kP=["@/components/site/","@/lib/generated/","@/lib/cms","@/lib/cms/"],_P=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),ly=new Set(["require","module","exports","__dirname","__filename"]),id=SP,CP=typeof id=="function"?id:id.default;function ad(e,t={}){let n=[],r=RP(t.hostCapabilities),o=od(e,t.style??sy),i;try{i=EP(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return{ok:!1,violations:[{code:"parse-failed",message:"Generated source failed Babel parsing."}],styleViolations:o}}t.themeStyleMode==="reject"&&PP(o)&&n.push({code:"style-forbidden",message:"Generated source must use public semantic design tokens instead of raw colors, hard-coded surfaces, or private tokens."});let s=u=>{n.some(f=>f.code===u.code&&f.name===u.name&&f.source===u.source)||n.push(u)};return CP(i,{ImportDeclaration(u){a(u.node.source.value)},ExportNamedDeclaration(u){let d=u.node.source?.value;d&&a(d)},ExportAllDeclaration(u){a(u.node.source.value)},CallExpression(u){let d=u.node.callee;if(d.type==="Import"){s({code:"dynamic-import-forbidden",message:"Generated source cannot use dynamic import()."});return}d.type==="Identifier"&&(d.name==="require"?s({code:"commonjs-forbidden",message:"Generated source cannot use CommonJS require().",name:d.name}):(d.name==="eval"||d.name==="Function")&&s({code:"dynamic-code-forbidden",message:`Generated source cannot execute dynamic code through ${d.name}().`,name:d.name}))},NewExpression(u){u.node.callee.type==="Identifier"&&u.node.callee.name==="Function"&&s({code:"dynamic-code-forbidden",message:"Generated source cannot construct functions dynamically through Function().",name:"Function"})},MetaProperty(u){u.node.meta.type==="Identifier"&&u.node.meta.name==="import"&&s({code:"import-meta-forbidden",message:"Generated source cannot use import.meta."})},MemberExpression(u){l(sd(u.node))},OptionalMemberExpression(u){l(sd(u.node))},Identifier(u){u.isReferencedIdentifier()&&l(u.node.name)},JSXAttribute(u){t.rejectInlineStyles&&u.node.name.type==="JSXIdentifier"&&u.node.name.name==="style"&&s({code:"inline-style-forbidden",message:"Generated source cannot use inline style attributes."})},JSXOpeningElement(u){t.rejectStyleElements&&u.node.name.type==="JSXIdentifier"&&u.node.name.name.toLowerCase()==="style"&&s({code:"inline-style-forbidden",message:"Generated source cannot declare style elements."})}}),{ok:n.length===0,violations:n,styleViolations:o};function a(u){if(!(t.trustedManagedImports?.includes(u)&&vP.safeParse(/^@\/components\/site\/generated\/forms\/form-([^/]+)$/u.exec(u)?.[1]).success)&&!(u.startsWith("./")||u.startsWith("../"))){if(t.allowSiteOwnedImports&&kP.some(d=>d.endsWith("/")?u.startsWith(d):u===d)){c(u);return}r?NP(u,r)||s({code:"import-forbidden",message:`Generated source imports a package or public path outside the trusted host capabilities: ${u}.`,source:u}):s({code:t.hostCapabilities===void 0?"host-capabilities-unavailable":"host-capabilities-invalid",message:"Generated code cannot use an external import without trusted host capabilities.",source:u}),c(u)}}function c(u){t.protectedImportPrefixes?.some(d=>u.startsWith(d))&&s({code:"protected-import-forbidden",message:`Generated source cannot import protected host output directly: ${u}.`,source:u})}function l(u){if(!(!u||!_P.has(u))){if(u==="eval"||u==="Function"){s({code:"dynamic-code-forbidden",message:`Generated source cannot execute dynamic code through ${u}.`,name:u});return}s({code:ly.has(u)?"commonjs-forbidden":"browser-global-forbidden",message:ly.has(u)?`Generated source cannot depend on the CommonJS global ${u}.`:`Generated source cannot depend on the restricted global ${u}.`,name:u})}}}function RP(e){if(e==null)return null;let t=IP.safeParse(e);return t.success?t.data:null}function NP(e,t){if(t.runtime_dependencies.some(({name:r})=>e===r||e.startsWith(`${r}/`)))return!0;if(!e.startsWith("@/"))return!1;let n=e.slice(2);return t.public_paths.some(r=>{let[o]=r.split("#",1);return o.endsWith("/*")?n.startsWith(o.slice(0,-1)):uy(n)===uy(o)})}function uy(e){return e.replace(/\.(?:jsx?|tsx?|json)$/i,"")}function PP(e){return e.hardCodedSurfaceHits.length>0||e.rawColorHits.length>0||e.privateTokenHits.length>0}function sd(e){return e.type==="Identifier"?e.name:e.type==="MemberExpression"||e.type==="OptionalMemberExpression"?sd(e.object):null}var yy="components/site/generated",fy="{{$INSTANCE}}",Va=5,MP=/^[a-z][a-z0-9-]{0,48}$/,BP=/^[a-f0-9]{8}$/,py=/\.tsx?$/,jP=/\.json$/,$P=/\.(?:tsx?|json)$/,VP=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,cd=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),ld=wP,UP=typeof ld=="function"?ld:ld.default;function KP(e){let t=Array.isArray(e.manifest.files)?e.manifest.files:[];if(t.length>dy)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file count exceeds the reusable limit."}};let n=oA(t);if(n)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Static prefab resolves duplicate target path: ${n}`,path:n}};let r=LP.safeParse(e.manifest);if(!r.success)return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab manifest failed schema validation."}};let o=tA(e.generatedRoot);if(!o)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Generated root must be ${yy}.`,path:e.generatedRoot}};if(!xy(r.data.instanceBaseName))return{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_INVALID",message:"Static prefab instanceBaseName must contain at least one safe word.",path:r.data.instanceBaseName}};let i=gy(r.data.files),s=gy(e.controlledFiles);if(!iA(i,s))return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Controlled file list must exactly match the manifest file templates."}};if(i.size>dy)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file count exceeds the reusable limit."}};let a=0;for(let[c,l]of r.data.files.entries()){let u=Buffer.byteLength(l.content,"utf8");if(u>OP)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file exceeds the per-file content limit.",file:l.pathTemplate,path:`files[${c}]`}};a+=u}return a>FP?{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab exceeds the reusable total content limit."}}:{ok:!0,data:{kind:"static-prefab-materialization",instanceName:"",generatedRoot:o,instanceRoot:"",entry:{path:"",export:r.data.entry.export},files:[]}}}async function JP(e){let t=KP(e);if(!t.ok)return t;let n=t.data.generatedRoot,r=xy(e.manifest.instanceBaseName),o=Math.max(1,Math.min(Va,e.maxAttempts??Va));for(let i=0;i<o;i+=1){let s=nA(e.instanceNameGenerator?.()??AP(4).toString("hex"));if(!s)return{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_INVALID",message:"Static prefab instance suffix must be 8 lowercase hex chars."}};let a=`${r}-${s}`,c=Ey(n,a),l=XP({manifest:e.manifest,generatedRoot:n,instanceName:a,instanceRoot:c,hostCapabilities:e.hostCapabilities??null,availableHostDependencies:e.availableHostDependencies});if(!l.ok)return l;if(!await HP(e.exists,c,l.data.files))return{ok:!0,data:l.data}}return{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:"Unable to allocate a create-only static prefab instance after repeated conflicts."}}}async function ud(e){let t=Math.max(1,Math.min(Va,e.maxAttempts??Va));for(let n=0;n<t;n+=1){let r=await JP({...e,maxAttempts:1});if(!r.ok){if(r.error.code==="MATERIALIZATION_INSTANCE_CONFLICT")continue;return r}let o=await e.commit(r.data);if(o.ok)return{ok:!0,plan:r.data,data:o.data};if(o.error.code!=="MATERIALIZATION_INSTANCE_CONFLICT")return o}return{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:"Unable to commit a complete static prefab instance after repeated conflicts."}}}function XP(e){let t=zP(e);if(t)return{ok:!1,error:t};let n=[],r=new Set;for(let s of e.manifest.files){let a=Di({pathTemplate:s.pathTemplate,generatedRoot:e.generatedRoot,instanceName:e.instanceName,instanceRoot:e.instanceRoot});if(!a.ok)return a;if(r.has(a.data))return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Static prefab resolves duplicate target path: ${a.data}`,path:a.data}};r.add(a.data),n.push({kind:"create-only",path:a.data,content:s.content,...s.role?{role:s.role}:{},sourcePathTemplate:s.pathTemplate})}n.sort((s,a)=>s.path.localeCompare(a.path));let o=Di({pathTemplate:e.manifest.entry.pathTemplate,generatedRoot:e.generatedRoot,instanceName:e.instanceName,instanceRoot:e.instanceRoot});if(!o.ok)return o;if(!n.some(s=>s.path===o.data))return{ok:!1,error:{code:"MATERIALIZATION_ENTRY_INVALID",message:"Entry path must match one of the static prefab files.",path:o.data}};let i=dd({files:n,instanceRoot:e.instanceRoot,entries:[{path:o.data,export:e.manifest.entry.export}],hostCapabilities:e.hostCapabilities,declaredProjectDependencies:Object.keys(e.manifest.projectDependencies??{}),availableHostDependencies:e.availableHostDependencies});return i.ok?{ok:!0,data:{kind:"static-prefab-materialization",instanceName:e.instanceName,generatedRoot:e.generatedRoot,instanceRoot:e.instanceRoot,entry:{path:o.data,export:e.manifest.entry.export},files:n}}:i}function zP(e){if(e.availableHostDependencies===void 0)return null;let t=new Set(Object.keys(e.manifest.projectDependencies??{})),n=new Set(e.availableHostDependencies);return n.size!==e.availableHostDependencies.length||[...n].some(r=>!t.has(r))?{code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Target host dependency evidence must match declared materialization dependencies."}:[...t].some(r=>!n.has(r))?{code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"The target host does not provide every declared materialization dependency."}:[...t].some(r=>!e.hostCapabilities?.runtime_dependencies.some(({name:o})=>o===r))?{code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Materialization dependencies exceed the trusted host capability contract."}:null}async function HP(e,t,n){if(await e(t))return!0;for(let r of n)if(await e(r.path))return!0;return!1}function Di(e){if(e.pathTemplate.split(fy).length!==2)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:"Static prefab path templates must include the instance placeholder exactly once.",path:e.pathTemplate}};let t=e.pathTemplate.replaceAll(fy,e.instanceName),n=rA(t);return n?Ey(e.generatedRoot,e.instanceName)!==e.instanceRoot?{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:"Static prefab instance root normalization failed.",path:e.pathTemplate}}:n!==e.instanceRoot&&!n.startsWith(`${e.instanceRoot}/`)?{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:"Static prefab path must stay under components/site/generated/<instance>.",path:n}}:n!==t?{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:"Static prefab path template cannot rely on path normalization semantics.",path:e.pathTemplate}}:n===e.instanceRoot||!$P.test(n)||VP.test(n)?{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:"Static prefab files must be .ts/.tsx/.json files and cannot be config, layout, provider, or global source files.",path:n}}:{ok:!0,data:n}:{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:"Static prefab path template resolves to an unsafe path.",path:e.pathTemplate}}}function dd(e){let{files:t,instanceRoot:n,entries:r,hostCapabilities:o}=e,i=new Set(e.declaredProjectDependencies??[]),s=e.availableHostDependencies===void 0?null:new Set(e.availableHostDependencies),a=new Set(t.map(g=>g.path)),c=new Map,l=new Map(t.map(g=>[g.path,new Set])),u=new Map;for(let g of t){if(jP.test(g.path)){if(g.path.endsWith($a)){let x=DP(g.content);if(!x.success)return Yn("MATERIALIZATION_DATA_UNSUPPORTED",x.error.message,g.path);u.set(g.path,new Set)}else try{JSON.parse(g.content)}catch{return Yn("MATERIALIZATION_DATA_UNSUPPORTED","Static prefab JSON file must contain valid JSON.",g.path)}continue}let p;try{p=TP(g.content,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files must parse as plain module source.",file:g.path}}}let m=ad(g.content,{hostCapabilities:o,protectedImportPrefixes:["@/components/site/generated/"],trustedManagedImports:e.trustedManagedImports,rejectInlineStyles:!1,rejectStyleElements:!0,themeStyleMode:e.preserveCapturedStyles?"report":"ignore",style:{colorMixPolicy:"always",includeExtendedColorFunctions:!0,includeRgbBackgroundImage:!0,rejectAnyRawColorLiteral:!1,rejectPrivateTokens:!1,rejectTailwindPalette:!1}}),y=GP(m.violations,g.path);if(y)return{ok:!1,error:y};c.set(g.path,p)}for(let g of t){if(!py.test(g.path))continue;let p=c.get(g.path),m=null;if(UP(p,{ImportDeclaration(y){let x=my({importer:g.path,source:y.node.source.value,instanceRoot:n,filePaths:a});if(!x.allowed)m??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab imports must resolve within the controlled instance or match the starter allowlist.",file:g.path},y.stop();else if(!x.internalPath&&!YP(y.node.source.value,i,s))m??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"External prefab imports must be declared and available in the target host.",file:g.path},y.stop();else if(x.internalPath&&(l.get(g.path).add(x.internalPath),x.internalPath.endsWith($a))){let S=qP({importer:g.path,imported:x.internalPath,source:y.node.source.value,ast:p});S.ok?u.get(x.internalPath).add(g.path):(m??=S.error,y.stop())}},ExportAllDeclaration(y){m??={code:"MATERIALIZATION_ENTRY_INVALID",message:"Static prefab files cannot use export-star declarations.",file:g.path},y.stop()},ExportNamedDeclaration(y){if(y.node.source){let x=my({importer:g.path,source:y.node.source.value,instanceRoot:n,filePaths:a});!x.allowed||!x.internalPath&&!e.trustedManagedImports?.includes(y.node.source.value)?(m??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab re-exports must resolve within the controlled instance.",file:g.path},y.stop()):x.internalPath&&l.get(g.path).add(x.internalPath)}},CallExpression(y){if(y.node.callee.type==="Import"){m??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab files cannot use dynamic import().",file:g.path},y.stop();return}y.node.callee.type==="Identifier"&&y.node.callee.name==="require"&&(m??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab files cannot use require().",file:g.path},y.stop())},NewExpression(y){y.node.callee.type==="Identifier"&&y.node.callee.name==="Function"&&(m??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot construct functions dynamically.",file:g.path},y.stop())},MetaProperty(y){y.node.meta.type==="Identifier"&&y.node.meta.name==="import"&&(m??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot use import.meta.",file:g.path},y.stop())},MemberExpression(y){let x=hy(y.node);x&&cd.has(x)&&(m??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${x}.`,file:g.path},y.stop())},OptionalMemberExpression(y){let x=hy(y.node);x&&cd.has(x)&&(m??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${x}.`,file:g.path},y.stop())},Identifier(y){y.isReferencedIdentifier()&&cd.has(y.node.name)&&(m??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${y.node.name}.`,file:g.path},y.stop())},JSXAttribute(y){!e.preserveCapturedStyles||y.node.name.type!=="JSXIdentifier"||y.node.name.name!=="style"||WP(y.node.value)||(m??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot use inline style attributes.",file:g.path},y.stop())},JSXOpeningElement(y){y.node.name.type==="JSXIdentifier"&&y.node.name.name.toLowerCase()==="style"&&(m??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot declare style elements.",file:g.path},y.stop())},StringLiteral(y){e.preserveCapturedStyles&&Ua(y.node.value)&&(m??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Captured styles cannot load URLs or execute CSS expressions.",file:g.path},y.stop())},TemplateElement(y){e.preserveCapturedStyles&&Ua(y.node.value.cooked??y.node.value.raw)&&(m??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Captured styles cannot load URLs or execute CSS expressions.",file:g.path},y.stop())},JSXElement(y){let x=y.node.openingElement.name;e.preserveCapturedStyles&&x.type==="JSXIdentifier"&&["script","iframe","object","embed"].includes(x.name.toLowerCase())&&(m??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Captured components cannot embed executable external documents.",file:g.path},y.stop())}}),m)return{ok:!1,error:m}}if(r.length===0)return Yn("MATERIALIZATION_ENTRY_INVALID","Static prefab requires at least one source entry.");let d=new Set;for(let g of r){if(d.has(g.path))return Yn("MATERIALIZATION_PATH_INVALID",`Static prefab contains duplicate source entries: ${g.path}`,g.path);if(d.add(g.path),!py.test(g.path))return Yn("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must be a .ts/.tsx source module.",g.path);let p=c.get(g.path);if(!p)return Yn("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must resolve to a controlled source file.",g.path);if(!QP(p,g.export))return Yn("MATERIALIZATION_EXPORT_MISSING","Static prefab entry does not declare the manifest export.",g.path)}for(let[g,p]of u)if(p.size!==1)return Yn("MATERIALIZATION_IMPORT_FORBIDDEN","Each component .i18n.json file must have exactly one same-name Client Component static importer.",g);let f=new Set;for(let g of r)for(let p of eA(g.path,l))f.add(p);return f.size!==t.length?Yn("MATERIALIZATION_ENTRY_INVALID","Every controlled source file must be reachable from the entry module.",r[0]?.path):{ok:!0}}function Ua(e){return/(?:url|expression)\s*\(|@import|javascript:|-moz-binding|\\/iu.test(e)}function WP(e){return e?.type!=="JSXExpressionContainer"||e.expression.type!=="ObjectExpression"?!1:e.expression.properties.every(t=>{if(t.type!=="ObjectProperty"||t.computed)return!1;let n=t.key.type==="Identifier"?t.key.name:t.key.type==="StringLiteral"?t.key.value:null;if(!n||n==="__proto__"||n==="constructor"||n==="prototype"||Ua(n))return!1;let r=t.value;return r.type==="StringLiteral"&&!Ua(r.value)||r.type==="NumericLiteral"||r.type==="NullLiteral"||r.type==="UnaryExpression"&&["-","+"].includes(r.operator)&&r.argument.type==="NumericLiteral"})}function GP(e,t){let n=e[0];if(!n)return null;let r=new Set(["host-capabilities-unavailable","host-capabilities-invalid","import-forbidden","protected-import-forbidden","dynamic-import-forbidden","commonjs-forbidden"]),o=new Set(["inline-style-forbidden","style-forbidden"]);return{code:r.has(n.code)?"MATERIALIZATION_IMPORT_FORBIDDEN":o.has(n.code)?"MATERIALIZATION_STYLE_FORBIDDEN":"MATERIALIZATION_DATA_UNSUPPORTED",message:n.message,file:t}}function my(e){if(!e.source.startsWith("./")&&!e.source.startsWith("../"))return{allowed:!0};if(e.source.includes("\\")||e.source.includes("\0"))return{allowed:!1};let t=Zn.posix.normalize(Zn.posix.join(Zn.posix.dirname(e.importer),e.source));if(t===e.instanceRoot||!t.startsWith(`${e.instanceRoot}/`))return{allowed:!1};let r=[t,`${t}.ts`,`${t}.tsx`,`${t}.json`,...["ts","tsx","json"].map(o=>`${t}/index.${o}`)].find(o=>e.filePaths.has(o));return r?{allowed:!0,internalPath:r}:{allowed:!1}}function YP(e,t,n){if(n===null)return!0;let r=ZP(e);return r===null||t.has(r)&&n.has(r)}function ZP(e){if(e.startsWith("@/")||e.startsWith("./")||e.startsWith("../")||e.startsWith("/"))return null;if(e.startsWith("@")){let[t,n]=e.split("/");return t&&n?`${t}/${n}`:e}return e.split("/")[0]||null}function qP(e){let t=Zn.posix.dirname(e.importer),n=Zn.posix.dirname(e.imported),r=Zn.posix.basename(e.importer).replace(/\.tsx?$/,""),o=Zn.posix.basename(e.imported).slice(0,-$a.length),i=`./${r}${$a}`;return!e.importer.endsWith(".tsx")||t!==n||r!==o||e.source!==i?{ok:!1,error:{code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Component i18n resources must use an explicit same-directory, same-name import from a .tsx file.",file:e.importer}}:e.ast.program.directives.some(a=>a.value.value==="use client")?{ok:!0}:{ok:!1,error:{code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:'A component that imports .i18n.json must declare the top-level "use client" directive.',file:e.importer}}}function QP(e,t){for(let n of e.program.body){if(t.kind==="default"&&n.type==="ExportDefaultDeclaration"||t.kind==="default"&&n.type==="ExportNamedDeclaration"&&n.exportKind!=="type"&&n.specifiers.some(o=>o.type==="ExportSpecifier"&&o.exportKind!=="type"&&o.exported.type==="Identifier"&&o.exported.name==="default"))return!0;if(t.kind!=="named"||n.type!=="ExportNamedDeclaration")continue;if(n.specifiers.some(o=>o.exported.type==="Identifier"&&o.exported.name===t.name))return!0;let r=n.declaration;if((r?.type==="FunctionDeclaration"||r?.type==="ClassDeclaration")&&r.id?.name===t.name||r?.type==="VariableDeclaration"&&r.declarations.some(o=>o.id.type==="Identifier"&&o.id.name===t.name))return!0}return!1}function eA(e,t){let n=new Set,r=[e];for(;r.length>0;){let o=r.pop();n.has(o)||(n.add(o),r.push(...t.get(o)??[]))}return n}function Yn(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{file:n}:{}}}}function tA(e){let t=by(e);return t===yy?t:null}function nA(e){let t=e.trim().toLowerCase();return BP.test(t)?t:null}function xy(e){let t=e.trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,49).replace(/-+$/g,"");return MP.test(t)?t:null}function by(e){if(!e||e.startsWith("/")||e.includes("\\"))return null;let t=Zn.posix.normalize(e);return t==="."||t.startsWith("../")||t.includes("/../")||t.includes("//")?null:t}function rA(e){let t=by(e);return!t||t!==e?null:t}function Ey(...e){return Zn.posix.join(...e)}function gy(e){return new Set(e.map(t=>t.pathTemplate))}function oA(e){let t=new Set;for(let n of e){if(t.has(n.pathTemplate))return n.pathTemplate;t.add(n.pathTemplate)}return null}function iA(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function hy(e){let t=e;for(;;){if(!t||typeof t!="object"||!("type"in t))return null;if(t.type==="Identifier"&&"name"in t&&typeof t.name=="string")return t.name;if(t.type==="MemberExpression"||t.type==="OptionalMemberExpression"){t=t.object;continue}return null}}import{createHash as Bd}from"node:crypto";import Td from"@babel/traverse";function fd(e){let t=new Map,n=new Map;for(let s of e){if(t.has(s.placementKey))throw new Error(`Duplicate placement key in page composition projection: ${s.placementKey}`);t.set(s.placementKey,s);let a=n.get(s.placementUnitKey)??[];a.push(s),n.set(s.placementUnitKey,a)}let r=new Map,o=new Map,i=new Map;for(let[s,a]of n){let c=Object.freeze([...a]),l=c.find(u=>u.anchorSourceRange!==null&&u.members.length>0)??c.find(u=>u.members.length>0)??c[0];l&&(o.set(s,c),i.set(s,l),r.set(s,Object.freeze({placementUnitKey:s,placementKeys:Object.freeze(c.map(u=>u.placementKey)),sourcePlacementKey:l.placementKey})))}return{placementByKey:t,unitByKey:r,placementsByUnitKey:o,sourcePlacementByUnitKey:i}}function Ka(e){if(e.node.alternate||!sA(e.get("test")))return!1;let t=e.get("consequent"),n=t.isBlockStatement()?t.get("body"):[t];if(n.length!==1)return!1;let r=n[0];if(r.isThrowStatement())return!0;if(!r.isExpressionStatement())return!1;let o=r.get("expression");if(!o.isCallExpression()||o.node.arguments.length!==0)return!1;let i=o.get("callee");if(!i.isIdentifier())return!1;let s=i.scope.getBinding(i.node.name);if(!s?.constant||s.constantViolations.length>0||!s.path.isImportSpecifier()||s.path.node.importKind==="type")return!1;let a=s.path.node.imported,c=a.type==="Identifier"?a.name:a.value,l=s.path.parentPath;return!!(c==="notFound"&&l?.isImportDeclaration()&&l.node.importKind!=="type"&&l.node.source.value==="next/navigation")}function sA(e){let t=Sy(e);return e.traverse({enter(n){Sy(n)||(t=!1,n.stop())}}),t}function Sy(e){if(e.isAssignmentExpression()||e.isUpdateExpression()||e.isAwaitExpression()||e.isYieldExpression()||e.isNewExpression()||e.isTaggedTemplateExpression()||e.isOptionalCallExpression()||e.isJSXElement()||e.isJSXFragment()||e.isFunction()||e.isUnaryExpression({operator:"delete"}))return!1;if(!e.isCallExpression())return!0;let t=e.get("callee"),n=e.get("arguments");if(!t.isMemberExpression()||t.node.computed||n.length!==1)return!1;let r=t.get("object"),o=t.get("property");if(!r.isIdentifier()||!o.isIdentifier())return!1;if(r.node.name==="Object"&&o.node.name==="keys"&&!r.scope.getBinding("Object"))return!n[0].isSpreadElement();let i=r.scope.getBinding(r.node.name);return!!(o.node.name==="includes"&&n[0].isStringLiteral()&&i?.constant&&i.path.isVariableDeclarator()&&i.path.parentPath?.isVariableDeclaration({kind:"const"}))}import{createHash as AA}from"node:crypto";import wy from"node:path";import*as Fo from"@babel/parser";import Sd from"@babel/traverse";import Id from"@babel/generator";import*as ue from"@babel/types";import yd from"@babel/generator";import{parse as yA}from"@babel/parser";import xd from"@babel/traverse";import*as Re from"@babel/types";import{PortableInvocationBindingSchema as xA}from"@vcp-dev/contracts";import pd from"@babel/traverse";import*as Ne from"@babel/types";var Iy=typeof pd=="function"?pd:pd.default;function hn(e){let t=ky(e.module,e.exportName,e.parsedModules??new Map([[e.module.file,e.module]]),new Set);return t?vy(t,e.allowNonRenderingGuards):mr("component-export-unresolved","The requested local component export is not a statically resolvable function.",e.module.file)}function gr(e){let t=aA(e.module,e.componentName,e.callSourceRange);return t.kind==="local"?vy(t.definition):t.kind==="imported"?!e.imported?.module&&!nt(t.specifier)?mr("component-external-module-opaque","External package components are opaque to the local source graph.",t.specifier):e.imported?e.imported.module?hn({module:e.imported.module,exportName:e.imported.exportName,parsedModules:e.imported.parsedModules}):mr("component-module-unavailable","The component source module is unavailable in the parsed graph.",e.imported.file):mr("component-local-binding-unresolved","The JSX call does not resolve to a statically declared local component function.",e.module.file):mr("component-local-binding-unresolved","The JSX call does not resolve to a statically declared local component function.",e.module.file)}function vy(e,t=!1){let n=fA(e.module.ast,e.node);if(!n)return mr("component-function-unresolved","The component function has no source AST path.",e.module.file);let r=_y(n,t);if(!r){let s=mA(n);return s?{ok:!0,componentName:e.name,sourceFile:e.module.file,metadataOnly:!1,roots:[s[0]],returnAlternatives:s}:mr("component-control-flow-unsupported","Component roots require an expression body or one direct return.",e.module.file)}let o=[],i=Cy(r);return Xa(r,o)?{ok:!0,componentName:e.name,sourceFile:e.module.file,metadataOnly:i,roots:o}:mr("component-root-dynamic","Component return contains an unsupported dynamic or spread root.",e.module.file)}function aA(e,t,n){let r={kind:"unresolved"};return Iy(e.ast,{JSXElement(o){if(!uA(o.node.loc,n))return;let i=o.node.openingElement.name;if(!Ne.isJSXIdentifier(i)||i.name!==t)return;let s=o.scope.getBinding(t);if(!s||s.constantViolations.length>0){o.stop();return}if(cA(s.path)){let c=s.path.parentPath;c?.isImportDeclaration()&&(r={kind:"imported",specifier:c.node.source.value}),o.stop();return}let a=lA(s.path);a&&(r={kind:"local",definition:{node:a,name:t,module:e}}),o.stop()}}),r}function cA(e){return e.isImportSpecifier()||e.isImportDefaultSpecifier()||e.isImportNamespaceSpecifier()}function lA(e){if(e.isFunctionDeclaration())return e.node;if(!e.isVariableDeclarator())return null;let t=e.get("init");return!Array.isArray(t)&&hd(t.node)?t.node:null}function uA(e,t){return e!=null&&e.start.line===t.startLine&&e.start.column===t.startColumn&&e.end.line===t.endLine&&e.end.column===t.endColumn}function ky(e,t,n,r){let o=`${e.file}#${t}`;if(r.has(o))return null;let i=new Set(r).add(o),s=(u,d)=>{let f=sr(e.file,u,n),g=f?n.get(f):void 0;return g?ky(g,d,n,i):null},a=u=>{let d=dA(e,u);if(d)return{...d,module:e};for(let f of e.ast.program.body)if(!(!Ne.isImportDeclaration(f)||f.importKind==="type")){for(let g of f.specifiers)if(g.local.name===u){if(Ne.isImportDefaultSpecifier(g))return s(f.source.value,"default");if(Ne.isImportSpecifier(g)&&g.importKind!=="type")return s(f.source.value,Ja(g.imported))}}return null};for(let u of e.ast.program.body){if(Ne.isExportDefaultDeclaration(u)&&t==="default"){let d=u.declaration;if(hd(d))return{node:d,name:hA(d)??"default",module:e};if(Ne.isIdentifier(d))return a(d.name)}if(!(!Ne.isExportNamedDeclaration(u)||u.exportKind==="type")){if(u.declaration){let d=gA(u.declaration,t);if(d)return a(d)}for(let d of u.specifiers)if(Ne.isExportSpecifier(d)&&d.exportKind!=="type"&&Ja(d.exported)===t)return u.source?s(u.source.value,Ja(d.local)):a(Ja(d.local))}}let c=e.ast.program.body.flatMap(u=>{if(!Ne.isExportAllDeclaration(u)||u.exportKind==="type"||t==="default")return[];let d=s(u.source.value,t);return d?[d]:[]}),l=c.filter((u,d)=>c.findIndex(f=>f.node===u.node&&f.module.file===u.module.file)===d);return l.length===1?l[0]:null}function dA(e,t){for(let n of e.ast.program.body){let r=Ne.isExportNamedDeclaration(n)?n.declaration:n;if(Ne.isFunctionDeclaration(r)&&r.id?.name===t)return{node:r,name:t};if(Ne.isVariableDeclaration(r)){for(let o of r.declarations)if(Ne.isIdentifier(o.id)&&o.id.name===t&&hd(o.init))return{node:o.init,name:t}}}return null}function fA(e,t){let n=null;return Iy(e,{Function(r){r.node===t&&(n=r,r.stop())}}),n}function _y(e,t=!1){let n=e.get("body");if(!n.isBlockStatement())return n;let r=n.get("body"),o=r.at(-1);return!o?.isReturnStatement()||!o.get("argument").node||!r.slice(0,-1).every(i=>i.isVariableDeclaration()||i.isFunctionDeclaration()||pA(i)||t&&i.isIfStatement()&&Ka(i))?null:o.get("argument")}function pA(e){if(!e.isExpressionStatement())return!1;let t=e.get("expression");if(!t.isCallExpression())return!1;let n=t.get("callee");if(!n.isIdentifier())return!1;let r=n.scope.getBinding(n.node.name);if(!r?.constant||!r.path.isImportSpecifier())return!1;let o=r.path.node.imported,i=r.path.parentPath;if(!Ne.isIdentifier(o,{name:"useEffect"})||!i?.isImportDeclaration()||i.node.source.value!=="react"||i.node.importKind==="type"||r.path.node.importKind==="type")return!1;let s=t.get("arguments")[0];return!!(s&&(s.isArrowFunctionExpression()||s.isFunctionExpression()))}function mA(e){let t=e.get("body");if(!t.isBlockStatement())return null;let n=md(t.get("body"));if(!n||n.length<2)return null;let r=[],o=null;for(let i of n){if(!i.isJSXElement())return null;let s=i.node.openingElement.name;if(!Ne.isJSXIdentifier(s)||!/^[A-Z]/.test(s.name))return null;let a=i.scope.getBinding(s.name);if(!a||a.constantViolations.length>0||o&&o!==a.path.node||(o=a.path.node,i.node.children.some(c=>!Ne.isJSXText(c)||c.value.trim()!=="")||i.node.openingElement.attributes.some(c=>Ne.isJSXSpreadAttribute(c)||Ne.isJSXAttribute(c)&&Ne.isJSXIdentifier(c.name,{name:"children"}))))return null;r.push(i)}return r}function md(e){for(let[t,n]of e.entries()){if(n.isVariableDeclaration()||n.isFunctionDeclaration())continue;if(n.isReturnStatement()){let a=n.get("argument");return a.node&&t===e.length-1?[a]:null}if(!n.isIfStatement())return null;let r=a=>md(a.isBlockStatement()?a.get("body"):[a]),o=r(n.get("consequent")),i=n.get("alternate"),s=i.node?t===e.length-1?r(i):null:md(e.slice(t+1));return o&&s?[...o,...s]:null}return null}function Xa(e,t){if(Cy(e))return!0;if(e.isJSXFragment()||e.isJSXElement()&&Ye(e)){let n=e.get("children");for(let r of Array.isArray(n)?n:[n])if(!r.isJSXText()&&(r.isJSXSpreadChild()||!Xa(r,t)))return!1;return!0}if(e.isJSXElement())return t.push(e),!0;if(e.isJSXExpressionContainer()){let n=e.get("expression");return n.isJSXEmptyExpression()||n.isNullLiteral()||Xa(n,t)}return e.isParenthesizedExpression()||e.isTSAsExpression()||e.isTSTypeAssertion()||e.isTSNonNullExpression()||e.isTypeCastExpression()?Xa(e.get("expression"),t):e.isNullLiteral()||e.isStringLiteral()||e.isNumericLiteral()||e.isBooleanLiteral()}function gd(e){return["base","link","meta","script","style","title"].includes(e)}function Cy(e){let t=!1,n=r=>{if(r.isJSXElement()){let o=r.node.openingElement.name;return Ne.isJSXIdentifier(o)&&gd(o.name)?(t=!0,!0):Ye(r)?r.get("children").every(i=>n(i)):!1}if(r.isJSXFragment())return r.get("children").every(o=>n(o));if(r.isJSXText())return r.node.value.trim()==="";if(r.isNullLiteral()||r.isBooleanLiteral()||r.isJSXEmptyExpression())return!0;if(r.isJSXExpressionContainer()||r.isParenthesizedExpression()||r.isTSAsExpression()||r.isTSTypeAssertion()||r.isTSNonNullExpression())return n(r.get("expression"));if(r.isConditionalExpression())return n(r.get("consequent"))&&n(r.get("alternate"));if(r.isArrayExpression())return r.get("elements").every(o=>!o.node||n(o));if(r.isCallExpression()){let o=r.get("callee"),i=r.get("arguments");if(!o.isMemberExpression()||o.node.computed||!Ne.isIdentifier(o.node.property,{name:"map"})||i.length!==1)return!1;let s=i[0];if(!s.isArrowFunctionExpression()&&!s.isFunctionExpression())return!1;let a=_y(s);return a!==null&&n(a)}return!1};return n(e)&&t}function gA(e,t){return Ne.isFunctionDeclaration(e)?e.id?.name===t?t:null:Ne.isVariableDeclaration(e)&&e.declarations.some(n=>Ne.isIdentifier(n.id)&&n.id.name===t)?t:null}function hd(e){return Ne.isFunctionDeclaration(e)||Ne.isFunctionExpression(e)||Ne.isArrowFunctionExpression(e)}function hA(e){return"id"in e&&e.id&&Ne.isIdentifier(e.id)?e.id.name:null}function Ja(e){return Ne.isIdentifier(e)?e.name:e.value}function mr(e,t,n){return{ok:!1,diagnostic:{code:e,message:t,file:n}}}var bd=typeof yd=="function"?yd:yd.default,Ry=typeof xd=="function"?xd:xd.default,Py=new Set(["sourceBlockId","source_block_id","originalBlockId","original_block_id"]),bA=new Set(["sourceOrder","source_order","originalOrder","original_order"]),EA=new Set(["data-site-block-id","data-site-block-order","data-vcp-block-id","data-vcp-edit-key","data-vcp-order","sourceBlockId","source_block_id","originalBlockId","original_block_id","sourceOrder","source_order","originalOrder","original_order"]),SA=/^[A-Za-z_$][A-Za-z0-9_$]*$/u,IA=/^[A-Za-z_$][A-Za-z0-9_$]*(?:\.[A-Za-z_$][A-Za-z0-9_$]*)*$/u;function yr(e){if(!Ty(e)||!Array.isArray(e.bindings))return hr("INVOCATION_INPUT_INVALID","bindings must be an array in a portable invocation.","bindings");let t=CA(e);if(!t||!IA.test(t))return hr("INVOCATION_COMPONENT_INVALID","Portable invocation requires a safe JSX component local name.","component");let n=Ay(e.targetBlockId);if(!n.ok)return n;let r=RA(e.targetOrder);if(!r.ok)return r;let o=e.searchParamsIdentifier??"searchParams";if(!SA.test(o))return hr("INVOCATION_VALUE_UNRESOLVED","The route searchParams binding requires a safe local identifier.","searchParamsIdentifier");let i=[],s=[],a=new Set,c=!1,l=0;for(let[d,f]of e.bindings.entries()){let g=xA.safeParse(f);if(!g.success)return hr("INVOCATION_VALUE_UNRESOLVED","Portable invocation values must use the closed JSON/server/identity contract.",`bindings.${d}`);let p=g.data;if(a.has(p.propName))return hr("INVOCATION_DUPLICATE_PROP",`Portable invocation contains duplicate prop ${p.propName}.`,`bindings.${d}.propName`);if(a.add(p.propName),bA.has(p.propName))return hr("INVOCATION_SOURCE_METADATA","Source block order cannot be copied or rebound as a component prop.",`bindings.${d}`);if(Py.has(p.propName)&&p.value.kind!=="target-block-id")return hr("INVOCATION_SOURCE_METADATA","Source block identity/order cannot be copied as a business prop.",`bindings.${d}`);if(p.value.kind==="target-block-id"&&(l+=1,l>1))return hr("INVOCATION_DUPLICATE_PROP","A portable invocation may bind the target block identity only once.",`bindings.${d}`);p.value.kind==="route-search-params"&&(c=!0),s.push(p),i.push(Re.jsxAttribute(Re.jsxIdentifier(p.propName),Re.jsxExpressionContainer(kA(p.value,n.value,o))))}let u=Re.jsxElement(Re.jsxOpeningElement(_A(t),i,!0),null,[],!0);return{ok:!0,plan:{kind:"portable-invocation",component:t,jsx:bd(u,{jsescOption:{minimal:!0}}).code,bindings:s,targetBlockId:n.value,targetOrder:r.value,requiresRouteSearchParams:c,searchParamsIdentifier:c?o:null}}}function vA(e){if(!Ty(e)||e.jsx===void 0==(e.source===void 0))return wo("BLOCK_METADATA_INPUT_INVALID","Provide exactly one JSX expression or full source module.","input");let t=Ay(e.targetBlockId);if(!t.ok)return wo("BLOCK_METADATA_TARGET_INVALID",t.error.message,"targetBlockId");if(!Number.isSafeInteger(e.targetOrder)||e.targetOrder<0)return wo("BLOCK_METADATA_TARGET_INVALID","targetOrder must be a non-negative safe integer.","targetOrder");let n=e.jsx!==void 0,r,o;try{if(!n&&e.entryExport){let g=je("portable-entry.tsx",e.source);if(!g.ok)throw new Error(g.diagnostic.message);o=g.module,r=o.ast}else r=yA(n?e.jsx:e.source,{sourceType:"module",plugins:["jsx","typescript"]})}catch(g){return wo("BLOCK_METADATA_PARSE_FAILED",g instanceof Error?g.message:String(g),n?"jsx":"source")}let i=[],s;if(o&&e.entryExport){let g=hn({module:o,exportName:e.entryExport.kind==="default"?"default":e.entryExport.name});g.ok&&g.roots.length===1&&(s=g.roots[0],i.push(s.node))}else Ry(r,{JSXElement(g){Ny(g)||i.push(g.node)},JSXFragment(g){Ny(g)||i.push(g.node)}});if(i.length!==1)return wo("BLOCK_METADATA_ROOT_AMBIGUOUS","Portable block metadata requires exactly one JSX root.",n?"jsx":"source");let a=i[0],c=NA(a);if(!c)return wo("BLOCK_METADATA_ROOT_AMBIGUOUS","Portable block metadata requires exactly one direct JSX element root.",n?"jsx":"source");let l=0,u=0,d=g=>{let p=PA(g.node.name);!p||!EA.has(p)||(p==="data-site-block-id"||p==="data-vcp-block-id"||Py.has(p)?l+=1:u+=1,g.remove())};s?s.traverse({JSXAttribute:d}):Ry(r,{JSXAttribute:d}),c.openingElement.attributes.push(Re.jsxAttribute(Re.jsxIdentifier("data-site-block-id"),Re.stringLiteral(t.value)),Re.jsxAttribute(Re.jsxIdentifier("data-site-block-order"),Re.jsxExpressionContainer(Re.numericLiteral(e.targetOrder))));let f=n?bd(a,{jsescOption:{minimal:!0}}).code:bd(r,{jsescOption:{minimal:!0}}).code;return{ok:!0,plan:{kind:"portable-block-metadata",source:f,jsx:f,targetBlockId:t.value,targetOrder:e.targetOrder,removedSourceBlockIdCount:l,removedSourceOrderCount:u}}}function kA(e,t,n){return e.kind==="route-search-params"?Re.identifier(n):e.kind==="target-block-id"?Re.stringLiteral(t):Ed(e.value)}function Ed(e){return e===null?Re.nullLiteral():typeof e=="string"?Re.stringLiteral(e):typeof e=="number"?Re.numericLiteral(e):typeof e=="boolean"?Re.booleanLiteral(e):Array.isArray(e)?Re.arrayExpression(e.map(t=>Ed(t))):Re.objectExpression(Object.entries(e).map(([t,n])=>Re.objectProperty(Re.stringLiteral(t),Ed(n))))}function _A(e){let t=e.split("."),n=Re.jsxIdentifier(t[0]);for(let r of t.slice(1))n=Re.jsxMemberExpression(n,Re.jsxIdentifier(r));return n}function CA(e){return typeof e.componentName=="string"?e.componentName:typeof e.component=="string"?e.component:e.component&&typeof e.component=="object"?e.component.localName:null}function Ay(e){return typeof e!="string"||e.length===0||e.trim()!==e||e.length>256?{ok:!1,error:{code:"INVOCATION_TARGET_BLOCK_INVALID",path:"targetBlockId",message:"targetBlockId must be a non-blank stable identity."}}:{ok:!0,value:e}}function RA(e){return e!=null?!Number.isSafeInteger(e)||e<0?{ok:!1,error:{code:"INVOCATION_TARGET_ORDER_INVALID",path:"targetOrder",message:"targetOrder must be a non-negative safe integer."}}:{ok:!0,value:e}:{ok:!0,value:null}}function NA(e){if(Re.isJSXElement(e))return e;let t=e.children.filter(Re.isJSXElement),n=e.children.some(r=>Re.isJSXText(r)&&r.value.trim().length>0);return t.length===1&&!n?t[0]??null:null}function Ny(e){let t=e.parentPath;for(;t;){if(t.isJSXElement()||t.isJSXFragment())return!0;t=t.parentPath}return!1}function PA(e){return Re.isJSXIdentifier(e)?e.name:null}function Ty(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function hr(e,t,n){return{ok:!1,error:{code:e,path:n,message:t}}}function wo(e,t,n){return{ok:!1,error:{code:e,path:n,message:t}}}var kd=typeof Id=="function"?Id:Id.default,TA=typeof Sd=="function"?Sd:Sd.default;function $i(e){let t=By(e);if(t)return{ok:!1,error:t};let n=e.projection,r=Ad(n,e.placementKey,e.expectedDocumentVersion);if(!r.ok)return{ok:!1,error:{code:r.diagnostic.code==="DOCUMENT_VERSION_STALE"?"VERSION_STALE":"RUNTIME_ANCHOR_UNRESOLVED",message:r.diagnostic.message,diagnostics:[r.diagnostic]}};let o=r.placement,i=FA(n,o),s=JA(e);if(!s.ok)return s;let a={jsx:s.invocation?.jsx??`<${e.component.localName} />`},c=wA(e);if(i){let p=_d(e);return p.ok?{ok:!0,plan:{kind:"route-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:e.placementKey,placementUnitKey:o.placementUnitKey,importStep:c,...s.invocation?{invocation:s.invocation}:{},...s.serverParamsStep?{serverParamsStep:s.serverParamsStep}:{},returnStep:{kind:"insert-return",node:a,placement:o.relation,replaceOriginal:n.container.kind==="starter-placeholder"},rewriteStep:{kind:"insert-root-expression",locator:p.locator,sourceHash:p.sourceHash,node:a,placement:o.relation,replaceOriginal:n.container.kind==="starter-placeholder"}}}:p.result}let l=o.containerSourceRange??n.container.sourceRange,u=o.containerSourceHash??(za(l,n.container.sourceRange)?n.container.sourceHash:null);if(!l||!u)return Mi("Route page composition does not expose a verifiable container boundary.");let d=ji(l),f=Fy(e.source,d,u,"Route page composition container");if(!f.ok)return f.result;let g=o.anchorSourceRange?ji(o.anchorSourceRange):void 0;if(g){if(!o.anchorSourceHash)return Mi("Route page composition placement does not expose a verifiable anchor boundary.");let p=Fy(e.source,g,o.anchorSourceHash,"Route page composition anchor");if(!p.ok)return p.result}return{ok:!0,plan:{kind:"route-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:e.placementKey,placementUnitKey:o.placementUnitKey,importStep:c,...s.invocation?{invocation:s.invocation}:{},...s.serverParamsStep?{serverParamsStep:s.serverParamsStep}:{},insertStep:{kind:"insert-child",parentLocator:d,node:a,placement:o.relation,...g?{anchorLocator:g}:{}},rewriteStep:{kind:"insert-child",parentLocator:d,node:a,placement:o.relation,...g?{anchorLocator:g}:{}}}}}function Nd(e){let t=je(e.entryFile,e.source);if(!t.ok)return xr("PORTABLE_ROUTE_SOURCE_INVALID",t.diagnostic.message);let n=yn({route:e.routeId,composition:e.composition??{routeId:e.routeId},entryFile:e.entryFile,version:e.documentVersion,source:e.source,ast:t.module.ast});if(!n.ok)return xr("PORTABLE_ROUTE_UNSUPPORTED","Portable route does not expose a supported page-composition boundary.",n.projection.diagnostics);let r=n.projection.placements.flatMap(l=>{if(l.relation!==e.anchor.relation)return[];if(e.anchor.sourceRange)return l.anchorSourceRange&&za(l.anchorSourceRange,e.anchor.sourceRange)?[{placement:l,matchCount:1}]:[];let u=l.members.reduce((d,f)=>d+Dy(f,e.anchor.componentName),0);return u===0?[]:[{placement:l,matchCount:u}]}),o=r.reduce((l,u)=>l+u.matchCount,0);if(o===0)return xr("PORTABLE_ROUTE_ANCHOR_MISSING","Portable route anchor was not found in the canonical page composition.");if(o!==1||r.length!==1)return xr("PORTABLE_ROUTE_ANCHOR_AMBIGUOUS","Portable route anchor does not identify exactly one page-composition gap.");let i=$i({routeId:e.routeId,entryFile:e.entryFile,currentDocumentVersion:e.documentVersion,expectedDocumentVersion:e.documentVersion,source:e.source,projection:n.projection,placementKey:r[0].placement.placementKey,component:e.component,invocation:e.invocation});if(!i.ok)return i;let s=e.source,a=i.plan.rewriteStep;if(a.kind==="insert-root-expression"){let l=Vi({source:s,locator:a.locator,expectedSourceHash:a.sourceHash,action:{kind:"insert",jsx:a.node.jsx,placement:a.placement,replaceOriginal:a.replaceOriginal}});if(!l.ok)return xr("PORTABLE_ROUTE_PATCH_FAILED",l.diagnostic.message);s=l.source}else{let l=on({source:s,locator:a.parentLocator,node:a.node,placement:a.placement,...a.anchorLocator?{anchorLocator:a.anchorLocator}:{}});if(!l.ok)return xr("PORTABLE_ROUTE_PATCH_FAILED",l.diagnostic.message);s=l.source}if(i.plan.serverParamsStep){let l=jy({source:s,step:i.plan.serverParamsStep});if(!l.ok)return xr("PORTABLE_ROUTE_PATCH_FAILED",l.diagnostic.message);s=l.source}let c=sn({source:s,moduleSpecifier:i.plan.importStep.moduleSpecifier,imports:i.plan.importStep.imports});return c.ok?{ok:!0,plan:i.plan,patch:{kind:"portable-route-composition-patch",path:e.entryFile,expectedSourceHash:t.module.sourceHash,source:c.source}}:xr("PORTABLE_ROUTE_PATCH_FAILED",c.diagnostic.message)}function Dy(e,t){return(e.label===t?1:0)+e.children.reduce((n,r)=>n+Dy(r,t),0)}function xr(e,t,n=[]){return{ok:!1,error:{code:e,message:t,diagnostics:n}}}function wA(e){let t=BA(e.entryFile,e.component.source);return e.component.exportName==="default"?{kind:"add-import",moduleSpecifier:t,imports:[{kind:"default",local:e.component.localName}]}:{kind:"add-import",moduleSpecifier:t,imports:[{kind:"named",imported:e.component.exportName,local:e.component.localName===e.component.exportName?void 0:e.component.localName}]}}function Vi(e){if(e.locator.root.kind!=="expression"||e.locator.path?.length)return no(e.source,"Root expression rewrite requires an exact expression locator.");let t=pi(e.source,"value");if(!t.ok)return no(e.source,t.diagnostic.message);let n=Ie(t.ast,e.locator);if(!n.ok)return no(e.source,n.diagnostic.message);let r=n.match.path;if(!r.isExpression())return no(e.source,"Resolved value locator does not point to an expression.");let o=Oo(e.source,r.node.start??null,r.node.end??null);if(!o||o!==e.expectedSourceHash)return no(e.source,"Root expression hash no longer matches the current source.");if(e.action.kind==="remove")return r.replaceWith(ue.nullLiteral()),{ok:!0,source:kd(t.ast,{}).code};let i;try{i=Fo.parseExpression(e.action.jsx,{plugins:["jsx","typescript"]})}catch(s){return no(e.source,s instanceof Error?s.message:String(s))}return!ue.isJSXElement(i)&&!ue.isJSXFragment(i)?no(e.source,"Root expression rewrite requires a JSX insertion expression."):(e.action.kind==="replace"?r.replaceWith(i):r.replaceWith(OA(r.node,i,e.action.placement,e.action.replaceOriginal)),{ok:!0,source:kd(t.ast,{}).code})}function OA(e,t,n,r){if(ue.isNullLiteral(e)||r)return t;let o=ue.isJSXFragment(e)?[...e.children]:[ue.isJSXElement(e)?e:ue.jsxExpressionContainer(e)],s=n==="before"||n==="prepend"?[t,...o]:[...o,t];return ue.jsxFragment(ue.jsxOpeningFragment(),ue.jsxClosingFragment(),s)}function no(e,t){return{ok:!1,source:e,diagnostic:{message:t}}}function Pd(e){let t=By(e);if(t)return{ok:!1,error:t};let n=e.projection,r=Xy(n,e.placementUnitKey,e.expectedDocumentVersion);if(!r.ok)return{ok:!1,error:{code:r.diagnostic.code==="DOCUMENT_VERSION_STALE"?"VERSION_STALE":"NO_SAFE_PAGE_PLACEMENT",message:r.diagnostic.message,diagnostics:[r.diagnostic]}};let o=r.placement;if(!o.sourceRange||!o.sourceHash)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Route page composition source placement does not expose a safe boundary.",diagnostics:[]}};if(LA(n,o)){let m=_d(e);return m.ok?e.operation==="remove-node"&&!Oy(n,o.placementUnitKey)?Mi("The last editable page unit cannot be deleted."):e.operation==="move-node"?Mi("A singleton root expression cannot be moved without a safe parent boundary."):{ok:!0,plan:{kind:"page-unit-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:o.placementKey,placementUnitKey:o.placementUnitKey,sourceHash:m.sourceHash,rewriteStep:{kind:e.operation==="remove-node"?"remove-root-expression":"replace-root-expression",locator:m.locator,sourceHash:m.sourceHash}}}:m.result}let s=ji(o.sourceRange),a=Pn(e.source,s);if(!a.ok||!a.match.node)return{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:a.ok===!1?a.diagnostic.message:"Route page composition source anchor could not be resolved.",diagnostics:a.ok?[]:[Bi(a.diagnostic)]}};if(Oo(e.source,a.match.node.start??null,a.match.node.end??null)!==o.sourceHash)return{ok:!1,error:{code:"VERSION_STALE",message:"Route page composition source placement hash no longer matches the current source.",diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:"Route page composition source placement hash no longer matches the current source."}]}};if(e.operation==="remove-node"){let m=_d(e);return m.ok?Oy(n,o.placementUnitKey)?{ok:!0,plan:{kind:"page-unit-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:o.placementKey,placementUnitKey:o.placementUnitKey,sourceHash:o.sourceHash,rewriteStep:{kind:"remove-node",locator:s}}}:Mi("The last editable page unit cannot be deleted."):m.result}if(e.operation==="replace-node")return{ok:!0,plan:{kind:"page-unit-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:o.placementKey,placementUnitKey:o.placementUnitKey,sourceHash:o.sourceHash,rewriteStep:{kind:"replace-node",locator:s}}};if(!e.targetPlacement)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Page-unit move requires a target placement.",diagnostics:[]}};if(e.targetPlacement.composition.routeId!==e.routeId||!MA(e.targetPlacement.composition,e.composition))return{ok:!1,error:{code:"CROSS_PAGE_MOVE_UNSUPPORTED",message:"Page-unit move across routes or composition templates is not supported.",diagnostics:[]}};if(e.targetPlacement.documentVersion!==e.expectedDocumentVersion)return{ok:!1,error:{code:"VERSION_STALE",message:"Page-unit target placement belongs to a different document version.",diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:"Page-unit target placement belongs to a different document version."}]}};let l=Ad(n,e.targetPlacement.placementKey,e.expectedDocumentVersion);if(!l.ok)return{ok:!1,error:{code:l.diagnostic.code==="DOCUMENT_VERSION_STALE"?"VERSION_STALE":"NO_SAFE_PAGE_PLACEMENT",message:l.diagnostic.message,diagnostics:[l.diagnostic]}};let u=l.placement;if(u.placementUnitKey!==e.targetPlacement.placementUnitKey||u.relation!==e.targetPlacement.relation)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Page-unit target placement metadata does not match the cached projection.",diagnostics:[]}};let d=u.containerSourceRange;if(!d||!u.containerSourceHash)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Route page composition target placement does not expose a verifiable container boundary.",diagnostics:[]}};let f=ji(d),g=Pn(e.source,f);if(!g.ok||!g.match.node)return{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:g.ok===!1?g.diagnostic.message:"Route page composition target container could not be resolved.",diagnostics:g.ok?[]:[Bi(g.diagnostic)]}};if(Oo(e.source,g.match.node.start??null,g.match.node.end??null)!==u.containerSourceHash)return Ly("Route page composition target container hash no longer matches the current source.");if(u.relation==="before"||u.relation==="after"){let m=u.anchorSourceRange,y=u.anchorSourceHash;if(!m||!y)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Route page composition target placement does not expose a verifiable anchor boundary.",diagnostics:[]}};let x=ji(m),S=Pn(e.source,x);return!S.ok||!S.match.node?{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:S.ok===!1?S.diagnostic.message:"Route page composition target anchor could not be resolved.",diagnostics:S.ok?[]:[Bi(S.diagnostic)]}}:Oo(e.source,S.match.node.start??null,S.match.node.end??null)!==y?Ly("Route page composition target anchor hash no longer matches the current source."):{ok:!0,plan:{kind:"page-unit-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:o.placementKey,placementUnitKey:o.placementUnitKey,sourceHash:o.sourceHash,rewriteStep:{kind:"move-node",locator:s,targetParentLocator:f,anchorLocator:x,placement:u.relation}}}}return{ok:!0,plan:{kind:"page-unit-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:o.placementKey,placementUnitKey:o.placementUnitKey,sourceHash:o.sourceHash,rewriteStep:{kind:"move-node",locator:s,targetParentLocator:f,placement:u.relation}}}}function Oy(e,t){for(let n of e.placementUnitByKey.values())if(n.placementUnitKey!==t&&n.members.length>0)return!0;return!1}function FA(e,t){let n=e.placementUnitByKey.get(t.placementUnitKey);return n&&e.container.kind!=="jsx-container"&&za(n.sourceRange,e.mutationTarget.sourceRange)&&n.sourceHash===e.mutationTarget.sourceHash?!0:e.container.sourceRange===null&&(e.container.kind==="virtual-route-root"||e.container.kind==="starter-placeholder")}function LA(e,t){return e.container.kind!=="jsx-container"&&za(t.sourceRange,e.mutationTarget.sourceRange)&&t.sourceHash===e.mutationTarget.sourceHash}function _d(e){let t=e.projection.mutationTarget,n={kind:"value",root:{kind:"expression",sourceRange:t.sourceRange}},r=Pn(e.source,n);return!r.ok||!r.match.node?{ok:!1,result:{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:r.ok===!1?r.diagnostic.message:"Route mutation target could not be resolved.",diagnostics:r.ok?[]:[Bi(r.diagnostic)]}}}:Oo(e.source,r.match.node.start??null,r.match.node.end??null)!==t.sourceHash?{ok:!1,result:My("Route mutation target hash no longer matches the current source.")}:{ok:!0,locator:n,sourceHash:t.sourceHash}}function Fy(e,t,n,r){let o=Pn(e,t);return!o.ok||!o.match.node?{ok:!1,result:{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:o.ok===!1?o.diagnostic.message:`${r} could not be resolved.`,diagnostics:o.ok?[]:[Bi(o.diagnostic)]}}}:Oo(e,o.match.node.start??null,o.match.node.end??null)!==n?{ok:!1,result:My(`${r} hash no longer matches the current source.`)}:{ok:!0}}function My(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function Mi(e){return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:e,diagnostics:[]}}}function Ly(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function Bi(e){return{code:"UNSUPPORTED_PAGE_SHAPE",message:e.message,details:{astCode:e.code}}}function By(e){let{projection:t}=e;return t.route!==e.routeId||t.entryFile!==e.entryFile?{code:"VERSION_STALE",message:"Cached page composition projection belongs to a different route.",diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:"Cached page composition projection belongs to a different route.",details:{expectedRouteId:e.routeId,projectedRouteId:t.route,expectedEntryFile:e.entryFile,projectedEntryFile:t.entryFile}}]}:e.composition&&!DA(t.composition,e.composition)?{code:"VERSION_STALE",message:"Cached page composition projection belongs to a different composition.",diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:"Cached page composition projection belongs to a different composition.",details:{expectedComposition:e.composition,projectedComposition:t.composition}}]}:e.currentDocumentVersion!==e.expectedDocumentVersion||t.documentVersion!==e.currentDocumentVersion?{code:"VERSION_STALE",message:"Route page composition version is stale.",diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:"Route page composition version is stale.",details:{expectedDocumentVersion:e.expectedDocumentVersion,currentDocumentVersion:e.currentDocumentVersion,projectedDocumentVersion:t.documentVersion}}]}:null}function DA(e,t){return e.routeId===t.routeId&&e.effectiveTemplateId===t.effectiveTemplateId}function MA(e,t){return e.routeId===t.routeId&&e.templateId===t.effectiveTemplateId}function BA(e,t){let n=wy.posix.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=wy.posix.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function ji(e){return{kind:"jsx-node",strategy:"source-range",sourceRange:e}}function Oo(e,t,n){return t==null||n==null?null:`sha256:${AA("sha256").update(e.slice(t,n)).digest("hex")}`}function za(e,t){return e===null||t===null?e===t:e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function jy(e){let t;try{t=Fo.parse(e.source,{sourceType:"module",plugins:["jsx","typescript"]})}catch(r){return{ok:!1,source:e.source,diagnostic:{message:r instanceof Error?r.message:String(r)}}}let n=jA(t,e.step);return n.ok?{ok:!0,source:kd(t,{}).code}:{ok:!1,source:e.source,diagnostic:{message:n.message}}}function jA(e,t){let n=Ky(e);if(!n)return{ok:!1,message:"Route default function could not be resolved for searchParams wiring."};let r=Rd(n.node.params[0]);if(t.action==="reuse")return n.node.params.length!==1||!r?{ok:!1,message:"Existing route searchParams binding no longer matches the plan."}:Vy(r)!==t.identifier?{ok:!1,message:"Existing route searchParams binding no longer matches the plan."}:{ok:!0};let o=$y(n.node.params,t.typescript);if(!o.ok||o.action!=="add"||o.identifier!==t.identifier)return{ok:!1,message:"Route searchParams signature changed before the patch was applied."};if(n.node.params.length===0)return n.node.params.push(t.typescript?Cd():$A()),{ok:!0};let i=n.node.params[0],s=Rd(i);return s?(VA(s,t.typescript),{ok:!0}):{ok:!1,message:"Route page parameter is not a supported object pattern."}}function $A(){return ue.objectPattern([ue.objectProperty(ue.identifier("searchParams"),ue.identifier("searchParams"),!1,!0)])}function Cd(){let t=Fo.parse("function __PortablePage({ searchParams }: { searchParams?: Promise<Record<string, string | string[] | undefined>> }) {}",{sourceType:"module",plugins:["typescript"]}).program.body[0];if(!ue.isFunctionDeclaration(t))throw new Error("Failed to construct the canonical searchParams type.");let n=t.params[0];if(!ue.isObjectPattern(n))throw new Error("Failed to construct the canonical searchParams pattern.");return ue.cloneNode(n,!0)}function VA(e,t){let n=ue.objectProperty(ue.identifier("searchParams"),ue.identifier("searchParams"),!1,!0),r=e.properties.findIndex(ue.isRestElement);if(r<0?e.properties.push(n):e.properties.splice(r,0,n),!t)return;let o=Uy(e);if(!o){e.typeAnnotation=Cd().typeAnnotation;return}if(!ue.isTSTypeLiteral(o.typeAnnotation))return;let i=Cd().typeAnnotation;if(!i||!ue.isTSTypeAnnotation(i)||!ue.isTSTypeLiteral(i.typeAnnotation))return;let s=i.typeAnnotation.members[0];s&&!UA(o.typeAnnotation)&&o.typeAnnotation.members.push(ue.cloneNode(s,!0))}function UA(e){return e.members.some(t=>!("key"in t)||!t.key?!1:Jy(t.key)==="searchParams")}function KA(e,t){if(t.isFunctionDeclaration()||t.isFunctionExpression()||t.isArrowFunctionExpression())return t;if(!t.isIdentifier())return null;let n=e.scope.getBinding(t.node.name);if(!n)return null;let r=n.path;if(r.isFunctionDeclaration()||r.isFunctionExpression())return r;if(r.isVariableDeclarator()){let o=r.get("init");if(o.isArrowFunctionExpression()||o.isFunctionExpression())return o}return null}function JA(e){if(!e.invocation)return{ok:!0};let t=yr({component:e.component.localName,bindings:e.invocation.bindings,targetBlockId:e.invocation.targetBlockId,targetOrder:e.invocation.targetOrder});if(!t.ok)return vd(t.error.message);let n;if(t.plan.requiresRouteSearchParams){let r=XA(e.source,e.entryFile);if(!r.ok)return vd(r.message,"UNSUPPORTED_ROUTE_PARAMS");if(n=r.step,r.step.identifier!==t.plan.searchParamsIdentifier&&(t=yr({component:e.component.localName,bindings:e.invocation.bindings,targetBlockId:e.invocation.targetBlockId,targetOrder:e.invocation.targetOrder,searchParamsIdentifier:r.step.identifier}),!t.ok))return vd(t.error.message)}return{ok:!0,invocation:t.plan,...n?{serverParamsStep:n}:{}}}function vd(e,t="PORTABLE_INVOCATION_INVALID"){return{ok:!1,error:{code:t,message:e,diagnostics:[]}}}function XA(e,t){let n;try{n=Fo.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch(s){return{ok:!1,message:s instanceof Error?s.message:String(s)}}if(n.program.directives.some(s=>s.value.value==="use client"))return{ok:!1,message:"Portable route searchParams wiring cannot cross a use client boundary."};let r=Ky(n);if(!r)return{ok:!1,message:"Portable route searchParams wiring requires a default server function."};let o=/\.(?:ts|tsx)$/iu.test(t),i=$y(r.node.params,o);return i.ok?{ok:!0,step:{kind:"ensure-search-params",action:i.action,identifier:i.identifier,typescript:o}}:i}function $y(e,t){if(e.length===0)return{ok:!0,action:"add",identifier:"searchParams"};if(e.length!==1)return{ok:!1,message:"Portable route searchParams wiring rejects a default page with multiple parameters."};let n=Rd(e[0]);if(!n)return{ok:!1,message:"Portable route searchParams wiring requires an object page parameter or an empty signature."};let r=Vy(n);return r==="unsupported"?{ok:!1,message:"Portable route searchParams wiring cannot prove the existing searchParams binding."}:r?{ok:!0,action:"reuse",identifier:r}:t&&!zA(n)?{ok:!1,message:"Portable route searchParams wiring cannot safely extend this typed page signature."}:{ok:!0,action:"add",identifier:"searchParams"}}function Rd(e){return!e||ue.isTSParameterProperty(e)?null:ue.isObjectPattern(e)?e:ue.isAssignmentPattern(e)&&ue.isObjectPattern(e.left)?e.left:null}function Vy(e){for(let t of e.properties)if(!(!ue.isObjectProperty(t)||t.computed||Jy(t.key)!=="searchParams"))return ue.isIdentifier(t.value)?t.value.name:ue.isAssignmentPattern(t.value)&&ue.isIdentifier(t.value.left)?t.value.left.name:"unsupported";return null}function zA(e){let t=Uy(e);return t?ue.isTSTypeLiteral(t.typeAnnotation):e.properties.length===0}function Uy(e){return e.typeAnnotation&&ue.isTSTypeAnnotation(e.typeAnnotation)?e.typeAnnotation:null}function Ky(e){let t=null;return TA(e,{ExportDefaultDeclaration(n){if(t)return;let r=KA(n,n.get("declaration"));r&&(t=r)}}),t}function Jy(e){return ue.isIdentifier(e)?e.name:ue.isStringLiteral(e)?e.value:null}var HA=typeof Td=="function"?Td:Td.default;function yn(e){if(!e.ast)return xn(e,[mt("UNSUPPORTED_PAGE_SHAPE","SourceGraph entry AST is required",{reason:"parsed-ast-required"})]);let t=tT(e.ast);if(!t)return xn(e,[mt("UNSUPPORTED_PAGE_SHAPE","Route default export must resolve to a local function component",{reason:"default-export-unresolved"})]);let n=rT(t);if(!n.ok)return xn(e,[n.diagnostic]);let r=n.expression;if(r.isIdentifier()){let o=iT(r,t);if(o.status==="resolved")r=o.expression;else if(o.status==="invalid")return xn(e,[mt("UNSUPPORTED_PAGE_SHAPE","Route default export local binding is not a supported JSX root")])}if(aT(r,t))return xn(e,[mt("INDIRECT_RETURN_ONLY","Route default export only returns through an indirect function boundary")]);if(r.isNullLiteral())return Od(e,t,"virtual-route-root",r);if(sT(r)){let o=dT({input:e,source:e.source,expression:r});return wd(e,t,o,{kind:"virtual-route-root",sourceKind:"atomic-expression"},r)}if(r.isConditionalExpression())return xn(e,[mt("UNSUPPORTED_PAGE_SHAPE","Route conditional root contains an unsupported branch shape",{reason:"ambiguous-placement"})]);if(r.isJSXElement()&&!Ye(r)&&!Ki(r)){let o=Dd(r),i=Wy({input:e,containerKind:"virtual-route-root",sourceKind:"jsx-element",source:e.source,containerPath:r,members:[o]});return wd(e,t,i,{kind:"virtual-route-root",sourceKind:"jsx-element"},r)}if(r.isJSXElement()||r.isJSXFragment()){let o=lT(r);if(!o.ok)return xn(e,[o.diagnostic]);let i=Lo(o.path);if(i.unsupported)return xn(e,[mt("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);if(cT(e.source,r,i.members))return Od(e,t,"starter-placeholder",r);let s=r.isJSXFragment()||Ye(r);if(i.members.length===0&&s)return Od(e,t,"virtual-route-root",r);let a=o.path===r&&s?"virtual-route-root":"jsx-container",c=o.path.isJSXFragment()?"jsx-fragment":"jsx-element",l=Wy({input:e,containerKind:a,sourceKind:c,source:e.source,containerPath:o.path,members:i.members});return wd(e,t,l,{kind:a,sourceKind:c},r)}return xn(e,[mt("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")])}function Ad(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:mt("DOCUMENT_VERSION_STALE","Placement lookup is stale for the requested document version",{expectedDocumentVersion:e.documentVersion,requestedDocumentVersion:n})};let r=e.placementByKey.get(t)??null;return r?{ok:!0,placement:r}:{ok:!1,diagnostic:mt("PLACEMENT_KEY_NOT_FOUND","Placement key was not found in the projected page composition",{placementKey:t})}}function Xy(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:mt("DOCUMENT_VERSION_STALE","Placement lookup is stale for the requested document version",{expectedDocumentVersion:e.documentVersion,requestedDocumentVersion:n})};let r=e.placementUnitByKey.get(t)??null;return r?{ok:!0,placement:r}:{ok:!1,diagnostic:mt("PLACEMENT_KEY_NOT_FOUND","Placement unit key was not found in the projected page composition",{placementUnitKey:t})}}function Gy(e){return e.ok?WA(e.projection):GA(e.projection)}function WA(e){let t=new Map,n=[];for(let l of e.placements)l.members.length===0&&e.placements.length>1||l.members.length>0&&!l.anchorSourceRange||t.has(l.placementUnitKey)||t.set(l.placementUnitKey,l);let r=new Map,o=new Map;for(let[l,u]of t){let d=u.members.flatMap((m,y)=>Yy(e,u,m,y,e.container.placementKey)),f=d.filter(({member:m})=>m.isBusinessMember).map(({sourceMember:m})=>ZA(l,m,u.independent)),g=d.length>0?d:[{sourceMember:{key:`source:${l}:empty`,kind:e.container.kind==="starter-placeholder"?"starter-placeholder":"null-return",containerKey:e.container.placementKey,label:"empty-page",sourceFile:e.entryFile,isAtomic:!0},member:null}];r.set(l,g.map(({sourceMember:m})=>m)),o.set(l,f);let p=g[0]?.sourceMember.key??l;n.push({key:l,containerKey:p,businessMemberKeys:f.map(m=>m.key),isMultiMember:u.memberCount>1})}let i=[...r.values()].flat(),s=[...o.values()].flat(),a=i[0]?.key??null,c=e.placements.map(l=>({kind:"page-composition",placementKey:l.placementKey,documentVersion:e.documentVersion,composition:e.composition,placementUnitKey:l.placementUnitKey,relation:l.relation}));return{status:"supported",version:e.version,composition:e.composition,container:YA(e,a),sourceMembers:i,businessMembers:s,placementUnits:n,placements:c}}function GA(e){let t=e.diagnostics.map(qA);return{status:"unsupported",version:e.version,composition:e.composition,reason:QA(e.diagnostics),diagnostics:t}}function YA(e,t){switch(e.container.kind){case"jsx-container":return{kind:"jsx-container",key:e.container.placementKey,sourceMemberKey:t??e.container.placementKey,sourceFile:e.entryFile,componentName:e.defaultExportName??void 0};case"starter-placeholder":return{kind:"starter-placeholder",key:e.container.placementKey,sourceFile:e.entryFile};case"virtual-route-root":return{kind:"virtual-route-root",key:e.container.placementKey}}}function Yy(e,t,n,r,o){let i=`source:${t.placementUnitKey}:${r}:${n.memberKey}`;return[{sourceMember:{key:i,kind:n.kind==="jsx-element"?"jsx-element":"jsx-expression",containerKey:o,label:n.label,sourceFile:e.entryFile,isAtomic:n.kind!=="jsx-element"},member:n},...n.children.flatMap((a,c)=>Yy(e,t,a,c,i))]}function ZA(e,t,n){return{key:`business:${e}:${t.key}`,sourceMemberKey:t.key,containerKey:e,label:t.label,isIndependent:n}}function qA(e){return{code:eT(e),message:e.message}}function QA(e){let t=e[0];if(!t)return"UNSUPPORTED_ROUTE_STRUCTURE";switch(t.code){case"ROUTE_RETURN_NOT_FOUND":return"ROUTE_RETURN_NOT_FOUND";case"MULTIPLE_PAGE_RETURNS":return"MULTIPLE_PAGE_RETURNS";case"INDIRECT_RETURN_ONLY":return"INDIRECT_RETURN_ONLY";case"PLACEMENT_KEY_NOT_FOUND":return"RUNTIME_ANCHOR_UNRESOLVED";case"DOCUMENT_VERSION_STALE":return"VERSION_STALE";case"UNSUPPORTED_PAGE_SHAPE":return t.details?.reason==="ambiguous-placement"?"PAGE_CONTAINER_AMBIGUOUS":"UNSUPPORTED_ROUTE_STRUCTURE";default:return"UNSUPPORTED_ROUTE_STRUCTURE"}}function eT(e){switch(e.code){case"PLACEMENT_KEY_NOT_FOUND":return"RUNTIME_ANCHOR_UNRESOLVED";case"DOCUMENT_VERSION_STALE":return"VERSION_STALE";case"UNSUPPORTED_PAGE_SHAPE":return e.details?.reason==="ambiguous-placement"?"PAGE_CONTAINER_AMBIGUOUS":"UNSUPPORTED_ROUTE_STRUCTURE";default:return e.code}}function tT(e){let t=null;return HA(e,{ExportDefaultDeclaration(n){let r=n.get("declaration");if(r.isArrowFunctionExpression()||r.isFunctionDeclaration()||r.isFunctionExpression()){t=r,n.stop();return}if(!r.isIdentifier())return;let o=n.scope.getBinding(r.node.name);if(!o)return;let i=nT(o.path);i&&(t=i,n.stop())}}),t}function nT(e){if(e.isArrowFunctionExpression()||e.isFunctionDeclaration()||e.isFunctionExpression())return e;if(e.isVariableDeclarator()){let t=e.get("init");if(t.isArrowFunctionExpression()||t.isFunctionExpression())return t}return null}function rT(e){let t=e.get("body");if(!t.isBlockStatement()){let s=Ui(t);return s?{ok:!0,expression:s}:{ok:!1,diagnostic:mt("ROUTE_RETURN_NOT_FOUND","Route default export does not contain a proven return boundary")}}let n=t.get("body"),r=n.at(-1);if(!r)return{ok:!1,diagnostic:mt("ROUTE_RETURN_NOT_FOUND","Route default export does not contain a proven return boundary")};if(!r.isReturnStatement())return{ok:!1,diagnostic:mt("UNSUPPORTED_PAGE_SHAPE","Route default export must end with a direct terminal return",{reason:"terminal-return-required"})};for(let s of n.slice(0,-1)){if(s.isIfStatement()){if(!oT(s)&&!Ka(s))return{ok:!1,diagnostic:mt("UNSUPPORTED_PAGE_SHAPE","Route guard return shape is not statically safe",{reason:"guard-shape"})};continue}if(Zy(s)||qy(s))return{ok:!1,diagnostic:mt("UNSUPPORTED_PAGE_SHAPE","Route default export contains unsupported control flow before the terminal return",{reason:"control-flow-return"})}}let o=r.get("argument"),i=Ui(o);return i?{ok:!0,expression:i}:{ok:!1,diagnostic:mt("ROUTE_RETURN_NOT_FOUND","Route default export returns without a boundary expression",{reason:"bare-return"})}}function oT(e){if(e.node.alternate)return null;let t=e.get("consequent");if(t.isReturnStatement())return t;if(!t.isBlockStatement())return null;let n=t.get("body"),r=n.at(-1);if(!r?.isReturnStatement())return null;for(let o of n.slice(0,-1))if(Zy(o)||qy(o))return null;return r}function Zy(e){return e.isForStatement()||e.isForInStatement()||e.isForOfStatement()||e.isWhileStatement()||e.isDoWhileStatement()||e.isSwitchStatement()||e.isTryStatement()||e.isWithStatement()}function qy(e){let t=!1;return e.traverse({Function(n){n.skip()},ReturnStatement(){t=!0}}),t}function iT(e,t){let n=t.scope.getBinding(e.node.name);if(!n||n.scope.path.node!==t.node)return{status:"not-local"};if(!n.path.isVariableDeclarator())return{status:"not-local"};let r=n.path.parentPath;if(!r?.isVariableDeclaration()||r.node.kind!=="const")return{status:"invalid"};let o=n.path.get("init");if(Array.isArray(o)||!o.node)return{status:"invalid"};let i=Ui(o);return!i||!i.isJSXElement()&&!i.isJSXFragment()?{status:"invalid"}:n.referencePaths.length!==1||n.referencePaths[0]?.node!==e.node||n.constantViolations.length!==0?{status:"invalid"}:{status:"resolved",expression:i}}function sT(e){return e.isConditionalExpression()?zy(Ui(e.get("consequent")))&&zy(Ui(e.get("alternate"))):!1}function zy(e){return!!(e&&(e.isJSXElement()||e.isJSXFragment()||e.isNullLiteral()))}function Ui(e){if(!e.node)return null;let t=e;for(;;){if(t.isParenthesizedExpression()){t=t.get("expression");continue}if(t.isTSAsExpression()||t.isTSTypeAssertion()){t=t.get("expression");continue}if(t.isTSNonNullExpression()||t.isTypeCastExpression()){t=t.get("expression");continue}break}return t.isExpression()?t:null}function aT(e,t){if(e.isIdentifier())return Hy(e.node.name,t);if(e.isCallExpression()){let n=e.get("callee");if(n.isIdentifier())return Hy(n.node.name,t)}return!1}function Hy(e,t){let n=t.scope.getBinding(e);if(!n)return!1;let r=n.path;if(r.isFunctionDeclaration()||r.isFunctionExpression()||r.isArrowFunctionExpression())return!0;if(r.isVariableDeclarator()){let o=r.get("init");return o.isFunctionExpression()||o.isArrowFunctionExpression()}return!1}function cT(e,t,n){return e.includes("DESIGN_PLAN_REPLACE_ME")&&t.isJSXElement()&&n.length>0&&Ld(t)}function Ld(e){for(let t of e.get("children")){if(t.isJSXText()){if(t.node.value.trim())return!1;continue}if(t.isJSXExpressionContainer()){let n=t.get("expression");if(n.isJSXEmptyExpression()||n.isNullLiteral())continue;return!1}if(t.isJSXFragment()){if(!Ld(t))return!1;continue}if(t.isJSXElement()&&!Ld(t))return!1}return!0}function lT(e){return{ok:!0,path:e}}function Lo(e){let t=[],n=!1;for(let r of e.get("children")){if(r.isJSXText()){if(!r.node.value.trim())continue;t.push({memberKey:Md(r.node.type,r.node.start,r.node.end),kind:"text",nodeType:r.node.type,sourceRange:ln(r.node.loc),businessMemberCount:0,parentSourceRange:ln(e.node.loc),children:[],isBusinessMember:!1,label:"text"});continue}if(r.isJSXExpressionContainer()){let o=r.get("expression");if(o.isJSXEmptyExpression()||o.isNullLiteral())continue;if(o.isJSXFragment()){let i=Lo(o);n||=i.unsupported,t.push(...i.members);continue}if(o.isJSXElement()){let i=Ki(o)?Lo(o):null;n||=i?.unsupported??!1,t.push({...Dd(o,i?.members),sourceRange:ln(r.node.loc),parentSourceRange:ln(e.node.loc)});continue}if(o.isJSXSpreadChild()){n=!0;continue}t.push({memberKey:Md(o.node.type,o.node.start,o.node.end),kind:"atomic-expression",nodeType:o.node.type,sourceRange:ln(r.node.loc),businessMemberCount:1,parentSourceRange:ln(e.node.loc),children:[],isBusinessMember:!0,label:"atomic-expression"});continue}if(r.isJSXFragment()||r.isJSXElement()&&Ye(r)){let o=Lo(r);n||=o.unsupported,t.push(...o.members);continue}if(r.isJSXElement()){let o=Ki(r)?Lo(r):null;n||=o?.unsupported??!1,t.push({...Dd(r,o?.members),parentSourceRange:ln(e.node.loc)})}}return{members:t,unsupported:n}}function Dd(e,t){let n=e.isJSXElement()&&Ki(e)?t??Lo(e).members:[],r=e.isJSXElement()&&!Ki(e)&&!Ye(e);return{memberKey:Md(e.node.type,e.node.start,e.node.end),kind:"jsx-element",nodeType:e.node.type,sourceRange:ln(e.node.loc),businessMemberCount:r?1:Qy(n),parentSourceRange:ln(e.parentPath?.node.loc),children:n,isBusinessMember:r,label:uT(e)}}function Ki(e){let t=e.node.openingElement.name;return t.type==="JSXIdentifier"&&t.name[0]===t.name[0]?.toLowerCase()}function uT(e){if(e.isJSXFragment())return"Fragment";let t=e.node.openingElement.name;if(t.type==="JSXIdentifier")return t.name;if(t.type==="JSXMemberExpression"){let n=t.object;return`${n.type==="JSXIdentifier"?n.name:"member"}.${t.property.name}`}return t.name.name}function Qy(e){return e.reduce((t,n)=>t+n.businessMemberCount,0)}function Ha(e){return e.length===0?0:Math.max(1,Qy(e))}function Wy(e){let t=ln(e.containerPath.node.loc),n=jd(e.source,e.containerPath.node.start,e.containerPath.node.end),r=un(e.input,e.containerKind,e.sourceKind,t),o=un(e.input,e.containerKind,"placement-unit",t);return{placementKey:r,placementUnitKey:o,version:e.input.version,containerKey:r,independent:Ha(e.members)<=1,memberCount:Ha(e.members),sourceRange:t,sourceHash:n,relation:"append",containerSourceRange:t,containerSourceHash:n,anchorSourceRange:null,anchorSourceHash:null,members:e.members}}function dT(e){let t=ln(e.expression.node.loc),n=jd(e.source,e.expression.node.start,e.expression.node.end),r=un(e.input,"virtual-route-root","atomic-expression",t),o=un(e.input,"virtual-route-root","placement-unit",t);return{placementKey:r,placementUnitKey:o,version:e.input.version,containerKey:r,independent:!0,memberCount:1,sourceRange:t,sourceHash:n,relation:"append",containerSourceRange:t,containerSourceHash:n,anchorSourceRange:null,anchorSourceHash:null,members:[{memberKey:un(e.input,"virtual-route-root","atomic-member",t),kind:"atomic-expression",nodeType:e.expression.node.type,sourceRange:t,businessMemberCount:1,parentSourceRange:null,children:[],isBusinessMember:!0,label:e.expression.node.type}]}}function ex(e,t){let n=ln(t.node.loc),r=jd(e.source,t.node.start,t.node.end);return!n||!r?null:{kind:"expression",documentVersion:e.version,sourceRange:n,sourceHash:r}}function wd(e,t,n,r,o){let i=ex(e,o);if(!i)return xn(e,[mt("UNSUPPORTED_PAGE_SHAPE","Route default export does not provide an exact mutation target",{reason:"mutation-target-unavailable"})]);let s=n.containerSourceRange??n.sourceRange,a=fT(e,n,s),c=fd(a),l={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:nx(t),container:{kind:r.kind,placementKey:n.placementKey,placementUnitKey:n.placementUnitKey,version:e.version,isEmptyPage:n.memberCount===0,sourceKind:r.sourceKind,sourceRange:s,sourceHash:n.sourceHash},placements:a,diagnostics:[],placementByKey:new Map,unitByKey:new Map,placementsByUnitKey:new Map,placementUnitByKey:new Map,mutationTarget:i};return Object.defineProperties(l,{placementByKey:{value:c.placementByKey,enumerable:!1},unitByKey:{value:c.unitByKey,enumerable:!1},placementsByUnitKey:{value:c.placementsByUnitKey,enumerable:!1},placementUnitByKey:{value:c.sourcePlacementByUnitKey,enumerable:!1}}),{ok:!0,projection:l}}function fT(e,t,n){if(t.members.length===0)return[t];let r=[],o=(l,u,d,f,g,p,m=n)=>({...t,placementKey:u,placementUnitKey:d,containerKey:t.placementKey,independent:Ha(p)<=1,memberCount:Ha(p),sourceRange:f,sourceHash:f?Fd(e.source,f):null,relation:l,containerSourceRange:m,containerSourceHash:m?Fd(e.source,m):null,anchorSourceRange:g,anchorSourceHash:g?Fd(e.source,g):null,members:p}),i=t.placementKey,s=t.members.map(l=>un(e,i,"placement-unit",l.sourceRange)),a=s[0]??t.placementUnitKey,c=s.at(-1)??t.placementUnitKey;r.push(o("prepend",un(e,i,"prepend",n),a,n,null,[]));for(let l of t.members){let u=l.parentSourceRange??n,d=un(e,i,"placement-unit",l.sourceRange);r.push(o("before",un(e,d,"before",l.sourceRange),d,l.sourceRange,l.sourceRange,[l],u)),r.push(o("after",un(e,d,"after",l.sourceRange),d,l.sourceRange,l.sourceRange,[l],u))}return r.push(o("append",i,c,n,null,[])),r}function Od(e,t,n,r){let o=ex(e,r);if(!o)return xn(e,[mt("UNSUPPORTED_PAGE_SHAPE","Route default export does not provide an exact mutation target",{reason:"mutation-target-unavailable"})]);let i=un(e,n,"empty-container",void 0),s=un(e,n,"empty-unit",void 0),a={placementKey:i,placementUnitKey:s,version:e.version,containerKey:i,independent:!0,memberCount:0,sourceRange:null,sourceHash:null,relation:"append",containerSourceRange:null,containerSourceHash:null,anchorSourceRange:null,anchorSourceHash:null,members:[]},c=fd([a]),l={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:nx(t),container:{kind:n,placementKey:i,placementUnitKey:s,version:e.version,isEmptyPage:!0,sourceKind:n==="starter-placeholder"?"starter-placeholder":"jsx-fragment",sourceRange:null,sourceHash:null},placements:[a],diagnostics:[],placementByKey:new Map,unitByKey:new Map,placementsByUnitKey:new Map,placementUnitByKey:new Map,mutationTarget:o};return Object.defineProperties(l,{placementByKey:{value:c.placementByKey,enumerable:!1},unitByKey:{value:c.unitByKey,enumerable:!1},placementsByUnitKey:{value:c.placementsByUnitKey,enumerable:!1},placementUnitByKey:{value:c.sourcePlacementByUnitKey,enumerable:!1}}),{ok:!0,projection:l}}function xn(e,t){return{ok:!1,projection:{status:"unsupported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,diagnostics:t}}}function mt(e,t,n){return n===void 0?{code:e,message:t}:{code:e,message:t,details:n}}function un(e,t,n,r){return tx([e.route,e.entryFile,String(e.version),t,n,r?`${r.startLine}:${r.startColumn}-${r.endLine}:${r.endColumn}`:"no-range"])}function Md(e,t,n){return tx(["member",e,String(t??-1),String(n??-1)])}function tx(e){return`pc_${Bd("sha256").update(e.join("\0")).digest("hex").slice(0,24)}`}function jd(e,t,n){return t==null||n==null?null:`sha256:${Bd("sha256").update(e.slice(t,n)).digest("hex")}`}function Fd(e,t){let n=[0];for(let i=0;i<e.length;i+=1)e.charCodeAt(i)===10&&n.push(i+1);let r=n[t.startLine-1],o=n[t.endLine-1];return r===void 0||o===void 0?null:`sha256:${Bd("sha256").update(e.slice(r+t.startColumn,o+t.endColumn)).digest("hex")}`}function ln(e){return e?{startLine:e.start.line,startColumn:e.start.column,endLine:e.end.line,endColumn:e.end.column}:null}function nx(e){if(e.isFunctionDeclaration())return e.node.id?.name??null;let t=e.parentPath;return t?.isVariableDeclarator()&&t.node.id.type==="Identifier"?t.node.id.name:null}import{createHash as kT}from"node:crypto";import*as bn from"@babel/types";function rx(e){if(!e.path.isIdentifier())return{kind:"not-alias"};let t=e.path.scope.getBinding(e.path.node.name);if(!t)return{kind:"unbound"};if(t.constantViolations.length>0)return{kind:"reassigned"};let n=t.path;if(!n.isVariableDeclarator())return{kind:"not-alias"};if(e.aliases.has(n.node)||e.aliases.size>=(e.maxDepth??32))return{kind:"guard"};let r=n.get("init");return Array.isArray(r)||!r.node?{kind:"not-alias"}:{kind:"initializer",initializer:r,aliases:new Set(e.aliases).add(n.node)}}import $d from"@babel/traverse";import*as Do from"@babel/types";var mT=typeof $d=="function"?$d:$d.default,gT=32;function br(e,t,n,r=new Set){if(r.has(e.ast)||r.size>=gT)return null;let o=new Set(r).add(e.ast),i;if(mT(e.ast,{Program(d){i=d,d.stop()}}),!i)return null;let s=(d,f)=>{let g=sr(e.file,d,n),p=g?n.get(g):void 0;return p?br(p,f,n,o):null},a=d=>{let f=i.scope.getBinding(d);if(!f||f.constantViolations.length)return null;let g=f.path.parentPath;return g?.isImportDeclaration()?g.node.importKind==="type"?null:f.path.isImportDefaultSpecifier()?s(g.node.source.value,"default"):f.path.isImportSpecifier()&&f.path.node.importKind!=="type"?s(g.node.source.value,Wa(f.path.node.imported)):null:f.path.isVariableDeclarator()?f.path.get("init"):f.path},c=[],l=[];for(let d of i.get("body"))if(d.isExportDefaultDeclaration()&&t==="default"){let f=d.get("declaration");c.push(f.isIdentifier()?a(f.node.name):f)}else if(d.isExportNamedDeclaration()&&d.node.exportKind!=="type"){let f=d.get("declaration");f.node&&Object.hasOwn(Do.getBindingIdentifiers(f.node),t)&&c.push(a(t));for(let g of d.node.specifiers)Do.isExportSpecifier(g)&&g.exportKind!=="type"&&Wa(g.exported)===t&&c.push(d.node.source?s(d.node.source.value,Wa(g.local)):a(Wa(g.local)))}else d.isExportAllDeclaration()&&d.node.exportKind!=="type"&&t!=="default"&&l.push(d.node.source.value);if(c.length)return c.length===1?c[0]:null;let u=l.map(d=>s(d,t)).filter(d=>d!==null);return u.length===1?u[0]:null}function Wa(e){return Do.isIdentifier(e)?e.name:e.value}import*as be from"@babel/types";var hT=32;function Kt(e,t=new Map,n=new Set){if(n.has(e.node)||n.size>=hT)return null;let r=new Set(n).add(e.node),o=t.get(e.node);if(o)return Ji(o,t,r);if(e.isTSAsExpression()||e.isTSTypeAssertion()||e.isTSNonNullExpression()||e.isTSSatisfiesExpression()||e.isParenthesizedExpression())return Kt(e.get("expression"),t,r);if(e.isIdentifier()){let i=e.scope.getBinding(e.node.name);return!i||i.constantViolations.length?null:Ud(i,t,r)}if(e.isMemberExpression()||e.isOptionalMemberExpression()){let i=Jt(e.node.property,e.node.computed),s=e.get("object"),a=Kt(s,t,r);return i!==null&&a?Za(a,i,t,r):null}if(e.isConditionalExpression())return Ji([e.get("consequent"),e.get("alternate")],t,r);if(e.isLogicalExpression())return Ji([e.get("left"),e.get("right")],t,r);if(e.isSequenceExpression()){let i=e.get("expressions").at(-1);return i?Kt(i,t,r):null}if(e.isCallExpression()&&be.isIdentifier(e.node.callee)){let i=e.scope.getBinding(e.node.callee.name);if(!i||!Mo(i))return null;let s=i.path.isFunctionDeclaration()?i.path:i.path.isVariableDeclarator()?i.path.get("init"):null;if(!s||!(s.isFunctionDeclaration()||s.isFunctionExpression()||s.isArrowFunctionExpression())||s.node.async||s.node.generator)return null;let a=s,c=new Map(t),l=e.get("arguments");for(let[g,p]of a.get("params").entries()){if(!p.isIdentifier())return null;let m=l[g];if(!m?.isExpression())return null;let y=Kt(m,t,r);if(!y)return null;let x=p.scope.getBinding(p.node.name);if(!x)return null;c.set(x.identifier,y)}let u=a.get("body"),d=u.isBlockStatement()?u.get("body")[0]:u;if(!d)return null;let f=d.isReturnStatement()?d.get("argument"):d;return f.node?Kt(f,c,r):null}return[e]}function Ud(e,t=new Map,n=new Set){if(e.constantViolations.length)return null;let r=t.get(e.identifier);if(r)return Ji(r,t,n);if(!e.path.isVariableDeclarator())return null;let o=e.path.get("init");if(!o.node)return null;let i=Kt(o,t,n);if(!i)return null;let s=Vd(e.path.node.id,e.identifier.name);return s?s.reduce((a,c)=>a&&Za(a,c,t,n),i):null}function Ga(e){if(!e.params.every(n=>be.isIdentifier(n)||be.isAssignmentPattern(n)&&be.isIdentifier(n.left)&&ro(n.right)))return!1;if(!be.isBlockStatement(e.body))return ro(e.body);if(e.body.body.length!==1)return!1;let t=e.body.body[0];return be.isReturnStatement(t)&&!!t.argument&&ro(t.argument)}function Mo(e){if(e.constantViolations.length>0)return!1;if(e.path.isFunctionDeclaration())return Ga(e.path.node);let t=e.path.isVariableDeclarator()?e.path:e.path.findParent(r=>r.isVariableDeclarator()),n=t?.isVariableDeclarator()?t.node.init:null;return be.isArrowFunctionExpression(n)||be.isFunctionExpression(n)?Ga(n):!1}function ro(e){let t=!0;return be.traverseFast(e,n=>{(be.isCallExpression(n)&&!Ya(n)||be.isOptionalCallExpression(n)||be.isNewExpression(n)||be.isAwaitExpression(n)||be.isAssignmentExpression(n)||be.isUpdateExpression(n)||be.isUnaryExpression(n,{operator:"delete"})||be.isYieldExpression(n)||be.isTaggedTemplateExpression(n))&&(t=!1)}),t}function Ya(e){return be.isIdentifier(e.callee,{name:"useTranslations"})&&e.arguments.length===1&&be.isStringLiteral(e.arguments[0])}function Ji(e,t,n){let r=[];for(let o of e){let i=Kt(o,t,n);if(!i)return null;r.push(...i)}return r.length?r:null}function Za(e,t,n,r=new Set){let o=[];for(let i of e)if(i.isObjectExpression()){let s=i.get("properties");if(s.some(c=>!c.isObjectProperty()||c.node.computed))return null;let a=s.filter(c=>c.isObjectProperty()&&Jt(c.node.key,!1)===t);if(a.length!==1||!a[0].isObjectProperty())return null;o.push(a[0].get("value"))}else if(i.isArrayExpression()&&/^(?:0|[1-9]\d*)$/u.test(t)){if(i.node.elements.some(a=>be.isSpreadElement(a)))return null;let s=i.get("elements")[Number(t)];if(!s?.node||s.isSpreadElement())return null;o.push(s)}else return null;return Ji(o,n,r)}function Kd(e,t){let n=Kt(e,t);return!!(n?.length&&n.every(r=>be.isLiteral(r.node)&&!r.isRegExpLiteral()||r.isTemplateLiteral()||r.isBinaryExpression()||r.isUnaryExpression()))}function Jt(e,t){return!t&&be.isIdentifier(e)?e.name:be.isStringLiteral(e)||be.isNumericLiteral(e)?String(e.value):null}function Vd(e,t){if(be.isIdentifier(e))return e.name===t?[]:null;if(be.isObjectPattern(e))for(let n of e.properties){if(!be.isObjectProperty(n)||n.computed)continue;let r=Jt(n.key,!1),o=Vd(n.value,t);if(r!==null&&o)return[r,...o]}if(be.isArrayPattern(e))for(let[n,r]of e.elements.entries()){if(!r)continue;let o=Vd(r,t);if(o)return[String(n),...o]}return null}function ox(e,t=new Set,n){return ix(e.get("callee"),t,n)}function ix(e,t,n){if(t.has(e.node)||t.size>=32)return{kind:"guard"};if(e.isIdentifier()){let r=e.scope.getBinding(e.node.name);if(!r)return{kind:"unknown"};if(t.has(r.path.node))return{kind:"guard"};let o=new Set(t).add(r.path.node),i=r.path.parentPath;if(i?.isImportDeclaration()&&n){let l=i.node.source.value;if(!(l.startsWith(".")||l.startsWith("@/")))return{kind:"unknown"};let u=r.path.scope.getProgramParent().path.node,d=[...n.values()].find(y=>y.ast.program===u),f=d&&sr(d.file,l,n),g=f?n.get(f):void 0,p=r.path.isImportDefaultSpecifier()?"default":r.path.isImportSpecifier()&&r.path.node.importKind!=="type"?Jt(r.path.node.imported,!1):null,m=g&&p&&i.node.importKind!=="type"?br(g,p,n):null;return m?Bo(m,o,n):{kind:"guard"}}let s=r.path.isVariableDeclarator()?r.path.get("init"):r.path;if(!s.node)return{kind:"unknown"};let a=Bo(s,o,n);if(a.kind!=="sources")return a;let c=[...a.sources];for(let l of r.constantViolations){if(!l.isAssignmentExpression({operator:"="}))return{kind:"guard"};let u=Bo(l.get("right"),o,n);if(u.kind!=="sources")return{kind:"guard"};c.push(...u.sources)}return{kind:"sources",sources:c,aliases:a.aliases}}if(e.isMemberExpression()||e.isOptionalMemberExpression()){let r=Jt(e.node.property,e.node.computed),o=e.get("object"),i=Kt(o);if(!i)return{kind:"unknown"};let s=[],a=new Set(t).add(e.node);for(let c of i){if(!c.isObjectExpression())return{kind:"unknown"};if(r===null||c.node.properties.some(d=>d.type!=="ObjectProperty"))return{kind:"guard"};let l=c.get("properties").filter(d=>d.isObjectProperty()&&Jt(d.node.key,d.node.computed)===r);if(l.length!==1||!l[0].isObjectProperty())return{kind:"guard"};let u=Bo(l[0].get("value"),a,n);if(u.kind!=="sources")return{kind:"guard"};s.push(...u.sources),a=u.aliases}return{kind:"sources",sources:s,aliases:a}}return Bo(e,new Set(t).add(e.node),n)}function Bo(e,t,n){if(e.isIdentifier())return ix(e,t,n);if(e.isTSAsExpression()||e.isTSTypeAssertion()||e.isTSNonNullExpression()||e.isParenthesizedExpression())return Bo(e.get("expression"),t,n);if(!(e.isFunctionDeclaration()||e.isFunctionExpression()||e.isArrowFunctionExpression()))return{kind:"unknown"};let r=e,o=[];for(let s of r.get("params"))s.isAssignmentPattern()&&o.push(s.get("right")),s.traverse({AssignmentPattern(a){o.push(a.get("right"))}});let i=r.get("body");return i.isBlockStatement()?i.traverse({Function(s){s.skip()},ReturnStatement(s){let a=s.get("argument");a.node&&o.push(a),s.skip()}}):o.push(i),{kind:"sources",sources:o,aliases:t}}function Qa(e,t){return JSON.stringify([t,e])}var xT=new Set;function ux(e,t){let n=new Map,r=[],o=new Map,i=(p,m)=>JSON.stringify([p,m.loc?.start.line,m.loc?.start.column,m.loc?.end.line,m.loc?.end.column]);for(let p of e.graph.elements.values()){let m=p.sourceRange;o.set(JSON.stringify([p.sourceFile,m.startLine,m.startColumn,m.endLine,m.endColumn]),p)}let s=p=>r.push({code:"render-occurrence-unproven",message:"A block render occurrence cannot be proven statically.",file:p}),a=(p,m)=>!lx(m)&&[...t].some(y=>e.graph.elements.get(y)?.sourceFile===p);function c(p,m,y,x,S,b=xT){if(p.isIdentifier())return x&&qa(p,x)?x.children.some(k=>c(k.path,k.file,y,k.substitution,S,b)):u({path:p,file:m,active:y,substitution:x,unknownIsRelevant:S,aliases:b});if(p.isCallExpression()||p.isOptionalCallExpression()){let k=p,I=ox(k,b,e.parsedModules);return I.kind==="guard"||I.kind==="sources"&&I.sources.some(v=>c(v,[...e.parsedModules.values()].find(N=>N.ast.program===v.scope.getProgramParent().path.node)?.file??m,y,x,S,I.aliases))?!0:k.get("arguments").some(v=>c(v,m,y,x,S,b))||I.kind==="unknown"&&S}if(p.isJSXElement()){if(Ye(p))return p.get("children").some(F=>c(F,m,y,x,S,b));let k=o.get(i(m,p.node));if(k){if(t.has(k.identity.key))return!0;if(k.boundaryKind==="component-boundary"&&!k.isPublicUiComponent){let F=e.parsedModules.get(k.sourceFile);if(!F)return!1;let B=gr({module:F,componentName:k.tag,callSourceRange:k.sourceRange,...k.importedFrom?{imported:{file:k.importedFrom,module:e.parsedModules.get(k.importedFrom),exportName:k.exportName??k.tag,parsedModules:e.parsedModules}}:{}});return B.ok?B.metadataOnly?!1:l(B,p,k.sourceFile,y,x,b):B.diagnostic.code==="component-external-module-opaque"?Xi(p).some(X=>c(X,m,y,x,!1,b)):a(F.file,B.diagnostic.code)}return p.get("children").some(F=>c(F,m,y,x,S,b))}let I=p.node.openingElement.name;if(!bn.isJSXIdentifier(I))return!1;if(/^[a-z]/.test(I.name))return p.get("children").some(F=>c(F,m,y,x,S,b));let v=e.parsedModules.get(m),N=p.node.loc;if(!v||!N)return!1;let A=vT({path:p,file:m,componentName:I.name,parsedModules:e.parsedModules}),w=gr({module:v,componentName:I.name,callSourceRange:{startLine:N.start.line,startColumn:N.start.column,endLine:N.end.line,endColumn:N.end.column},...A?{imported:A}:{}});return w.ok?w.metadataOnly?!1:l(w,p,m,y,x,b):w.diagnostic.code==="component-external-module-opaque"?Xi(p).some(F=>c(F,m,y,x,!1,b)):a(v.file,w.diagnostic.code)}if(p.isJSXFragment())return p.get("children").some(k=>c(k,m,y,x,S,b));if(p.isJSXExpressionContainer()||p.isParenthesizedExpression()||p.isTSAsExpression()||p.isTSNonNullExpression()||p.isTSTypeAssertion())return c(p.get("expression"),m,y,x,S,b);let E=!1;return p.traverse({"CallExpression|OptionalCallExpression"(k){c(k,m,y,x,S,b)&&(E=!0),k.skip(),E&&k.stop()},ReferencedIdentifier(k){c(k,m,y,x,S,b)&&(E=!0),E&&k.stop()},JSXElement(k){c(k,m,y,x,S,b)&&(E=!0),k.skip(),E&&k.stop()},JSXFragment(k){c(k,m,y,x,S,b)&&(E=!0),k.skip(),E&&k.stop()}}),E?!0:S&&!oo(p)}function l(p,m,y,x,S,b){let E=`${p.sourceFile}#${p.componentName}`;if(x.has(E))return!1;let k=new Set(x).add(E);return p.returnAlternatives?.some(I=>Xi(I).some(v=>c(v,p.sourceFile,k,null,!1,b)))||p.roots.some(I=>c(I,p.sourceFile,k,null,!1,b))?!0:sx(p.roots).kind==="none"?!1:cx(m).some(I=>c(I,y,k,S,!0,b))}function u(p){if(!p.path.isIdentifier())return p.unknownIsRelevant;let m=rx({path:p.path,aliases:p.aliases});return m.kind==="unbound"?p.unknownIsRelevant&&p.path.node.name!=="undefined":m.kind==="guard"||m.kind==="reassigned"?!0:m.kind==="not-alias"?p.unknownIsRelevant:c(m.initializer,p.file,p.active,p.substitution,p.unknownIsRelevant,m.aliases)?!0:Jd(m.initializer).isIdentifier()?!1:p.unknownIsRelevant&&!oo(m.initializer)}let d=(p,m,y,x,S,b)=>{if(p.isIdentifier()){c(p,m,x,b,!1)&&s(m);return}if(p.isJSXElement()){if(Ye(p)){for(let I of p.get("children"))d(I,m,y,x,S,b);return}let E=o.get(i(m,p.node));if(!E)return;let k=E.identity.key;if(t.has(k)){S||s(m);let I=n.get(k)??[];I.push(Qa(k,y)),n.set(k,I)}if(E.boundaryKind==="component-boundary"&&!E.isPublicUiComponent){let I=e.parsedModules.get(E.sourceFile);if(!I)return;let v=gr({module:I,componentName:E.tag,callSourceRange:E.sourceRange,...E.importedFrom?{imported:{file:E.importedFrom,module:e.parsedModules.get(E.importedFrom),exportName:E.exportName??E.tag,parsedModules:e.parsedModules}}:{}});if(!v.ok){if(v.diagnostic.code==="component-external-module-opaque"){Xi(p).some(X=>c(X,m,x,b,!1))&&s(m);return}[...t].some(X=>e.graph.elements.get(X)?.sourceFile===I.file)&&!lx(v.diagnostic.code)&&s(I.file);return}if(v.metadataOnly)return;let N=`${v.sourceFile}#${v.componentName}`;if(x.has(N)){s(I.file);return}let A=new Set(x).add(N);v.returnAlternatives?.some(X=>Xi(X).some($=>c($,v.sourceFile,A,b,!1)))&&s(v.sourceFile);let w=sx(v.roots),F=IT(p);if(w.kind==="unproven"||w.kind==="supported"&&F){for(let X of cx(p))if(c(X,m,A,b,!0)){s(m);break}}let B=w.kind==="supported"&&!F?{bindingNode:w.bindingNode,children:p.get("children").map(X=>({path:X,file:m,substitution:b}))}:null;for(let X of v.roots)d(X,v.sourceFile,[...y,k],A,S,B);return}for(let I of p.get("children"))d(I,m,y,x,S,b);return}if(p.isJSXFragment()){for(let E of p.get("children"))d(E,m,y,x,S,b);return}if(p.isJSXExpressionContainer()){let E=p.get("expression");if(b&&!E.isJSXEmptyExpression()){let k=Jd(E);if(qa(k,b)){for(let I of b.children)d(I.path,I.file,y,x,S,I.substitution);return}if(bT(E,b))for(let I of b.children)d(I.path,I.file,y,x,!1,I.substitution)}d(E,m,y,x,S,b);return}if(p.isParenthesizedExpression()||p.isTSAsExpression()||p.isTSNonNullExpression()||p.isTSTypeAssertion()){d(p.get("expression"),m,y,x,S,b);return}c(p,m,x,b,!1)&&s(m),p.traverse({JSXElement(E){d(E,m,y,x,!1,b),E.skip()}})},f=e.parsedModules.get(e.entryFile);if(!f)return{occurrences:n,diagnostics:r};let g=hn({module:f,exportName:"default",allowNonRenderingGuards:!0});if(!g.ok)return s(e.entryFile),{occurrences:n,diagnostics:r};for(let p of g.roots)d(p,f.file,[],new Set,!0,null);return{occurrences:n,diagnostics:r}}function Jd(e){let t=e;for(;t.isParenthesizedExpression()||t.isTSAsExpression()||t.isTSNonNullExpression()||t.isTSTypeAssertion();)t=t.get("expression");return t}function oo(e){let t=Jd(e);return t.isStringLiteral()||t.isNumericLiteral()||t.isBooleanLiteral()||t.isNullLiteral()||t.isBigIntLiteral()||t.isJSXElement()||t.isJSXFragment()?!0:t.isIdentifier()?t.node.name==="undefined"&&!t.scope.getBinding("undefined"):t.isTemplateLiteral()?t.node.expressions.length===0:t.isArrayExpression()?t.get("elements").every(n=>!n.node||oo(n)):t.isConditionalExpression()?oo(t.get("consequent"))&&oo(t.get("alternate")):t.isLogicalExpression()?oo(t.get("left"))&&oo(t.get("right")):!1}function qa(e,t){if(!e.isIdentifier())return!1;let n=e.scope.getBinding(e.node.name);return!!(n&&(n.path.node===t.bindingNode||n.identifier===t.bindingNode))}function bT(e,t){if(qa(e,t))return!0;let n=!1;return e.traverse({Identifier(r){qa(r,t)&&(n=!0,r.stop())}}),n}function sx(e){let t=e[0]?.getFunctionParent();if(!t)return{kind:"none"};let n=t.get("params")[0];return n?n.isAssignmentPattern()?ax(n.get("left"),!0):ax(n,!1):{kind:"none"}}function ax(e,t){if(e.isObjectPattern()){let n=[],r=!1;for(let i of e.get("properties")){if(i.isObjectProperty()){if(i.node.computed){wn(i.get("value"))&&(r=!0);continue}let s=i.node.key;(bn.isIdentifier(s)?s.name:bn.isStringLiteral(s)?s.value:null)==="children"&&n.push(i);continue}i.isRestElement()&&wn(i.get("argument"))&&(r=!0)}if(n.length>1)return r||n.some(i=>wn(i.get("value")))?{kind:"unproven"}:{kind:"none"};if(n.length===0)return r?{kind:"unproven"}:{kind:"none"};if(r)return{kind:"unproven"};let o=n[0].get("value");if(o.isIdentifier()){let i=o.scope.getBinding(o.node.name);return!i||i.path.node!==o.node&&i.identifier!==o.node?{kind:"unproven"}:i.constantViolations.length>0?{kind:"unproven"}:i.referencePaths.length===0?{kind:"none"}:i.referencePaths.every(s=>ET(s))?t?{kind:"unproven"}:{kind:"supported",bindingNode:o.node}:{kind:"unproven"}}return wn(o)?{kind:"unproven"}:{kind:"none"}}if(e.isIdentifier()){let n=e.scope.getBinding(e.node.name);return!n||n.referencePaths.length===0?{kind:"none"}:n.referencePaths.every(r=>ST(r))?{kind:"none"}:{kind:"unproven"}}return wn(e)?{kind:"unproven"}:{kind:"none"}}function wn(e){if(e.isIdentifier()){let t=e.scope.getBinding(e.node.name);return!!(t&&t.referencePaths.length>0)}return e.isAssignmentPattern()?wn(e.get("left")):e.isRestElement()?wn(e.get("argument")):e.isObjectPattern()?e.get("properties").some(t=>t.isObjectProperty()?wn(t.get("value")):t.isRestElement()?wn(t.get("argument")):!0):e.isArrayPattern()?e.get("elements").some(t=>t.node?wn(t):!1):!0}function ET(e){let t=e.parentPath;for(;t&&(t.isParenthesizedExpression()||t.isTSAsExpression()||t.isTSNonNullExpression()||t.isTSTypeAssertion());)t=t.parentPath;if(!t||!t.isJSXExpressionContainer())return!1;let n=t.parentPath;return!!(n&&(n.isJSXElement()||n.isJSXFragment()))}function ST(e){let t=e.parentPath;if(!t||!t.isMemberExpression()&&!t.isOptionalMemberExpression()||t.node.object!==e.node)return!1;let n=t.node.property;return t.node.computed?bn.isStringLiteral(n)&&n.value!=="children":bn.isIdentifier(n)&&n.name!=="children"}function IT(e){for(let t of e.get("openingElement").get("attributes")){if(t.isJSXAttribute()){let n=t.node.name;if(bn.isJSXIdentifier(n)&&n.name==="children")return!0;continue}if(t.isJSXSpreadAttribute()&&dx(t.get("argument")))return!0}return!1}function cx(e){let t=e.get("children").map(n=>n);for(let n of e.get("openingElement").get("attributes")){if(n.isJSXAttribute()){let r=n.node.name;if(!bn.isJSXIdentifier(r)||r.name!=="children")continue;let o=n.get("value");o&&!Array.isArray(o)&&t.push(o);continue}if(n.isJSXSpreadAttribute()){let r=n.get("argument");dx(r)&&t.push(r)}}return t}function Xi(e){let t=e.get("children").map(n=>n);for(let n of e.get("openingElement").get("attributes"))if(n.isJSXSpreadAttribute())t.push(n.get("argument"));else if(n.isJSXAttribute()){let r=n.get("value");r&&!Array.isArray(r)&&t.push(r)}return t}function dx(e){if(e.isJSXElement()||e.isJSXFragment())return!0;let t=!1;return e.traverse({JSXElement(n){t=!0,n.stop()},JSXFragment(n){t=!0,n.stop()}}),t}function vT(e){let t=e.path.scope.getBinding(e.componentName);if(!t)return;let n=t.path;if(!n.isImportDefaultSpecifier()&&!n.isImportSpecifier())return;let r=n.parentPath;if(!r?.isImportDeclaration())return;let o=sr(e.file,r.node.source.value,e.parsedModules);if(!o)return;let i=n.isImportDefaultSpecifier()?"default":bn.isIdentifier(n.node.imported)?n.node.imported.name:n.node.imported.value;return{file:o,module:e.parsedModules.get(o),exportName:i,parsedModules:e.parsedModules}}function lx(e){return e==="component-export-unresolved"||e==="component-local-binding-unresolved"}function mx(e){let t=[],n=[];return gx(e.element,e,[],e.ownerNode,e.element,[],new Set,t,n),{roots:t,diagnostics:n}}function gx(e,t,n,r,o,i,s,a,c,l=[]){if(l.length>1&&(e.boundaryKind!=="component-boundary"||e.isPublicUiComponent)){c.push({code:"conditional-component-root-unproven",message:"Conditional returns require one proven local component definition.",file:e.sourceFile});return}if(e.boundaryKind!=="component-boundary"||e.isPublicUiComponent){if(gd(e.tag))return;a.push({element:e,callChain:n,ownerNode:r,ownerMember:o,ownerCallChain:i});return}let u=t.parsedModules.get(e.sourceFile);if(!u){c.push({code:"component-module-unavailable",message:"The component source module is unavailable in the parsed graph.",file:e.sourceFile,structuralPath:e.identity.structuralPath});return}let d=gr({module:u,componentName:e.tag,callSourceRange:e.sourceRange,...e.importedFrom?{imported:{file:e.importedFrom,module:t.parsedModules.get(e.importedFrom),exportName:e.exportName??e.tag,parsedModules:t.parsedModules}}:{}});if(!d.ok){c.push({...d.diagnostic,structuralPath:e.identity.structuralPath});return}if(d.metadataOnly)return;let f=d.sourceFile,g=`${f}#${d.componentName}`;if(s.has(g)){c.push({code:"component-call-cycle",message:"A component call cycle cannot be expanded safely.",file:e.sourceFile,structuralPath:e.identity.structuralPath});return}if(d.roots.length===0){c.push({code:"component-root-empty",message:"A component call has no statically addressable JSX root.",file:f,structuralPath:e.identity.structuralPath});return}let p=[...n,{sourceFile:e.sourceFile,component:e.tag,exportName:e.exportName??e.tag,callLocator:{key:e.identity.key,structuralPath:e.identity.structuralPath,sourceRange:e.sourceRange},...l.length>1?{alternativeLocators:l.map(S=>({key:S.identity.key,structuralPath:S.identity.structuralPath,sourceRange:S.sourceRange}))}:{}}],m=d.roots.length>1?{kind:"component-definition",key:g}:r,y=new Set(s);y.add(g);let x=[];for(let S of d.returnAlternatives??[]){let b=px(S),E=b?fx(t.graph,f,b):[];if(E.length!==1){c.push({code:"conditional-component-root-unproven",message:"A conditional call site is absent or ambiguous in the source graph.",file:f});return}x.push(E[0])}for(let S of d.roots){let b=px(S),E=b?fx(t.graph,f,b):[];if(E.length!==1){c.push({code:E.length?"component-root-ambiguous":"component-root-unresolved",message:"The component root could not be matched to one source graph node.",file:f,structuralPath:e.identity.structuralPath});continue}gx(E[0],t,p,m,d.roots.length>1?E[0]:o,d.roots.length>1?p:i,y,a,c,x)}}function fx(e,t,n){return(e.fileIndex.get(t)??[]).map(r=>e.elements.get(r)).filter(r=>!!r&&r.sourceRange.startLine===n.startLine&&r.sourceRange.startColumn===n.startColumn&&r.sourceRange.endLine===n.endLine&&r.sourceRange.endColumn===n.endColumn)}function px(e){let t=e.node.loc;return t?{startLine:t.start.line,startColumn:t.start.column,endLine:t.end.line,endColumn:t.end.column}:null}function ec(e){let t=[],n=[];if(e.projection.entryFile!==e.entryFile||!yx(e.projection.composition,e.composition)||e.graph.composition&&!yx(e.graph.composition,e.composition))return{roots:[],diagnostics:[zi("composition-mismatch",e.entryFile)]};if(!e.parsedModules.has(e.entryFile))return{roots:[],diagnostics:[zi("entry-module-unavailable",e.entryFile)]};for(let i of e.graph.diagnostics??[])t.push({code:`source-graph-${i.code}`,message:i.message,file:i.path});let r=e.projection.placements.filter(i=>i.relation==="before").flatMap(i=>i.members);for(let i of r){if(i.kind==="text")continue;if(i.kind!=="jsx-element"||!i.sourceRange){t.push(zi("route-member-not-addressable",e.entryFile));continue}let s=CT(e.graph,e.entryFile,i.sourceRange);if(s.length!==1){t.push(zi(s.length?"route-root-ambiguous":"route-root-unresolved",e.entryFile));continue}let a=s[0],c=mx({element:a,graph:e.graph,parsedModules:e.parsedModules,ownerNode:{kind:"route-member",key:a.parentKey??`${e.entryFile}#${e.projection.container.placementKey}`}});t.push(...c.diagnostics);for(let l of c.roots){let u=l.ownerMember;n.push({...l,parentStructuralPath:u.parentKey?e.graph.elements.get(u.parentKey)?.identity.structuralPath??null:null})}}let o=ux(e,new Set(n.map(i=>i.element.identity.key)));t.push(...o.diagnostics);for(let i of n){let s=i.element.identity.key,a=Qa(s,i.callChain.map(c=>c.callLocator.key));o.occurrences.get(s)?.filter(c=>c===a).length!==1&&t.push(zi("render-occurrence-unproven",i.element.sourceFile))}return{roots:_T(n,e.composition,o.occurrences),diagnostics:t}}function _T(e,t,n){let r=e.map(i=>{let s=i.element,a=n.get(s.identity.key)??[],c=i.callChain.map(l=>l.callLocator.key);return{rootKey:kT("sha256").update(JSON.stringify([t,c,s.identity.key])).digest("hex"),rootRef:{key:s.identity.key,...a.length>1?{instanceIndex:a.indexOf(Qa(s.identity.key,c)),instanceCount:a.length}:{}},sourceFile:s.sourceFile,structuralPath:s.identity.structuralPath,sourceRange:s.sourceRange,callChain:i.callChain,ownerNode:i.ownerNode,ownerMemberKey:i.ownerMember.identity.key,ownerCallKeys:i.ownerCallChain.map(l=>l.callLocator.key),parentStructuralPath:i.parentStructuralPath,siblingRootKeys:[],siblingIndex:0}}),o=new Map;for(let i of r){let s=hx(i);o.set(s,[...o.get(s)??[],i])}return r.map(i=>{let s=o.get(hx(i))??[i];return{...i,siblingIndex:s.indexOf(i),siblingRootKeys:s.filter(a=>a!==i).map(a=>a.rootKey)}})}function hx(e){return JSON.stringify([e.ownerNode.kind,e.ownerNode.key,e.parentStructuralPath,e.ownerCallKeys])}function CT(e,t,n){return(e.fileIndex.get(t)??[]).map(r=>e.elements.get(r)).filter(r=>!!r&&r.sourceRange.startLine===n.startLine&&r.sourceRange.startColumn===n.startColumn&&r.sourceRange.endLine===n.endLine&&r.sourceRange.endColumn===n.endColumn)}function yx(e,t){return e.routeId===t.routeId&&e.effectiveTemplateId===t.effectiveTemplateId}function zi(e,t){return{code:e,message:"Page block roots could not be proven from the current source graph.",file:t}}import{SiteEditPageBlockDirectorySchema as RT,SiteEditPageBlockDescriptorSchema as NT,SiteEditSourcePathSchema as bx}from"@vcp-dev/contracts";function tc(e){let t=new Map;for(let[n,r]of e.elements){let o=/^[A-Z]/.test(r.tag),i={file:r.sourceFile,componentName:r.componentName,isProxy:o},s=r.boundaryKind,a=[];r.isOpaque&&a.push({kind:"opaque-region",reason:`Component '${r.tag}' is opaque: internal structure not editable`}),o&&!r.isOpaque&&a.push({kind:"component-boundary",reason:`Component '${r.tag}' boundary: editing requires source file access`});let c={key:n,writeTarget:i,boundaryKind:s,parentKey:r.parentKey,childKeys:[...r.childKeys],constraints:a};t.set(n,c)}for(let n of e.regions){let r=n.kind==="repeat-region"?"repeat-region":n.kind==="conditional-region"?"conditional-region":n.kind==="opaque-region"?"opaque-region":"component-boundary",o=n.kind==="repeat-region"?"Node is inside a repeat region: operations affect the template, not individual instances":n.kind==="conditional-region"?"Node is inside a conditional region: visibility depends on runtime condition":`Node is inside a ${n.kind}`;for(let i of n.childKeys){let s=t.get(i);s&&s.constraints.push({kind:r,reason:o}),xx(i,r,o,t,e)}}return{nodes:t,rootKeys:[...e.rootKeys]}}function xx(e,t,n,r,o){let i=o.elements.get(e);if(i)for(let s of i.childKeys){let a=r.get(s);a&&!a.constraints.some(c=>c.kind===t)&&(a.constraints.push({kind:t,reason:n}),xx(s,t,n,r,o))}}function Hi(e){let t=[],n={...e.graph,composition:e.composition},r=ma(tc(n),n),o=[],i=new Map;for(let a of e.roots){let c=e.graph.elements.get(a.rootRef.key),l=e.graph.elements.get(a.ownerMemberKey),u=e.parsedModules.get(a.sourceFile),d=TT(a,e.graph),f=d?e.parsedModules.get(d):void 0;if(!c||!l||l.sourceFile!==d||!u||!bx.safeParse(a.sourceFile).success||!d||!f||!bx.safeParse(d).success){t.push(Xd("root-source-unavailable",a.sourceFile));continue}if(i.has(a.rootKey)){t.push(Xd("block-key-ambiguous",a.sourceFile));continue}let g=ke(u.source),p=NT.safeParse({blockKey:a.rootKey,rootRef:a.rootRef,definitionKey:a.rootRef.key,source:{file:a.sourceFile,structuralPath:a.structuralPath,contentHash:g},owner:a.ownerNode,siblingBlockKeys:a.siblingRootKeys,placementUnitKey:wT(a,e),capabilities:PT(c,r),...AT(c,r)});if(!p.success){t.push(Xd("page-block-descriptor-invalid",a.sourceFile));continue}let m=p.data;o.push(m),i.set(a.rootKey,{blockKey:a.rootKey,composition:e.composition,documentVersion:e.documentVersion,descriptor:m,root:a,ownerFile:d,ownerSourceHash:ke(f.source),ownerSourceContent:f.source,sourceHash:g,sourceContent:u.source,ownerLocator:{kind:"jsx-element",file:l.sourceFile,sourceRange:l.sourceRange,structuralPath:l.identity.structuralPath,componentName:l.componentName},rootLocator:{kind:"jsx-element",file:c.sourceFile,sourceRange:c.sourceRange,structuralPath:c.identity.structuralPath,componentName:c.componentName}})}let s=RT.safeParse(o);return s.success?{composition:e.composition,documentVersion:e.documentVersion,descriptors:s.data,bindings:i,diagnostics:t}:{composition:e.composition,documentVersion:e.documentVersion,descriptors:[],bindings:new Map,diagnostics:[...t,{code:"page-block-directory-invalid",message:"The proven page block directory failed its strict contract."}]}}function PT(e,t){let n=t.get(e.identity.key),r=e.parentKey?t.get(e.parentKey):void 0;return{insert:r?r.canInsertChild:!0,replace:!!(n?.canRemove&&(!r||r.canInsertChild)),move:n?.canMove??!1,remove:n?.canRemove??!1,save:!0}}function AT(e,t){let n=t.get(e.identity.key),r={},o=n?.constraints[0]?.message??"The existing Engine capability check denied this operation.";return(!n||!n.canRemove)&&(r.replace={code:n?"CAPABILITY_DENIED":"CAPABILITY_UNAVAILABLE",reason:o},r.remove={code:n?"CAPABILITY_DENIED":"CAPABILITY_UNAVAILABLE",reason:o}),(!n||!n.canMove)&&(r.move={code:n?"CAPABILITY_DENIED":"CAPABILITY_UNAVAILABLE",reason:o}),Object.keys(r).length?{unavailableReasons:r}:{}}function TT(e,t){if(e.ownerNode.kind==="component-definition"){let n=e.ownerNode.key.lastIndexOf("#");return n>0?e.ownerNode.key.slice(0,n):null}return t.elements.get(e.ownerMemberKey)?.sourceFile??null}function wT(e,t){let n=e.callChain[0]?.callLocator.key??e.rootRef.key,r=t.graph.elements.get(n);if(r)return t.projection.placements.find(o=>o.members.some(i=>i.sourceRange!==null&&i.sourceRange.startLine===r.sourceRange.startLine&&i.sourceRange.startColumn===r.sourceRange.startColumn&&i.sourceRange.endLine===r.sourceRange.endLine&&i.sourceRange.endColumn===r.sourceRange.endColumn))?.placementUnitKey}function Xd(e,t){return{code:e,message:"The page block source binding could not be proven.",file:t}}import zd from"@babel/traverse";import{BlockRenderRefSchema as OT,SiteEditPageBlockPositionSchema as FT,SiteEditPageBlockTargetSchema as LT}from"@vcp-dev/contracts";var DT=typeof zd=="function"?zd:zd.default;function jo(e,t,n,r){if(!LT.safeParse(t).success)return Bt("INVALID_PARAMS","Invalid page block target.");if(n!==e.documentVersion)return Bt("VERSION_STALE","The page block index is stale.");if(t.composition.routeId!==e.composition.routeId||t.composition.templateId!==e.composition.effectiveTemplateId)return Bt("INVALID_TARGET","The target belongs to another composition.");let o=e.bindings.get(t.blockKey);return o?r&&(!OT.safeParse(r).success||r.key!==o.descriptor.rootRef.key||r.instanceIndex!==o.descriptor.rootRef.instanceIndex||r.instanceCount!==o.descriptor.rootRef.instanceCount)?Bt("INVALID_TARGET","The render occurrence does not match the target."):{ok:!0,binding:o}:Bt("INVALID_TARGET","The page block target was not found.")}function nc(e,t){if(!FT.safeParse(t).success)return Bt("INVALID_PARAMS","Invalid page block boundary.");if(t.documentVersion!==e.documentVersion)return Bt("VERSION_STALE","The page block boundary is stale.");if(t.composition.routeId!==e.composition.routeId||t.composition.templateId!==e.composition.effectiveTemplateId)return Bt("INVALID_TARGET","The boundary belongs to another composition.");let n=e.bindings.get(t.anchorBlockKey);if(!n)return Bt("INVALID_TARGET","The boundary anchor was not found.");let r=[n,...n.descriptor.siblingBlockKeys.map(u=>e.bindings.get(u))];if(r.some(u=>!u))return Bt("INVALID_TARGET","A verified sibling binding is unavailable.");let o=r.sort((u,d)=>u.root.siblingIndex-d.root.siblingIndex),i=Ex(n);if(!i)return Bt("INVALID_TARGET","The operation owner call site is unavailable.");let s=Sx(n,i);if(s===void 0)return Bt("INVALID_TARGET","The boundary parent source range is ambiguous.");for(let u of o)if(u.ownerFile!==n.ownerFile||u.root.ownerNode.kind!==n.root.ownerNode.kind||u.root.ownerNode.key!==n.root.ownerNode.key||!MT(Sx(u,Ex(u)),s))return Bt("INVALID_TARGET","Siblings do not share one proven source boundary.");let a=o.findIndex(u=>u.blockKey===n.blockKey);if(a<0)return Bt("INVALID_TARGET","Anchor order is ambiguous.");let c=t.placement==="before"?o[a-1]:n,l=t.placement==="before"?n:o[a+1];return{ok:!0,boundary:{ownerFile:n.ownerFile,parentLocator:s,anchorLocator:i,sourceHash:n.ownerSourceHash,placement:t.placement,beforeBlockKey:c?.blockKey??null,afterBlockKey:l?.blockKey??null}}}function Ex(e){return e.ownerLocator.file===e.ownerFile?e.ownerLocator:null}function Sx(e,t){if(!t)return;let n=je(t.file,e.ownerSourceContent);if(!n.ok)return;let r=[];if(DT(n.module.ast,{JSXElement(i){let s=Hd(i.node);s&&s.startLine===t.sourceRange.startLine&&s.startColumn===t.sourceRange.startColumn&&s.endLine===t.sourceRange.endLine&&s.endColumn===t.sourceRange.endColumn&&r.push(i)}}),r.length!==1)return;let o=r[0].parentPath;for(;o;){if(o.isJSXFragment()){let i=Hd(o.node);return i?{kind:"jsx-fragment",file:t.file,sourceRange:i}:void 0}if(o.isJSXElement()){let i=Hd(o.node),s=t.structuralPath?.lastIndexOf("/")??-1,a=s<0?void 0:t.structuralPath.slice(0,s);return i?{kind:"jsx-element",file:t.file,sourceRange:i,...a?{structuralPath:a}:{},...t.componentName?{componentName:t.componentName}:{}}:void 0}o=o.parentPath}return null}function MT(e,t){return e===void 0||t===void 0||e===null||t===null?e===t:e.file===t.file&&e.kind===t.kind&&e.sourceRange.startLine===t.sourceRange.startLine&&e.sourceRange.startColumn===t.sourceRange.startColumn&&e.sourceRange.endLine===t.sourceRange.endLine&&e.sourceRange.endColumn===t.sourceRange.endColumn}function Hd(e){let t=e.loc;return t?{startLine:t.start.line,startColumn:t.start.column,endLine:t.end.line,endColumn:t.end.column}:null}function Bt(e,t){return{ok:!1,code:e,message:t}}import kx from"node:path";import{SiteEditSourcePathSchema as WT}from"@vcp-dev/contracts";import rc from"node:path";import Wd from"@babel/traverse";import*as Er from"@babel/types";import{SiteEditSourcePathSchema as Ix,SiteEditPageBlockTargetSchema as BT}from"@vcp-dev/contracts";var jT=typeof Wd=="function"?Wd:Wd.default;function vx(e){if(!e.operationId)return st("INVALID_PARAMS","An operationId is required.");if(!BT.safeParse(e.target).success)return st("INVALID_PARAMS","Invalid page block target.");if(e.target.kind!=="page-block"||e.target.blockKey!==e.binding.blockKey||e.target.composition.routeId!==e.binding.composition.routeId||e.target.composition.templateId!==e.binding.composition.effectiveTemplateId)return st("INVALID_TARGET","The request target does not match its resolved block binding.");if(e.documentVersion!==e.binding.documentVersion)return st("VERSION_STALE","The resolved block belongs to a stale document version.");if(e.operation==="move-node"||e.operation==="remove-node")return st("UNSUPPORTED_OPERATION","Move and remove are planned by the structural operation task.");if(!e.node)return st("INVALID_PARAMS","An insert/replacement node is required.");let t=e.operation==="insert-child"?e.boundary?.ownerFile:e.binding.ownerFile;if(!t||!Ix.safeParse(t).success)return st("INVALID_TARGET","The exact owner source file is unavailable.");let n=e.files.get(t);if(n===void 0)return st("INVALID_TARGET","The exact owner source is absent from the fixed file map.");if(ke(n)!==e.binding.ownerSourceHash)return st("VERSION_STALE","The owner source hash changed after target resolution.");let r=e.files.get(e.binding.descriptor.source.file);if(r===void 0||ke(r)!==e.binding.descriptor.source.contentHash)return st("VERSION_STALE","The block source hash changed after target resolution.");let o;if(e.operation==="insert-child"){if(o=e.boundary,!o||o.ownerFile!==e.binding.ownerFile||o.sourceHash!==e.binding.ownerSourceHash||o.anchorLocator.file!==t||o.parentLocator?.file!==t)return st("INVALID_TARGET","The insertion boundary is not in the resolved source owner.");let l=o.placement==="before"?o.afterBlockKey:o.beforeBlockKey;if(l!==e.binding.blockKey&&!e.binding.descriptor.siblingBlockKeys.includes(l??""))return st("INVALID_TARGET","The boundary anchor is not a verified same-owner sibling.");if(!o.parentLocator)return st("UNSUPPORTED_OPERATION","A root without a source parent has no safe sibling insertion boundary.")}let i=VT(e.node,t,n,e.files);if(!i.ok)return i;let s=e.operation==="replace-node"?ko({source:n,locator:$T(e.binding),node:{jsx:i.value.jsx}}):on({source:n,locator:Gd(o.parentLocator),anchorLocator:Gd(o.anchorLocator),placement:o.placement,node:{jsx:i.value.jsx}});if(!s.ok)return st("UNSUPPORTED_OPERATION",s.diagnostic.message);let a=s.source;if(i.value.import){let l=sn({source:a,moduleSpecifier:i.value.import.moduleSpecifier,imports:i.value.import.specifiers});if(!l.ok)return st("UNSUPPORTED_OPERATION",l.diagnostic.message);a=l.source}return{ok:!0,plan:{operationId:e.operationId,kind:"source-edit",target:e.target,documentVersion:e.documentVersion,conflictPolicy:"compare-and-swap",edits:[{operation:"upsert",file:t,content:a,baseContentHash:e.binding.ownerSourceHash}]}}}function $T(e){return Gd(e.ownerLocator)}function Gd(e){return{kind:"jsx-node",strategy:"source-range",sourceRange:e.sourceRange,...e.structuralPath&&e.componentName?{expectedIdentity:{file:e.file,component:e.componentName,structuralPath:e.structuralPath}}:{}}}function VT(e,t,n,r){if(e.kind==="native-tag")return/^[A-Za-z][A-Za-z0-9:_-]*$/.test(e.tag)?{ok:!0,value:{jsx:e.text===void 0?`<${e.tag} />`:`<${e.tag}>{${JSON.stringify(e.text)}}</${e.tag}>`}}:st("INVALID_PARAMS","The native JSX tag is invalid.");if(!e.component)return st("UNSUPPORTED_OPERATION","A materialized component entry is resolved by the materialization task.");let o=UT(t,e.component.source,r);if(!o)return st("INVALID_TARGET","The component source is not in the safe fixed file map.");let i=je(t,n);if(!i.ok)return st("UNSUPPORTED_OPERATION",i.diagnostic.message);let s=KT(i.module.ast.program.body,e.component.source,e.component.exportName),a=s??XT(zT(e.component.exportName,o),JT(i.module.ast)),c=HT(e.props??{});if(!c.ok)return c;let l=`<${a}${c.value?` ${c.value}`:""} />`;if(s)return{ok:!0,value:{jsx:l}};let u=e.component.exportName==="default"?{kind:"default",local:a}:{kind:"named",imported:e.component.exportName,...a!==e.component.exportName?{local:a}:{}};return{ok:!0,value:{jsx:l,import:{moduleSpecifier:e.component.source,specifiers:[u]}}}}function UT(e,t,n){let r=t.startsWith("@/")?t.slice(2):t.startsWith("./")||t.startsWith("../")?rc.posix.normalize(rc.posix.join(rc.posix.dirname(e),t)):null;return r?(/\.(?:tsx?|jsx?)$/i.test(r)?[r]:[".tsx",".ts",".jsx",".js"].map(i=>`${r}${i}`).concat([".tsx",".ts",".jsx",".js"].map(i=>`${r}/index${i}`))).find(i=>Ix.safeParse(i).success&&n.has(i))??null:null}function KT(e,t,n){for(let r of e)if(!(!Er.isImportDeclaration(r)||r.source.value!==t)){for(let o of r.specifiers)if(n==="default"&&Er.isImportDefaultSpecifier(o)||n!=="default"&&Er.isImportSpecifier(o)&&(Er.isIdentifier(o.imported)?o.imported.name:o.imported.value)===n)return o.local.name}return null}function JT(e){let t=new Set;return jT(e,{Program(n){n.scope.crawl(),t=new Set(Object.keys(n.scope.bindings)),n.stop()}}),t}function XT(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n+=1;return`${e}${n}`}function zT(e,t){let r=(e==="default"?rc.posix.basename(t).replace(/\.(?:tsx?|jsx?)$/i,""):e).replace(/[^A-Za-z0-9_$]/g,""),o=r?r[0].toUpperCase()+r.slice(1):"Component";return/^[A-Za-z_$][\w$]*$/.test(o)?o:"Component"}function HT(e){let t=[];for(let[n,r]of Object.entries(e)){if(!/^[A-Za-z_][A-Za-z0-9_:.-]*$/.test(n))return st("INVALID_PARAMS","A component prop name is invalid.");let o;try{o=JSON.stringify(r)}catch{return st("INVALID_PARAMS","Component props must be JSON serializable.")}if(o===void 0)return st("INVALID_PARAMS","Component props must be JSON serializable.");t.push(`${n}={${o}}`)}return{ok:!0,value:t.join(" ")}}function st(e,t){return{ok:!1,code:e,message:t}}function _x(e){if(e.materialization.kind!=="static-prefab-materialization"||!e.materialization.files.some(i=>i.path===e.materialization.entry.path))return oc("MATERIALIZATION_ENTRY_INVALID","The materialization entry must identify one controlled create-only file.");if(!e.materialization.files.every(i=>i.kind==="create-only"&&WT.safeParse(i.path).success))return oc("MATERIALIZATION_PATH_INVALID","Every materialized output must remain a safe create-only Snapshot source.");if(e.materialization.files.some(i=>e.files.has(i.path)))return oc("MATERIALIZATION_INSTANCE_CONFLICT","A generated materialization path already exists in the fixed Snapshot source map.");let t=e.operation==="insert-child"?e.boundary?.ownerFile:e.binding.ownerFile;if(!t||!e.files.has(t))return oc("INVALID_TARGET","The exact page-block owner source is missing from the fixed file map.");let n=YT(t,e.materialization.entry.path),r=vx({operationId:e.operationId,documentVersion:e.documentVersion,target:e.target,binding:e.binding,...e.boundary?{boundary:e.boundary}:{},operation:e.operation,node:{kind:"component-call",component:{source:n,exportName:e.materialization.entry.export.kind==="default"?"default":e.materialization.entry.export.name},props:{}},files:GT(e.files,e.materialization)});if(!r.ok)return r;let o=e.materialization.files.map(i=>({operation:"create-only",file:i.path,content:i.content}));return{ok:!0,plan:{...r.plan,target:e.target,edits:[...o,...r.plan.edits]}}}function GT(e,t){let n=new Map(e);for(let r of t.files)n.set(r.path,r.content);return n}function YT(e,t){let n=kx.posix.relative(kx.posix.dirname(e),t);return n.startsWith(".")?n:`./${n}`}function oc(e,t){return{ok:!1,code:e,message:t}}import{PageTemplateIdSchema as aw}from"@vcp-dev/contracts";import k1 from"node:fs";import C1 from"node:path";var ZT=/^page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function Wi(e){let t=e.map(r=>sw(r.path)),n=qT(t);return n?t.filter(r=>ew(n,r)).map(r=>({routeId:tw(n,r),entryFile:r})).sort((r,o)=>r.routeId.localeCompare(o.routeId)):[]}function Yd(e,t=""){let r=((e??"/").trim()||"/").split(/[?#]/,1)[0]||"/",o=r.startsWith("/")?r:`/${r}`,i=iw(t),s=i&&(o===i||o.startsWith(`${i}/`))?o.slice(i.length)||"/":o,a=s.startsWith("/")?s:`/${s}`;return a==="/"?"/":a.replace(/\/+$/,"")}function qT(e){return e.some(r=>r.startsWith("app/")&&!QT(r))?"app":e.some(r=>r.startsWith("src/app/"))?"src/app":null}function QT(e){return/^(?:src\/)?app\/(?:_vcp|\.vcp)/.test(e)}function ew(e,t){if(!t.startsWith(`${e}/`))return!1;let n=t.slice(t.lastIndexOf("/")+1);return ZT.test(n)?t.slice(e.length+1,-n.length-1).split("/").filter(Boolean).every(r=>!r.startsWith("_")&&!r.startsWith(".")):!1}function tw(e,t){let n=t.slice(e.length+1).split("/").slice(0,-1).map(rw).filter(r=>!!r);return n.length===0?"/":`/${n.join("/")}`}function nw(e){return e.startsWith("(")&&e.endsWith(")")}function rw(e){return!e||e.startsWith("@")||e.startsWith("_")||nw(e)?null:ow(e)}function ow(e){return e.replace(/^\((?:\.|\.\.|\.\.\.)\)/,"")}function iw(e){let t=e.trim();return!t||t==="/"?"":(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"")}function sw(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}var Gi=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="PageTemplateManagedSourceError"}};function jt(e,t={}){throw new Gi("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Invalid page-template source (${e}): ${t.path??t.routeId??t.templateId??""}`,{reason:e,...t})}function Zd(e){return aw.safeParse(e).success||jt("invalid-template-id",{templateId:e}),Buffer.from(e,"utf8").toString("base64url")}function Cx(e){/^[A-Za-z0-9_-]{1,255}$/.test(e)||jt("invalid-template-key",{path:e});let t;try{t=new TextDecoder("utf-8",{fatal:!0}).decode(Buffer.from(e,"base64url"))}catch{return jt("invalid-template-key",{path:e})}return Zd(t)!==e&&jt("noncanonical-template-key",{path:e}),t}function cw(e){let t=Yd(e),n=t.slice(1).split("/");return(!e.startsWith("/")||/[?#\\%\u0000-\u001f]/.test(e)||t.startsWith("/.vcp")||t!=="/"&&n.some(r=>!r||r==="."||r===".."||r.startsWith("@")||r.startsWith("_")||r.startsWith("(")||lw(r)&&!Rx(r)))&&jt("invalid-public-route",{routeId:e}),t}function lw(e){return e.includes("[")||e.includes("]")}function Rx(e){return/^\[\[\.\.\.[^\[\]]+\]\]$|^\[[^\[\]]+\]$/.test(e)}function Nx(e){return e.some(Rx)}function Px(e,t,n="app"){n!=="app"&&n!=="src/app"&&jt("invalid-app-root");let r=cw(e),o=Zd(t),i=Nx(r.slice(1).split("/")),s=i?`${n}/.vcp/page-templates/${o}${r}`:`${n}/.vcp/page-templates${r==="/"?"":r}`,a=i?`${s}/page.tsx`:`${s}/${o}/page.tsx`;return(Buffer.byteLength(a,"utf8")>4095||a.split("/").some(c=>Buffer.byteLength(c,"utf8")>255))&&jt("path-too-long",{path:a}),{appRoot:n,routeRoot:s,templateKey:o,templateEntryFile:a}}function Ax(e){return/^(?:src\/)?app\/\.vcp\/page-templates\//.test(e)}function Tx(e){let t=Array.isArray(e)?e.map(r=>[r.path,r.content]):[...e],n=new Map;for(let[r,o]of t){let i=r.replace(/\\/g,"/").replace(/^\.\//,"");i.split("/").some(s=>s===".."||s===".")&&jt("invalid-file-path",{path:i}),n.has(i)&&jt("duplicate-file-path",{path:i}),n.set(i,o)}return n}function sc(e){let t=Tx(e.files),n=Wi([...t.keys()].map(i=>({path:i}))),r=new Map;for(let i of n){if(r.has(i.routeId))throw new Gi("PAGE_TEMPLATE_ROUTE_AMBIGUOUS",`Multiple canonical entries for ${i.routeId}`,{reason:"duplicate-route-id",routeId:i.routeId,candidates:n.filter(s=>s.routeId===i.routeId).map(s=>s.entryFile)});r.set(i.routeId,i.entryFile)}let o=[];for(let i of t.keys()){if(!Ax(i))continue;let s=/^(app|src\/app)\/\.vcp\/page-templates\/(.+)\/page\.tsx$/.exec(i);s||jt("candidate-must-be-single-page",{path:i});let a=s[1],c=s[2].split("/"),l=Nx(c),u=l?c[0]:c.pop(),d=l?c.slice(1):c,f=Cx(u),g=d.length?`/${d.join("/")}`:"/";Px(g,f,a).templateEntryFile!==i&&jt("candidate-path-mismatch",{path:i,routeId:g});let m=r.get(g);(!m||!m.startsWith(`${a}/`))&&jt("canonical-entry-missing",{path:i,routeId:g}),o.push({routeId:g,templateId:f,entryFile:i,canonicalEntryFile:m,appRoot:a})}return o.sort((i,s)=>ic(i.routeId,s.routeId)||ic(i.templateId,s.templateId))}function ac(e){let t=Tx(e.files),n=sc({files:t}),r=Wi([...t.keys()].map(o=>({path:o}))).map(o=>({context:{routeId:o.routeId},entryFile:o.entryFile}));return r.push(...n.map(o=>({context:{routeId:o.routeId,effectiveTemplateId:o.templateId},entryFile:o.entryFile}))),r.sort((o,i)=>ic(o.context.routeId,i.context.routeId)||(o.context.effectiveTemplateId===void 0?-1:i.context.effectiveTemplateId===void 0?1:ic(o.context.effectiveTemplateId,i.context.effectiveTemplateId)))}function uw(e){let t=Yd(e.selector.routeId),n=ac({files:e.files}),r=n.find(i=>i.context.routeId===t&&i.context.effectiveTemplateId===void 0);(!r||r.entryFile!==e.canonicalEntryFile)&&jt("canonical-entry-mismatch",{routeId:t,path:e.canonicalEntryFile});let o=e.selector.templateId===void 0?r:n.find(i=>i.context.routeId===t&&i.context.effectiveTemplateId===e.selector.templateId);return o||jt("template-selection-not-found",{routeId:t,templateId:e.selector.templateId}),{...o,mode:e.selector.templateId===void 0?"direct":"candidate",effectiveEntryFile:o.entryFile}}function ic(e,t){return e<t?-1:e>t?1:0}import{HOME_PAGE_URL_PATH as ww}from"@vcp-dev/contracts";import{parse as kw}from"@babel/parser";import{parse as U1}from"@babel/parser";import{FormBlockIdSchema as J1,FormSpecV1Schema as X1}from"@vcp-dev/contracts";import{posix as L1}from"node:path";import dw from"@babel/traverse";var qd=dw,M1=typeof qd=="function"?qd:qd.default,B1=Symbol("unknown-member");var Yi="components/site/generated/forms",H1=`${Yi}/vcp-form-runtime.tsx`,cc="[A-Za-z0-9][A-Za-z0-9_-]{0,127}",W1=new RegExp(`^${Yi}/form-(${cc})\\.spec\\.ts$`),G1=new RegExp(`^${Yi}/form-(${cc})\\.tsx$`),Y1=new RegExp(`^@/${Yi}/form-(${cc})$`),Z1=new RegExp(`(?:^|/)${Yi}/form-(${cc})(?:\\.tsx?)?$`);var q1=Symbol("invalid-literal");import{createHash as tX}from"node:crypto";import{posix as rX}from"node:path";import{parse as iX}from"@babel/parser";import{FormSpecV1Schema as aX}from"@vcp-dev/contracts";var cX=Symbol("dynamic");import{parse as fw}from"@babel/parser";function lc(e){return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&typeof t.type=="string"):[]}var pw=/^(?:src\/)?app\/(.*)page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function wx(e){let t=pw.exec(e);if(!t)return null;let r=(t[1]??"").split("/").filter(o=>o.length>0&&!/^\(.+\)$/.test(o));return r.length===0?"/":`/${r.join("/")}`}function mw(e){let t=e;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function Ox(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function gw(e){let t=e;for(;t&&(t.type==="TSAsExpression"||t.type==="TSSatisfiesExpression"||t.type==="ParenthesizedExpression");)t=t.expression??null;return t}function Qd(e){let t=e;if(t?.type==="StringLiteral"||t?.type==="NumericLiteral"||t?.type==="BooleanLiteral")return t.value;if(t?.type==="NullLiteral")return null;if(t?.type==="ArrayExpression")return(t.elements??[]).map(Qd);if(t?.type==="ObjectExpression"){let n={};for(let r of lc(t.properties)){if(r.type!=="ObjectProperty"||r.computed)throw new Error("dynamic object property");let o=Ox(r.key);if(!o)throw new Error("unsupported object key");n[o]=Qd(r.value)}return n}throw new Error(`unsupported static value: ${t?.type??"unknown"}`)}function ef(e,t){let n=[],r=wx(t);if(r===null)return{found:!1,seo:null,diagnostics:n};let o;try{o=fw(e,{sourceType:"module",plugins:["typescript","jsx"]})}catch(l){return n.push({code:"page-seo.parse-failed",message:l instanceof Error?l.message:String(l)}),{found:!1,seo:null,diagnostics:n}}let i;for(let l of lc(o.program.body)){let u=l.type==="ExportNamedDeclaration"?l.declaration:l;if(u?.type==="VariableDeclaration")for(let d of lc(u.declarations)){let f=d.id;f?.type==="Identifier"&&f.name==="PAGE_SEO"&&(i=d.init)}}if(i==null)return{found:!1,seo:null,diagnostics:n};let s=gw(i);if(!s)return{found:!1,seo:null,diagnostics:n};if(s.type!=="ObjectExpression")return n.push({code:"page-seo.dynamic-declaration",message:"PAGE_SEO is not a static object literal"}),{found:!1,seo:null,diagnostics:n};let a={};for(let l of lc(s.properties)){if(l.type!=="ObjectProperty"||l.computed)continue;let u=Ox(l.key);if(!(u!=="path"&&u!=="title"&&u!=="description"&&u!=="keywords"&&u!=="meta_tags_json"&&u!=="schema_json"&&u!=="breadcrumbs_json")){if(u==="path"||u==="title"||u==="description"||u==="keywords"){let d=mw(l.value);if(d===void 0){n.push({code:"page-seo.dynamic-field",message:`PAGE_SEO.${u} is not a static string; skipped`});continue}a[u]=d;continue}try{let d=Qd(l.value);u==="meta_tags_json"&&d!==null&&typeof d=="object"&&!Array.isArray(d)?a.meta_tags_json=d:u==="schema_json"&&d!==null&&typeof d=="object"?a.schema_json=d:u==="breadcrumbs_json"&&Array.isArray(d)?a.breadcrumbs_json=d:n.push({code:"page-seo.dynamic-field",message:`PAGE_SEO.${u} has unsupported static shape; skipped`})}catch(d){n.push({code:"page-seo.dynamic-field",message:`PAGE_SEO.${u} is not a static JSON-like value; skipped: ${d instanceof Error?d.message:String(d)}`})}}}let c=r;return a.path!==void 0&&(a.path!==r&&n.push({code:"page-seo.path-mismatch",message:`PAGE_SEO.path "${a.path}" != derived "${r}"; using PAGE_SEO.path`}),c=a.path),{found:!0,seo:{path:c,...a.title!==void 0?{title:a.title}:{},...a.description!==void 0?{description:a.description}:{},...a.keywords!==void 0?{keywords:a.keywords}:{},...a.meta_tags_json!==void 0?{meta_tags_json:a.meta_tags_json}:{},...a.schema_json!==void 0?{schema_json:a.schema_json}:{},...a.breadcrumbs_json!==void 0?{breadcrumbs_json:a.breadcrumbs_json}:{}},diagnostics:n}}import{parse as hw}from"@babel/parser";var Fx=["page","anchor","external","email","phone","group","file"],yw=["link","cta"],Dx=["description","badge","iconKey"],tf=["label","targetType","href","role","openInNewTab","nofollow","children",...Dx],xw=new Set(tf);function qi(e){return Array.isArray(e)?e:[]}function Zi(e){let t=e;return t?.type==="StringLiteral"&&typeof t.value=="string"?t.value:void 0}function bw(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function Lx(e){let t=e;return t?.type==="BooleanLiteral"&&typeof t.value=="boolean"?t.value:void 0}function nf(e){let t=[],n;try{n=hw(e,{sourceType:"module",plugins:["typescript","jsx"]})}catch(i){return{items:[],diagnostics:[{severity:"fatal",path:"NAV_ITEMS",message:`parse failed: ${String(i)}`}]}}let r;for(let i of qi(n.program.body)){let s=i.type==="ExportNamedDeclaration"?i.declaration:i;if(s?.type==="VariableDeclaration")for(let a of qi(s.declarations)){let c=a.id;c?.type==="Identifier"&&c.name==="NAV_ITEMS"&&(r=a.init)}}for(;r&&(r.type==="TSAsExpression"||r.type==="TSSatisfiesExpression"||r.type==="TSInstantiationExpression");)r=r.expression;if(!r||r.type!=="ArrayExpression")return{items:[],diagnostics:[{severity:"fatal",path:"NAV_ITEMS",message:"missing top-level NAV_ITEMS array literal"}]};let o=[];return qi(r.elements).forEach((i,s)=>{let a=Mx(i,`NAV_ITEMS[${s}]`,t);a&&o.push(a)}),{items:o,diagnostics:t}}function Mx(e,t,n){if(e?.type!=="ObjectExpression")return n.push({severity:"fatal",path:t,message:"nav item must be an object literal"}),null;let r={};for(let l of qi(e.properties)){if(l.type!=="ObjectProperty"||l.computed)continue;let u=bw(l.key);u&&(r[u]=l.value)}let o=Zi(r.label),i=Zi(r.targetType);if(!o)return n.push({severity:"fatal",path:`${t}.label`,message:"label must be a static string"}),null;if(!i||!Fx.includes(i))return n.push({severity:"fatal",path:`${t}.targetType`,message:`targetType must be one of ${Fx.join("/")}`}),null;r.group!==void 0&&n.push({severity:"warning",code:"leaf-group-field",path:`${t}.group`,message:'unsupported leaf group field ignored; use a canonical targetType: "group" node with children'});let s={label:o,targetType:i};for(let l of Dx){if(r[l]===void 0)continue;let u=Zi(r[l]);u!==void 0?s[l]=u:n.push({severity:"warning",path:`${t}.${l}`,message:`${l} ignored: not a static string`})}r.icon!==void 0&&n.push({severity:"warning",path:`${t}.icon`,message:"icon component ref ignored; use static iconKey"});for(let l of Object.keys(r))xw.has(l)||l==="group"||l==="icon"||n.push({severity:"warning",code:"unknown-field",path:`${t}.${l}`,message:`unsupported field \`${l}\` ignored; NAV_ITEMS only carries ${tf.join("/")}`});if(r.children!==void 0){if(r.children.type!=="ArrayExpression")return n.push({severity:"fatal",path:`${t}.children`,message:"children must be a static array"}),null;let l=[];qi(r.children.elements).forEach((u,d)=>{let f=Mx(u,`${t}.children[${d}]`,n);f&&l.push(f)}),s.children=l}if(i==="group")return s.children?s:(n.push({severity:"fatal",path:`${t}.children`,message:"group item requires children"}),null);let a=Zi(r.href);if(!a)return n.push({severity:"fatal",path:`${t}.href`,message:"href must be a static string for non-group item"}),null;s.href=a;let c=Zi(r.role);if(c!==void 0&&(yw.includes(c)?s.role=c:n.push({severity:"warning",path:`${t}.role`,message:"role ignored: not link/cta"})),r.openInNewTab!==void 0){let l=Lx(r.openInNewTab);l!==void 0?s.openInNewTab=l:n.push({severity:"warning",path:`${t}.openInNewTab`,message:"openInNewTab ignored: not a static boolean"})}if(r.nofollow!==void 0){let l=Lx(r.nofollow);l!==void 0?s.nofollow=l:n.push({severity:"warning",path:`${t}.nofollow`,message:"nofollow ignored: not a static boolean"})}return s}import{parse as Ew}from"@babel/parser";function Qi(e){return Array.isArray(e)?e:[]}function Bx(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression";)t=t.expression;return t?.type==="ArrayExpression"?t:void 0}function Sw(e){let t;try{t=Ew(e,{sourceType:"module",plugins:["typescript","jsx"],tokens:!0})}catch{return{status:"unsupported"}}let n=[];for(let o of Qi(t.program.body)){let i=o.type==="ExportNamedDeclaration"?o.declaration:o;if(i?.type==="VariableDeclaration")for(let s of Qi(i.declarations)){let a=s.id;a?.type==="Identifier"&&a.name==="NAV_ITEMS"&&n.push(s)}}if(n.length===0)return{status:"navigation_not_found"};if(n.length!==1)return{status:"unsupported"};let r=Bx(n[0]?.init);return!r||typeof r.start!="number"||typeof r.end!="number"?{status:"unsupported"}:{status:"ok",array:r,start:r.start,end:r.end}}function rf(e,t){let n=jx(t);if(!n)return{status:"unsupported",source:e};let r=Sw(e);if(r.status!=="ok")return{status:r.status,source:e};let o=r.array;if(nf(e).diagnostics.some(({severity:l})=>l==="fatal"))return{status:"unsupported",source:e};let s=[],a=l=>{let u=Qi(l.elements);for(let[d,f]of u.entries()){if(vw(f,n)){let p=u[d+1],m=u[d-1],y=f.start,x=f.end;if(typeof y!="number"||typeof x!="number")continue;if(p&&typeof p.start=="number")s.push({start:y,end:p.start});else if(m&&typeof m.end=="number")s.push({start:m.end,end:x});else{let S=/^\s*,/.exec(e.slice(x));s.push({start:y,end:S?x+S[0].length:x})}continue}let g=Iw(f);g&&a(g)}};if(a(o),s.length===0)return{status:"not_found",source:e};let c=e;for(let l of s.sort((u,d)=>d.start-u.start))c=c.slice(0,l.start)+c.slice(l.end);return{status:"removed",source:c,removedCount:s.length}}function Iw(e){if(e.type==="ObjectExpression")for(let t of Qi(e.properties)){if(t.type!=="ObjectProperty")continue;let n=t.key;if((n?.name??n?.value)==="children")return Bx(t.value)}}function jx(e){let t=e.trim();return t.startsWith("/")?t==="/"?t:t.replace(/\/+$/,""):null}function vw(e,t){if(e.type!=="ObjectExpression")return!1;let n,r;for(let o of Qi(e.properties)){if(o.type!=="ObjectProperty")continue;let i=o.key,s=o.value,a=i?.name??i?.value;s?.type==="StringLiteral"&&(a==="href"&&(n=String(s.value)),a==="targetType"&&(r=String(s.value)))}return r==="page"&&jx(n??"")===t}import{estimateNavLabelWidth as xX}from"@vcp-dev/contracts";import{parse as SX}from"@babel/parser";function qn(e,t){let n;try{n=kw(e,{sourceType:"module",sourceFilename:t.filePath,plugins:["jsx","typescript"]})}catch(N){let A=N.loc;return{form_codes:[],components:[],uncertain_components:[],rendered_component_openings:[],renders_native_form:!1,diagnostics:[{code:"rendered-module.parse-failed",message:N instanceof Error?N.message:"Rendered module failed Babel parsing.",file_path:t.filePath??"",line:A?.line??1}]}}let r=n.program,o=Xt(r?.body),i=new Map,s=new Map,a=new Map,c=new Map,l=N=>{if(N?.type==="FunctionDeclaration"){let A=N.id;A?.type==="Identifier"&&typeof A.name=="string"&&s.set(A.name,N);return}if(N?.type==="VariableDeclaration")for(let A of Xt(N.declarations)){let w=A.id,F=A.init;w?.type==="Identifier"&&typeof w.name=="string"&&F&&(Sr(F)?s.set(w.name,F):F.type==="Identifier"&&typeof F.name=="string"&&a.set(w.name,F.name))}};for(let N of o){if(N.type==="ImportDeclaration"){let A=N.source?.value;if(typeof A!="string")continue;for(let w of Xt(N.specifiers)){let F=w.local;if(!(F?.type!=="Identifier"||typeof F.name!="string")){if(w.type==="ImportDefaultSpecifier")i.set(F.name,{source:A,exportName:"default"});else if(w.type==="ImportNamespaceSpecifier")i.set(F.name,{source:A,exportName:"*"});else if(w.type==="ImportSpecifier"){let B=w.imported,X=B?.type==="Identifier"&&typeof B.name=="string"?B.name:B?.type==="StringLiteral"&&typeof B.value=="string"?B.value:"";X&&i.set(F.name,{source:A,exportName:X})}}}continue}N.type==="ExportNamedDeclaration"?l(N.declaration):l(N)}for(let N of o){if(N.type==="ExportDefaultDeclaration"){let F=N.declaration;F&&Sr(F)?c.set("default",F):F?.type==="Identifier"&&typeof F.name=="string"&&c.set("default",F.name);continue}if(N.type!=="ExportNamedDeclaration")continue;let A=N.declaration;if(A?.type==="FunctionDeclaration"){let F=A.id;F?.type==="Identifier"&&typeof F.name=="string"&&c.set(F.name,F.name)}else if(A?.type==="VariableDeclaration")for(let F of Xt(A.declarations)){let B=F.id;B?.type==="Identifier"&&typeof B.name=="string"&&c.set(B.name,B.name)}let w=N.source?.value;for(let F of Xt(N.specifiers)){let B=Ux(F.local),X=Ux(F.exported);if(!(!B||!X))if(typeof w=="string"){let $=`#re-export:${X}`;i.set($,{source:w,exportName:B}),c.set(X,$)}else c.set(X,B)}}let u=new Set,d=[],f=new Set,g=[],p=new Set,m=[],y=new Map,x=!1,S=[],b=new Map,E=new Map,k=(N,A="rendered")=>{let w=Vx(N,i);if(!w)return!1;let F=`${w.source}\0${w.exportName}`;if(A==="uncertain")return!f.has(F)&&!p.has(F)&&(p.add(F),g.push({source:w.source,export_name:w.exportName})),!0;if(!f.has(F)&&(f.add(F),d.push({source:w.source,export_name:w.exportName}),p.delete(F))){let B=g.findIndex(X=>X.source===w.source&&X.export_name===w.exportName);B>=0&&g.splice(B,1)}return!0},I=(N,A="rendered",w=[])=>{let F=`${A}\0${sf(w)}`,B=b.get(N)??new Set,X=E.get(N)??new Set;if(B.has(F)||X.has(A))return;B.add(F),b.set(N,B),X.add(A),E.set(N,X);let $=new Map(s),G=new Map,M=[],fe=(Ee,lt=!1)=>{if(uc(Ee)){if(!lt&&Sr(Ee)){if(Ee.type==="FunctionDeclaration"){let Le=Ee.id;Le?.type==="Identifier"&&typeof Le.name=="string"&&$.set(Le.name,Ee)}return}if(Ee.type==="VariableDeclarator"){let Le=Ee.id,pe=Ee.init;Le?.type==="Identifier"&&typeof Le.name=="string"&&pe&&(Sr(pe)?$.set(Le.name,pe):G.set(Le.name,pe))}else if(Ee.type==="ReturnStatement"){let Le=Ee.argument;Le&&M.push(Le)}if(Ee.type==="CallExpression"){let Le=Ee.callee;if(Le?.type==="Import"&&S.push({code:"rendered-module.dynamic-import",message:"Rendered component graph must use static imports.",file_path:t.filePath??"",line:Ee.loc?.start.line??1}),es(Le)==="cms.forms.getConfig"){let pe=Xt(Ee.arguments)[0];pe?.type==="StringLiteral"&&typeof pe.value=="string"&&pe.value.trim()?A==="rendered"?u.add(pe.value.trim()):S.push({code:"rendered-module.unresolved-export",message:"Unable to prove whether a CMS form inside a JSX prop is rendered.",file_path:t.filePath??"",line:Ee.loc?.start.line??1}):S.push({code:"rendered-module.dynamic-form-code",message:"Rendered cms.forms.getConfig() requires a non-empty string literal.",file_path:t.filePath??"",line:Ee.loc?.start.line??1})}}for(let[Le,pe]of Object.entries(Ee))if(Le!=="loc")if(Array.isArray(pe))for(let $e of pe)fe($e);else fe(pe)}};fe(N,!0);let Fe=new Set,ot=new Set,Tt=(Ee,lt=A,Le=w)=>{if(!(!uc(Ee)||Sr(Ee))){if(Ee.type==="Identifier"&&typeof Ee.name=="string"){let pe=G.get(Ee.name),$e=`${lt}\0${Ee.name}\0${sf(Le)}`;pe&&!Fe.has($e)&&!ot.has(Ee.name)?(Fe.add($e),ot.add(Ee.name),Tt(pe,lt,Le),ot.delete(Ee.name)):k(Ee.name,lt);return}if(Ee.type==="CallExpression"){let pe=Ee.callee,$e=Xt(Ee.arguments),kt=es(pe),pn=pe?.type==="Identifier"&&typeof pe.name=="string"?i.get(pe.name):void 0;if(lt==="rendered"&&(kt==="createElement"||kt.endsWith(".createElement")||pn?.source==="react"&&pn.exportName==="createElement")&&$e[0]?.type==="StringLiteral"&&$e[0].value==="form"&&(x=!0),pe?.type==="Identifier"&&typeof pe.name=="string"){let _t=$.get(pe.name);if(_t){I(_t,lt,Le);return}}if(pe&&Sr(pe)){I(pe,lt,Le);return}if(Rw(pe)){for(let _t of $e)if(Sr(_t))I(_t,lt,Le);else if(_t.type==="Identifier"&&typeof _t.name=="string"){let Fs=$.get(_t.name);Fs&&I(Fs,lt,Le)}return}for(let _t of $e)Nw(_t)&&S.push({code:"rendered-module.unresolved-export",message:"Unable to prove whether a JSX-producing call argument is rendered.",file_path:t.filePath??"",line:_t.loc?.start.line??1});return}if(Ee.type==="JSXElement"){let pe=Ee.openingElement,$e=pe?$x(Le,_w(pe)):Le;Tt(pe,lt,$e);for(let kt of Xt(Ee.children))Tt(kt,lt,$e);return}if(Ee.type==="JSXOpeningElement"){let pe=dc(Ee.name);lt==="rendered"&&pe==="form"&&(x=!0);let $e=pe?Vx(pe,i):void 0;if(lt==="rendered"&&$e&&typeof Ee.start=="number"){let kt=`${$e.source}\0${$e.exportName}\0${Ee.start}`,pn=y.get(kt);if(!pn){let _t=Pw(Ee).get("formBlockId");pn={source:$e.source,export_name:$e.exportName,start_offset:Ee.start,...typeof _t=="string"?{static_form_block_id:_t}:{}},y.set(kt,pn),m.push(pn)}Le.length>0&&(pn.static_render_blockers=$x(pn.static_render_blockers??[],Le))}if(pe&&!k(pe,lt)){let kt=$.get(pe);kt?I(kt,lt,Le):G.has(pe)?Tt(G.get(pe),lt,Le):Cw(pe)||/^[A-Z]/.test(pe)&&S.push({code:"rendered-module.dynamic-import",message:`Unable to resolve rendered component ${pe} from a static import.`,file_path:t.filePath??"",line:Ee.loc?.start.line??1})}for(let kt of Xt(Ee.attributes))Tt(kt,"uncertain",Le);return}if(Ee.type==="JSXAttribute"){let pe=Ee.value,$e=pe?.type==="JSXExpressionContainer"?pe.expression:pe;$e&&Sr($e)?I($e,"uncertain",Le):Tt($e,"uncertain",Le);return}for(let[pe,$e]of Object.entries(Ee))if(!(pe==="loc"||pe==="closingElement"))if(Array.isArray($e))for(let kt of $e)Tt(kt,lt,Le);else Tt($e,lt,Le)}},Vr=N.body;Vr&&Vr.type!=="BlockStatement"&&M.push(Vr);for(let Ee of M)Tt(Ee);X.delete(A)},v=c.get(t.exportName);if(typeof v=="string"){let N=v,A=new Set;for(;a.has(N)&&!A.has(N);)A.add(N),N=a.get(N);if(!k(N)){let w=s.get(N);w?I(w):S.push(Kx(t))}}else v?I(v):S.push(Kx(t));return{form_codes:[...u],components:d,uncertain_components:g,rendered_component_openings:m,renders_native_form:x,diagnostics:S}}function sf(e){return e.map(t=>`${t.start_offset}:${t.reason}`).join("|")}function $x(e,t){return[...new Map([...e,...t].map(r=>[sf([r]),r])).values()]}function _w(e){let t=new Map;for(let a of Xt(e.attributes)){if(a.type==="JSXSpreadAttribute"){t.clear();continue}let c=Jx(a.name);if(!c)continue;let l=a.value;t.set(c,l?.type==="JSXExpressionContainer"?l.expression:l)}let n=dc(e.name)??"unknown",r=[],o=a=>{r.push({element_name:n,line:e.loc?.start.line??1,start_offset:Tw(e.start),reason:a})};for(let a of["hidden","inert","aria-hidden","disabled"]){if(!t.has(a)||a==="disabled"&&n!=="fieldset")continue;let c=of(t.get(a));(c===!0||(a==="aria-hidden"?c==="true":typeof c=="string"))&&o(a)}let i=t.get("style");if(i?.type==="ObjectExpression"){let a=new Map;for(let l of Xt(i.properties)){let u=l.key,d=!l.computed&&u?.type==="Identifier"?u.name:u?.type==="StringLiteral"?u.value:void 0;l.type!=="ObjectProperty"||typeof d!="string"?a.clear():a.set(d,of(l.value))}a.get("display")==="none"&&o("style.display=none"),a.get("visibility")==="hidden"&&o("style.visibility=hidden");let c=a.get("opacity");(c===0||typeof c=="string"&&c.trim()==="0")&&o("style.opacity=0")}let s=of(t.get("className"));if(typeof s=="string"){let a=s.split(/\s+/).filter(Boolean),l={hidden:new Set(["block","inline","inline-block","flex","inline-flex","grid","inline-grid","table","inline-table","table-row","table-cell","flow-root","contents","list-item"]),invisible:new Set(["visible"]),"sr-only":new Set(["not-sr-only"])};for(let[u,d]of Object.entries(l))a.includes(u)&&!a.some(f=>d.has(f.split(":").at(-1)))&&o(`className=${u}`)}return r}function of(e){if(e===null)return!0;if(e){if(e.type==="StringLiteral"||e.type==="BooleanLiteral"||e.type==="NumericLiteral")return e.value;if(e.type==="TemplateLiteral"&&Xt(e.expressions).length===0)return Xt(e.quasis)[0]?.value?.cooked}}function Vx(e,t){let n=t.get(e);if(n)return n;let[r,...o]=e.split(".");if(!r||o.length===0)return;let i=t.get(r);if(i?.exportName==="*")return{source:i.source,exportName:o.join(".")}}function Cw(e){return e.endsWith(".Provider")||e.endsWith(".Consumer")}function Sr(e){return e?.type==="FunctionDeclaration"||e?.type==="FunctionExpression"||e?.type==="ArrowFunctionExpression"}function Rw(e){let t=es(e),n=e?.type==="MemberExpression"&&e.computed!==!0?e.property:void 0;return t==="Array.from"||t==="React.Children.map"||n?.type==="Identifier"&&(n.name==="map"||n.name==="flatMap")}function Nw(e){let t=!1;return af(e,n=>{if(!t){if(n.type==="JSXOpeningElement"){t=!0;return}n.type==="CallExpression"&&es(n.callee)==="cms.forms.getConfig"&&(t=!0)}}),t}function Ux(e){return e?.type==="Identifier"&&typeof e.name=="string"?e.name:e?.type==="StringLiteral"&&typeof e.value=="string"?e.value:""}function Kx(e){return{code:"rendered-module.unresolved-export",message:`Unable to resolve rendered export ${e.exportName}.`,file_path:e.filePath??"",line:1}}function es(e){if(!e)return"";if(e.type==="Identifier"&&typeof e.name=="string")return e.name;if(e.type!=="MemberExpression"||e.computed===!0)return"";let t=es(e.object),n=e.property;return!t||n?.type!=="Identifier"||typeof n.name!="string"?"":`${t}.${n.name}`}function Pw(e){let t=new Map,n=Array.isArray(e.attributes)?e.attributes:[];for(let r of n){let o=r;if(o.type!=="JSXAttribute")continue;let i=Jx(o.name);i&&t.set(i,Aw(o.value))}return t}function Aw(e){if(e==null)return!0;let t=e;if(t.type==="StringLiteral")return t.value;if(t.type!=="JSXExpressionContainer")return;let n=t.expression;if(n&&(n.type==="StringLiteral"||n.type==="NumericLiteral"))return n.value}function Jx(e){let t=e;if(t?.type==="JSXIdentifier")return typeof t.name=="string"?t.name:void 0}function Tw(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function af(e,t){if(uc(e)){t(e);for(let[n,r]of Object.entries(e))if(n!=="loc"){if(Array.isArray(r)){for(let o of r)af(o,t);continue}af(r,t)}}}function uc(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}function dc(e){let t=e;if(!t)return"";if(t.type==="JSXIdentifier")return typeof t.name=="string"?t.name:"";if(t.type==="JSXMemberExpression"){let n=dc(t.object),r=dc(t.property);return n&&r?`${n}.${r}`:r||n}return""}function Xt(e){return Array.isArray(e)?e.filter(t=>uc(t)):[]}var Ow="components/site/generated/",ts=[".tsx",".ts",".jsx",".js"];function Xx(e){if(e.expectedUrlPath===ww)return{ok:!1,code:"HOME_PAGE_LOCKED",message:"The homepage source is protected from deletion."};let t=new Set(Wi(Object.keys(e.files).map(m=>({path:m}))).map(m=>m.entryFile)),n=Object.entries(e.files).filter(([m,y])=>{let x=m.replace(/\\/g,"/");if(!t.has(x))return!1;let S=ef(y,x);return S.found&&S.seo?.path===e.expectedUrlPath});if(n.length===0)return{ok:!1,code:"ROUTE_NOT_FOUND",message:"No route uniquely matches the requested page identity."};if(n.length>1)return{ok:!1,code:"ROUTE_AMBIGUOUS",message:"Multiple routes match the requested page identity."};let[r]=n[0],o=new Set([r]);try{let m=sc({files:new Map(Object.entries(e.files))});for(let y of m)y.canonicalEntryFile===r&&o.add(y.entryFile)}catch(m){return{ok:!1,code:"SOURCE_DEPENDENCY_UNSAFE",message:m instanceof Error?m.message:"Invalid page template source."}}let i=Fw(e.files);if(!i.ok)return i.error;let s=i.graph,a=Bw(o,s),c=jw(o,a,s),l=[...a].filter(m=>!c.has(m)).sort((m,y)=>m.localeCompare(y)),u=[...o,...[...c].sort((m,y)=>m.localeCompare(y))],d=new Set(u),f=u.map(m=>({operation:"delete",file:m})),g=[],p=[];for(let[m,y]of Object.entries(e.files))if(!d.has(m)){if(y.includes("NAV_ITEMS")){let x=rf(y,e.expectedUrlPath);x.status==="removed"?(f.push({operation:"upsert",file:m,content:x.source}),g.push(m)):x.status==="unsupported"&&p.push(`unsupported_navigation:${m}`)}y.includes(e.expectedUrlPath)&&!y.includes("NAV_ITEMS")&&p.push(`preserved_link:${m}`)}return{ok:!0,edits:f,deletedFiles:u,updatedFiles:g,preservedSharedFiles:l,warnings:p}}function Fw(e){let t=new Set(Object.keys(e)),n=new Map;for(let[r,o]of Object.entries(e)){let i=r.replace(/\\/g,"/");if(i==="next-env.d.ts"||i.endsWith("/next-env.d.ts")||!Lw(r))continue;let s=je(r,o);if(!s.ok)return{ok:!1,error:{ok:!1,code:"SOURCE_DEPENDENCY_UNSAFE",message:`Page source dependencies could not be proven safe: ${r} (parse-failed).`}};let a=new Set;for(let{specifier:c}of s.module.imports){if(Dw(c))continue;let l=Cn(r,c),u=Mw(l,t);if(!u)return{ok:!1,error:{ok:!1,code:"SOURCE_DEPENDENCY_UNSAFE",message:`Page source dependencies could not be proven safe: ${r} -> ${c} (import-not-found).`}};a.add(u)}n.set(r,a)}return{ok:!0,graph:n}}function Lw(e){let t=e.toLowerCase();return ts.some(n=>t.endsWith(n))}function Dw(e){return!!(/\.([a-z0-9]+)$/i.exec(e)&&!ts.some(n=>e.endsWith(n)))}function Mw(e,t){let n=e.replace(/\\/g,"/");return(ts.some(o=>n.endsWith(o))?[n]:[...ts.map(o=>`${n}${o}`),...ts.map(o=>`${n}/index${o}`)]).find(o=>t.has(o))??null}function Bw(e,t){let n=new Set,r=[...e].flatMap(o=>[...t.get(o)??[]]);for(;r.length>0;){let o=r.pop();!o.startsWith(Ow)||n.has(o)||(n.add(o),r.push(...t.get(o)??[]))}return n}function jw(e,t,n){let r=new Set(t),o=!0;for(;o;){o=!1;for(let i of[...r])[...n].some(([a,c])=>!e.has(a)&&!r.has(a)&&c.has(i))&&(r.delete(i),o=!0)}return r}import*as zb from"@babel/parser";import*as Oe from"@babel/types";import*as Pc from"node:path";import*as Ue from"@babel/types";function zx(e){if(e.path.isVariableDeclarator()){let n=e.path.get("init");return n?.isExpression()?{expressionPath:n}:null}if(!e.path.isIdentifier()||!e.path.parentPath?.isVariableDeclarator())return null;let t=e.path.parentPath.get("init");return t?.isExpression()?{expressionPath:t}:null}function On(e){if(e.path.isObjectPattern()||e.path.isArrayPattern())return io(e.path.node,e.identifier.name);if(e.path.isVariableDeclarator()){let n=e.path.node.id;if(Ue.isObjectPattern(n)||Ue.isArrayPattern(n))return io(n,e.identifier.name)}if(!e.path.isIdentifier())return!1;let t=e.path.parentPath;for(;t;){if(t.isAssignmentPattern()){let n=t.get("left");if(Vw(e.path,n))return!0}if(t.isFunction()||t.isVariableDeclarator())return!1;t=t.parentPath}return!1}function io(e,t,n=!1){return Ue.isIdentifier(e)?e.name===t&&n:Ue.isObjectPattern(e)?e.properties.some(r=>Ue.isObjectProperty(r)?io(r.value,t,n):io(r.argument,t,n)):Ue.isArrayPattern(e)?e.elements.some(r=>{if(!r)return!1;let o=Ue.isRestElement(r)?r.argument:r;return io(o,t,n)}):Ue.isAssignmentPattern(e)?io(e.left,t,!0):Ue.isRestElement(e)?io(e.argument,t,n):!1}function $o(e,t){if(e.path.isObjectPattern()){if(t){let r=En(e.path.node,t.base),[o,...i]=r??[];if(o?.kind==="property")return{propName:o.name,remainingPath:[...i,...t.path],hasDefault:On(e)}}return t?{propName:t.base,remainingPath:t.path,hasDefault:On(e)}:null}if(e.path.isVariableDeclarator()){let r=e.path.get("init");if(r?.isExpression()){let o=Hx(r),i=!1,s=o?o.initBinding&&cf(o.initBinding)?(i=On(o.initBinding),[...o.initPathPrefix]):o.initBinding?(()=>{let c=$o(o.initBinding,{kind:"identifier",expression:o.initBinding.identifier.name,base:o.initBinding.identifier.name,path:[]});return i=c?.hasDefault??!1,c?[{kind:"property",name:c.propName},...c.remainingPath,...o.initPathPrefix]:null})():null:null,a=En(e.path.node.id,e.identifier.name);if(s&&a){let c=[...s,...a],[l,...u]=c;return!l||l.kind!=="property"?null:{propName:l.name,remainingPath:[...u,...t?.path??[]],hasDefault:i||On(e)}}}}let n=Jw(e);if(n){let r=$w(n,e);if(r){let[s,...a]=r.path;return!s||s.kind!=="property"?null:{propName:s.name,remainingPath:[...a,...t?.path??[]],hasDefault:r.hasDefault||On(e)}}if(n.findParent(s=>s.isVariableDeclarator()))return null;let o=Uw(e);if(o){let[s,...a]=o;return!s||s.kind!=="property"?null:{propName:s.name,remainingPath:[...a,...t?.path??[]],hasDefault:On(e)}}let i=ns(n.node);return i?{propName:i,remainingPath:t?.path??[],hasDefault:On(e)}:null}if(cf(e)){let[r,...o]=t?.path??[];return!r||r.kind!=="property"?null:{propName:r.name,remainingPath:o,hasDefault:On(e)}}return null}function $w(e,t){let n=e.findParent(u=>u.isVariableDeclarator());if(!n?.isVariableDeclarator())return null;let r=n.get("init");if(!r?.isExpression())return null;let o=Hx(r);if(!o)return null;let{initBinding:i,initPathPrefix:s}=o;if(!i)return null;let a=!1,c=cf(i)?(a=On(i),[...s]):(()=>{let u=$o(i,{kind:"identifier",expression:i.identifier.name,base:i.identifier.name,path:[]});return a=u?.hasDefault??!1,u?[{kind:"property",name:u.propName},...u.remainingPath,...s]:null})();if(!c)return null;let l=En(n.node.id,t.identifier.name);return l?{path:[...c,...l],hasDefault:a||On(t)}:null}function Hx(e){if(e.isIdentifier())return{initBinding:e.scope.getBinding(e.node.name),initPathPrefix:[]};if(!e.isMemberExpression())return null;let t=Xw(e.node);return t?{initBinding:e.scope.getBinding(t.base),initPathPrefix:t.path}:null}function cf(e){return e.path.isIdentifier()&&e.path.key===0&&Array.isArray(e.path.container)&&e.path.parentPath?.isFunction()===!0}function Vw(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function Uw(e){let t=e.identifier.name,n=e.path.getFunctionParent();if(!n)return null;let r=n.get("params"),o=Array.isArray(r)?r:[r];for(let i of o){let a=En(i.node,t);if(a)return a}return null}function Wx(e,t,n){if(e.path.isVariableDeclarator()){let a=e.path.get("id");if(!Array.isArray(a)&&(a.isObjectPattern()||a.isArrayPattern())){let c=fc(a,e.identifier.name);if(c&&(!n||c.propName===n))return{propName:c.propName,componentName:t,expressionPath:c.expressionPath,displayPath:`${t}.${c.propName}.default`}}}if(e.path.isObjectPattern())for(let a of e.path.get("properties")){if(!a.isObjectProperty())continue;let c=ns(a.node);if(!c||n&&c!==n)continue;let l=a.get("value");if(!l.isAssignmentPattern())continue;let u=l.get("right");if(u.isExpression())return{propName:c,componentName:t,expressionPath:u,displayPath:`${t}.${c}.default`}}let r=Kw(e);if(!r)return null;let o=r.parentPath;if(!o?.isObjectProperty())return null;let i=ns(o.node);if(!i||n&&i!==n)return null;let s=r.get("right");return s.isExpression()?{propName:i,componentName:t,expressionPath:s,displayPath:`${t}.${i}.default`}:null}function fc(e,t){if(e.isObjectPattern()){for(let n of e.get("properties"))if(n.isObjectProperty()){let r=ns(n.node),o=n.get("value");if(o.isAssignmentPattern()){let i=o.get("left"),s=o.get("right");if(r&&!Array.isArray(i)&&En(i.node,t)&&!Array.isArray(s)&&s.isExpression())return{propName:r,expressionPath:s}}if(!Array.isArray(o)&&(o.isObjectPattern()||o.isArrayPattern())){let i=fc(o,t);if(i)return i}}else if(n.isRestElement()){let r=n.get("argument");if(!Array.isArray(r)&&(r.isObjectPattern()||r.isArrayPattern())){let o=fc(r,t);if(o)return o}}}if(e.isArrayPattern())for(let n of e.get("elements")){if(!n)continue;let r=n.isRestElement()&&!Array.isArray(n.get("argument"))?n.get("argument"):n;if(!Array.isArray(r)&&(r.isObjectPattern()||r.isArrayPattern())){let o=fc(r,t);if(o)return o}}return null}function En(e,t,n=[]){if(Ue.isIdentifier(e))return e.name===t?n:null;if(Ue.isObjectPattern(e)){for(let r of e.properties)if(Ue.isObjectProperty(r)){let o=ns(r);if(!o)continue;let i=En(r.value,t,[...n,{kind:"property",name:o}]);if(i)return i}else if(Ue.isRestElement(r)){let o=En(r.argument,t,n);if(o)return o}}if(Ue.isArrayPattern(e))for(let r=0;r<e.elements.length;r+=1){let o=e.elements[r];if(!o)continue;let i=Ue.isRestElement(o)?o.argument:o,s=En(i,t,[...n,{kind:"index",index:r}]);if(s)return s}return Ue.isAssignmentPattern(e)?En(e.left,t,n):null}function Kw(e){if(!e.path.isIdentifier())return null;let t=e.path.parentPath;return t?.isAssignmentPattern()&&t.node.left===e.path.node?t:null}function Jw(e){if(!e.path.isIdentifier())return null;let t=e.path.parentPath;if(t?.isObjectProperty()&&t.parentPath?.isObjectPattern())return t;let n=t?.isAssignmentPattern()?t.parentPath:null;return n?.isObjectProperty()&&n.parentPath?.isObjectPattern()?n:null}function ns(e){return e.computed?null:Ue.isIdentifier(e.key)?e.key.name:Ue.isStringLiteral(e.key)?e.key.value:null}function Xw(e){let t=[],n=e;for(;Ue.isMemberExpression(n);){if(n.computed)if(Ue.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(Ue.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(Ue.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return Ue.isIdentifier(n)?{base:n.name,path:t}:null}import*as eb from"@babel/parser";import df from"@babel/traverse";import*as Vo from"@babel/types";import*as _e from"@babel/types";var Gx=new WeakMap;function gc(e,t=[]){if(e.isIdentifier()){let n=e.scope.getBinding(e.node.name);return n?pc(n,t):null}if(e.isMemberExpression()){let n=Zw(e.node),r=zw(e.node);if(!n||r===null)return null;let o=e.scope.getBinding(n);return o?pc(o,[...r,...t]):null}return e.isAwaitExpression()||uf(e.node)?Ir(Qw(e.node),t,"awaited or fetched expression"):null}function zw(e){let t=[],n=e;for(;_e.isMemberExpression(n);){if(n.computed)if(_e.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(_e.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(_e.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return _e.isIdentifier(n)?t:null}function pc(e,t=[],n){let r=Hw(e,t);if(r)return r;let o=Ww(e,t,n);if(o)return o;let i=Gw(e,t,n);return i||null}function os(e){return e?.kind==="api-source"}function Hw(e,t){if(e.path.isVariableDeclarator()&&_e.isIdentifier(e.path.node.id)){let s=e.path.get("init");if(s?.isCallExpression()&&lf(s.node)&&t[0]?.kind==="property"&&t[0].name==="data")return Ir(e.identifier.name,t,"query hook result.data binding")}if(e.path.isVariableDeclarator()&&_e.isObjectPattern(e.path.node.id)){let s=e.path.node.id.properties.find(c=>_e.isObjectProperty(c)&&qx(c)==="data"&&rs(c.value,e.identifier.name)),a=e.path.get("init");if(s&&a?.isCallExpression()&&lf(a.node))return Ir(e.identifier.name,t,"query hook data binding")}let n=Yw(e);if(!n||qx(n.node)!=="data")return null;let o=n.findParent(s=>s.isVariableDeclarator());if(!o?.isVariableDeclarator())return null;let i=o.get("init");return!i?.isCallExpression()||!lf(i.node)?null:Ir(e.identifier.name,t,"query hook data binding")}function Ww(e,t,n){if(e.path.isVariableDeclarator()&&_e.isArrayPattern(e.path.node.id)){let c=e.path.get("init");if(!c?.isCallExpression()||!Zx(c.node))return null;let[l,u]=e.path.node.id.elements;return!_e.isIdentifier(l)||l.name!==e.identifier.name||!_e.isIdentifier(u)?null:Yx(e,u.name,n)?Ir(e.identifier.name,t,"state setter is updated by API data"):null}if(!e.path.isIdentifier())return null;let r=e.path.parentPath;if(!r?.isArrayPattern())return null;let o=r.parentPath;if(!o?.isVariableDeclarator())return null;let i=o.get("init");if(!i?.isCallExpression()||!Zx(i.node)||r.node.elements.findIndex(c=>c===e.path.node)!==0)return null;let a=r.node.elements[1];return _e.isIdentifier(a)&&Yx(e,a.name,n)?Ir(e.identifier.name,t,"state setter is updated by API data"):null}function Gw(e,t,n){let r=e.path.isVariableDeclarator()?e.path:e.path.findParent(i=>i.isVariableDeclarator());if(!r?.isVariableDeclarator())return null;let o=r.get("init");return o?.isExpression()?o.isAwaitExpression()?Ir(e.identifier.name,t,"awaited binding result"):uf(o.node,n)?Ir(e.identifier.name,t,"fetch-backed binding result"):null:null}function Yw(e){if(!e.path.isIdentifier())return null;let t=e.path.parentPath;return t?.isObjectProperty()?t:t?.isAssignmentPattern()&&t.parentPath?.isObjectProperty()?t.parentPath:null}function rs(e,t){return _e.isIdentifier(e)?e.name===t:_e.isAssignmentPattern(e)?rs(e.left,t):_e.isObjectPattern(e)?e.properties.some(n=>_e.isObjectProperty(n)?rs(n.value,t):rs(n.argument,t)):_e.isArrayPattern(e)?e.elements.some(n=>!!n&&rs(_e.isRestElement(n)?n.argument:n,t)):!1}function Yx(e,t,n){let r=!1,o=!1,i=e.scope.path,s;if(n){let c=Gx.get(n);c||(c=new WeakMap,Gx.set(n,c)),s=c.get(i.node),s||(s=new Map,c.set(i.node,s));let l=s.get(t);if(l!==void 0)return l}i.traverse({CallExpression(c){uf(c.node)&&(r=!0),(qw(c.node.callee,t)||c.node.arguments.some(l=>_e.isIdentifier(l)&&l.name===t))&&(o=!0)}});let a=r&&o;return s?.set(t,a),a}function lf(e){let t=hc(e.callee);return t==="useQuery"||t==="useSWR"||t==="useSuspenseQuery"}function Zx(e){return hc(e.callee)==="useState"}function uf(e,t){let n=t?.get(e);if(n!==void 0)return n;let r=mc(e,o=>_e.isCallExpression(o)&&hc(o.callee)==="fetch");return t?.set(e,r),r}function Zw(e){let t=e;for(;_e.isMemberExpression(t);)t=t.object;return _e.isIdentifier(t)?t.name:null}function qx(e){return e.computed?null:_e.isIdentifier(e.key)?e.key.name:_e.isStringLiteral(e.key)?e.key.value:null}function hc(e){return _e.isIdentifier(e)?e.name:_e.isMemberExpression(e)&&_e.isIdentifier(e.property)?e.property.name:null}function qw(e,t){return mc(e,n=>_e.isIdentifier(n)&&n.name===t)}function mc(e,t){if(t(e))return!0;let n=_e.VISITOR_KEYS[e.type];if(!n)return!1;for(let r of n){let o=e[r];if(Array.isArray(o)){for(let i of o)if(_e.isNode(i)&&mc(i,t))return!0;continue}if(_e.isNode(o)&&mc(o,t))return!0}return!1}function Qw(e){return _e.isIdentifier(e)?e.name:_e.isCallExpression(e)?hc(e.callee)??"api":_e.isAwaitExpression(e)?"awaited-api":"api"}function Ir(e,t,n){return{kind:"api-source",readonly:!0,sourceId:e,displayPath:eO(e,t),reason:n}}function eO(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}var tb=typeof df=="function"?df:df.default;function nb(e,t){let n=ob(e);if(!n)return{allowed:!0};let r=!1;return tb(n,{CallExpression(o){if(!ib(o.node,t.sourceRange)||!tO(o.node))return;let i=o.get("callee");if(!i.isMemberExpression())return;let s=i.get("object");Array.isArray(s)||!s.isExpression()||os(gc(s))&&(r=!0,o.stop())}}),r?{allowed:!1,reason:"Cannot add data-backed items to a dynamic API list"}:{allowed:!0}}function rb(e,t){let n=ob(e);if(!n)return{allowed:!0};let r=!1;return tb(n,{JSXExpressionContainer(o){ib(o.node,t.sourceRange)&&(Vo.isJSXEmptyExpression(o.node.expression)||(r=!0,o.stop()))}}),r?{allowed:!1,reason:"Cannot move subtree across files because it depends on local binding expressions"}:{allowed:!0}}function ob(e){try{return eb.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function tO(e){let t=e.callee;return Vo.isMemberExpression(t)&&Vo.isIdentifier(t.property)&&t.property.name==="map"}function ib(e,t){let n=e.loc;return n?Qx({line:n.start.line,column:n.start.column},{line:t.startLine,column:t.startColumn})>=0&&Qx({line:n.end.line,column:n.end.column},{line:t.endLine,column:t.endColumn})<=0:!1}function Qx(e,t){return e.line!==t.line?e.line<t.line?-1:1:e.column!==t.column?e.column<t.column?-1:1:0}import*as te from"@babel/types";import*as sb from"@babel/parser";import ff from"@babel/traverse";import*as qe from"@babel/types";import*as Uo from"node:path";var Sn=typeof ff=="function"?ff:ff.default;function yt(e){try{return sb.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function pf(e){return e.computed?qe.isStringLiteral(e.key)||qe.isNumericLiteral(e.key)?String(e.key.value):null:nO(e.key)}function nO(e){return qe.isIdentifier(e)?e.name:qe.isStringLiteral(e)||qe.isNumericLiteral(e)?String(e.value):null}function so(e){return qe.isParenthesizedExpression(e)||qe.isTSAsExpression(e)||qe.isTSSatisfiesExpression(e)||qe.isTSNonNullExpression(e)||qe.isTSTypeAssertion(e)?so(e.expression):qe.isExpression(e)?e:null}function mf(e){if(qe.isIdentifier(e))return[e.name];if((qe.isMemberExpression(e)||qe.isOptionalMemberExpression(e))&&!e.computed&&qe.isIdentifier(e.property)){let t=so(e.object),n=t?mf(t):null;return n?[...n,e.property.name]:null}return null}function ao(e,t){return t.startsWith("@/")?t.slice(2).replace(/\\/g,"/"):t.startsWith(".")?Uo.normalize(Uo.join(Uo.dirname(e),t)).replace(/\\/g,"/"):t}function zt(e,t){return yc(e)===yc(t)}function yc(e){let t=Ko(e);return t.endsWith("/index")?t.slice(0,-6):t}function Ko(e){return e.replace(/\.(tsx|ts|jsx|js)$/,"")}function lb(e,t,n){let r=pb(e,t);if(mb(e,r),gb(e,r))return{ok:!1,reason:"Cannot move prop-backed repeat child because the component is referenced through an unsupported value usage"};let o=[];return Sn(e,{JSXElement(s){bb(s,r)&&o.push(s)}}),o.length!==1?{ok:!1,reason:"Cannot move prop-backed repeat child without a single unambiguous component call site"}:xc(o[0])!==n?{ok:!1,reason:"Cannot move prop-backed repeat child because the call site is outside the target component"}:{ok:!0,path:o[0]}}function ub(e,t){let n=new Map,r=i=>{let s=Jo(i);return n.has(s)?!1:(n.set(s,i),!0)};r(t);let o=!0;for(;o;){o=!1;for(let i of e)for(let s of rO(i,n))o=r(s)||o}return[...n.values()]}function rO(e,t){let n=[],r=oO(e,t);for(let o of e.ast.program.body){if(te.isExportDefaultDeclaration(o)&&te.isIdentifier(o.declaration)&&(r.get(o.declaration.name)?.length??0)>0){let i=r.get(o.declaration.name)??[];for(let s of i){if(s.namespace){let a=is(s.namespace,o.declaration.name,"default");a&&n.push({file:e.file,namespace:a,exportName:s.exportName});continue}n.push({file:e.file,exportName:"default"})}continue}if(te.isExportNamedDeclaration(o)&&o.source&&typeof o.source.value=="string"){let i=ao(e.file,o.source.value);for(let s of o.specifiers){if(te.isExportNamespaceSpecifier(s)){let l=vr(s.exported);for(let u of t.values())zt(u.file,i)&&n.push({file:e.file,namespace:gf(l,u.namespace),exportName:u.exportName});continue}if(!te.isExportSpecifier(s))continue;let a=vr(s.local),c=[...t.values()].filter(l=>zt(l.file,i)&&co(l.namespace,a));if(c.length>0){let l=vr(s.exported);for(let u of c){let d=is(u.namespace,a,l);d&&n.push({file:e.file,namespace:d,exportName:u.exportName})}continue}t.has(Jo({file:i,exportName:a}))&&n.push({file:e.file,exportName:vr(s.exported)})}continue}if(te.isExportNamedDeclaration(o)&&!o.source){for(let i of o.specifiers){if(!te.isExportSpecifier(i))continue;let s=vr(i.local),a=r.get(s)??[];if(a.length>0){let c=vr(i.exported);n.push({file:e.file,exportName:c});for(let l of a){let u=is(l.namespace,s,c);u&&n.push({file:e.file,namespace:u,exportName:l.exportName})}}}continue}if(te.isExportAllDeclaration(o)&&typeof o.source.value=="string"){let i=ao(e.file,o.source.value),s=o.exported;if(s){let a=vr(s);for(let c of t.values())zt(c.file,i)&&n.push({file:e.file,namespace:gf(a,c.namespace),exportName:c.exportName});continue}for(let a of t.values())zt(a.file,i)&&(a.namespace||a.exportName!=="default")&&n.push({file:e.file,namespace:a.namespace,exportName:a.exportName})}}return n}function gf(e,t){return t?`${e}.${t}`:e}function co(e,t){return e===t||e?.startsWith(`${t}.`)===!0}function is(e,t,n){return!co(e,t)||!e?null:e===t?n:`${n}${e.slice(t.length)}`}function oO(e,t){let n=new Map,r=(i,s)=>{let a=n.get(i)??[];a.push(s),n.set(i,a)};for(let i of e.ast.program.body){if(!te.isImportDeclaration(i)||typeof i.source.value!="string")continue;let s=ao(e.file,i.source.value);for(let a of i.specifiers){if(te.isImportDefaultSpecifier(a)){let c=t.get(Jo({file:s,exportName:"default"}));c&&r(a.local.name,c);let l=[...t.values()].filter(u=>zt(u.file,s)&&co(u.namespace,"default"));for(let u of l){let d=is(u.namespace,"default",a.local.name);d&&r(a.local.name,{...u,namespace:d})}continue}if(te.isImportSpecifier(a)){let c=vr(a.imported),l=[...t.values()].filter(d=>zt(d.file,s)&&co(d.namespace,c));for(let d of l)r(a.local.name,d);let u=t.get(Jo({file:s,exportName:c}));u&&r(a.local.name,u);continue}if(te.isImportNamespaceSpecifier(a))for(let c of t.values())zt(c.file,s)&&r(a.local.name,{...c,namespace:gf(a.local.name,c.namespace)})}}let o=!0;for(;o;){o=!1;for(let i of e.ast.program.body)if(te.isVariableDeclaration(i))for(let s of i.declarations){if(!te.isIdentifier(s.id)||!s.init)continue;let a=so(s.init);if(!a||!te.isIdentifier(a))continue;let c=n.get(a.name)??[];if(c.length===0)continue;let l=n.get(s.id.name)??[],u=new Set(l.map(Jo));for(let d of c){let f=is(d.namespace,a.name,s.id.name),g=f?{...d,namespace:f}:d,p=Jo(g);u.has(p)||(r(s.id.name,g),u.add(p),o=!0)}}}return n}function Jo(e){let t=e.namespace?`${e.namespace}.${e.exportName}`:e.exportName;return`${yc(e.file)}#${t}`}function vr(e){return te.isIdentifier(e)?e.name:e.value}function db(e,t){for(let n of e.program.body){if(te.isExportDefaultDeclaration(n)){let o=n.declaration;if((te.isFunctionDeclaration(o)||te.isClassDeclaration(o))&&o.id?.name===t)return{exportName:"default"};if(te.isIdentifier(o)&&o.name===t)return{exportName:"default"}}if(!te.isExportNamedDeclaration(n))continue;let r=n.declaration;if((te.isFunctionDeclaration(r)||te.isClassDeclaration(r))&&r.id?.name===t)return{exportName:t};if(te.isVariableDeclaration(r)){for(let o of r.declarations)if(te.isIdentifier(o.id,{name:t}))return{exportName:t}}for(let o of n.specifiers){if(!te.isExportSpecifier(o)||o.local.name!==t)continue;return{exportName:te.isIdentifier(o.exported)?o.exported.name:o.exported.value}}}return null}function yf(e){let t=iO(e),n=[],r=gb(e.ast,t);return Sn(e.ast,{JSXElement(o){zt(e.file,e.sourceFile)&&xc(o)===e.sourceComponent||bb(o,t)&&n.push({file:e.file,path:o})}}),{callSites:n,hasUnsafeReference:r}}function fb(){return{localBindings:new Set,namespaceMembers:new Map,hasUnsupportedAlias:!1}}function pb(e,t){let n=fb();return Sn(e,{Program(r){let o=r.scope.getBinding(t);o&&n.localBindings.add(o),r.stop()}}),n}function iO(e){let t=fb();return zt(e.file,e.sourceFile)&&sO(t,pb(e.ast,e.sourceComponent)),Sn(e.ast,{ImportDeclaration(n){let r=n.node,o=r.source.value;if(typeof o!="string")return;let i=ao(e.file,o),s=e.componentIdentities.filter(a=>zt(a.file,i));if(s.length!==0)for(let a of r.specifiers){let c=n.scope.getBinding(a.local.name);if(c){if(te.isImportDefaultSpecifier(a)&&s.some(l=>l.exportName==="default")&&t.localBindings.add(c),te.isImportDefaultSpecifier(a)){let l=s.filter(u=>co(u.namespace,"default"));if(l.length>0){let u=t.namespaceMembers.get(c)??new Set;for(let d of l){let f=cb(d,"default");f&&u.add(f)}t.namespaceMembers.set(c,u)}continue}if(te.isImportSpecifier(a)){let l=te.isIdentifier(a.imported)?a.imported.name:a.imported.value,u=s.filter(d=>co(d.namespace,l));if(u.length>0){let d=t.namespaceMembers.get(c)??new Set;for(let f of u){let g=cb(f,l);g&&d.add(g)}t.namespaceMembers.set(c,d);continue}s.some(d=>!d.namespace&&d.exportName===l)&&t.localBindings.add(c);continue}if(te.isImportNamespaceSpecifier(a))for(let l of s){let u=l.namespace?`${l.namespace}.${l.exportName}`:l.exportName,d=t.namespaceMembers.get(c)??new Set;d.add(u),t.namespaceMembers.set(c,d)}}}}}),mb(e.ast,t),t}function sO(e,t){e.hasUnsupportedAlias||=t.hasUnsupportedAlias;for(let n of t.localBindings)e.localBindings.add(n);for(let[n,r]of t.namespaceMembers){let o=e.namespaceMembers.get(n)??new Set;for(let i of r)o.add(i);e.namespaceMembers.set(n,o)}}function mb(e,t){Sn(e,{VariableDeclarator(n){if(!n.node.init)return;let r=so(n.node.init);if(r){if(te.isIdentifier(n.node.id)){let o=lo(r,t,n),i=n.scope.getBinding(n.node.id.name);o&&i&&hf(t,i,o);return}if(te.isObjectPattern(n.node.id)){let o=lo(r,t,n);o?.unsupported||o?.local?t.hasUnsupportedAlias=!0:o&&o.namespaceMembers.size>0&&xb(n.node.id,o.namespaceMembers,t,n)}}}})}function gb(e,t){if(t.hasUnsupportedAlias)return!0;let n=!1;return Sn(e,{ReferencedIdentifier(r){if(n){r.stop();return}aO(r)||!r.isIdentifier()||!hb(r,t)||cO(r,t)||lO(r)||(n=!0,r.stop())}}),n}function aO(e){let t=e;for(;t.parentPath?.isJSXMemberExpression();)t=t.parentPath;let n=t.parentPath;return!!(n?.isJSXOpeningElement()&&n.node.name===t.node||n?.isJSXClosingElement()&&n.node.name===t.node)}function hb(e,t){let n=e.scope.getBinding(e.node.name);if(!n)return null;let r=e;for(;r.parentPath?.isMemberExpression()&&r.parentPath.node.object===r.node&&!r.parentPath.node.computed;)r=r.parentPath;return t.localBindings.has(n)||t.namespaceMembers.has(n)&&lo(r.node,t,r)?r:null}function cO(e,t){let n=e.findParent(c=>c.isVariableDeclarator());if(!n?.isVariableDeclarator())return!1;let r=n.get("init");if(!r?.isExpression()||!ab(e,r))return!1;let o=hb(e,t);if(!o)return!1;if(so(r.node)===o.node)return!!lo(r.node,t,r);let s=e.findParent(c=>c.isObjectProperty());if(!s?.isObjectProperty())return!1;let a=s.get("value");return a.isExpression()&&ab(e,a)&&!!lo(a.node,t,a)}function lO(e){let t=e.parentPath;return t?.isExportDefaultDeclaration()&&t.node.declaration===e.node?!0:!!(t?.isExportSpecifier()&&t.node.local===e.node)}function ab(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function lo(e,t,n){let r=so(e);if(!r)return null;if(te.isIdentifier(r)){let a=n.scope.getBinding(r.name);if(!a)return null;let c=t.namespaceMembers.get(a);return t.localBindings.has(a)?{local:!0,namespaceMembers:new Set,unsupported:!1}:c?{local:!1,namespaceMembers:new Set(c),unsupported:!1}:null}if(te.isObjectExpression(r))return uO(r,t,n);let o=mf(r);if(!o||o.length===0)return null;let i=n.scope.getBinding(o[0]);if(!i)return null;let s=t.namespaceMembers.get(i);return s?yb(s,o.slice(1).join(".")):null}function uO(e,t,n){let r=new Set,o=!1;for(let i of e.properties){if(!te.isObjectProperty(i))continue;let s=pf(i);if(!s||!te.isExpression(i.value)){te.isExpression(i.value)&&(o||=lo(i.value,t,n)!==null);continue}let a=lo(i.value,t,n);if(a){o||=a.unsupported,a.local&&r.add(s);for(let c of a.namespaceMembers)r.add(`${s}.${c}`)}}return r.size>0||o?{local:!1,namespaceMembers:r,unsupported:o}:null}function yb(e,t){if(!t)return{local:!1,namespaceMembers:new Set(e),unsupported:!1};let n=new Set,r=!1;for(let o of e){if(o===t){r=!0;continue}o.startsWith(`${t}.`)&&n.add(o.slice(t.length+1))}return r||n.size>0?{local:r,namespaceMembers:n,unsupported:!1}:null}function hf(e,t,n){if(e.hasUnsupportedAlias||=n.unsupported,n.local&&e.localBindings.add(t),n.namespaceMembers.size>0){let r=e.namespaceMembers.get(t)??new Set;for(let o of n.namespaceMembers)r.add(o);e.namespaceMembers.set(t,r)}}function xb(e,t,n,r){for(let o of e.properties){if(te.isRestElement(o)){if(te.isIdentifier(o.argument)){let c=r.scope.getBinding(o.argument.name);c&&hf(n,c,{local:!1,namespaceMembers:new Set(t),unsupported:!1})}else n.hasUnsupportedAlias=!0;continue}if(!te.isObjectProperty(o))continue;let i=pf(o);if(!i){n.hasUnsupportedAlias=!0;continue}let s=yb(t,i);if(!s)continue;n.hasUnsupportedAlias||=s.unsupported;let a=te.isAssignmentPattern(o.value)?o.value.left:o.value;if(te.isIdentifier(a)){let c=r.scope.getBinding(a.name);c&&hf(n,c,s);continue}if(te.isObjectPattern(a)&&s.namespaceMembers.size>0){xb(a,s.namespaceMembers,n,r);continue}n.hasUnsupportedAlias=!0}}function cb(e,t){if(!co(e.namespace,t))return null;if(e.namespace===t)return e.exportName;let n=e.namespace?.slice(t.length+1);return n?`${n}.${e.exportName}`:e.exportName}function bb(e,t){let n=e.node.openingElement.name;if(te.isJSXIdentifier(n)){let o=e.scope.getBinding(n.name);return!!(o&&t.localBindings.has(o))}let r=Eb(n);if(r&&r.length>1){let o=e.scope.getBinding(r[0]);return o?t.namespaceMembers.get(o)?.has(r.slice(1).join("."))===!0:!1}return!1}function Eb(e){if(te.isJSXIdentifier(e))return[e.name];if(te.isJSXMemberExpression(e)){let t=Eb(e.object);return t?[...t,e.property.name]:null}return null}function xc(e){let t=e.getFunctionParent();if(!t)return null;if(t.isFunctionDeclaration())return t.node.id?.name??null;if(t.isArrowFunctionExpression()||t.isFunctionExpression()){let n=t.parentPath;if(n?.isVariableDeclarator()&&te.isIdentifier(n.node.id))return n.node.id.name}return null}function Sb(e,t){let n=yt(e);if(!n||!t.tag||!t.importedFrom||!t.exportName)return Number.POSITIVE_INFINITY;let r=yf({ast:n,file:t.file,sourceFile:t.file,sourceComponent:t.tag,componentIdentities:[{file:t.importedFrom,exportName:t.exportName}]});return r.hasUnsafeReference?Number.POSITIVE_INFINITY:r.callSites.length}function Ve(e){return e.structuralPath.includes("#repeat:")||e.isRepeatItemRoot||e.isRepeatRegion?{kind:"jsx-node",strategy:"source-range",sourceRange:e.sourceRange}:{kind:"jsx-node",strategy:"structural-path",file:e.file,component:e.component,structuralPath:e.structuralPath,expectedRange:e.sourceRange}}function Me(e){return typeof e.start=="number"&&typeof e.end=="number"?{start:e.start,end:e.end}:null}function Fn(e,t){let n=Me(e);return!!(n&&Ht(t,n))}function Ht(e,t){return t.start>=e.start&&t.end<=e.end}function dn(e,t){let n=Ie(e,Ve(t));return n.ok&&n.match.path.isJSXElement()?n.match.path:bc(e,t)}function Xo(e,t){let n=Me(t);return n?e.slice(n.start,n.end):""}function Ib(e,t){return e.start===t.start&&e.end===t.end}function bc(e,t){let n=null;return Sn(e,{JSXElement(r){let o=r.node.loc;o&&o.start.line===t.sourceRange.startLine&&o.start.column===t.sourceRange.startColumn&&o.end.line===t.sourceRange.endLine&&o.end.column===t.sourceRange.endColumn&&(n=r,r.stop())}}),n}function Ec(e,t){return xf(e,t).length>0}function Sc(e,t){let n=Me(e.node),r=Me(t.node);if(!n||!r)return!1;let o=e.parentPath;for(;o;){if((o.isIfStatement()||o.isSwitchCase())&&(!!!t.findParent(s=>s.node===o?.node)||o.isIfStatement()&&!dO(o,n,r)))return!0;o=o.parentPath}return!1}function dO(e,t,n){let r=Me(e.node.consequent);if(r&&Ht(r,t)&&!Ht(r,n))return!1;let o=e.node.alternate?Me(e.node.alternate):null;return!(o&&Ht(o,t)&&!Ht(o,n))}function xf(e,t){let n=Me(e.node);if(!n)return[];let r=[],o=e.parentPath;for(;o;){let i=!!t.findParent(s=>s.node===o?.node);if(!i&&o.isConditionalExpression()){let s=Me(o.node.consequent),a=Me(o.node.alternate);s&&n.start>=s.start&&n.end<=s.end?r.push({kind:"conditional",path:o,conditionPath:o.get("test"),branch:"consequent"}):a&&n.start>=a.start&&n.end<=a.end&&r.push({kind:"conditional",path:o,conditionPath:o.get("test"),branch:"alternate"})}else if(!i&&o.isLogicalExpression()&&bf(o.node.operator)){let s=Me(o.node.right);s&&n.start>=s.start&&n.end<=s.end&&r.push({kind:"logical",path:o,conditionPath:o.get("left"),operator:o.node.operator})}o=o.parentPath}return r}function bf(e){return e==="&&"||e==="||"||e==="??"}function vb(e,t){let n=Me(e.consequent);if(n&&Ht(n,t))return n;let r=Me(e.alternate);return r&&Ht(r,t)?r:null}function kb(e){if(!e.knownSourceFiles)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component without project-wide source visibility"};if(!e.routeEntryFiles)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component without registered route visibility"};let t=new Set(e.knownSourceFiles.map(a=>Ko(a.file)));if(!t.has(Ko(e.sourceFile))||!t.has(Ko(e.targetFile)))return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component without source and target file visibility"};for(let a of e.routeEntryFiles)if(!t.has(Ko(a)))return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component until all registered route entries are loaded"};let n=db(e.sourceAst,e.sourceComponent);if(!n)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component without an exported source component identity"};let r=[];for(let a of e.knownSourceFiles){let c=yt(a.content);if(!c)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component because a loaded source file cannot be parsed"};r.push({file:a.file,ast:c})}let o=ub(r,{file:e.sourceFile,exportName:n.exportName}),i=[];for(let a of r){let c=yf({ast:a.ast,file:a.file,sourceFile:e.sourceFile,sourceComponent:e.sourceComponent,componentIdentities:o});if(c.hasUnsafeReference)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component because the component has unsupported value usages"};i.push(...c.callSites)}if(i.length!==1)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component without a single project-wide component call site"};let[s]=i;return!zt(s.file,e.targetFile)||xc(s.path)!==e.targetComponent?{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component because the only call site is outside the target component"}:{ok:!0,callSitePath:s.path}}import{SiteEditSetPropsParamsSchema as yO}from"@vcp-dev/contracts";function Ic(e){let{state:t,scope:n,operation:r,selectionRef:o,repeatTarget:i}=e;if(!t||t.status==="blocked")return{ok:!1,code:"readonly-property",reason:t?.diagnostic?.message??"No safe property write target is available"};if(t.status==="binding"){let s=t.target;if(s?.kind!=="value-binding"||!s.target.locator||n!=="selection"||r!=="set")return ss();let a=s.target,c=a.locator;if(a.sourceKind==="repeat-template"){let l=o?.instanceIndex;if(l===void 0)return ss();let u=fO(a,l,o?.instanceCount);if(!u)return ss();c=u}return{ok:!0,target:{kind:"value-binding",file:a.file,locator:c}}}return o?.instanceIndex!==void 0?n!=="selection"||!i?.ok?{ok:!1,code:"repeat-target-failed",reason:i&&!i.ok?i.reason:"No safe selected repeat property target is available"}:{ok:!0,target:{kind:"repeat-property",target:i}}:e.isRepeat&&n!=="template"||t.status==="direct"&&t.target?.kind!=="jsx-attribute"?ss():{ok:!0,target:{kind:"jsx-attribute"}}}function ss(){return{ok:!1,code:"unsupported-binding",reason:"Property does not have a safe typed binding write target for this scope and operation"}}function fO(e,t,n){if(!e.locator||!Number.isInteger(t)||t<0)return null;let r=e.collectionPathMap?.length??e.collectionIndexMap?.length;if(r!==void 0&&(t>=r||n!==void 0&&n!==r))return null;let o=e.collectionPathMap?.[t];if(o)return{...e.locator,path:o};let i=e.locator.path??[],s=i.findLastIndex(c=>c.kind==="index");if(s<0)return null;let a=i.map((c,l)=>l===s&&c.kind==="index"?{kind:"index",index:e.collectionIndexMap?.[t]??t}:c);return{...e.locator,path:a}}import*as Ln from"@babel/types";import{SiteEditSetPropsParamsSchema as pO}from"@vcp-dev/contracts";function _b(e){let t=e.changes??(e.change?[e.change]:[]);if(!pO.safeParse({kind:"set-props",scope:"selection",changes:t}).success)return as("invalid-change","Repeat property changes are invalid");if(t.length!==1||t[0].name!==e.target.propertyName)return as("target-mismatch","A repeat property plan must contain exactly one change for its target property");let r=t[0];if(r.operation==="remove"&&e.target.propertyState==="missing")return{ok:!0,steps:[]};let o=We(e.source,"value");if(!o.ok)return as("invalid-target","Repeat property source could not be parsed");let i=[{type:"set-property-binding",order:0,file:e.target.templateFile,locator:e.target.targetElementLocator,name:r.name,object:e.target.callbackItemName,property:r.name}];for(let[s,a]of e.target.parentObjectLocators.entries()){let c=Ie(o.ast,a);if(!c.ok||!c.match.path.isObjectExpression())return as("unsupported-object",`Repeat item ${s} is not a writable object expression`);let l=s===e.target.sourceItemIndex?mO(r):gO(c.match.path.node,r.name);if(!l)return as("unsupported-property-value",`Repeat item ${s} has an unsupported value for '${r.name}'`);i.push({type:"upsert-object-property",order:i.length,file:e.target.sourceFile,locator:a,name:r.name,value:l})}return{ok:!0,steps:i}}function mO(e){return e.operation==="set"?{kind:"value",value:e.value}:{kind:"undefined"}}function gO(e,t){let n=e.properties.filter(i=>Ln.isObjectProperty(i)&&hO(i.key)===t);if(n.length>1)return null;let r=n[0];if(!r)return{kind:"undefined"};if(!Ln.isExpression(r.value))return null;let o=Tn(r.value);return o.status==="undefined"?{kind:"undefined"}:o.status!=="resolved"?null:{kind:"value",value:o.value}}function hO(e){return Ln.isIdentifier(e)?e.name:Ln.isStringLiteral(e)?e.value:Ln.isNumericLiteral(e)?String(e.value):null}function as(e,t){return{ok:!1,errorCode:e,reason:t}}function Cb(e){if(e.change.name!=="className"&&e.change.name!=="class")return cs("unsupported-owner",`No specialized property owner is available for '${e.change.name}'`);let t=e.classNameSource;if(!t||t.filePath!==e.node.file)return cs("owner-source-unavailable","className source details are unavailable for the selected node");if(e.change.name==="class"&&t.sourceKind==="missing")return cs("owner-source-unavailable","The class alias requires an existing className source");if(t.sourceKind==="expression")return cs("owner-source-dynamic","Dynamic className expressions are not writable by the generic property owner");if(e.change.operation==="set"&&typeof e.change.value!="string")return cs("owner-value-invalid","The className owner accepts only string values");if(e.change.operation==="remove"&&t.sourceKind==="missing")return{ok:!0,steps:[]};let n=t.sourceKind==="missing",r=e.change.operation==="set"?`className=${JSON.stringify(e.change.value)}`:null,o=e.change.operation==="remove"?"remove-attribute":n?"create-attribute":"replace-static-classname";return{ok:!0,steps:[{type:"set-class-name-source",order:0,file:e.node.file,request:{kind:"set-class-name-source",key:e.node.key,filePath:e.node.file,expectedVersion:t.version,oldAttrRaw:t.attrRaw,oldAttrRange:t.attrRange,openingElementRange:t.openingElementRange,newAttrRaw:r,intent:{source:"style-panel",operation:o}}}]}}function cs(e,t){return{ok:!1,errorCode:e,reason:t}}async function Nb(e){let t=yO.safeParse({kind:"set-props",scope:e.scope,changes:e.changes});if(!t.success)return kr("invalid-change","Typed property changes are invalid");if(e.node.importedFrom==="next/link"&&e.node.exportName==="default"){let r=t.data.changes.find(o=>o.name==="href");if(r&&(r.operation==="remove"||typeof r.value!="string"||r.value.trim().length===0))return kr("invalid-change","next/link requires a non-empty href; use the dedicated link-target operation to remove the link")}let n=[];for(let r of t.data.changes){let o=await xO(e,r);if(o){if(!o.ok)return kr("owner-plan-failed",o.reason);Rb(n,o.steps);continue}let i=await e.getPropertyState(e.node.key,r.name,e.selectionRef);if(!i)return kr("missing-property-state",`No authoritative property state is available for '${r.name}'`);if(i.status==="blocked")return kr("readonly-property",i.diagnostic?.message??`Property '${r.name}' is not writable`);if(SO(i,r)||r.operation==="remove"&&i.status==="missing")continue;let s=e.selectionRef?.instanceIndex!==void 0&&i.status!=="binding"?await e.getRepeatPropertyTarget?.(e.node.key,r.name,e.selectionRef):void 0,a=Ic({state:i,scope:e.scope,operation:r.operation,selectionRef:e.selectionRef,repeatTarget:s});if(!a.ok)return kr(a.code,a.reason);let c=a.target;if(c.kind==="value-binding"&&r.operation==="set"){Ef(n,{type:"update-value",order:n.length,file:c.file,locator:c.locator,value:r.value});continue}if(c.kind==="repeat-property"){let l=_b({source:e.getFileContent(c.target.sourceFile),target:c.target,changes:[r]});if(!l.ok)return kr("repeat-target-failed",l.reason);Rb(n,l.steps);continue}Ef(n,{type:"set-property-changes",order:n.length,file:e.node.file,locator:bO(e.node),scope:e.scope,changes:[r]})}return n.forEach((r,o)=>{r.order=o}),EO(n)?kr("step-conflict","Property changes resolve to conflicting write steps"):{ok:!0,steps:n}}async function xO(e,t){return t.name!=="className"&&t.name!=="class"?null:Cb({node:e.node,change:t,classNameSource:e.classNameSource})}function bO(e){return e.structuralPath.includes("#repeat:")||e.key.includes("::repeat-item#")?{kind:"jsx-node",strategy:"source-range",sourceRange:e.sourceRange}:{kind:"jsx-node",strategy:"structural-path",file:e.file,component:e.component,structuralPath:e.structuralPath,expectedRange:e.sourceRange}}function EO(e){let t=new Set;for(let n of e){let{order:r,...o}=n,i=`${n.file}:${n.type}:${JSON.stringify(o)}`;if(t.has(i))return!0;t.add(i)}return!1}function Rb(e,t){for(let n of t)Ef(e,{...n,order:e.length})}function Ef(e,t){if(t.type==="set-property-changes"){let n=e.find(r=>r.type==="set-property-changes"&&r.file===t.file&&JSON.stringify(r.locator)===JSON.stringify(t.locator)&&r.scope===t.scope);if(n){n.changes.push(...t.changes);return}}e.push(t)}function SO(e,t){if(t.operation!=="set"||e.status!=="direct")return!1;let n=e.attribute?.resolution;return n?.status==="resolved"?Sf(n.value,t.value):e.attribute?.source===null&&e.attribute.value===t.value}function Sf(e,t){if(Object.is(e,t))return!0;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((n,r)=>Sf(n,t[r]));if(e&&t&&typeof e=="object"&&typeof t=="object"){let n=e,r=t,o=Object.keys(n);return o.length===Object.keys(r).length&&o.every(i=>Sf(n[i],r[i]))}return!1}function kr(e,t){return{ok:!1,errorCode:e,reason:t}}import*as Ho from"@babel/types";import*as ae from"@babel/types";function If(e,t,n){let r=dn(t,n);return r?Dn(e,r):null}function Dn(e,t){let n=t.findParent(m=>m.isArrowFunctionExpression()||m.isFunctionExpression());if(!n||!n.isArrowFunctionExpression()&&!n.isFunctionExpression())return null;let r=n,o=r.parentPath;if(!o||!o.isCallExpression()&&!o.isOptionalCallExpression())return null;let i=o;if(i.node.arguments.findIndex(m=>m===r.node)!==0)return null;let a=i.get("callee");if(!a.isMemberExpression()&&!a.isOptionalMemberExpression())return null;let c=a.node,l=c.property;if(!ae.isIdentifier(l)||l.name!=="map"||c.computed)return null;let u=a.get("object"),d=Xo(e,u.node),f=r.node.params.map(m=>Xo(e,m)),g=Me(i.node),p=Me(r.node);return!d||f.some(m=>m.length===0)||!g||!p?null:{callStart:g.start,callEnd:g.end,callbackStart:p.start,callbackEnd:p.end,collectionExpression:d,callbackParams:f,mapOperator:ae.isOptionalMemberExpression(c)&&c.optional?"?.map":".map",collectionNeedsParens:vc(u.node),callbackPath:r,collectionPath:u}}function ls(e,t){return!!(e&&t&&e.callStart===t.callStart&&e.callEnd===t.callEnd&&e.callbackStart===t.callbackStart&&e.callbackEnd===t.callbackEnd)}function IO(e,t){let n=Me(e.node);return n?vO(t).some(r=>{let o=Me(r);return r===e.node||!!(o&&o.start===n.start&&o.end===n.end)}):!1}function vO(e){let t=e.callbackPath.node.body;return ae.isBlockStatement(t)?_r(t.body):Cr(t)}function _r(e){let t=[];for(let n of e){if(ae.isReturnStatement(n)){n.argument&&t.push(...Cr(n.argument));continue}if(ae.isBlockStatement(n)){t.push(..._r(n.body));continue}if(ae.isIfStatement(n)){let r=ae.isBlockStatement(n.consequent)?n.consequent.body:[n.consequent];if(t.push(..._r(r)),n.alternate){let o=ae.isBlockStatement(n.alternate)?n.alternate.body:[n.alternate];t.push(..._r(o))}continue}if(ae.isSwitchStatement(n)){for(let r of n.cases)t.push(..._r(r.consequent));continue}ae.isTryStatement(n)&&(t.push(..._r(n.block.body)),n.handler&&t.push(..._r(n.handler.body.body)),n.finalizer&&t.push(..._r(n.finalizer.body)))}return t}function Cr(e){return ae.isJSXElement(e)?kO(e)?Pb(e.children):[e]:ae.isJSXFragment(e)?Pb(e.children):ae.isParenthesizedExpression(e)||ae.isTSAsExpression(e)||ae.isTSSatisfiesExpression(e)||ae.isTSNonNullExpression(e)||ae.isTSTypeAssertion(e)?Cr(e.expression):ae.isConditionalExpression(e)?[...Cr(e.consequent),...Cr(e.alternate)]:ae.isLogicalExpression(e)&&bf(e.operator)?Cr(e.right):[]}function Pb(e){return e.flatMap(t=>ae.isJSXElement(t)||ae.isJSXFragment(t)?Cr(t):ae.isJSXExpressionContainer(t)&&(ae.isJSXElement(t.expression)||ae.isJSXFragment(t.expression)||ae.isConditionalExpression(t.expression)||ae.isLogicalExpression(t.expression))?Cr(t.expression):[])}function kO(e){let t=e.openingElement.name;return ae.isJSXIdentifier(t)?t.name==="Fragment":ae.isJSXMemberExpression(t)&&t.property.name==="Fragment"}function Ab(e,t){return!!(e&&t&&e.callbackStart<t.callbackStart&&e.callbackEnd>t.callbackEnd)}function vc(e){return!(ae.isIdentifier(e)||ae.isThisExpression(e)||ae.isMemberExpression(e)||ae.isOptionalMemberExpression(e)||ae.isCallExpression(e)||ae.isOptionalCallExpression(e))}function Tb(e){let t=e.parentPath;if(!t||!t.isCallExpression()&&!t.isOptionalCallExpression()||t.node.arguments[0]!==e.node)return!1;let n=t.node.callee;return(ae.isMemberExpression(n)||ae.isOptionalMemberExpression(n))&&ae.isIdentifier(n.property)&&n.property.name==="map"&&!n.computed}function zo(e,t){let n=yt(e);if(!n)return t.isRepeatItemRoot===!0;let r=Ie(n,Ve(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:bc(n,t);if(!o)return t.isRepeatItemRoot===!0;let i=Dn(e,o);return i?IO(o,i):t.isRepeatItemRoot===!0}function wb(e,t){let n=yt(e);if(!n)return!1;let r=Ie(n,Ve(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:bc(n,t);return o?!!o.findParent(i=>{if(!i.isCallExpression()&&!i.isOptionalCallExpression())return!1;let s=i.node.callee;return(ae.isMemberExpression(s)||ae.isOptionalMemberExpression(s))&&ae.isIdentifier(s.property)&&s.property.name==="map"}):!1}import*as Xe from"@babel/types";function vf(e){if(Xe.isJSXIdentifier(e))return/^[A-Z]/.test(e.name)?e.name:null;if(Xe.isJSXMemberExpression(e)){let t=e;for(;Xe.isJSXMemberExpression(t);)t=t.object;return t.name}return null}function _O(e,t){let n=Me(e.node);if(!n)return[];let r=new Set,o=(i,s)=>{let a=s.scope.getBinding(i);!a||Fn(a.path.node,n)||Rr(a,i,t)||r.add(i)};return e.traverse({ReferencedIdentifier(i){o(i.node.name,i)},JSXOpeningElement(i){let s=vf(i.node.name);s&&o(s,i)}}),[...r].sort()}function kf(e,t,n){let r=yt(e);if(!r)return{ok:!0};let o=Ie(r,Ve(t));if(!o.ok||!o.match.path.isJSXElement())return{ok:!0};let i=Ie(r,Ve(n));if(!i.ok||!i.match.path.isJSXElement())return{ok:!0};let s=Ii(o.match.path,i.match.path);if(Ec(s,i.match.path))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let a=_O(s,i.match.path);return a.length>0?{ok:!1,bindingNames:a}:{ok:!0}}function Fb(e){let t=e;for(;Xe.isTSQualifiedName(t);)t=t.left;return Xe.isIdentifier(t)?t.name:null}function us(e,t){e.isIdentifier()&&e.isReferencedIdentifier()&&t(e),e.traverse({ReferencedIdentifier(n){n.isIdentifier()&&t(n)}})}function kc(e){let t=[],n=r=>{if(r){if(Xe.isIdentifier(r)){t.push(r.name);return}if(Xe.isObjectPattern(r)){for(let o of r.properties){if(Xe.isRestElement(o)){n(o.argument);continue}Xe.isObjectProperty(o)&&n(o.value)}return}if(Xe.isArrayPattern(r)){for(let o of r.elements)n(o);return}if(Xe.isAssignmentPattern(r)){n(r.left);return}if(Xe.isRestElement(r)){n(r.argument);return}Xe.isTSParameterProperty(r)&&n(r.parameter)}};return n(e),t}function _f(e,t){let n=Me(e.node),r=Me(t.node);if(!n||!r)return{ok:!1,reason:"Cannot move repeat-backed child out of a component without proving the component call-site render scope"};let o=Ob(e),i=Ob(t);if(!o||!i||!Ib(o,i))return{ok:!1,reason:"Cannot move repeat-backed child out of a component because the component call site is rendered in a different return branch"};let s=e.parentPath;for(;s;){if(s.isConditionalExpression()){let a=vb(s.node,n);if(a&&!Ht(a,r))return{ok:!1,reason:"Cannot move repeat-backed child out of a component because the component call site is conditionally rendered outside the target scope"}}else if(s.isLogicalExpression()){let a=Me(s.node.right);if(a&&Ht(a,n)&&!Ht(a,r))return{ok:!1,reason:"Cannot move repeat-backed child out of a component because the component call site is conditionally rendered outside the target scope"}}else if((s.isArrowFunctionExpression()||s.isFunctionExpression())&&Tb(s)){let a=Me(s.node.body)??Me(s.node);if(a&&!Ht(a,r))return{ok:!1,reason:"Cannot move repeat-backed child out of a component because the component call site is repeated outside the target scope"}}s=s.parentPath}return{ok:!0}}function Ob(e){let t=e;for(;t;){if(t.isReturnStatement())return t.node.argument?Me(t.node.argument):null;if(t.isArrowFunctionExpression()&&(Xe.isJSXElement(t.node.body)||Xe.isJSXFragment(t.node.body)||Xe.isConditionalExpression(t.node.body)||Xe.isLogicalExpression(t.node.body)))return Me(t.node.body);t=t.parentPath}return null}function Rr(e,t,n){return n.scope.getBinding(t)===e}function Cf(e,t,n,r={}){if(!r.preserveConditionalBoundary&&Ec(e,t))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let o=Me(e.node);if(!o)return{ok:!0};let i=new Set(n.callbackPath.node.params.flatMap(c=>kc(c)).map(c=>n.callbackPath.scope.getBinding(c)?.path.node).filter(Boolean)),s=new Set,a=(c,l)=>{let u=l.scope.getBinding(c);!u||Fn(u.path.node,o)||i.has(u.path.node)||Rr(u,c,t)||s.add(c)};return e.traverse({ReferencedIdentifier(c){a(c.node.name,c)},JSXOpeningElement(c){let l=vf(c.node.name);l&&a(l,c)}}),s.size>0?{ok:!1,bindingNames:[...s].sort()}:{ok:!0}}function Rf(e,t,n){let r=Me(e.node);if(!r)return{ok:!0};let o=new Set(n.callbackPath.node.params.flatMap(s=>kc(s)).map(s=>n.callbackPath.scope.getBinding(s)?.path.node).filter(Boolean)),i=new Set;return us(e,s=>{let a=s.scope.getBinding(s.node.name);!a||Fn(a.path.node,r)||o.has(a.path.node)||Rr(a,s.node.name,t)||i.add(s.node.name)}),i.size>0?{ok:!1,bindingNames:[...i].sort()}:{ok:!0}}function Lb(e,t){let n=new Set(e.callbackPath.node.params.flatMap(a=>kc(a)).map(a=>e.callbackPath.scope.getBinding(a)?.path.node).filter(Boolean)),r=new Set,o=(a,c)=>{let l=c.scope.getBinding(a);!l||n.has(l.path.node)||Rr(l,a,t)||r.add(a)},i=e.callbackPath.get("params"),s=Array.isArray(i)?i:[i];for(let a of s)a.traverse({ReferencedIdentifier(c){o(c.node.name,c)},TSTypeReference(c){let l=c.node.typeName;if(Ho.isIdentifier(l))o(l.name,c);else{let u=Fb(l);u&&o(u,c)}}});return r.size>0?{ok:!1,bindingNames:[...r].sort()}:{ok:!0}}function Nf(e,t){let n=Me(e.node),r=new Set;return us(e,o=>{let i=o.scope.getBinding(o.node.name);i&&(n&&Fn(i.path.node,n)||Rr(i,o.node.name,t)||r.add(o.node.name))}),r.size>0?{ok:!1,bindingNames:[...r].sort(),reason:"Cannot move repeat-backed child because the repeat collection is not visible at the target"}:{ok:!0}}function Db(e){let t=[];for(let n of e.callbackPath.node.params){if(Ho.isIdentifier(n)){t.push(n.name);continue}if(Ho.isRestElement(n)&&Ho.isIdentifier(n.argument)){t.push(`...${n.argument.name}`);continue}return{ok:!1,reason:"Cannot move cross-file repeat child because the callback parameters are not portable to the target file"}}return{ok:!0,callbackParams:t}}function Mb(e,t){return{...e,callbackParams:t}}function Pf(e,t){return`${e.collectionNeedsParens?`(${e.collectionExpression})`:e.collectionExpression}${e.mapOperator}((${e.callbackParams.join(", ")}) => ${t})`}function ds(e,t,n){return n?.finalSource?.kind==="component-prop"?"Cannot edit prop-backed node structure with a generic node operation":t?.kind==="value-binding"&&t.sourceKind==="repeat-template"&&!e.isRepeatItemRoot?"Cannot edit repeat-backed child node structure with a generic node operation":t?.kind==="value-binding"&&t.file!==e.file&&t.sourceKind!=="repeat-template"?"Cannot edit upstream-bound node structure with a generic node operation":null}function Bb(e,t,n,r){return e.parentKey===t.key&&e.file===t.file&&n?.kind==="value-binding"&&n.file!==e.file&&n.sourceKind!=="repeat-template"&&r?.finalSource?.kind!=="component-prop"}function uo(e){return{file:e.file,component:e.component}}function CO(e){return e.target.kind==="node"?e.target.key:null}function RO(e){return"kind"in e&&e.kind==="page-composition"}function Rc(e){return typeof e=="object"&&e!==null&&"kind"in e&&e.kind==="block-boundary"}function _c(e){return!RO(e)&&!Rc(e)}function Ff(e,t){let n=Pc.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=Pc.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function Af(e,t){let n=e.getFileContent(t.file);if(!n)return;let r=Pn(n,Ve(t));if(r.ok)return n.slice(r.match.start,r.match.end)}function Df(e){if(!e.component)return"Component";if(e.component.exportName!=="default")return e.component.exportName;let t=e.component.source.replace(/\\/g,"/").replace(/\/$/,""),n=t.split("/").pop()||"Component",i=(n==="index"?t.split("/").slice(-2,-1)[0]||"Component":n).replace(/\.[^.]+$/,"").split(/[^A-Za-z0-9]+/).filter(Boolean);return i.length===0?"Component":i.map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join("")}function NO(e){if(e.isNumericLiteral())return!0;if(!e.isUnaryExpression({operator:"-"}))return!1;let t=e.get("argument");return!Array.isArray(t)&&t.isNumericLiteral()}function PO(e){let t=e.trim();if(!/^[+-]?(?:(?:\d+\.?\d*)|(?:\.\d+))(?:[eE][+-]?\d+)?$/.test(t))return null;let n=Number(t);return Number.isFinite(n)?n:null}function Tf(e){return e==="Cannot edit repeat-backed child node structure with a generic node operation"}function AO(e){let t=lb(e.ast,e.sourceNode.component,e.targetParent.component);if(!t.ok)return{ok:!1,reason:t.reason};let n=_f(t.path,e.targetParentPath);if(!n.ok)return{ok:!1,reason:n.reason};let r=TO({source:e.source,sourceContext:e.sourceContext,callSitePath:t.path,targetParentPath:e.targetParentPath});if(!r.ok)return r;let o=Hb(r.collectionExpression);return{ok:!0,context:{...e.sourceContext,collectionExpression:r.collectionExpression,collectionNeedsParens:o?vc(o):!0}}}function TO(e){let t=Me(e.sourceContext.collectionPath.node);if(!t)return{ok:!1,reason:"Cannot move prop-backed repeat child because the collection expression cannot be mapped"};let n=new Map,r=new Set,o=null,i=s=>{if(o)return;let a=s.scope.getBinding(s.node.name);if(!a||Fn(a.path.node,t))return;let c=FO(s,a,t);if(c){if(c.hasDefault){o="Cannot move prop-backed repeat child because the collection prop has a default value that cannot be preserved safely";return}let l=DO(e.callSitePath,c.propName,e.source);if(!l.ok){o=l.reason;return}let u=wO(l.expression,c.remainingPath);if(!u){o="Cannot move prop-backed repeat child because the mapped prop path is not a portable expression";return}let d=Nf(l.expressionPath,e.targetParentPath);if(!d.ok){o=d.reason??`Cannot move prop-backed repeat child because the mapped prop source is not visible at the target: ${d.bindingNames.join(", ")}`;return}n.set(`${c.range.start}:${c.range.end}`,{...c.range,text:u});return}Rr(a,s.node.name,e.targetParentPath)||r.add(s.node.name)};return e.sourceContext.collectionPath.isIdentifier()&&e.sourceContext.collectionPath.isReferencedIdentifier()&&i(e.sourceContext.collectionPath),e.sourceContext.collectionPath.traverse({ReferencedIdentifier(s){s.isIdentifier()&&i(s)}}),o?{ok:!1,reason:o}:r.size>0?{ok:!1,reason:`Cannot move prop-backed repeat child because the collection depends on bindings outside the target scope: ${[...r].sort().join(", ")}`}:n.size===0?{ok:!1,reason:"Cannot move repeat-backed child out of its component without an explicit prop mapping"}:{ok:!0,collectionExpression:MO(e.source,t,[...n.values()])}}function wO(e,t){if(t.length===0)return e;let n=Hb(e);if(!n)return null;let r=vc(n)?`(${e})`:e;for(let o of t){if(o.kind==="property"){r=OO(o.name)?`${r}.${o.name}`:`${r}[${JSON.stringify(o.name)}]`;continue}r=`${r}[${o.index}]`}return r}function OO(e){return/^[$A-Z_a-z][$\w]*$/.test(e)}function FO(e,t,n){let r=LO(e,n),o=r?{kind:"member-expression",expression:e.node.name,base:e.node.name,path:[{kind:"property",name:r.propertyName}]}:{kind:"identifier",expression:e.node.name,base:e.node.name,path:[]},i=$o(t,o);if(!i)return null;let s=r?.range??Me(e.node);return s?{propName:i.propName,remainingPath:i.remainingPath,hasDefault:i.hasDefault,range:s}:null}function LO(e,t){let n=e.parentPath;if(!n||!n.isMemberExpression()&&!n.isOptionalMemberExpression()||n.node.object!==e.node||!Fn(n.node,t)||n.node.computed||!Oe.isIdentifier(n.node.property))return null;let r=Me(n.node);return r?{propertyName:n.node.property.name,range:r}:null}function DO(e,t,n){let r=e.get("openingElement").get("attributes");if(r.some(c=>c.isJSXSpreadAttribute()))return{ok:!1,reason:"Cannot move prop-backed repeat child through spread props; use an explicit prop mapping"};let o=r.find(c=>c.isJSXAttribute()&&Oe.isJSXIdentifier(c.node.name)&&c.node.name.name===t);if(!o?.isJSXAttribute())return{ok:!1,reason:`Cannot move prop-backed repeat child because prop '${t}' is not passed explicitly`};let i=o.get("value");if(!i.isJSXExpressionContainer())return{ok:!1,reason:`Cannot move prop-backed repeat child because prop '${t}' is not an expression`};let s=i.get("expression");if(!s.isExpression())return{ok:!1,reason:`Cannot move prop-backed repeat child because prop '${t}' is not a usable expression`};let a=Xo(n,s.node);return a?{ok:!0,expression:a,expressionPath:s}:{ok:!1,reason:`Cannot move prop-backed repeat child because prop '${t}' cannot be read`}}function MO(e,t,n){let r=e.slice(t.start,t.end),o=[...n].sort((i,s)=>s.start-i.start);for(let i of o)r=r.slice(0,i.start-t.start)+i.text+r.slice(i.end-t.start);return r}function Hb(e){try{let n=zb.parse(`const __VD_EXPR__ = (${e});`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0],r=Oe.isVariableDeclaration(n)?n.declarations[0]?.init:null;return r&&Oe.isExpression(r)?r:null}catch{return null}}function BO(e){let t=Me(e.sourceContext.collectionPath.node);if(!t)return{ok:!1,reason:"Cannot move cross-file repeat child because the collection expression cannot be inspected"};let n=new Map,r=new Set,o=i=>{let s=i.scope.getBinding(i.node.name);if(!s||Fn(s.path.node,t))return;let a=jb(s,e.sourceFile,e.targetFile);if(a){let c=e.targetParentPath.scope.getBinding(a.localName);if(c){let u=jb(c,e.targetFile,e.targetFile);(!u||u.moduleFile!==a.moduleFile||!jO(u.importSpec,a.importSpec))&&r.add(a.localName);return}let l=n.get(a.moduleSpecifier)??[];l.some(u=>JSON.stringify(u)===JSON.stringify(a.importSpec))||l.push(a.importSpec),n.set(a.moduleSpecifier,l);return}r.add(i.node.name)};return us(e.sourceContext.collectionPath,o),r.size>0?{ok:!1,reason:`Cannot move cross-file repeat child because the collection depends on non-importable bindings: ${[...r].sort().join(", ")}`}:{ok:!0,imports:[...n.entries()].map(([i,s])=>({moduleSpecifier:i,imports:s}))}}function jO(e,t){return e.kind!==t.kind?!1:e.kind==="named"&&t.kind==="named"?e.imported===t.imported&&e.local===t.local:e.kind==="default"&&t.kind==="default"||e.kind==="namespace"&&t.kind==="namespace"?e.local===t.local:!1}function jb(e,t,n){let r=$O(e),o=r?.parentPath;if(!r||!o?.isImportDeclaration())return null;let i=o.node.source.value;if(typeof i!="string")return null;let s=ao(t,i),a=i.startsWith(".")?Ff(n,s):i;if(r.isImportDefaultSpecifier()){let c=r.node.local.name;return{localName:c,moduleFile:s,moduleSpecifier:a,importSpec:{kind:"default",local:c}}}if(r.isImportNamespaceSpecifier()){let c=r.node.local.name;return{localName:c,moduleFile:s,moduleSpecifier:a,importSpec:{kind:"namespace",local:c}}}if(r.isImportSpecifier()){let c=Oe.isIdentifier(r.node.imported)?r.node.imported.name:r.node.imported.value,l=r.node.local.name;return{localName:l,moduleFile:s,moduleSpecifier:a,importSpec:{kind:"named",imported:c,local:l===c?void 0:l}}}return null}function $O(e){let t=e.path;for(;t&&!t.isImportDeclaration();){if(t.isImportSpecifier()||t.isImportDefaultSpecifier()||t.isImportNamespaceSpecifier())return t;t=t.parentPath}return null}function $b(e,t,n,r){let o=xf(t,n);if(o.length===0)return{sourceJsx:r,conditionPaths:[]};let i=r,s=[];for(let a of o){let c=Xo(e,a.conditionPath.node);if(!c)return{sourceJsx:r,conditionPaths:[]};let l=VO(a.conditionPath,c);if(s.push(a.conditionPath),a.kind==="logical"){i=`${l} ${a.operator} ${KO(i)}`;continue}i=a.branch==="consequent"?`${l} ? ${i} : null`:`${l} ? null : ${i}`}return{sourceJsx:i,conditionPaths:s}}function VO(e,t){return UO(e.node)?t:`(${t})`}function UO(e){return Oe.isIdentifier(e)||Oe.isThisExpression(e)||Oe.isSuper(e)||Oe.isMemberExpression(e)||Oe.isOptionalMemberExpression(e)||Oe.isCallExpression(e)||Oe.isOptionalCallExpression(e)||Oe.isBooleanLiteral(e)||Oe.isNumericLiteral(e)||Oe.isStringLiteral(e)||Oe.isNullLiteral(e)||Oe.isUnaryExpression(e)}function KO(e){return e.trim().startsWith("<")?e:`(${e})`}var JO={table:new Set(["caption","colgroup","thead","tbody","tfoot","tr"]),thead:new Set(["tr"]),tbody:new Set(["tr"]),tfoot:new Set(["tr"]),tr:new Set(["th","td"]),ul:new Set(["li"]),ol:new Set(["li"]),select:new Set(["option","optgroup"]),optgroup:new Set(["option"])};function Cc(e,t){if(t.kind!=="native-tag")return null;let n=e.tag?.toLowerCase();if(!n||n!==e.tag||n.startsWith("component:"))return null;let r=JO[n];if(!r)return null;let o=t.tag.toLowerCase();return r.has(o)?null:`Cannot insert <${t.tag}> into <${e.tag}>; expected ${[...r].map(i=>`<${i}>`).join(", ")}`}function XO(e,t){for(let n of e.program.body){if(!Oe.isImportDeclaration(n)||n.source.value!==t)continue;let r=n.specifiers.find(o=>Oe.isImportDefaultSpecifier(o));if(r&&Oe.isImportDefaultSpecifier(r))return r.local.name}return null}function zO(e,t,n){for(let r of e.program.body){if(!Oe.isImportDeclaration(r)||r.source.value!==t)continue;let o=r.specifiers.find(i=>Oe.isImportSpecifier(i)&&(Oe.isIdentifier(i.imported)?i.imported.name:i.imported.value)===n);if(o&&Oe.isImportSpecifier(o))return o.local.name}return null}function Vb(e){let t=new Set;return Sn(e,{Program(n){for(let r of Object.keys(n.scope.bindings))t.add(r);n.stop()}}),t}function Ub(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n+=1;return`${e}${n}`}function HO(e,t){if(!e.component)return{localName:"Component"};let n=e.component,r=Df(e),o=yt(t);if(n.exportName!=="default"){let a=o?zO(o,n.source,n.exportName):null;if(a)return{localName:a};let c=o?Ub(r,Vb(o)):r;return{localName:c,importStep:wf(e,c)}}if(!o)return{localName:r,importStep:wf(e,r)};let i=XO(o,n.source);if(i)return{localName:i};let s=Ub(r,Vb(o));return{localName:s,importStep:wf(e,s)}}function WO(e,t){if(e.kind==="native-tag")return e.text?`<${e.tag}>${e.text}</${e.tag}>`:`<${e.tag} />`;let n=t??Df(e);if(e.props&&Object.keys(e.props).length>0){let r=Object.entries(e.props).map(([o,i])=>typeof i=="string"?`${o}="${i}"`:`${o}={${JSON.stringify(i)}}`).join(" ");return`<${n} ${r} />`}return`<${n} />`}function GO(e){if(e.kind==="native-tag")return e.text===void 0?{kind:e.kind,tag:e.tag}:{kind:e.kind,tag:e.tag,text:e.text};if(!e.component)return{kind:e.kind};let t=e.props?YO(e.props):void 0;return{kind:e.kind,component:{source:e.component.source,exportName:e.component.exportName},...t?{props:t}:{}}}function YO(e){return Object.fromEntries(Object.entries(e).filter(t=>Lf(t[1])))}function Lf(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(Lf):typeof e=="object"?Object.values(e).every(Lf):!1}function wf(e,t=Df(e)){if(!e.component)throw new Error("Materialized component calls do not have a component import");return{moduleSpecifier:e.component.source,imports:e.component.exportName==="default"?[{kind:"default",local:t}]:[{kind:"named",imported:e.component.exportName,...t!==e.component.exportName?{local:t}:{}}]}}function Kb(e,t){if("kind"in e)return{parentNode:null,anchorNode:null,placement:e.relation};if(e.relation==="prepend"||e.relation==="append"){let o=t.getNode(e.parentKey);return{parentNode:o,anchorNode:null,placement:e.relation,...o?{}:{error:{errorCode:"locator-miss",reason:`Target parent '${e.parentKey}' not found in graph`}}}}if(!("anchorKey"in e))return{parentNode:null,anchorNode:null,placement:e.relation,error:{errorCode:"invalid-target",reason:`Sibling target '${e.relation}' requires an anchor`}};let n=t.getNode(e.anchorKey),r=t.getNode(e.parentKey);return n?r?n.parentKey!==r.key?{parentNode:r,anchorNode:n,placement:e.relation,error:{errorCode:"invalid-target",reason:`Target anchor '${n.key}' belongs to parent '${n.parentKey??"<root>"}', expected '${r.key}'`}}:{parentNode:r,anchorNode:n,placement:e.relation}:{parentNode:null,anchorNode:n,placement:e.relation,error:{errorCode:"locator-miss",reason:`Target parent '${e.parentKey}' not found in graph`}}:{parentNode:r,anchorNode:null,placement:e.relation,error:{errorCode:"locator-miss",reason:`Target anchor '${e.anchorKey}' not found in graph`}}}function ZO(e,t,n){let r=e;for(;r;){if(r===t)return!0;r=n.getNode(r)?.parentKey}return!1}function Wo(e,t){return`Operation kind '${e}' does not match params.kind '${t}'`}function Mf(e,t=e.path){return{kind:"value",root:e.root,path:t&&t.length>0?t:void 0,expectedRange:e.expectedRange}}function fs(e){let t=e.path??[];for(let n=t.length-1;n>=0;n-=1){let r=t[n];if(r.kind==="index")return{locator:Mf(e,t.slice(0,n)),index:r.index}}return null}function Of(e,t){return e.locator?e.collectionPathMap?.[t]?Mf(e.locator,e.collectionPathMap[t]):fs(e.locator)?QO(e.locator,eF(t,e.collectionIndexMap)):null:null}function qO(e,t){let n=e.path??[],r=n.findLastIndex(i=>i.kind==="index");if(r===-1)return;let o=n.slice(r+1);return o.length===0?t:Wb(o,t)}function Wb(e,t){let[n,...r]=e;if(!n)return t;if(n.kind!=="property")return;let o=Wb(r,t);return o===void 0?void 0:{[n.name]:o}}function QO(e,t){let n=e.path??[];for(let r=n.length-1;r>=0;r-=1)if(n[r].kind==="index"){let i=[...n];return i[r]={kind:"index",index:t},Mf(e,i)}return null}function eF(e,t){return t?.[e]??e}function Jb(e,t){return!t||t.length===0?e:e<=0?t[0]??0:e>=t.length?(t[t.length-1]??t.length-1)+1:t[e]??e}function tF(e,t){return nF(e.root,t.root)&&oF(e.path??[],t.path??[])}function nF(e,t){if(e.kind!==t.kind)return!1;switch(e.kind){case"binding":case"hook-state":case"named-export":return"name"in t&&e.name===t.name;case"default-export":return!0;case"expression":return"sourceRange"in t&&rF(e.sourceRange,t.sourceRange)}}function rF(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function oF(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],o=t[n];if(r.kind!==o.kind)return!1;if(r.kind==="property"){if(o.kind!=="property"||r.name!==o.name)return!1;continue}if(o.kind!=="index"||r.index!==o.index)return!1}return!0}var Nc=class{constructor(t){this.operationCounter=0,this.graph=t}async plan(t){let n=`op-${++this.operationCounter}-${Date.now()}`;switch(t.kind){case"update-text":{if(t.params.kind!=="update-text")return{ok:!1,errorCode:"unknown",reason:Wo(t.kind,t.params.kind)};let r=t,o=this.resolveNodeRequest(t);if(!o.ok)return o.result;let i=o.node,s=this.graph.getFileVersion(i.file);return t.documentVersion!==s?{ok:!1,errorCode:"stale-version",reason:`Document version ${t.documentVersion} is stale or otherwise does not match current version (current: ${s})`}:this.planUpdateText(n,r,i,this.graph.getCapability(i.key),await this.graph.getTextWriteTarget(i.key,r.params.segmentIndex))}case"update-array-item":{if(t.params.kind!=="update-array-item")return{ok:!1,errorCode:"unknown",reason:Wo(t.kind,t.params.kind)};let r=t,o=this.resolveNodeRequest(t);if(!o.ok)return o.result;let i=o.node,s=this.graph.getFileVersion(i.file);return t.documentVersion!==s?{ok:!1,errorCode:"stale-version",reason:`Document version ${t.documentVersion} is stale or otherwise does not match current version (current: ${s})`}:this.planUpdateArrayItem(n,r,this.graph.getCapability(i.key),await this.graph.getTextWriteTarget(i.key,r.params.segmentIndex))}case"remove-node":{if(t.params.kind!=="remove-node")return{ok:!1,errorCode:"unknown",reason:Wo(t.kind,t.params.kind)};let r=t,o=this.resolveNodeRequest(t);if(!o.ok)return o.result;let i=o.node,s=this.graph.getFileVersion(i.file);return t.documentVersion!==s?{ok:!1,errorCode:"stale-version",reason:`Document version ${t.documentVersion} is stale or otherwise does not match current version (current: ${s})`}:this.planRemoveNode(n,r,i,this.graph.getCapability(i.key))}case"insert-child":{if(t.params.kind!=="insert-child")return{ok:!1,errorCode:"unknown",reason:Wo(t.kind,t.params.kind)};let r=t;if(Rc(r.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page-block boundaries require the page-block resolver"};if(!_c(r.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};let o=Kb(r.params.position,this.graph);if(o.error)return{ok:!1,errorCode:o.error.errorCode,reason:o.error.reason};if(!o.parentNode)return{ok:!1,errorCode:"locator-miss",reason:`Insert target parent for request '${t.id}' not found in graph`};let i=this.graph.getFileVersion(o.parentNode.file);return t.documentVersion!==i?{ok:!1,errorCode:"stale-version",reason:`Document version ${t.documentVersion} is stale or otherwise does not match current version (current: ${i})`}:this.planInsertChild(n,r,o.parentNode,this.graph.getCapability(o.parentNode.key),o.anchorNode)}case"move-node":{if(t.params.kind!=="move-node")return{ok:!1,errorCode:"unknown",reason:Wo(t.kind,t.params.kind)};let r=t,o=this.resolveNodeRequest(t);if(!o.ok)return o.result;let i=o.node,s=this.graph.getFileVersion(i.file);return t.documentVersion!==s?{ok:!1,errorCode:"stale-version",reason:`Document version ${t.documentVersion} is stale or otherwise does not match current version (current: ${s})`}:this.planMoveNode(n,r,i,this.graph.getCapability(i.key))}case"set-class-name-source":{let r=this.resolveNodeRequest(t);if(!r.ok)return r.result;let o=this.graph.getFileVersion(r.node.file);return t.documentVersion!==o?{ok:!1,errorCode:"stale-version",reason:`Document version ${t.documentVersion} is stale or otherwise does not match current version (current: ${o})`}:this.planNodeAttributeOperation(n,t,r.node)}case"set-props":{let r=this.resolveNodeRequest(t);if(!r.ok)return r.result;let o=this.graph.getFileVersion(r.node.file);return t.documentVersion!==o?{ok:!1,errorCode:"stale-version",reason:`Document version ${t.documentVersion} is stale or otherwise does not match current version (current: ${o})`}:await this.planSetProps(n,t,r.node)}case"set-link-target":{if(t.params.kind!=="set-link-target")return{ok:!1,errorCode:"invalid-params",reason:Wo(t.kind,t.params.kind)};let r=this.resolveNodeRequest(t);if(!r.ok)return r.result;let o=this.graph.getFileVersion(r.node.file);return t.documentVersion!==o?{ok:!1,errorCode:"stale-version",reason:`Document version ${t.documentVersion} is stale or otherwise does not match current version (current: ${o})`}:this.planSetLinkTarget(n,t,r.node)}case"apply-style-draft":{let r=this.resolveNodeRequest(t);if(!r.ok)return r.result;let o=this.graph.getFileVersion(r.node.file);return t.documentVersion!==o?{ok:!1,errorCode:"stale-version",reason:`Document version ${t.documentVersion} is stale or otherwise does not match current version (current: ${o})`}:await this.planApplyStyleDraft(n,t,r.node)}default:return{ok:!1,errorCode:"unknown",reason:`Unknown operation kind: ${t.kind}`}}}resolveNodeRequest(t){let n=CO(t);if(!n)return{ok:!1,result:{ok:!1,errorCode:"invalid-target",reason:`Operation '${t.kind}' requires a node target`}};let r=this.graph.getNode(n);return r?{ok:!0,node:r}:{ok:!1,result:{ok:!1,errorCode:"locator-miss",reason:`Target key '${n}' not found in graph`}}}planNodeAttributeOperation(t,n,r){let o=r.file,i=this.graph.getCapability(r.key);return n.params.filePath!==o?{ok:!1,errorCode:"stale-version",reason:"The className source file changed before save."}:this.buildPlan(t,n,[{order:0,file:o,type:"set-class-name-source",request:{...n.params,key:r.key}}],i)}async planSetProps(t,n,r){let o=this.graph.getCapability(r.key),i=await this.buildTypedPropertySteps({node:r,scope:n.params.scope,changes:n.params.changes,selectionRef:n.selectionRef});return i.ok?this.buildPlan(t,n,i.steps,o):Xb(i)}async planSetLinkTarget(t,n,r){if(r.tag!=="a"&&!(r.importedFrom==="next/link"&&r.exportName==="default"))return{ok:!1,errorCode:"capability-denied",reason:"Only native anchors and source-verified next/link nodes can be changed"};if(r.structuralPath.includes("#repeat:")||r.isRepeatRegion||r.isRepeatItemRoot)return{ok:!1,errorCode:"capability-denied",reason:"Link target changes are not supported inside repeat templates"};if(n.selectionRef?.instanceIndex!==void 0||(n.selectionRef?.instanceCount??1)>1)return{ok:!1,errorCode:"capability-denied",reason:"Link target changes require a single non-repeated selection"};if(n.params.changes.length>0){let o=await this.buildTypedPropertySteps({node:r,scope:"selection",changes:n.params.changes,selectionRef:n.selectionRef});if(!o.ok)return Xb(o);if(o.steps.some(i=>i.type!=="set-property-changes"||i.file!==r.file))return{ok:!1,errorCode:"capability-denied",reason:"Link descriptions must have a direct, unique source in the selected file"}}return this.buildPlan(t,n,[{type:"set-link-target",order:0,file:r.file,locator:Ve(r),link:n.params.link,changes:n.params.changes}],this.graph.getCapability(r.key))}async planApplyStyleDraft(t,n,r){let o=r.file,i=this.graph.getCapability(r.key),s=[];if(n.params.className){if(n.params.className.filePath!==o)return{ok:!1,errorCode:"stale-version",reason:"The className source file changed before save."};s.push({order:s.length,file:o,type:"set-class-name-source",request:{kind:"set-class-name-source",...n.params.className,key:r.key}})}if(n.params.props){let a=await this.buildStyleDraftPropertySteps({initialOrder:s.length,node:r,props:n.params.props,selectionRef:n.selectionRef});if(!a.ok)return a;s.push(...a.steps)}return this.buildPlan(t,n,s,i)}async buildTypedPropertySteps(t){let n=this.graph.getPropertyState;return n?Nb({node:t.node,scope:t.scope,changes:t.changes,selectionRef:t.selectionRef,getPropertyState:n,getRepeatPropertyTarget:this.graph.getRepeatPropertyTarget,getFileContent:r=>this.graph.getFileContent(r),getFileVersion:r=>this.graph.getFileVersion(r),classNameSource:this.graph.getClassNameSource?.(t.node.key)??void 0}):{ok:!1,errorCode:"missing-property-state",reason:"Typed property planning requires authoritative property provenance"}}async buildStyleDraftPropertySteps(t){let{initialOrder:n,node:r,props:o,selectionRef:i}=t,s=[],a=[];for(let[c,l]of Object.entries(o)){if(l===void 0)continue;let u=await this.graph.getElementPropertyWriteTarget?.(r.key,c),d=r.attributes?.find(g=>g.name===c);if((await this.graph.getPropertyState?.(r.key,c,i))?.status==="blocked"||!u&&d?.source)return{ok:!1,errorCode:"capability-denied",reason:`apply-style-draft cannot overwrite a derived or unresolved property '${c}'`};if(!(typeof d?.resolvedValue=="string"&&d.resolvedValue===l||d?.source===null&&d.value===l)){if(u?.kind==="external-entry")return{ok:!1,errorCode:"capability-denied",reason:`apply-style-draft cannot overwrite readonly external property '${c}'`};if(u?.kind==="value-binding"&&u.locator){let g=u.locator;if(u.sourceKind==="repeat-template"&&typeof i?.instanceIndex=="number"){let p=Of(u,i.instanceIndex);if(!p)return{ok:!1,errorCode:"invalid-params",reason:"apply-style-draft could not resolve the selected repeat item"};g=p}s.push({order:n+s.length,file:u.file,type:"update-value",locator:g,value:l});continue}a.push({operation:"set",name:c,value:l})}}return a.length>0&&s.push({order:n+s.length,file:r.file,type:"set-property-changes",locator:Ve(r),scope:"selection",changes:a}),{ok:!0,steps:s}}buildTextRewriteSteps(t,n,r,o,i){if(o?.kind==="value-binding"&&o.locator){if(o.sourceKind==="repeat-template"&&typeof i?.instanceIndex=="number"){let a=Of(o,i.instanceIndex);if(!a)return{ok:!1,errorCode:"invalid-params",reason:"update-text could not resolve the selected repeat item"};let c=this.coerceTextValueForValueTarget(o.file,a,r);return c.ok?{ok:!0,steps:[{order:0,file:o.file,type:"update-array-item",locator:a,value:c.value}]}:c}let s=this.coerceTextValueForValueTarget(o.file,o.locator,r);return s.ok?{ok:!0,steps:[{order:0,file:o.file,type:"update-value",locator:o.locator,value:s.value}]}:s}return{ok:!0,steps:o?.kind==="external-entry"?[{order:0,file:`external:${o.sourceId}`,type:"invoke-external-adapter",sourceType:o.sourceType,sourceId:o.sourceId,adapterId:o.adapterId,capability:"write-text",value:r}]:[{order:0,file:t.file,type:"update-text",locator:Ve(t),segmentIndex:n,newText:r}]}}coerceTextValueForValueTarget(t,n,r,o="update-text"){let i=this.graph.getFileContent(t),s=yt(i);if(!s)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not inspect the value source`};let a=Ie(s,n);if(!a.ok)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not resolve the value source`};if(!NO(a.match.path))return{ok:!0,value:r};let c=PO(r);return c===null?{ok:!1,errorCode:"invalid-params",reason:`${o} value must be a valid number for numeric source`}:{ok:!0,value:c}}planUpdateArrayItem(t,n,r,o){if(!r.canUpdateText)return{ok:!1,errorCode:"capability-denied",reason:"Cannot update repeated text on this node"};if(o?.kind!=="value-binding"||o.sourceKind!=="repeat-template"||!o.locator)return{ok:!1,errorCode:"invalid-params",reason:"update-array-item requires a writable repeat-template source"};let{index:i,value:s}=n.params,a=o.collectionPathMap?.length??o.collectionIndexMap?.length;if(a!==void 0&&i>=a)return{ok:!1,errorCode:"invalid-params",reason:`update-array-item index ${i} is outside the repeated source`};let c=Of(o,i);if(!c)return{ok:!1,errorCode:"invalid-params",reason:"update-array-item could not resolve the selected repeat item"};let l=this.coerceTextValueForValueTarget(o.file,c,s,"update-array-item");return l.ok?this.isValueTargetUnchanged(o.file,c,l.value)?{ok:!1,errorCode:"invalid-params",reason:"update-array-item value is unchanged"}:this.buildPlan(t,n,[{order:0,file:o.file,type:"update-array-item",locator:c,value:l.value}],r):l}isValueTargetUnchanged(t,n,r){let o=yt(this.graph.getFileContent(t));if(!o)return!1;let i=Ie(o,n);if(!i.ok)return!1;let s=i.match.path;if(s.isStringLiteral())return typeof r=="string"&&s.node.value===r;if(s.isNumericLiteral())return typeof r=="number"&&Object.is(s.node.value,r);if(s.isBooleanLiteral())return typeof r=="boolean"&&s.node.value===r;if(s.isNullLiteral())return r===null;if(s.isUnaryExpression({operator:"-"})){let a=s.get("argument");return typeof r=="number"&&!Array.isArray(a)&&a.isNumericLiteral()&&Object.is(-a.node.value,r)}return!1}planUpdateText(t,n,r,o,i){let s=this.graph.getTextProvenance?.(r.key,n.params.segmentIndex);if(s&&(s.editMode==="readonly"||s.editMode==="unsupported"))return{ok:!1,errorCode:"unsupported-operation",reason:"Text has no identity-preserving write target"};if(!o.canUpdateText)return{ok:!1,errorCode:"capability-denied",reason:"Cannot update text on this node"};let a=this.buildTextRewriteSteps(r,n.params.segmentIndex,n.params.value,i,n.selectionRef);return a.ok?this.buildPlan(t,n,a.steps,o):a}async planRemoveNode(t,n,r,o){if(!o.canRemove)return{ok:!1,errorCode:"capability-denied",reason:"Cannot remove this node"};let i=await this.graph.getTextWriteTarget(r.key,0);if(i?.kind==="external-entry")return this.buildPlan(t,n,[{order:0,file:`external:${i.sourceId}`,type:"invoke-external-adapter",sourceType:i.sourceType,sourceId:i.sourceId,adapterId:i.adapterId,capability:"remove-node",value:{operation:"remove-node"}}],o);if(r.isRepeatItemRoot){let d=i;if(d?.kind==="value-binding"&&d.locator){let f=fs(d.locator);if(f)return this.buildPlan(t,n,[{order:0,file:d.file,type:"remove-bound-array-item",locator:f.locator,index:f.index}],o)}return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed node removal requires a writable array target"}}let s=ds(r,i,this.graph.getTextProvenance?.(r.key,0)??null);if(s)return{ok:!1,errorCode:"unsupported-operation",reason:s};let a=this.getRepeatBackedTemplateStructureReason(r);if(a)return{ok:!1,errorCode:"unsupported-operation",reason:a};let c=await this.getUpstreamBackedDescendantReason(r);if(c)return{ok:!1,errorCode:"unsupported-operation",reason:c};let l=[{order:0,file:r.file,type:"remove-node",locator:Ve(r),removeWhitespace:!0}],u=this.buildRemoveComponentImportStep(r);return u&&l.push({...u,order:l.length}),this.buildPlan(t,n,l,o)}buildRemoveComponentImportStep(t,n=this.graph.getFileContent(t.file)){if(!t.importedFrom||!t.exportName||!t.tag||Sb(n,t)>1)return null;let r=Ff(t.file,t.importedFrom);return{order:0,file:t.file,type:"remove-import",moduleSpecifier:r,imports:t.exportName==="default"?[{kind:"default"}]:[{kind:"named",imported:t.exportName}]}}async planInsertChild(t,n,r,o,i){if(!_c(n.params.position))return Rc(n.params.position)?{ok:!1,errorCode:"unsupported-operation",reason:"Page-block boundaries require the page-block resolver"}:{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};if(n.params.node.kind==="component-call"&&!n.params.node.component)return{ok:!1,errorCode:"unsupported-operation",reason:"Materialized component insertion requires the materialization transaction planner"};if(!o.canInsertChild)return{ok:!1,errorCode:"capability-denied",reason:"Cannot insert child into this node"};let s=this.graph.getEditableTextSegmentIndex(r.key),a=s!==null?await this.graph.getTextWriteTarget(r.key,s):null,c=ds(r,a,s!==null?this.graph.getTextProvenance?.(r.key,s)??null:null);if(c)return{ok:!1,errorCode:"unsupported-operation",reason:c};let l=await this.getUpstreamBackedDescendantReason(r);if(l)return{ok:!1,errorCode:"unsupported-operation",reason:l};let u=await this.planExternalBackedInsertChild(t,n,r,o,i,a);if(u)return u;let d=await this.planRepeatBackedInsertChild(t,n,r,o);if(d)return d;let f=this.getRepeatBackedTemplateStructureReason(r);if(f)return{ok:!1,errorCode:"unsupported-operation",reason:f};let g=nb(this.graph.getFileContent(r.file),r);if(!g.allowed)return{ok:!1,errorCode:"unsupported-operation",reason:g.reason??"Cannot insert child into this node"};let p=Cc(r,n.params.node);if(p)return{ok:!1,errorCode:"unsupported-operation",reason:p};let m=[],y=0,x=n.params.node.kind==="component-call"?HO(n.params.node,this.graph.getFileContent(r.file)):void 0,S=x?.importStep;return S&&m.push({order:y++,file:r.file,type:"add-import",moduleSpecifier:S.moduleSpecifier,imports:S.imports}),m.push({order:y++,file:r.file,type:"insert-child",parentLocator:Ve(r),node:{jsx:WO(n.params.node,x?.localName)},placement:n.params.position.relation,anchorLocator:i?Ve(i):void 0}),this.buildPlan(t,n,m,o)}async planExternalBackedInsertChild(t,n,r,o,i,s){if(!_c(n.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};let a=s?.kind==="external-entry"?s:await this.findExternalInsertContext(r,i);if(!a)return null;let c=i?await this.graph.getTextWriteTarget(i.key,0):null;return this.buildPlan(t,n,[{order:0,file:`external:${a.sourceId}`,type:"invoke-external-adapter",sourceType:a.sourceType,sourceId:a.sourceId,adapterId:a.adapterId,capability:"insert-child",value:{operation:"insert-child",relation:n.params.position.relation,parentKey:r.key,anchorSourceId:c?.kind==="external-entry"?c.sourceId:null,node:GO(n.params.node)}}],o)}async findExternalInsertContext(t,n){if(n){let o=await this.graph.getTextWriteTarget(n.key,0);if(o?.kind==="external-entry")return o}if(!this.graph.getChildNodes)return null;let r=[...this.graph.getChildNodes(t.key)];for(;r.length>0;){let o=r.shift();if(!o)continue;let i=await this.graph.getTextWriteTarget(o.key,0);if(i?.kind==="external-entry")return i;let s=this.graph.getTextProvenance?.(o.key,0)?.finalSource?.externalSource;if(s)return{kind:"external-entry",file:`external:${s.sourceId}`,sourceType:s.sourceType,sourceId:s.sourceId,adapterId:s.adapterId,displayExpression:s.sourceId};r.push(...this.graph.getChildNodes(o.key))}return null}async planRepeatBackedInsertChild(t,n,r,o){if(!_c(n.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};if(n.params.position.relation!=="append"&&n.params.position.relation!=="prepend")return null;let i=n.params.node;if(i.kind!=="native-tag"||i.text===void 0||!this.graph.getChildNodes)return null;let s=this.graph.getChildNodes(r.key).find(d=>d.isRepeatItemRoot&&d.tag?.toLowerCase()===i.tag.toLowerCase());if(!s)return null;let a=await this.graph.getTextWriteTarget(s.key,0);if(!a||a.kind!=="value-binding"||!a.locator)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child requires a writable value target"};let c=fs(a.locator);if(!c)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child requires an array-backed target"};let l=qO(a.locator,i.text);if(l===void 0)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child could not infer an item shape from the template"};let u=n.params.position.relation==="prepend"?Jb(0,a.collectionIndexMap):Jb(a.collectionIndexMap?.length??c.index+1,a.collectionIndexMap);return this.buildPlan(t,n,[{order:0,file:a.file,type:"insert-bound-array-item",locator:c.locator,index:u,value:l}],o)}async getUpstreamBackedDescendantReason(t){if(!this.graph.getChildNodes)return null;let n=[...this.graph.getChildNodes(t.key)];for(;n.length>0;){let r=n.shift();if(!r)continue;let o=this.graph.getEditableTextSegmentIndex(r.key),i=o!==null?await this.graph.getTextWriteTarget(r.key,o):null,s=ds(r,i,o!==null?this.graph.getTextProvenance?.(r.key,o)??null:null);if(s)return s;n.push(...this.graph.getChildNodes(r.key))}return null}getRepeatBackedTemplateStructureReason(t){if(t.isRepeatItemRoot)return zo(this.graph.getFileContent(t.file),t)?"Cannot edit repeat-backed item template structure with a generic node operation":"Cannot edit repeat-backed child node structure with a generic node operation";if(t.structuralPath.includes("#repeat:")||wb(this.graph.getFileContent(t.file),t))return"Cannot edit repeat-backed child node structure with a generic node operation";let n=t.parentKey;for(;n;){let r=this.graph.getNode(n);if(!r)return null;if(r.isRepeatItemRoot||r.isRepeatRegion)return"Cannot edit repeat-backed child node structure with a generic node operation";n=r.parentKey}return null}planRepeatTemplateInternalMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&zo(this.graph.getFileContent(r.file),r)||r.file!==o.file)return null;let c=this.graph.getFileContent(r.file),l=yt(c);if(!l)return null;let u=dn(l,r),d=dn(l,o);if(!u||!d)return null;let f=Dn(c,u),g=Dn(c,d);if(!ls(f,g))return null;if(a&&(s==="before"||s==="after")){let m=dn(l,a),y=m?Dn(c,m):null;if(!ls(f,y))return null}if(Sc(u,d))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child across statement-level conditional branches"};let p=kf(c,r,o);return p.ok?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:Ve(r),targetParentLocator:Ve(o),placement:s,anchorLocator:a?Ve(a):void 0,selectionContext:uo(o)}],i):{ok:!1,errorCode:"unsupported-operation",reason:p.reason??`Cannot move node because it depends on bindings outside the target scope: ${p.bindingNames.join(", ")}`}}planRepeatTemplateHoistMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&zo(this.graph.getFileContent(r.file),r)||r.file!==o.file)return null;let c=this.graph.getFileContent(r.file),l=yt(c);if(!l)return null;let u=dn(l,r),d=dn(l,o);if(!u||!d)return null;let f=Dn(c,u);if(!f)return null;let g=Dn(c,d);if(ls(f,g))return null;if(g&&!Ab(g,f))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child into a different repeat template"};if(a&&(s==="before"||s==="after")){let b=If(c,l,a);if(g&&!ls(g,b)||!g&&b)return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child relative to a repeat-template anchor outside the target scope"}}if(r.tag&&r.tag.toLowerCase()===r.tag){let b=Cc(o,{kind:"native-tag",tag:r.tag});if(b)return{ok:!1,errorCode:"unsupported-operation",reason:b}}let p=Af(this.graph,r);if(!p)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(Sc(u,d))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let m=$b(c,u,d,p);for(let b of m.conditionPaths){let E=Rf(b,d,f);if(!E.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its condition depends on bindings outside the target scope: ${E.bindingNames.join(", ")}`}}let y=Cf(u,d,f,{preserveConditionalBoundary:m.conditionPaths.length>0});if(!y.ok)return{ok:!1,errorCode:"unsupported-operation",reason:y.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${y.bindingNames.join(", ")}`};let x=Lb(f,d);if(!x.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its callback parameters depend on bindings outside the target scope: ${x.bindingNames.join(", ")}`};let S=f;if(r.component!==o.component){let b=AO({source:c,ast:l,sourceContext:f,sourceNode:r,targetParent:o,targetParentPath:d});if(!b.ok)return{ok:!1,errorCode:"unsupported-operation",reason:b.reason};S=b.context}else{let b=Nf(f.collectionPath,d);if(!b.ok)return{ok:!1,errorCode:"unsupported-operation",reason:b.reason??`Cannot move repeat-backed child because the repeat collection is not visible at the target: ${b.bindingNames.join(", ")}`}}return this.buildPlan(t,n,[{order:0,file:r.file,type:"move-repeat-template-child",locator:Ve(r),targetParentLocator:Ve(o),placement:s,anchorLocator:a?Ve(a):void 0,repeatExpression:Pf(S,m.sourceJsx),selectionContext:uo(o)}],i)}planCrossFileRepeatTemplateHoistMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&zo(this.graph.getFileContent(r.file),r)||r.file===o.file)return null;let c=this.graph.getFileContent(r.file),l=this.graph.getFileContent(o.file),u=yt(c),d=yt(l);if(!u||!d)return null;let f=kb({knownSourceFiles:this.graph.getKnownSourceFiles?.(),routeEntryFiles:this.graph.getRouteEntryFiles?.(),sourceAst:u,sourceFile:r.file,targetFile:o.file,sourceComponent:r.component,targetComponent:o.component});if(!f.ok)return{ok:!1,errorCode:"unsupported-operation",reason:f.reason};let g=dn(u,r),p=dn(d,o);if(!g||!p)return null;let m=_f(f.callSitePath,p);if(!m.ok)return{ok:!1,errorCode:"unsupported-operation",reason:m.reason};let y=Dn(c,g);if(!y)return null;if(Dn(l,p))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child into a different repeat template"};if(a&&(s==="before"||s==="after")&&If(l,d,a))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child relative to a repeat-template anchor outside the target scope"};if(r.tag&&r.tag.toLowerCase()===r.tag){let A=Cc(o,{kind:"native-tag",tag:r.tag});if(A)return{ok:!1,errorCode:"unsupported-operation",reason:A}}let S=Af(this.graph,r);if(!S)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(Sc(g,p))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let b=$b(c,g,p,S);for(let A of b.conditionPaths){let w=Rf(A,p,y);if(!w.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its condition depends on bindings outside the target scope: ${w.bindingNames.join(", ")}`}}let E=Cf(g,p,y,{preserveConditionalBoundary:b.conditionPaths.length>0});if(!E.ok)return{ok:!1,errorCode:"unsupported-operation",reason:E.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${E.bindingNames.join(", ")}`};let k=BO({sourceFile:r.file,targetFile:o.file,sourceContext:y,targetParentPath:p});if(!k.ok)return{ok:!1,errorCode:"unsupported-operation",reason:k.reason};let I=Db(y);if(!I.ok)return{ok:!1,errorCode:"unsupported-operation",reason:I.reason};let v=Mb(y,I.callbackParams),N=[{order:0,file:r.file,type:"remove-node",locator:Ve(r),removeWhitespace:!0}];for(let A of k.imports)N.push({order:N.length,file:o.file,type:"add-import",moduleSpecifier:A.moduleSpecifier,imports:A.imports});return N.push({order:N.length,file:o.file,type:"insert-jsx-expression-child",parentLocator:Ve(o),expression:Pf(v,b.sourceJsx),placement:s,anchorLocator:a?Ve(a):void 0,selectionContext:uo(o)}),this.buildPlan(t,n,N,i)}async planMoveNode(t,n,r,o){if(!o.canMove)return{ok:!1,errorCode:"capability-denied",reason:"Cannot move this node"};if(Rc(n.params.target))return{ok:!1,errorCode:"unsupported-operation",reason:"Page-block boundaries require the page-block resolver"};if("kind"in n.params.target&&n.params.target.kind==="source-sibling"){let b=n.params.target,E=this.graph.getNode(b.anchorKey);if(!E||r.file!==E.file||r.component!==E.component)return{ok:!1,errorCode:"locator-miss",reason:"Source sibling move requires a sibling in the same component file"};let k=this.graph.getFileVersion(r.file);if(n.documentVersion!==k)return{ok:!1,errorCode:"stale-version",reason:`Document version ${n.documentVersion} is stale or otherwise does not match source sibling file version (current: ${k})`};let I=this.graph.getFileContent(r.file),v=yt(I),N=v?dn(v,r):null,A=v?dn(v,E):null,w=N?.parentPath,F=A?.parentPath;if(!N||!A||!w||!F||w.node!==F.node||!w.isJSXFragment()&&!(w.isJSXElement()&&Ye(w)))return{ok:!1,errorCode:"unsupported-operation",reason:"Source sibling move requires two direct children of the same transparent Fragment"};let B=w.node.loc;return B?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:Ve(r),targetParentLocator:{kind:"jsx-node",strategy:"source-range",sourceRange:{startLine:B.start.line,startColumn:B.start.column,endLine:B.end.line,endColumn:B.end.column}},placement:b.relation,anchorLocator:Ve(E),selectionContext:uo(r)}],o):{ok:!1,errorCode:"locator-miss",reason:"Source Fragment has no stable source range"}}let i=Kb(n.params.target,this.graph);if(i.error)return{ok:!1,errorCode:i.error.errorCode,reason:i.error.reason};let s=i.parentNode;if(!s)return{ok:!1,errorCode:"locator-miss",reason:`Target parent for request '${n.id}' not found in graph`};let a=this.graph.getFileVersion(s.file);if(n.documentVersion!==a)return{ok:!1,errorCode:"stale-version",reason:`Document version ${n.documentVersion} is stale or otherwise does not match target parent version (current: ${a})`};if(ZO(s.key,r.key,this.graph))return{ok:!1,errorCode:"capability-denied",reason:"Cannot move node into its own subtree"};if(r.isRepeatRegion&&s.isBoundary)return{ok:!1,errorCode:"capability-denied",reason:"Cannot move repeat-region node across boundary"};if(!this.graph.getCapability(s.key).canInsertChild)return{ok:!1,errorCode:"capability-denied",reason:"Cannot move node into this parent"};let c=await this.graph.getTextWriteTarget(r.key,0);if(c?.kind==="external-entry"){let b=n.params.target.relation,E=i.anchorNode&&(b==="before"||b==="after")?await this.graph.getTextWriteTarget(i.anchorNode.key,0):null;return this.buildPlan(t,n,[{order:0,file:`external:${c.sourceId}`,type:"invoke-external-adapter",sourceType:c.sourceType,sourceId:c.sourceId,adapterId:c.adapterId,capability:"move-node",value:{operation:"move-node",relation:b,anchorSourceId:E?.kind==="external-entry"?E.sourceId:null,parentKey:"parentKey"in n.params.target?n.params.target.parentKey:null}}],o)}let l=r.file!==s.file,u=n.params.target.relation,d=i.anchorNode,f=this.graph.getTextProvenance?.(r.key,0)??null,g=ds(r,c,f);if(g&&!Tf(g)&&!Bb(r,s,c,f))return{ok:!1,errorCode:"unsupported-operation",reason:g};if(r.isRepeatItemRoot&&d?.isRepeatItemRoot&&r.repeatOwnerKey&&r.repeatOwnerKey===d.repeatOwnerKey&&(u==="before"||u==="after")){let b=c,E=await this.graph.getTextWriteTarget(d.key,0);if(b?.kind==="value-binding"&&E?.kind==="value-binding"&&b.locator&&E.locator){let k=fs(b.locator),I=fs(E.locator);if(k&&I&&b.file===E.file&&tF(k.locator,I.locator)){let v=k.index,N=I.index,A=u==="before"?N-(v<N?1:0):N+(v<N?0:1);return this.buildPlan(t,n,[{order:0,file:b.file,type:"move-array-item",locator:k.locator,fromIndex:v,toIndex:A}],o)}}}if(r.isRepeatItemRoot&&zo(this.graph.getFileContent(r.file),r))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed item outside its collection"};let p=this.getRepeatBackedTemplateStructureReason(r),m=Tf(g)?g:p;if(m&&Tf(m)){let b=this.planRepeatTemplateInternalMove(t,n,r,s,o,u,d);if(b)return b;let E=this.planRepeatTemplateHoistMove(t,n,r,s,o,u,d);if(E)return E;let k=this.planCrossFileRepeatTemplateHoistMove(t,n,r,s,o,u,d);return k||{ok:!1,errorCode:"unsupported-operation",reason:m}}if(p)return{ok:!1,errorCode:"unsupported-operation",reason:p};let y=await this.getUpstreamBackedDescendantReason(r);if(y)return{ok:!1,errorCode:"unsupported-operation",reason:y};if(r.tag&&r.tag.toLowerCase()===r.tag){let b=Cc(s,{kind:"native-tag",tag:r.tag});if(b)return{ok:!1,errorCode:"unsupported-operation",reason:b}}if(l)return this.planCrossFileMove(t,n,r,s,o,u,d);let x=kf(this.graph.getFileContent(r.file),r,s);if(!x.ok)return{ok:!1,errorCode:"unsupported-operation",reason:x.reason??`Cannot move node because it depends on bindings outside the target scope: ${x.bindingNames.join(", ")}`};let S=[{order:0,file:r.file,type:"move-node",locator:Ve(r),targetParentLocator:Ve(s),placement:u,anchorLocator:d?Ve(d):void 0,selectionContext:uo(s)}];return this.buildPlan(t,n,S,o)}planCrossFileMove(t,n,r,o,i,s,a){let c=[],l=0,u=this.graph.getFileContent(r.file),d=Af(this.graph,r)??`<${r.component} />`,f=rb(u,r);if(!f.allowed)return{ok:!1,errorCode:"unsupported-operation",reason:f.reason??"Cannot move subtree across files"};if(c.push({order:l++,file:r.file,type:"remove-node",locator:Ve(r),removeWhitespace:!0}),r.importedFrom&&r.exportName){let p=r.tag??r.component,y={moduleSpecifier:Ff(o.file,r.importedFrom),imports:r.exportName==="default"?[{kind:"default",local:p}]:[{kind:"named",imported:r.exportName,local:p===r.exportName?void 0:p}]};c.push({order:l++,file:o.file,type:"add-import",moduleSpecifier:y.moduleSpecifier,imports:y.imports}),c.push({order:l++,file:o.file,type:"insert-child",parentLocator:Ve(o),node:{jsx:d},placement:s,anchorLocator:a?Ve(a):void 0,selectionContext:uo(o)})}else c.push({order:l++,file:o.file,type:"insert-child",parentLocator:Ve(o),node:{jsx:d},placement:s,anchorLocator:a?Ve(a):void 0,selectionContext:uo(o)});let g=this.buildRemoveComponentImportStep(r,u);return g&&c.push({...g,order:l++}),this.buildPlan(t,n,c,i)}buildPlan(t,n,r,o){let s=[...new Set(r.map(a=>a.file))].map(a=>({file:a,content:this.graph.getFileContent(a),version:this.graph.getFileVersion(a),exists:!0,sha256:ke(this.graph.getFileContent(a))}));return{ok:!0,plan:{operationId:t,kind:n.kind,target:n.target,documentVersion:n.documentVersion,steps:r,preSnapshots:s,validatedCapability:o}}}};function Xb(e){return{ok:!1,errorCode:e.errorCode==="readonly-property"?"capability-denied":e.errorCode==="missing-property-state"||e.errorCode==="repeat-target-failed"||e.errorCode==="unsupported-binding"?"unsupported-operation":"invalid-params",reason:e.reason}}import Jf from"@babel/generator";import{parse as xF,parseExpression as bF}from"@babel/parser";import*as C from"@babel/types";import*as Mn from"@babel/types";import Bf from"@babel/generator";import*as Ke from"@babel/types";var iF=typeof Bf=="function"?Bf:Bf.default,sF=/(?:token|secret|key|password|authorization|cookie|signature|credential)/i,aF=/^((?:https?:)?\/\/)[^/@\s]+@/i,cF=/(\/(?:token|secret|api[-_]?key|password|credential|signature)\/)[^/?#]+/gi;function Yb(e,t){let n=Wt(e.callee);if(!n)return null;if(n==="fetch")return jf(e.arguments[0],"GET",t,["fetch call"]);if(n.startsWith("axios.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(Gb(r))return jf(e.arguments[0],r,t,["axios client contract"])}if(n.startsWith("ky.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(Gb(r))return jf(e.arguments[0],r,t,["ky client contract"])}return null}function jf(e,t,n,r){if(!e||Ke.isSpreadElement(e)||Ke.isJSXNamespacedName(e))return fF(t,n,r,"missing url argument");let o=ps(e);return{sourceKind:dF(o),...o?{endpointPattern:o}:{},method:t,confidence:o?"exact":"partial",evidence:[{file:n.file,reason:[...r,o?"endpoint pattern resolved":"endpoint pattern unresolved"].join("; ")}]}}function ps(e){if(Ke.isStringLiteral(e))return fo(e.value);if(Ke.isTemplateLiteral(e))return fo(lF(e));if(Ke.isBinaryExpression(e)&&e.operator==="+"){let t=ps(e.left),n=ps(e.right);return!t&&!n?void 0:fo(`${t??$f(e.left)}${n??$f(e.right)}`)}if(Ke.isMemberExpression(e)){let t=Zb(e);if(t)return`env:${t}`}if(!(Ke.isCallExpression(e)&&Wt(e.callee)==="new URL")){if(Ke.isNewExpression(e)&&Ke.isIdentifier(e.callee,{name:"URL"})){let[t,n]=e.arguments,r=t&&!Ke.isSpreadElement(t)?ps(t):void 0,o=n&&!Ke.isSpreadElement(n)?ps(n):void 0;return o&&r?fo(`${o} + ${r}`):r??o}if(Ke.isIdentifier(e))return`:${e.name}`}}function lF(e){let t="";for(let n=0;n<e.quasis.length;n+=1){t+=e.quasis[n]?.value.cooked??e.quasis[n]?.value.raw??"";let r=e.expressions[n];r&&(t+=$f(r))}return t}function $f(e){if(Ke.isIdentifier(e))return`:${e.name}`;if(Ke.isMemberExpression(e)){let t=Zb(e);if(t)return`env:${t}`}return`:${uF(e)}`}function uF(e){return iF(e,{comments:!1}).code.replace(/[^a-zA-Z0-9_$]+/g,"_").replace(/^_+|_+$/g,"")||"param"}function fo(e){let[t]=e.split("#"),[n,r]=t.split("?"),o=n.replace(aF,"$1<redacted>@").replace(cF,"$1<redacted>");if(!r)return o;let i=r.split("&").map(s=>{let[a]=s.split("=");return a?sF.test(a)?`${a}=<redacted>`:`${a}=:${a}`:""}).filter(Boolean).join("&");return i?`${o}?${i}`:o}function dF(e){return e?e.startsWith("/api/")?"site-api-route":/^(?:https?:)?\/\//.test(e)||e.startsWith("env:")?"external-api":e.startsWith("/")?"site-api-route":"unknown-api":"unknown-api"}function fF(e,t,n,r){return{sourceKind:"unknown-api",method:e,confidence:"partial",evidence:[{file:t.file,reason:[...n,r].join("; ")}]}}function Gb(e){return["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(e)}function Zb(e){return!Ke.isMemberExpression(e.object)||!Ke.isIdentifier(e.object.object,{name:"process"})||!pF(e.object.property,"env")?null:Ke.isIdentifier(e.property)?e.property.name:Ke.isStringLiteral(e.property)?e.property.value:null}function pF(e,t){return Ke.isIdentifier(e)&&e.name===t}function Wt(e){if(Ke.isIdentifier(e))return e.name;if(Ke.isMemberExpression(e)){let t=Wt(e.object),n=Ke.isIdentifier(e.property)?e.property.name:Ke.isStringLiteral(e.property)?e.property.value:null;if(t&&n)return`${t}.${n}`}return null}var mF=new Set(["list","listStrict","get","getStrict","getByUrl","getByUrlStrict","schema","categories"]),gF=new Set(["getConfig","submit"]);function Ac(e,t){let n=qb(Wt(e.callee),t);if(!n)return null;let r="cms.collections.";if(n.startsWith(r)){let i=n.slice(r.length);if(!mF.has(i))return null;let s=Vf(e,0),a=i==="getByUrl"||i==="getByUrlStrict",c=a?void 0:s,l=a?s??"/:record-url":c?`/collections/${c}`:"/collections/:collection";return{sourceKind:"vcp-cms-collection",sourceType:"cms-field",operation:i,...c?{collection:c}:{},endpointPattern:l,confidence:s?"exact":"partial",evidence:[{file:t.file,symbol:n,reason:"VCP CMS collection facade"}]}}let o="cms.forms.";if(n.startsWith(o)){let i=n.slice(o.length);if(!gF.has(i))return null;let s=Vf(e,0);return{sourceKind:"vcp-cms-form",sourceType:"cms-field",operation:i,...s?{collection:s}:{},endpointPattern:s?`/forms/${s}`:"/forms/:form",confidence:s?"exact":"partial",evidence:[{file:t.file,symbol:n,reason:"VCP CMS form facade"}]}}if(n==="cmsFetch"||n==="cmsFetchResult"||n==="cmsFetchEnvelope"){let i=Vf(e,0)??hF(e,0,"path")??"/cms/:path",s=yF(i);return{sourceKind:"vcp-cms-collection",sourceType:"cms-field",operation:n,...s?{collection:s}:{},endpointPattern:i,confidence:i==="/cms/:path"?"partial":"safe-derived",evidence:[{file:t.file,symbol:n,reason:"VCP CMS fetch helper"}]}}return null}function qb(e,t){if(!e)return null;let n=e.indexOf("."),r=n<0?e:e.slice(0,n),o=n<0?"":e.slice(n),i=t.imports?.get(r);return i?i.importedName==="cms"&&/^(?:src\/)?lib\/cms(?:\/index)?\.[cm]?[jt]s$/.test(i.source)?`cms${o}`:i.importedName==="collections"&&/^(?:src\/)?lib\/cms\/collections\.[cm]?[jt]s$/.test(i.source)?`cms.collections${o}`:!o&&["cmsFetch","cmsFetchResult","cmsFetchEnvelope"].includes(i.importedName)&&/^(?:src\/)?lib\/cms\/client\.[cm]?[jt]s$/.test(i.source)?i.importedName:null:null}function Qb(e,t){let n=Wt(e);return n==="cms.settings"?{sourceKind:"vcp-cms-settings",sourceType:"cms-field",operation:"settings",endpointPattern:"/settings",confidence:"exact",evidence:[{file:t.file,symbol:n,reason:"VCP CMS settings facade"}]}:n==="cms.navigation"?{sourceKind:"vcp-cms-navigation",sourceType:"cms-field",operation:"navigation",endpointPattern:"/navigation",confidence:"exact",evidence:[{file:t.file,symbol:n,reason:"VCP CMS navigation facade"}]}:null}function Tc(e,t){let n=Wt(e.callee),r=t?qb(n,t):n;return typeof r=="string"&&r.startsWith("cms.field.")}function Vf(e,t){let n=e.arguments[t];return Mn.isStringLiteral(n)?n.value:null}function hF(e,t,n){let r=e.arguments[t];if(!Mn.isObjectExpression(r))return null;for(let o of r.properties)if(Mn.isObjectProperty(o)&&!o.computed&&(Mn.isIdentifier(o.key)&&o.key.name===n||Mn.isStringLiteral(o.key)&&o.key.value===n)&&Mn.isStringLiteral(o.value))return o.value.value;return null}function yF(e){let t=/^\/collections\/([^/]+)(?:\/|$)/.exec(e)?.[1];return t&&/^[a-z0-9][a-z0-9_-]*$/i.test(t)?t:null}import*as dt from"@babel/types";var Uf=new WeakMap;function Nr(e,t){let n=Uf.get(e)?.get(t);if(n!==void 0)return n;let r=new Set([t]),o=l=>{let u=l;for(;dt.isMemberExpression(u)||dt.isOptionalMemberExpression(u);)u=u.object;return dt.isIdentifier(u)?u.name:null},i=!0;for(;i;)i=!1,dt.traverseFast(e,l=>{if(!dt.isVariableDeclarator(l)||!l.init)return;let u=o(l.init);if(!(!u||!r.has(u)))for(let d of Object.keys(dt.getBindingIdentifiers(l.id)))r.has(d)||(r.add(d),i=!0)});let s=l=>{let u=o(l);return u?r.has(u):Object.keys(dt.getBindingIdentifiers(l)).some(d=>r.has(d))},a=!1;dt.traverseFast(e,l=>{(dt.isAssignmentExpression(l)&&s(l.left)||dt.isUpdateExpression(l)&&s(l.argument)||dt.isUnaryExpression(l,{operator:"delete"})&&s(l.argument))&&(a=!0)});let c=Uf.get(e)??new Map;return c.set(t,a),Uf.set(e,c),a}function eE(e=4096){if(!Number.isSafeInteger(e)||e<1)throw new RangeError("Re-export relation capacity must be positive.");let t=new Map,n=new Set,r=o=>{let i=t.get(o.fromFile),s=i?.get(o.exportName),a=s?.get(o.targetFile);a?.get(o.maxImportDepth)===o&&(a.delete(o.maxImportDepth),a.size===0&&s.delete(o.targetFile),s.size===0&&i.delete(o.exportName),i.size===0&&t.delete(o.fromFile),n.delete(o))};return{resolve(o,i){let{fromFile:s,exportName:a,targetFile:c,maxImportDepth:l}=o,u=t.get(s)?.get(a)?.get(c)?.get(l);if(u)return u.pending;let d=i();n.size>=e&&r(n.values().next().value);let f={fromFile:s,exportName:a,targetFile:c,maxImportDepth:l,pending:d},g=t.get(s)??new Map,p=g.get(a)??new Map,m=p.get(c)??new Map;return m.set(l,f),p.set(c,m),g.set(a,p),t.set(s,g),n.add(f),d.catch(()=>{r(f)}),d}}}import*as Nt from"@babel/types";import{posix as Kf}from"node:path";function Go(e,t,n=new Set){if(n.has(e))return;let r=new Set(n).add(e);if(Nt.isBooleanLiteral(e))return e.value;if(Nt.isUnaryExpression(e,{operator:"!"})){let l=Go(e.argument,t,r);return l===void 0?void 0:!l}if(Nt.isLogicalExpression(e)){let l=Go(e.left,t,r),u=Go(e.right,t,r);if(e.operator==="&&")return l===!1||u===!1?!1:l===!0?u:void 0;if(e.operator==="||")return l===!0||u===!0?!0:l===!1?u:void 0}if(!Nt.isCallExpression(e)||!Nt.isIdentifier(e.callee))return;let o=t.imports.get(e.callee.name),i=o?.source.startsWith(".")&&t.file?Kf.normalize(Kf.join(Kf.dirname(t.file),o.source)):o?.source;if(o?.importedName==="isProductionBuildPhase"&&/(?:^|\/)lib\/cms\/build-sample(?:\.[jt]s)?$/.test(i??""))return!1;let s=t.functions.get(e.callee.name);if(!s||n.has(s))return;let a=Nt.isExpression(s.body)?s.body:s.body.body.length===1&&Nt.isReturnStatement(s.body.body[0])?s.body.body[0].argument:null;if(!a||!Nt.isExpression(a))return;let c=s.params.flatMap(l=>Nt.isIdentifier(l)?[l.name]:[]);return Go(a,{file:t.file,imports:new Map([...t.imports].filter(([l])=>!c.includes(l))),functions:new Map([...t.functions].filter(([l])=>!c.includes(l)))},r.add(s))}var CH=typeof Jf=="function"?Jf:Jf.default,uE=new WeakMap;function dE(e){let t=new Map;return uE.set(t,new Map([...e].map(n=>[n.file,n]))),t}var EF={maxFunctionDepth:8,maxImportDepth:6},SF=new Set(["src","href","alt","poster","content","title","aria-label"]),tE=new WeakMap;function IF(e,t,n){let r=tE.get(t.fileCache);r||(r=new WeakMap,tE.set(t.fileCache,r));let o=r.get(e);if(!o){o={imported:[],local:new Map};let u=0;for(let d of e.elements.values()){let f={element:d,order:u++};d.importedFrom&&d.exportName&&o.imported.push(f);let g=o.local.get(d.sourceFile);g||(g=new Map,o.local.set(d.sourceFile,g));let p=g.get(d.tag)??[];p.push(f),g.set(d.tag,p)}r.set(e,o)}let i=o.local.get(t.file)?.get(n)??[],s=o.imported,a=[],c=0,l=0;for(;c<s.length||l<i.length;){let u=s[c],d=i[l];u&&(!d||u.order<d.order)?(a.push(u.element),c++):d&&(!u||d.order<u.order)?(a.push(d.element),l++):(a.push(u.element),c++,l++)}return a}async function fE(e){if(!e.element.textSegments.some(s=>s.source||s.value.includes("("))&&!(e.element.attributes??[]).some(s=>(s.source||s.syntaxKind==="expression"&&s.resolution?.status!=="resolved")&&rE(s,e.element))&&!e.graph.regions.some(s=>s.ownerKey===e.element.identity.key&&(s.kind==="repeat-region"||s.kind==="conditional-region")))return{hasDynamicData:!1,bindings:[]};let t=e.fileCache??new Map,n=Yf(e.file,e.source,t),r={file:e.file,analysis:n,readFile:e.readFile,exists:e.exists,fileCache:t,options:{...EF,...e.options},variableCache:new Map,functionDepth:0,importDepth:0,paramSources:new Map,paramArguments:new Map,resolvingVariables:new Set,resolvingComponentProps:new Set,scopeVariables:RE(n,e.element.componentName),scopeFunction:Zf(n,e.element.componentName)};await pE(e.element.componentName,e.graph,r);let o=[];o.push(...await CF(e.element,e.graph,r),...await RF(e.element,e.graph,r));for(let s of e.element.textSegments){let a=await NF(s,e.element,e.graph,r);a&&o.push(jc(a,"text","children"))}for(let s of e.element.attributes??[]){let a=rE(s,e.element);if(!a)continue;let c=await hE(s.source,e.element,e.graph,r);if(!c&&s.syntaxKind==="expression"&&!(s.source&&mo(s.source.base,e.element,e.graph))){let u=n.jsxElementsByRange.get(Vc(e.element.sourceRange))?.openingElement.attributes.find(d=>C.isJSXAttribute(d)&&C.isJSXIdentifier(d.name,{name:s.name}));C.isJSXExpressionContainer(u?.value)&&C.isExpression(u.value.expression)&&!xE(u.value.expression,e.element,e.graph)&&(c=await Ze(u.value.expression,r))}c&&o.push(jc(c,a,s.name))}let i=$F(o).sort(_E);return{hasDynamicData:i.length>0,bindings:i}}async function pE(e,t,n){if(n.importDepth>=n.options.maxImportDepth)return;let r=n.analysis.functions.get(e)??n.analysis.functions.get("default"),o=r?.params[0];if(!r||!o)return;let i=n.analysis.functions.get("default")===r?"default":e,s=[];for(let l of IF(t,n,e)){if(l.sourceFile===n.file&&l.tag===e){s.push(l);continue}!l.importedFrom||!l.exportName||l.importedFrom===n.file&&l.exportName!==i||(l.importedFrom===n.file||await vF(l.importedFrom,l.exportName,n.file,n))&&s.push(l)}if(s.length===0)return;let a=new Map;for(let l of s){let u=`${n.file}#${e}<-${l.identity.key}`;if(!n.resolvingComponentProps.has(u)){n.resolvingComponentProps.add(u);try{let d=await gE(l.sourceFile,n);if(!d)continue;let f=wr(d,n,{importDepth:n.importDepth+1});f.paramSources.clear(),f.scopeVariables=RE(d,l.componentName),f.scopeFunction=Zf(d,l.componentName),f.lexicalContext=void 0,await pE(l.componentName,t,f);let g=await kF(l,t,f);for(let[p,m]of g){if(!m)continue;let y=a.get(p)??[];y.push(m),a.set(p,y)}}finally{n.resolvingComponentProps.delete(u)}}}let c=new Map;for(let[l,u]of a){let d=Gf(u);d.length===1&&c.set(l,d[0])}_F(o,c,n)}var nE=new WeakMap;function vF(e,t,n,r){let o=nE.get(r.fileCache);return o||(o=eE(),nE.set(r.fileCache,o)),o.resolve({fromFile:e,exportName:t,targetFile:n,maxImportDepth:r.options.maxImportDepth},()=>mE(e,t,n,r))}async function mE(e,t,n,r,o=new Set){if(e===n)return!0;if(o.size>=r.options.maxImportDepth||o.has(`${e}#${t}`))return!1;o.add(`${e}#${t}`);let s=(await gE(e,r))?.imports.get(t);if(!s||!nt(s.source))return!1;let a=await Qf(e,s.source,r.exists);return a?a===n?!0:mE(a,s.importedName,n,r,o):!1}async function kF(e,t,n){let r=new Map,o=n.analysis.jsxElementsByRange.get(Vc(e.sourceRange));if(o)for(let s of o.openingElement.attributes)!C.isJSXAttribute(s)||!C.isJSXIdentifier(s.name)||!C.isJSXExpressionContainer(s.value)||!C.isExpression(s.value.expression)||r.set(s.name.name,s.value.expression);let i=new Map;for(let[s,a]of r){let c=e.attributes?.find(d=>d.name===s)?.source??null,u=(c?mo(c.base,e,t):null)?await Uc(c,e,t,n):xE(a,e,t)?null:await Ze(a,n);u&&i.set(s,u)}return i}function Vc(e){return`${e.startLine}:${e.startColumn}:${e.endLine}:${e.endColumn}`}async function gE(e,t){let n=t.fileCache.get(e);if(n)return n;if(!await t.exists(e))return null;let r=await t.readFile(e);return Yf(e,r,t.fileCache)}function _F(e,t,n){if(C.isIdentifier(e)){t.size>0&&n.paramSources.set(e.name,Bc(Object.fromEntries(t),n.file));return}if(C.isObjectPattern(e))for(let r of e.properties){if(!C.isObjectProperty(r)||r.computed||!C.isIdentifier(r.key))continue;let o=t.get(r.key.name);if(!o)continue;let i=C.isAssignmentPattern(r.value)?r.value.left:r.value;C.isIdentifier(i)&&n.paramSources.set(i.name,St(o))}}function rE(e,t){return e.name==="dangerouslySetInnerHTML"?"richtext":SF.has(e.name)?"attribute":t.importedFrom||/^[A-Z]/.test(t.tag)?"component-prop":null}async function CF(e,t,n){let r=[];for(let o of t.regions){if(o.kind!=="repeat-region"||o.ownerKey!==e.identity.key)continue;let i=o.sourceCandidates?.find(a=>a.kind==="repeat-template");if(!i)continue;let s=await Kc(i.collectionSource,n);s&&r.push(jc(Pr(s),"repeat-region",i.collectionExpression))}return r}async function RF(e,t,n){let r=[];for(let o of t.regions){if(o.kind!=="conditional-region"||o.ownerKey!==e.identity.key)continue;let i=o.sourceCandidates?.find(a=>a.kind==="conditional-branch");if(!i)continue;let s=await Kc(i.conditionSource,n);s&&r.push(jc(Pr(s),"conditional-region",i.conditionExpression))}return r}async function NF(e,t,n,r){if(!e.source){let i=r.analysis.jsxElementsByRange.get(Vc(t.sourceRange))?.children.find(s=>C.isJSXExpressionContainer(s)&&s.loc?.start.line===e.sourceRange.startLine&&s.loc.start.column===e.sourceRange.startColumn&&s.loc.end.line===e.sourceRange.endLine&&s.loc.end.column===e.sourceRange.endColumn);return C.isJSXExpressionContainer(i)&&C.isCallExpression(i.expression)&&Tc(i.expression)?yE(i.expression,t,n,r):null}return hE(e.source,t,n,r)}async function hE(e,t,n,r){return e&&mo(e.base,t,n)?Uc(e,t,n,r):Kc(e,r)}async function Uc(e,t,n,r,o){if(!e)return null;let i=mo(e.base,t,n,o);if(!i||i.candidate.itemParamName!==e.base)return null;let s=i.candidate.collectionSource,c=(s?mo(s.base,t,n,i.region):null)?await Uc(s,t,n,r,i.region):s?await Kc(s,r):await PF(i.candidate.collectionExpression,t,n,r,i.region);return c?ms(c,e.path,!0):null}async function PF(e,t,n,r,o){let i;try{i=bF(e,{plugins:["typescript","jsx"]})}catch{return null}return yE(i,t,n,r,o)}async function yE(e,t,n,r,o){let i=wr(r.analysis,r),s=new Set;C.traverseFast(e,a=>{C.isIdentifier(a)&&s.add(a.name)});for(let a of s){let c=mo(a,t,n,o);if(!c)continue;if(c.candidate.itemParamName!==a)return null;let l=await Uc({kind:"identifier",expression:a,base:a,path:[]},t,n,r,o);if(!l)return null;i.paramSources.set(a,l)}return Ze(e,i)}function mo(e,t,n,r){let o=t.identity.key,i=null;for(;o;){for(let s of n.regions){if(s.kind!=="repeat-region"||!s.childKeys.includes(o)||r&&!oE(s.sourceRange,r.sourceRange))continue;let a=s.sourceCandidates?.find(c=>c.kind==="repeat-template"&&(c.itemParamName===e||c.indexParamName===e));a&&(!i||oE(i.region.sourceRange,s.sourceRange))&&(i={candidate:a,region:s})}o=n.elements.get(o)?.parentKey??null}return i}function oE(e,t){let n=e.startLine-t.startLine||e.startColumn-t.startColumn,r=e.endLine-t.endLine||e.endColumn-t.endColumn;return n<=0&&r>=0&&(n<0||r>0)}function xE(e,t,n){let r=!1;return C.traverseFast(e,o=>{!r&&C.isIdentifier(o)&&mo(o.name,t,n)&&(r=!0)}),r}async function Kc(e,t){if(!e)return null;let n=await Hf(e.base,t);return n?ms(n,e.path,!1):null}async function Hf(e,t){let n=t.paramSources.get(e);if(n)return St(n);if(t.variableCache.has(e))return VF(t.variableCache.get(e)??null);let r=Tr(e,t);if(r&&r!==t)return Hf(e,r);if(t.resolvingVariables.has(e))return null;t.resolvingVariables.add(e);let o=await TF(e,t);if(o)return t.variableCache.set(e,St(o)),t.resolvingVariables.delete(e),o;let i=t.scopeVariables?.has(e),s=i?t.scopeVariables.get(e):r?null:t.analysis.variables.get(e);if(s){let c=C.isArrayExpression(s)&&s.elements.length===0?await AF(e,t):await Ze(s,t);return t.variableCache.set(e,c?St(c):null),t.resolvingVariables.delete(e),c}if(i||r)return t.resolvingVariables.delete(e),t.variableCache.set(e,null),null;let a=t.analysis.imports.get(e);if(a&&t.importDepth<t.options.maxImportDepth){let c=await qf(a,t);if(c){let l=wr(c,t,{importDepth:t.importDepth+1}),u=NE(a,c);if(u){let g=(await po(u,[],l)).returnSource;return t.variableCache.set(e,g?St(g):null),t.resolvingVariables.delete(e),g}let d=c.variables.get(a.importedName);if(d){let f=await Ze(d,l);return t.variableCache.set(e,f?St(f):null),t.resolvingVariables.delete(e),f}}}return t.variableCache.set(e,null),t.resolvingVariables.delete(e),null}function Tr(e,t){return t.scopeVariables?.has(e)||t.scopeFunction?.params.some(n=>Ar(n).includes(e))?t:t.lexicalContext?Tr(e,t.lexicalContext):void 0}function wc(e,t,n=new Set){if(C.isIdentifier(e)){let s=Tr(e.name,t);if(s&&s!==t)return wc(e,s,n)}if(n.has(e))return null;if(n.add(e),C.isStringLiteral(e))return e.value;if(!C.isIdentifier(e))return null;let r=Tr(e.name,t),o=t.paramArguments.get(e.name);if(o)return wc(o.expression,o.context,n);let i=t.scopeVariables?.has(e.name)?t.scopeVariables.get(e.name):r?null:t.analysis.variables.get(e.name);return i?wc(i,t,n):null}function Bn(e,t,n=new Set){if(n.has(e))return null;let r=new Set(n).add(e);if(C.isStringLiteral(e))return e.value;if(C.isNumericLiteral(e))return String(e.value);if(C.isIdentifier(e)){if(/token|secret|password|authorization|cookie|credential/i.test(e.name))return":redacted";let o=Tr(e.name,t),i=o??t,s=i.paramArguments.get(e.name),a=i.scopeVariables?.has(e.name)?i.scopeVariables.get(e.name):o?null:i.analysis.variables.get(e.name);return(s?Bn(s.expression,s.context,r):a?Bn(a,i,r):null)??`:${e.name}`}if(C.isBinaryExpression(e,{operator:"+"})){let o=Bn(e.left,t,r),i=Bn(e.right,t,r);return o!==null&&i!==null?o+i:null}if(C.isTemplateLiteral(e)){let o=e.quasis[0]?.value.cooked??"";for(let[i,s]of e.expressions.entries()){if(!C.isExpression(s))return null;o+=(Bn(s,t,r)??":param")+(e.quasis[i+1]?.value.cooked??"")}return o}if(C.isCallExpression(e)&&C.isIdentifier(e.callee)&&["encodeURIComponent","decodeURIComponent"].includes(e.callee.name)&&C.isExpression(e.arguments[0])){let o=Bn(e.arguments[0],t,r);if(o===null||o.startsWith(":"))return o;try{return e.callee.name==="encodeURIComponent"?encodeURIComponent(o):decodeURIComponent(o)}catch{return null}}return C.isTSAsExpression(e)||C.isTSNonNullExpression(e)||C.isParenthesizedExpression(e)?Bn(e.expression,t,r):null}async function AF(e,t){let n=t.scopeFunction;if(!n)return null;let r=[],o=!1,i=0,s=u=>{let d=!1;return C.traverseFast(u,f=>{C.isIdentifier(f,{name:e})&&(d=!0)}),d},a=u=>{let d=u;for(;C.isMemberExpression(d);)d=d.object;return C.isIdentifier(d,{name:e})},c=async(u,d)=>{if(!o){if(C.isFunction(u)){s(u)&&(o=!0);return}if(C.isVariableDeclarator(u)&&(Ar(u.id).includes(e)&&i++,u.init&&s(u.init)&&(o=!0)),(C.isAssignmentExpression(u)||C.isUpdateExpression(u))&&a(C.isAssignmentExpression(u)?u.left:u.argument)){o=!0;return}if(C.isUnaryExpression(u,{operator:"delete"})&&a(u.argument)){o=!0;return}if(C.isCallExpression(u)){if(C.isMemberExpression(u.callee)&&C.isIdentifier(u.callee.object,{name:e})){if(!C.isIdentifier(u.callee.property,{name:"push"})||u.callee.computed||!u.arguments.length){o=!0;return}for(let f of u.arguments){let g=C.isSpreadElement(f)?f.argument:f,p=C.isExpression(g)?await Ze(g,d):null;p?r.push(zf(p)):o=!0}return}if(u.arguments.some(f=>s(f))){o=!0;return}}if(C.isForOfStatement(u)){let f=await Ze(u.right,d),g=wr(d.analysis,d),p=C.isVariableDeclaration(u.left)?u.left.declarations[0]?.id:u.left;f&&p&&Dc(p,zf(f),g),await c(u.body,g);return}for(let f of C.VISITOR_KEYS[u.type]??[]){let g=u[f];for(let p of Array.isArray(g)?g:[g])C.isNode(p)&&await c(p,d)}}};await c(n.body,t);let l=Gf(r);return!o&&i===1&&l.length===1?Pr(l[0]):null}async function TF(e,t){let n=t.analysis.stateSetters.get(e);if(!n)return null;let r=t.analysis.stateSetterCandidates.get(n)??[];for(let o of r){let i=await Ze(o,t);if(i)return i}return null}async function Ze(e,t){if(C.isIdentifier(e))return Hf(e.name,t);if(C.isMemberExpression(e)||C.isOptionalMemberExpression(e)){let n=C.isMemberExpression(e)?Qb(e,{file:t.file}):null;if(n)return vE(n);let r=await wF(e,t);if(!r)return null;let o=jF(e);return ms(r,o,!1)}if(C.isAwaitExpression(e))return C.isExpression(e.argument)?Ze(e.argument,t):null;if((C.isCallExpression(e)||C.isOptionalCallExpression(e))&&(C.isMemberExpression(e.callee)||C.isOptionalMemberExpression(e.callee))&&!e.callee.computed&&C.isIdentifier(e.callee.property)&&["trim","trimStart","trimEnd"].includes(e.callee.property.name)&&e.arguments.length===0&&C.isExpression(e.callee.object))return Zo(await Ze(e.callee.object,t));if(C.isCallExpression(e))return EE(e,t);if(C.isObjectExpression(e)){let n=await IE(e,t);return Object.keys(n).length>0?Bc(n,t.file):null}if(C.isArrayExpression(e)){let n={};for(let[r,o]of e.elements.entries()){if(!C.isExpression(o))continue;let i=await Ze(o,t);i&&(n[String(r)]=i)}return Object.keys(n).length?Bc(n,t.file):null}if(C.isConditionalExpression(e)){let n=await Ze(e.consequent,t),r=await Ze(e.alternate,t);return Zo(aE(n,r))}if(C.isLogicalExpression(e)){let n=await Ze(e.left,t),r=await Ze(e.right,t);return Zo(aE(n,r))}return C.isTSAsExpression(e)||C.isTSSatisfiesExpression(e)||C.isTSNonNullExpression(e)||C.isTypeCastExpression(e)||C.isParenthesizedExpression(e)?Ze(e.expression,t):null}async function wF(e,t){let n=e;for(;C.isMemberExpression(n)||C.isOptionalMemberExpression(n);)n=n.object;return C.isExpression(n)?Ze(n,t):null}async function bE(e,t,n=0){if(n>=t.options.maxFunctionDepth)return null;let r=Tr(e,t);if(r){if(r.scopeFunction&&Nr(r.scopeFunction,e))return null;let s=r.paramArguments.get(e);return s&&C.isIdentifier(s.expression)?bE(s.expression.name,s.context,n+1):null}let o=t.analysis.imports.get(e);if(!o||!["cms","collections","cmsFetch","cmsFetchResult","cmsFetchEnvelope"].includes(o.importedName)||Nr(t.analysis.ast,e))return null;let i=await Qf(t.file,o.source,t.exists);return i?{...o,source:i}:null}async function EE(e,t){let n=e.arguments[0],r=C.isExpression(n)?wc(n,t):null,i=Wt(e.callee)?.split(".")[0],s=i?await bE(i,t):null,a=r!==null&&!C.isStringLiteral(n)?{...e,arguments:[C.stringLiteral(r),...e.arguments.slice(1)]}:e;if(s&&["cmsFetch","cmsFetchResult","cmsFetchEnvelope"].includes(s.importedName)&&C.isObjectExpression(n)){let x=SE(n,"path"),S=x&&Bn(x,t);S?.startsWith("/")&&(a={...e,arguments:[{...n,properties:n.properties.map(b=>C.isObjectProperty(b)&&Qo(b)==="path"?{...b,value:C.stringLiteral(fo(S))}:b)},...e.arguments.slice(1)]})}let c=Ac(a,{file:t.file,imports:i&&s?new Map([[i,s]]):new Map});if(c){if(s&&["cmsFetch","cmsFetchResult","cmsFetchEnvelope"].includes(s.importedName)&&c.endpointPattern==="/content/by-url"&&C.isObjectExpression(n)){let x=iE(n,"query"),S=C.isObjectExpression(x)?iE(x,"path"):null,E=(S&&Bn(S,t))?.match(/^\/([a-z0-9][a-z0-9_-]*)\/[^/?#]+(?:[?#].*)?$/i)?.[1];E&&(c.collection=E,c.evidence.push({file:t.file,reason:"CMS collection namespace from the actual content request path"}))}if(C.isMemberExpression(e.callee)){let x=await Qn(e.callee,t);if(x&&!Oc(x.node))return null;if(x&&Oc(x.node)){let S=await Xf(e,t,{node:x.node,context:x.context});return S&&{...S,...S.sourceKind===c.sourceKind?{operation:c.operation}:{}}}}if((c.operation==="getByUrl"||c.operation==="getByUrlStrict")&&C.isExpression(n)){let x=Bn(n,t);x?.startsWith("/")&&(c.endpointPattern=fo(x))}return vE(c)}if(Wt(e.callee)==="Promise.all"&&C.isArrayExpression(n))return Ze(n,t);if(Tc(e)){if(!Tc(e,{file:t.file,imports:i&&s?new Map([[i,s]]):new Map})||!C.isExpression(e.callee))return null;let x=await Qn(e.callee,t);if(x)return Oc(x.node)?Xf(e,t,{node:x.node,context:x.context}):null;let S=e.arguments[0];if(S&&C.isExpression(S))return Zo(await Ze(S,t))}let l=await OF(e,t);if(l)return l;let u=Yb(e,{file:t.file});if(u)return{sourceKind:u.sourceKind,sourceType:"api-field",endpointPattern:u.endpointPattern,valuePath:u.valuePath,confidence:u.confidence,readonly:!0,evidence:u.evidence};let d=await LF(e,t);if(d)return d;let f=await DF(e,t);if(f)return f;let g=await MF(e,t);if(g)return g;let p=await Xf(e,t);if(p)return p;let m=[];for(let x of e.arguments)if(C.isExpression(x)){let S=await Ze(x,t);S&&m.push(S)}let y=Gf(m);return y.length===1?Zo(y[0]):null}async function OF(e,t){let n=Wt(e.callee);if(n!=="useQuery"&&n!=="useSuspenseQuery"&&n!=="useInfiniteQuery"&&n!=="useSWR")return null;if(n==="useSWR"){let i=FF(e.arguments[0],t.file,"SWR key"),s=e.arguments[1];if(C.isIdentifier(s)){let a=await qo(s.name,t);if(a)return(await po(a.node,i?[i]:[],a.context)).returnSource??i}return i}let r=e.arguments[0];if(!C.isObjectExpression(r))return Fc(t.file,`${n} without static options`);let o=SE(r,"queryFn");if(!o)return Fc(t.file,`${n} without queryFn`);if(C.isIdentifier(o)){let i=await qo(o.name,t);return i?(await po(i.node,[],i.context)).returnSource:Fc(t.file,`${n} queryFn unresolved`)}return C.isArrowFunctionExpression(o)||C.isFunctionExpression(o)?(await po(o,[],t)).returnSource:C.isCallExpression(o)?EE(o,t):null}function SE(e,t){for(let n of e.properties){if(!C.isObjectProperty(n)||!C.isExpression(n.value))continue;if(Qo(n)===t)return n.value}return null}function iE(e,t){let n=new Set;for(let i of e.properties){if(!C.isObjectProperty(i)||i.computed)return null;let s=Qo(i);if(!s||n.has(s))return null;n.add(s)}let r=e.properties.filter(i=>C.isObjectProperty(i)&&Qo(i)===t);if(r.length!==1)return null;let o=r[0];return C.isObjectProperty(o)&&C.isExpression(o.value)?o.value:null}function FF(e,t,n){return C.isStringLiteral(e)?{sourceKind:e.value.startsWith("/api/")?"site-api-route":"external-api",sourceType:"api-field",endpointPattern:e.value,confidence:"exact",readonly:!0,evidence:[{file:t,reason:n}]}:null}async function LF(e,t){if(!C.isMemberExpression(e.callee)||!C.isIdentifier(e.callee.property))return null;let n=e.callee.property.name;if(!["map","filter","slice","sort","toSorted","reverse","toReversed"].includes(n))return null;let r=C.isExpression(e.callee.object)?await Ze(e.callee.object,t):null;if(!r)return null;if(n!=="map")return Pr(r);let o=e.arguments[0];if(C.isIdentifier(o)){let i=await qo(o.name,t);if(!i)return Pr(r);let s=await po(i.node,[r],i.context);return{...Pr(r),...s.objectReturnMap??s.returnSource?.fieldMap?{fieldMap:s.objectReturnMap??s.returnSource.fieldMap}:{}}}if(C.isArrowFunctionExpression(o)||C.isFunctionExpression(o)){let i=await po(o,[r],t);return{...Pr(r),...i.objectReturnMap??i.returnSource?.fieldMap?{fieldMap:i.objectReturnMap??i.returnSource.fieldMap}:{}}}return Pr(r)}async function DF(e,t){return!C.isMemberExpression(e.callee)||!C.isIdentifier(e.callee.property,{name:"json"})||!C.isExpression(e.callee.object)?null:Ze(e.callee.object,t)}async function MF(e,t){return!C.isMemberExpression(e.callee)||!C.isIdentifier(e.callee.property,{name:"then"})||!C.isExpression(e.callee.object)?null:Zo(await Ze(e.callee.object,t))}async function Xf(e,t,n){let r=n;if(!r&&C.isIdentifier(e.callee))r=await qo(e.callee.name,t)??void 0;else if(!r&&C.isMemberExpression(e.callee)){let s=await Qn(e.callee,t);s&&Oc(s.node)&&(r={node:s.node,context:s.context})}if(!r)return null;let o=[];for(let s of e.arguments){if(!C.isExpression(s)){o.push(Fc(t.file,`unsupported argument for ${Wt(e.callee)??"call"}`));continue}let a=await Ze(s,t);o.push(a)}return(await po(r.node,o,r.context,{arguments:e.arguments,context:t})).returnSource}function Oc(e){return C.isFunctionDeclaration(e)||$c(e)||C.isObjectMethod(e)&&e.kind==="method"}async function Qn(e,t,n=new Set){let r={node:null,context:t};if(n.has(e)||n.size>=32)return r;let o=new Set(n).add(e);if(C.isTSAsExpression(e)||C.isTSSatisfiesExpression(e)||C.isTSNonNullExpression(e))return Qn(e.expression,t,o);if(C.isIdentifier(e)){let i=Tr(e.name,t),s=i??t;if(Nr(i?.scopeFunction??t.analysis.ast,e.name))return r;let a=s.paramArguments.get(e.name);if(a)return Qn(a.expression,a.context,o);let c=i?i.scopeVariables?.get(e.name):s.analysis.variables.get(e.name);if(c)return Qn(c,s,o);if(i)return null;let l=s.analysis.functions.get(e.name);if(l)return{node:l,context:s};let u=s.analysis.imports.get(e.name);if(!u||s.importDepth>=s.options.maxImportDepth)return null;let d=await qf(u,s);return d?Qn(C.identifier(u.importedName),wr(d,s,{importDepth:s.importDepth+1}),o):null}if(C.isMemberExpression(e)&&C.isExpression(e.object)){let i=e.computed?C.isStringLiteral(e.property)?e.property.value:null:C.isIdentifier(e.property)?e.property.name:null;if(!i)return null;let s=await Qn(e.object,t,o);if(!s)return null;if(!C.isObjectExpression(s.node))return{node:null,context:s.context};if(s.node.properties.some(l=>C.isSpreadElement(l)||l.computed))return{node:null,context:s.context};let a=s.node.properties.filter(l=>(C.isObjectMethod(l)||C.isObjectProperty(l))&&(C.isIdentifier(l.key)?l.key.name:C.isStringLiteral(l.key)?l.key.value:null)===i);if(a.length===0)return null;if(a.length!==1)return{node:null,context:s.context};let c=a[0];return C.isObjectMethod(c)?c.kind==="method"?{node:c,context:s.context}:null:C.isObjectProperty(c)&&C.isExpression(c.value)?Qn(c.value,s.context,o):null}return{node:e,context:t}}async function qo(e,t,n=new Set){let r=t.paramArguments.get(e);if(r&&!n.has(r.expression)){if(n.add(r.expression),$c(r.expression))return{node:r.expression,context:r.context};if(C.isIdentifier(r.expression))return qo(r.expression.name,r.context,n)}let o=t.analysis.functions.get(e);if(o)return{node:o,context:t};let i=t.analysis.imports.get(e);if(!i||t.importDepth>=t.options.maxImportDepth)return null;let s=await qf(i,t);if(!s)return null;let a=wr(s,t,{importDepth:t.importDepth+1}),c=NE(i,s);return c?{node:c,context:a}:qo(i.importedName,a)}async function po(e,t,n,r){if(n.functionDepth>=n.options.maxFunctionDepth)return{returnSource:null};let o=wr(n.analysis,n,{functionDepth:n.functionDepth+1}),i=n.analysis.functionParents.get(e),s=n;for(;s&&(s.analysis!==n.analysis||s.scopeFunction!==i);)s=s.lexicalContext;o.lexicalContext=s,o.paramSources=new Map,o.paramArguments=new Map,o.scopeVariables=n.analysis.functionVariables.get(e),o.scopeFunction=e,e.params.forEach((d,f)=>{for(let y of Ar(d))o.paramSources.delete(y),o.paramArguments.delete(y);let g=C.isAssignmentPattern(d)?d.left:d,p=r?.arguments[f];C.isIdentifier(g)&&C.isExpression(p)&&r&&o.paramArguments.set(g.name,{expression:p,context:r.context});let m=t[f];m&&Dc(d,zf(m),o)});let a=BF(e,o),c=null,l,u=!1;for(let d of a){let f=wr(n.analysis,o);if(C.isObjectExpression(d)){l={...l??{},...await IE(d,f)},c=c??Bc(l,n.file);continue}let g=await Ze(d,f);if(g){if(!c){c=g;continue}let p=Wf(c,g);if(!p){u=!0,c=null;continue}c=p}}return{returnSource:u?null:c,...l?{objectReturnMap:l}:{}}}function Dc(e,t,n){if(C.isIdentifier(e)){n.paramSources.set(e.name,St(t));return}if(C.isAssignmentPattern(e)){Dc(e.left,t,n);return}if(C.isObjectPattern(e))for(let r of e.properties){if(!C.isObjectProperty(r)||r.computed||!C.isIdentifier(r.key))continue;let o=ms(t,[{kind:"property",name:r.key.name}],!0),i=C.isAssignmentPattern(r.value)?r.value.left:r.value;o&&Dc(i,o,n)}}function BF(e,t){if(C.isArrowFunctionExpression(e)&&C.isExpression(e.body))return[e.body];let n=[],r=e.body;if(!C.isBlockStatement(r))return n;let o=i=>{if(C.isFunction(i)&&i!==e)return;if(C.isReturnStatement(i)){i.argument&&C.isExpression(i.argument)&&n.push(i.argument);return}if(C.isIfStatement(i)){let a=Go(i.test,{file:t.file,imports:new Map([...t.analysis.imports].filter(([c])=>!Tr(c,t))),functions:t.analysis.functions});if(a!==void 0){a?o(i.consequent):i.alternate&&o(i.alternate);return}}let s=C.VISITOR_KEYS[i.type];for(let a of s??[]){let c=i[a];if(Array.isArray(c))for(let l of c)C.isNode(l)&&o(l);else C.isNode(c)&&o(c)}};return o(r),n}async function IE(e,t){let n={};for(let r of e.properties){if(!C.isObjectProperty(r))continue;let o=Qo(r);if(!o||!C.isExpression(r.value))continue;let i=await Ze(r.value,t);i&&(n[o]=i)}return n}function Qo(e){return C.isIdentifier(e.key)&&!e.computed?e.key.name:C.isStringLiteral(e.key)?e.key.value:null}function jF(e){let t=[],n=e;for(;C.isMemberExpression(n)||C.isOptionalMemberExpression(n);){let r=n.property;n.computed?C.isStringLiteral(r)?t.unshift({kind:"property",name:r.value}):C.isNumericLiteral(r)&&t.unshift({kind:"index",index:r.value}):C.isIdentifier(r)&&t.unshift({kind:"property",name:r.name}),n=n.object}return C.isIdentifier(n),t}function ms(e,t,n){if(t.length===0)return St(e);let r=t[0],o=r?.kind==="property"?r.name:r?String(r.index):null;if(e.fieldMap&&o!==null){let s=e.fieldMap[o];return s?ms(s,t.slice(1),n):null}let i=St(e);if(i.sourceType==="cms-field"){let s=t.filter(c=>c.kind==="property").map(c=>c.name);if(s[0]==="data"&&s[1]==="items")return i.valuePath=Yo(i.valuePath,"data.items[]"),i.cmsFieldRoot=!1,i;let a=s[0]==="fields"?0:s[0]==="data"&&s[1]==="fields"?1:-1;return a>=0?(a===1&&(i.valuePath=Yo(i.valuePath,"data")),i.fieldPath=Yo(i.fieldPath,s.slice(a+1).join(".")),i.cmsFieldRoot=!0,i):i.cmsFieldRoot||n||i.fieldMap?(i.fieldPath=Yo(i.fieldPath,s.join(".")),i):(i.valuePath=Yo(i.valuePath,sE(t)),i)}return i.valuePath=Yo(i.valuePath,sE(t)),i}function sE(e){return e.map(t=>t.kind==="property"?t.name:`[${t.index}]`).join(".").replace(/\.\[/g,"[")}function Yo(e,t){return t?e?t.startsWith("[")?`${e}${t}`:`${e}.${t}`:t:e}function vE(e){return{sourceKind:e.sourceKind,sourceType:e.sourceType,operation:e.operation,collection:e.collection,endpointPattern:e.endpointPattern,valuePath:e.valuePath,confidence:e.confidence,readonly:!0,evidence:e.evidence}}function Pr(e){let t=St(e);return t.sourceType==="cms-field"&&!t.valuePath&&(t.valuePath="items[]"),t}function zf(e){let t=St(e);return t.valuePath=void 0,t.sourceType==="cms-field"&&!t.fieldPath&&(t.cmsFieldRoot=!1),t}function Zo(e){return e?{...St(e),confidence:e.confidence==="unknown"?"unknown":"safe-derived",evidence:[...e.evidence,{file:e.evidence[0]?.file??"unknown",reason:"safe derived expression"}]}:null}function aE(e,t){return e?t?Wf(e,t):St(e):t?St(t):null}function Wf(e,t){if(Mc(e)!==Mc(t))return null;let n=CE(e.confidence,t.confidence)<=0?e.confidence:t.confidence;return{...e,confidence:n,evidence:[...e.evidence,...t.evidence]}}function Gf(e){let t=new Map;for(let n of e){let r=Mc(n),o=t.get(r);t.set(r,o?Wf(o,n):St(n))}return[...t.values()]}function Mc(e){let t=e.fieldMap?Object.fromEntries(Object.entries(e.fieldMap).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>[n,Mc(r)])):void 0;return JSON.stringify({sourceKind:e.sourceKind,sourceType:e.sourceType,endpointPattern:e.endpointPattern,operation:e.operation,collection:e.collection,fieldPath:e.fieldPath,valuePath:e.valuePath,cmsFieldRoot:e.cmsFieldRoot,fieldMap:t})}function Bc(e,t){let n=Object.values(e)[0];return{sourceKind:n?.sourceKind??"unknown-api",sourceType:n?.sourceType??"api-field",endpointPattern:n?.endpointPattern,operation:n?.operation,collection:n?.collection,confidence:n?.confidence??"partial",readonly:!0,evidence:n?.evidence??[{file:t,reason:"object return map"}],fieldMap:e}}function Fc(e,t){return{sourceKind:"unknown-api",sourceType:"api-field",confidence:"unknown",readonly:!0,evidence:[{file:e,reason:t}]}}function jc(e,t,n){return{sourceKind:e.sourceKind,sourceType:e.sourceType,...e.endpointPattern?{endpointPattern:e.endpointPattern}:{},...e.operation?{operation:e.operation}:{},...e.collection?{collection:e.collection}:{},...e.fieldPath?{fieldPath:e.fieldPath}:{},...e.valuePath?{valuePath:e.valuePath}:{},targetKind:t,targetName:n,confidence:e.confidence,readonly:!0,evidence:e.evidence.map(r=>({...r}))}}function kE(e){let t=[...e].sort(_E),n=t[0],r=[...new Set(t.flatMap(o=>o.sourceKind==="vcp-cms-collection"&&o.collection?[o.collection]:[]))];return{hasDynamicData:t.length>0,sourceKinds:[...new Set(t.map(o=>o.sourceKind))],...r.length>0?{collections:r}:{},...n?.endpointPattern?{primaryEndpoint:n.endpointPattern}:{},...n?.collection?{primaryCollection:n.collection}:{},...n?.fieldPath?{primaryFieldPath:n.fieldPath}:{}}}function $F(e){let t=new Set,n=[];for(let r of e){let o=JSON.stringify({sourceKind:r.sourceKind,endpointPattern:r.endpointPattern,collection:r.collection,fieldPath:r.fieldPath,valuePath:r.valuePath,targetKind:r.targetKind,targetName:r.targetName});t.has(o)||(t.add(o),n.push(r))}return n}function _E(e,t){return cE(e.targetKind)-cE(t.targetKind)||CE(e.confidence,t.confidence)||lE(e.sourceKind)-lE(t.sourceKind)||e.targetName.localeCompare(t.targetName)}function cE(e){return{"repeat-region":0,"conditional-region":1,text:2,richtext:3,attribute:4,"component-prop":5}[e]}function lE(e){return e.startsWith("vcp-cms-")?0:e==="site-api-route"?1:e==="external-api"?2:3}function CE(e,t){let n={exact:0,"safe-derived":1,partial:2,unknown:3};return n[e]-n[t]}function Yf(e,t,n){let r=n.get(e);if(r?.source===t)return r;let o=uE.get(n)?.get(e),i=o?.source===t?o.ast:xF(t,{sourceType:"module",plugins:["jsx","typescript"]}),s={file:e,source:t,ast:i,variables:new Map,functions:new Map,imports:new Map,stateSetters:new Map,stateSetterCandidates:new Map,jsxElementsByRange:new Map,functionVariables:new WeakMap,functionParents:new WeakMap},a=[],c=[];C.traverse(i,{enter(d){switch(C.isFunction(d)&&(s.functionParents.set(d,a.at(-1)??null),a.push(d)),d.type){case"CallExpression":c.push(d);break;case"JSXElement":{let f=d.loc;if(!f)return;let g=Vc({startLine:f.start.line,startColumn:f.start.column,endLine:f.end.line,endColumn:f.end.column});s.jsxElementsByRange.has(g)||s.jsxElementsByRange.set(g,d);break}case"ImportDeclaration":{let f=d.source.value;for(let g of d.specifiers)C.isImportSpecifier(g)&&C.isIdentifier(g.local)?s.imports.set(g.local.name,{source:f,importedName:C.isIdentifier(g.imported)?g.imported.name:g.imported.value,localName:g.local.name,isDefault:!1}):C.isImportDefaultSpecifier(g)&&s.imports.set(g.local.name,{source:f,importedName:"default",localName:g.local.name,isDefault:!0});break}case"FunctionDeclaration":{d.id?.name&&s.functions.set(d.id.name,d);break}case"VariableDeclarator":{let f=a.at(-1),g=f&&(C.isFunctionDeclaration(f)||C.isFunctionExpression(f)||C.isArrowFunctionExpression(f)||C.isObjectMethod(f))?f:null,p=g?s.functionVariables.get(g)??new Map:s.variables;g&&!s.functionVariables.has(g)&&s.functionVariables.set(g,p);for(let[m,y]of Lc(d.id,C.isExpression(d.init)?d.init:null))p.set(m,y);if(C.isArrayPattern(d.id)&&C.isCallExpression(d.init)&&Wt(d.init.callee)==="useState"){let[m,y]=d.id.elements;C.isIdentifier(m)&&C.isIdentifier(y)&&s.stateSetters.set(m.name,y.name)}C.isIdentifier(d.id)&&$c(d.init)&&s.functions.set(d.id.name,d.init);break}case"ExportNamedDeclaration":{let f=d.declaration,g=d.source?.value;if(g)for(let p of d.specifiers){if(!C.isExportSpecifier(p))continue;let m=C.isIdentifier(p.exported)?p.exported.name:p.exported.value,y=p.local.name;s.imports.set(m,{source:g,importedName:y,localName:m,isDefault:y==="default"})}if(C.isFunctionDeclaration(f)&&f.id?.name&&s.functions.set(f.id.name,f),C.isVariableDeclaration(f))for(let p of f.declarations)C.isIdentifier(p.id)&&$c(p.init)&&s.functions.set(p.id.name,p.init);break}case"ExportDefaultDeclaration":{let f=d.declaration;if((C.isFunctionDeclaration(f)||C.isFunctionExpression(f)||C.isArrowFunctionExpression(f))&&s.functions.set("default",f),C.isIdentifier(f)){let g=s.functions.get(f.name);g&&s.functions.set("default",g)}break}}},exit(d){C.isFunction(d)&&a.pop()}});let l=new Set(s.stateSetters.values()),u=(d,f)=>{let g=s.stateSetterCandidates.get(d)??[];g.push(f),s.stateSetterCandidates.set(d,g)};if(l.size>0)for(let d of c){let f=C.isIdentifier(d.callee)?d.callee.name:null;f&&l.has(f)&&C.isExpression(d.arguments[0])&&u(f,d.arguments[0]);let g=new Set;for(let p of d.arguments)C.isIdentifier(p)&&p.name!==f&&l.has(p.name)&&g.add(p.name);for(let p of g)u(p,d)}return n.set(e,s),s}function Lc(e,t){return C.isIdentifier(e)?[[e.name,t]]:C.isAssignmentPattern(e)?Lc(e.left,t):C.isArrayPattern(e)?e.elements.flatMap((n,r)=>n&&!C.isRestElement(n)?Lc(n,t?C.memberExpression(t,C.numericLiteral(r),!0):null):[]):C.isObjectPattern(e)?e.properties.flatMap(n=>{if(!C.isObjectProperty(n)||n.computed)return[];let r=Qo(n);return r?Lc(n.value,t?C.memberExpression(t,C.stringLiteral(r),!0):null):[]}):[]}function Ar(e){return!e||C.isVoidPattern(e)?[]:C.isIdentifier(e)?[e.name]:C.isObjectPattern(e)?e.properties.flatMap(t=>C.isObjectProperty(t)?Ar(t.value):Ar(t.argument)):C.isArrayPattern(e)?e.elements.flatMap(t=>t?Ar(C.isRestElement(t)?t.argument:t):[]):C.isAssignmentPattern(e)?Ar(e.left):C.isRestElement(e)?Ar(e.argument):[]}function $c(e){return C.isFunctionExpression(e)||C.isArrowFunctionExpression(e)}function RE(e,t){let n=Zf(e,t);return n?e.functionVariables.get(n):void 0}function Zf(e,t){return e.functions.get(t)??e.functions.get("default")}async function qf(e,t){let n=await Qf(t.file,e.source,t.exists);if(!n)return null;let r=await t.readFile(n);return Yf(n,r,t.fileCache)}function NE(e,t){return e.isDefault?t.functions.get("default")??t.functions.get(e.localName)??null:t.functions.get(e.importedName)??null}async function Qf(e,t,n){return nt(t)?Jr(e,t,n):null}function wr(e,t,n={}){return{file:e.file,analysis:e,readFile:t.readFile,exists:t.exists,fileCache:t.fileCache,options:t.options,variableCache:new Map,functionDepth:n.functionDepth??t.functionDepth,importDepth:n.importDepth??t.importDepth,paramSources:new Map(t.paramSources),paramArguments:e===t.analysis?new Map(t.paramArguments):new Map,resolvingVariables:new Set,resolvingComponentProps:t.resolvingComponentProps,scopeVariables:e===t.analysis?t.scopeVariables:void 0,scopeFunction:e===t.analysis?t.scopeFunction:void 0,lexicalContext:e===t.analysis?t.lexicalContext:void 0}}function VF(e){return e?St(e):null}function St(e){return{...e,evidence:e.evidence.map(t=>({...t})),...e.fieldMap?{fieldMap:Object.fromEntries(Object.entries(e.fieldMap).map(([t,n])=>[t,St(n)]))}:{}}}import*as tp from"@babel/parser";import ep from"@babel/traverse";import*as ce from"@babel/types";import{classifySiteEditPropertyName as UF}from"@vcp-dev/contracts";var np=typeof ep=="function"?ep:ep.default;function rp(e){let t=UF(e.propertyName);if(t.owner!=="generic")return Gt("invalid-property",t.diagnostic?.message??`Property '${e.propertyName}' is not a generic property`);let n=e.selectionRef;if(!n)return Gt("missing-selection-ref","A repeat property target requires a complete selection reference");if(n.key!==e.element.identity.key)return Gt("selection-mismatch","Selection reference does not identify the requested element");if(n.instanceIndex===void 0)return Gt("missing-instance-index","A repeat property target requires an instance index");let r;try{r=tp.parse(e.source,{sourceType:"module",plugins:["typescript","jsx"]})}catch(y){return Gt("repeat-not-found",`Unable to parse repeat source: ${y instanceof Error?y.message:String(y)}`)}let o=KF(r,e.element.sourceRange);if(!o)return Gt("repeat-not-found","The selected element is not inside a supported map repeat");if(!ce.isIdentifier(o.callback.params[0]))return Gt("unsupported-callback","Repeat property materialization requires an identifier callback item");let i=JF(r,o.collection,e.file,e.sources);if(!i)return Gt("collection-not-found","The repeat collection is not a visible local static array");let{array:s,locator:a,sourceFile:c}=i,l=[],u=[];for(let[y,x]of s.elements.entries()){if(!x||!ce.isObjectExpression(x)||!FE(x))return Gt("unsafe-collection","Repeat materialization requires an array of local static objects without spreads");let S=[{kind:"index",index:y}];l.push(S),u.push({kind:"value",root:a.root,path:S})}let d=u.length;if(n.instanceCount!==void 0&&n.instanceCount!==d)return Gt("count-mismatch",`Selection reports ${n.instanceCount} instances but the source collection has ${d}`);let f=n.instanceIndex;if(f>=d)return Gt("index-out-of-range",`Selected repeat instance ${f} is outside the source collection`);let g=s.elements[f];if(!g||!ce.isObjectExpression(g))return Gt("unsafe-collection","Selected repeat item is not an object");let p=YF(e.element,e.propertyName),m=WF(g,e.propertyName);return m?{ok:!0,sourceFile:c,templateFile:e.file,collectionLocator:a,parentObjectLocators:u,selectedParentObjectLocator:u[f],sourceItemIndex:f,sourceItemPath:l[f],collectionIndexMap:Array.from({length:d},(y,x)=>x),callbackItemName:o.callback.params[0].name,targetElementLocator:{kind:"jsx-node",strategy:"structural-path",file:e.element.identity.file,component:e.element.identity.component,structuralPath:e.element.identity.structuralPath,expectedRange:e.element.sourceRange},propertyName:e.propertyName,propertyState:m,selectedResolution:GF(g,e.propertyName),...p?{property:p}:{},selectionRef:n}:Gt("unsafe-property-source",`Property '${e.propertyName}' has a dynamic or unsupported source in the repeat item`)}function KF(e,t){let n=[];return np(e,{CallExpression(r){let o=PE(r.node);o&&TE(o.callback,t)&&n.push({...o,span:AE(r.node)})},OptionalCallExpression(r){let o=PE(r.node);o&&TE(o.callback,t)&&n.push({...o,span:AE(r.node)})}}),n.sort((r,o)=>r.span-o.span),n[0]??null}function PE(e){let t=e.callee;if(!ce.isMemberExpression(t)&&!ce.isOptionalMemberExpression(t)||t.computed||!ce.isIdentifier(t.property)||t.property.name!=="map"||!ce.isExpression(t.object))return null;let n=e.arguments[0];return!n||!ce.isExpression(n)||!ce.isArrowFunctionExpression(n)&&!ce.isFunctionExpression(n)?null:{collection:t.object,callback:n}}function JF(e,t,n,r){let o=gs(t);if(o&&ce.isArrayExpression(o))return{array:o,locator:{kind:"value",root:{kind:"expression",sourceRange:DE(o)}},sourceFile:n};if(!ce.isIdentifier(t))return null;let i=[];if(np(e,{VariableDeclarator(s){ce.isIdentifier(s.node.id)&&s.node.id.name===t.name&&s.node.init&&i.push(s.node)}}),i.length===1){let s=gs(i[0].init);return!s||!ce.isArrayExpression(s)?null:{array:s,locator:{kind:"value",root:{kind:"binding",name:t.name}},sourceFile:n}}return XF(e,t.name,n,r)}function XF(e,t,n,r){if(!r)return null;for(let o of e.program.body){if(!ce.isImportDeclaration(o))continue;let i=o.specifiers.find(f=>f.local.name===t);if(!i||!ce.isStringLiteral(o.source)||!ce.isImportSpecifier(i))continue;let s=HF(n,o.source.value,r);if(!s)return null;let a=ce.isIdentifier(i.imported)?i.imported.name:i.imported.value,c=r.get(s);if(c===void 0)return null;let l;try{l=tp.parse(c,{sourceType:"module",plugins:["typescript","jsx"]})}catch{return null}let u=zF(l,a),d=u?gs(u):null;return!d||!ce.isArrayExpression(d)?null:{array:d,locator:{kind:"value",root:{kind:"binding",name:a}},sourceFile:s}}return null}function zF(e,t){let n=null;return np(e,{VariableDeclarator(r){n||!ce.isIdentifier(r.node.id)||r.node.id.name!==t||!r.node.init||!ce.isExpression(r.node.init)||(n=r.node.init)}}),n}function HF(e,t,n){let r=Cn(e,t);return[r,r+".tsx",r+".ts",r+".jsx",r+".js",r+"/index.tsx",r+"/index.ts",r+"/index.jsx",r+"/index.js"].find(i=>n.has(i))??null}function gs(e){return ce.isParenthesizedExpression(e)?gs(e.expression):ce.isTSAsExpression(e)?OE(e.typeAnnotation)?gs(e.expression):null:ce.isTSSatisfiesExpression(e)?null:e}function OE(e){return ce.isTSTypeReference(e)&&ce.isIdentifier(e.typeName)&&e.typeName.name==="const"}function FE(e){return e.properties.every(t=>!ce.isObjectProperty(t)||t.computed||!ce.isExpression(t.value)?!1:Jc(t.value))}function Jc(e){if(ce.isTSAsExpression(e)&&OE(e.typeAnnotation))return Jc(e.expression);if(ce.isTSSatisfiesExpression(e))return!1;if(ce.isArrayExpression(e))return e.elements.every(n=>!n||ce.isSpreadElement(n)||!ce.isExpression(n)?!1:Jc(n));if(ce.isObjectExpression(e))return FE(e);let t=Tn(e);return t.status==="resolved"||t.status==="undefined"}function WF(e,t){let n=e.properties.filter(o=>ce.isObjectProperty(o)&&LE(o.key)===t);if(n.length>1)return null;let r=n[0];return r?ce.isExpression(r.value)?Jc(r.value)?"static":ce.isIdentifier(r.value)||ce.isMemberExpression(r.value)?"binding":null:null:"missing"}function GF(e,t){let n=e.properties.filter(o=>ce.isObjectProperty(o)&&LE(o.key)===t);if(n.length>1)return{status:"unresolved"};let r=n[0];return!r||!ce.isExpression(r.value)?{status:"undefined"}:Tn(r.value)}function YF(e,t){let n=e.attributes?.filter(r=>r.name===t)??[];return n.length===1?n[0]:void 0}function LE(e){return ce.isIdentifier(e)?e.name:ce.isStringLiteral(e)?e.value:ce.isNumericLiteral(e)?String(e.value):null}function DE(e){return{startLine:e.loc?.start.line??0,startColumn:e.loc?.start.column??0,endLine:e.loc?.end.line??0,endColumn:e.loc?.end.column??0}}function AE(e){return e.start==null||e.end==null?Number.MAX_SAFE_INTEGER:e.end-e.start}function TE(e,t){let n=DE(e);return wE(n.startLine,n.startColumn,t.startLine,t.startColumn)<=0&&wE(n.endLine,n.endColumn,t.endLine,t.endColumn)>=0}function wE(e,t,n,r){return e===n?t-r:e-n}function Gt(e,t){return{ok:!1,errorCode:e,reason:t}}import{classifySiteEditPropertyName as FL}from"@vcp-dev/contracts";import*as de from"@babel/types";import Es from"node:path";import*as Z from"@babel/types";import*as UE from"@babel/parser";import op from"@babel/traverse";import*as ye from"@babel/types";function zc(e,t){let n=[],r=e;for(;ye.isMemberExpression(r);){if(r.computed)if(ye.isNumericLiteral(r.property))n.unshift({kind:"index",index:r.property.value});else if(ye.isStringLiteral(r.property))n.unshift({kind:"property",name:r.property.value});else return null;else{if(!ye.isIdentifier(r.property))return null;n.unshift({kind:"property",name:r.property.name})}r=r.object}return!ye.isIdentifier(r)||r.name!==t?null:n}function ME(e){if(ye.isIdentifier(e))return{base:e.name,path:[]};if(!ye.isMemberExpression(e))return null;let t=[],n=e;for(;ye.isMemberExpression(n);){if(n.computed)if(ye.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(ye.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else{if(!ye.isIdentifier(n.property))return null;t.unshift({kind:"property",name:n.property.name})}n=n.object}return ye.isIdentifier(n)?{base:n.name,path:t}:null}function Pt(e,t){let n=e;for(let r of t){if(r.kind==="property"){if(n===null||Array.isArray(n)||typeof n!="object"||!(r.name in n))return;n=n[r.name];continue}if(!Array.isArray(n)||r.index<0||r.index>=n.length)return;n=n[r.index]}return n}var jn=Symbol("not-closed-literal");function Xc(e){switch(e.type){case"StringLiteral":case"NumericLiteral":case"BooleanLiteral":return e.value;case"NullLiteral":return null;case"TemplateLiteral":return e.expressions.length===0&&e.quasis.length===1?e.quasis[0].value.cooked??e.quasis[0].value.raw:jn;case"TSAsExpression":case"TSSatisfiesExpression":case"TSNonNullExpression":return Xc(e.expression);case"ArrayExpression":{let t=[];for(let n of e.elements){if(!n||ye.isSpreadElement(n))return jn;let r=Xc(n);if(r===jn)return jn;t.push(r)}return t}case"ObjectExpression":{let t={};for(let n of e.properties){if(!ye.isObjectProperty(n)||n.computed||n.shorthand||!ye.isExpression(n.value))return jn;let r=ye.isIdentifier(n.key)?n.key.name:ye.isStringLiteral(n.key)?n.key.value:null;if(!r)return jn;let o=Xc(n.value);if(o===jn)return jn;t[r]=o}return t}default:return jn}}function BE(e){let{resolveBindingTarget:t}=e;async function n(i,s,a,c,l,u,d){let f=Xc(i);if(f!==jn)return f;if(!ye.isTemplateLiteral(i)){if(ye.isTSAsExpression(i)||ye.isTSSatisfiesExpression(i)||ye.isTSNonNullExpression(i))return await n(i.expression,s,a,c,l,u,d);if(ye.isIdentifier(i)){let g=s.getBinding(i.name);if(!g)return;let p=await t({currentFile:a,binding:g,readFile:c,exists:l,fileCache:u,visited:d});return p?.kind==="static"?p.value:void 0}if(ye.isArrayExpression(i)){let g=[];for(let p of i.elements){if(!p||ye.isSpreadElement(p))return;let m=await r(p,s,a,c,l,u,d);if(m===void 0)return;g.push(m)}return g}if(ye.isObjectExpression(i)){let g={};for(let p of i.properties){if(!ye.isObjectProperty(p)||p.computed)return;let m=null;if(ye.isIdentifier(p.key)?m=p.key.name:ye.isStringLiteral(p.key)&&(m=p.key.value),!m)return;if(p.shorthand){if(!ye.isIdentifier(p.value))return;let x=await r(p.value,s,a,c,l,u,d);if(x===void 0)return;g[m]=x;continue}if(!ye.isExpression(p.value))return;let y=await r(p.value,s,a,c,l,u,d);y!==void 0&&(g[m]=y)}return g}if(ye.isMemberExpression(i)){let g=await o(i,s,a,c,l,u,d);if(!g)return;let p=s.getBinding(g.base);if(!p)return;let m=await t({currentFile:a,binding:p,readFile:c,exists:l,fileCache:u,visited:d});return!m||m.kind!=="static"?void 0:Pt(m.value,g.path)}}}async function r(i,s,a,c,l,u,d){if(!ye.isSpreadElement(i))return await n(i,s,a,c,l,u,d)}async function o(i,s,a,c,l,u,d){if(ye.isIdentifier(i))return{base:i.name,path:[]};if(!ye.isMemberExpression(i))return null;let f=[],g=i;for(;ye.isMemberExpression(g);){if(g.computed){let p=g.property;if(ye.isNumericLiteral(p))f.unshift({kind:"index",index:p.value});else if(ye.isStringLiteral(p))f.unshift({kind:"property",name:p.value});else{let m=ye.isExpression(p)?await n(p,s,a,c,l,u,d):void 0;if(typeof m=="string")f.unshift({kind:"property",name:m});else if(Number.isInteger(m))f.unshift({kind:"index",index:m});else return null}}else{if(!ye.isIdentifier(g.property))return null;f.unshift({kind:"property",name:g.property.name})}g=g.object}return ye.isIdentifier(g)?{base:g.name,path:f}:null}return{normalizeExpressionWithScope:o,evaluateStaticExpression:n}}var KE=typeof op=="function"?op:op.default,jE=new WeakMap;function JE(e){try{return UE.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function Hc(e,t,n){let r=e.get(t);if(r?.source===n)return r.ast;let o=JE(n);return e.set(t,{source:n,ast:o}),o}function Wc(e,t){return ip(hs(e).expressionRanges,t,!1)}function XE(e,t){return hs(e).exactExpressions.get(zE(t))??null}function Gc(e,t){return ip(hs(e).jsxRanges,t,!0)}function hs(e){let t=jE.get(e);if(t)return t;let n={expressions:[],expressionRanges:[],jsxRanges:[],exactExpressions:new Map};return KE(e,{Expression(r){let o=r;n.expressions.push(o);let i=$E(o,n.expressions.length-1);if(!i)return;n.expressionRanges.push(i);let s=zE(i.range),a=n.exactExpressions.get(s);(!a||i.span<=(a.node.end??0)-(a.node.start??0))&&n.exactExpressions.set(s,o)},JSXElement(r){let o=$E(r,n.jsxRanges.length);o&&n.jsxRanges.push(o)}}),n.expressionRanges.sort(VE),n.jsxRanges.sort(VE),jE.set(e,n),n}function $E(e,t){let n=ys(e.node);return n?{path:e,range:n,traversalIndex:t,span:(e.node.end??0)-(e.node.start??0)}:null}function zE(e){return`${e.startLine}:${e.startColumn}:${e.endLine}:${e.endColumn}`}function VE(e,t){return e.range.startLine-t.range.startLine||e.range.startColumn-t.range.startColumn||e.traversalIndex-t.traversalIndex}function ip(e,t,n,r){let o=0,i=e.length;for(;o<i;){let c=o+Math.floor((i-o)/2),l=e[c].range;l.startLine<t.startLine||l.startLine===t.startLine&&l.startColumn<t.startColumn?o=c+1:i=c}let s=null,a=n?1/0:-1;for(let c=o;c<e.length;c++){let l=e[c],u=l.range;if(u.startLine>t.endLine||u.startLine===t.endLine&&u.startColumn>t.endColumn)break;if(u.endLine>t.endLine||u.endLine===t.endLine&&u.endColumn>t.endColumn||r&&!r(l.path))continue;((n?l.span<a:l.span>a)||l.span===a&&(!s||l.traversalIndex>s.traversalIndex))&&(s=l,a=l.span)}return s?.path??null}function ys(e){return e.loc?{startLine:e.loc.start.line,startColumn:e.loc.start.column,endLine:e.loc.end.line,endColumn:e.loc.end.column}:null}function ei(e,t){if(t)return sp(e,t);let n=ME(e);return n?n.path.reduce((r,o)=>o.kind==="property"?`${r}.${o.name}`:`${r}[${o.index}]`,n.base):""}function sp(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function xs(e,t,n){let r=null,o=Number.POSITIVE_INFINITY;for(let i of hs(e).expressions){if(sp(i.node,t)!==n)continue;let s=(i.node.end??0)-(i.node.start??0);s<=o&&(r=i,o=s)}return r}function HE(e,t,n,r){return ip(hs(e).expressionRanges,r,!0,o=>sp(o.node,t)===n)}function ti(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}function bs(e){let t=null;if(KE(e,{Program(n){t=n.scope,n.stop()}}),!t)throw new Error("Unable to determine program scope");return t}async function In(e,t,n){let r=n.get(e);if(r)return r;let o=await t(e),i=JE(o),s={source:o,ast:i};return n.set(e,s),s}function ZF(e){return Z.isIdentifier(e.callee)&&(e.callee.name==="useState"||e.callee.name==="useReducer")?e.callee.name:Z.isMemberExpression(e.callee)&&Z.isIdentifier(e.callee.property)&&(e.callee.property.name==="useState"||e.callee.property.name==="useReducer")?e.callee.property.name:null}function qF(e){if(!Z.isNewExpression(e)||!Z.isIdentifier(e.callee,{name:"Proxy"})||e.arguments.length!==2||!Z.isIdentifier(e.arguments[0])||!Z.isObjectExpression(e.arguments[1])||e.arguments[1].properties.length!==1)return null;let[t]=e.arguments[1].properties;if(!Z.isObjectMethod(t)||t.kind!=="method"||t.computed||t.async||t.generator||!Z.isIdentifier(t.key,{name:"get"})||t.params.length!==3||!t.params.every(Z.isIdentifier)||t.body.body.length!==2)return null;let[n,r,o]=t.params,[i,s]=t.body.body;if(Z.isIfStatement(i)&&Z.isBlockStatement(i.consequent)&&i.consequent.body.length!==1)return null;let a=Z.isIfStatement(i)?i.test:null,c=a&&Z.isLogicalExpression(a,{operator:"&&"})?a.right:null,l=Z.isIfStatement(i)?Z.isBlockStatement(i.consequent)?i.consequent.body[0]:i.consequent:null,u=Z.isReturnStatement(s)?s.argument:null;return!a||!Z.isLogicalExpression(a,{operator:"&&"})||!Z.isBinaryExpression(a.left,{operator:"==="})||!Z.isUnaryExpression(a.left.left,{operator:"typeof"})||!Z.isIdentifier(a.left.left.argument,{name:r.name})||!Z.isStringLiteral(a.left.right,{value:"string"})||!Z.isUnaryExpression(c,{operator:"!"})||!Z.isBinaryExpression(c.argument,{operator:"in"})||!Z.isIdentifier(c.argument.left,{name:r.name})||!Z.isIdentifier(c.argument.right,{name:n.name})||!Z.isReturnStatement(l)||!Z.isIfStatement(i)||i.alternate||!Z.isCallExpression(u)||!Z.isMemberExpression(u.callee)||!Z.isIdentifier(u.callee.object,{name:"Reflect"})||!Z.isIdentifier(u.callee.property,{name:"get"})||u.arguments.length!==3||!Z.isIdentifier(u.arguments[0],{name:n.name})||!Z.isIdentifier(u.arguments[1],{name:r.name})||!Z.isIdentifier(u.arguments[2],{name:o.name})?null:e.arguments[0].name}function QF(e){let t=e.getFunctionParent();if(!t)return null;if(t.isFunctionDeclaration()){let s=t.node.id?.name;if(!s)return null;let a=t.parentPath?.isExportDefaultDeclaration()?"default":(t.parentPath?.isExportNamedDeclaration(),s);return{componentName:s,exportName:a}}if(!t.isArrowFunctionExpression()&&!t.isFunctionExpression())return null;let n=t.parentPath;if(!n?.isVariableDeclarator()||!Z.isIdentifier(n.node.id))return null;let r=n.node.id.name,o=n.parentPath,i=o?.parentPath?.isExportDefaultDeclaration()?"default":(o?.parentPath?.isExportNamedDeclaration(),r);return{componentName:r,exportName:i}}function WE(e,t){let n=QF(e.path);if(!n)return null;let r=$o(e,t);return r?{...n,...r}:null}function GE(e,t,n,r){return e.importedFrom===t?r?e.exportName===r:!0:e.sourceFile===t&&e.tag===n}function ap(e,t){let n=[{kind:"component-prop",file:t.file,displayName:`${t.componentName}.${t.propName}`,canEditHere:!0}];return e.kind==="external"?{...e,chainPrefix:[...n,...e.chainPrefix??[]],editMode:e.editMode==="readonly"?"readonly":"upstream"}:{...e,chainPrefix:[...n,...e.chainPrefix??[]],editMode:"upstream"}}function cp(e,t){for(let n of e.program.body){if(t==="default"&&Z.isExportDefaultDeclaration(n))return Z.isExpression(n.declaration)?{kind:"default-expression",expression:n.declaration}:(Z.isFunctionDeclaration(n.declaration)||Z.isClassDeclaration(n.declaration))&&n.declaration.id?{kind:"default-binding",name:n.declaration.id.name}:null;if(Z.isExportNamedDeclaration(n)){if(n.declaration){if(Z.isVariableDeclaration(n.declaration)){for(let r of n.declaration.declarations)if(Z.isIdentifier(r.id)&&r.id.name===t)return{kind:"local-binding",name:r.id.name}}if((Z.isFunctionDeclaration(n.declaration)||Z.isClassDeclaration(n.declaration))&&n.declaration.id&&n.declaration.id.name===t)return{kind:"local-binding",name:t}}for(let r of n.specifiers)if((Z.isIdentifier(r.exported)?r.exported.name:r.exported.value)===t&&Z.isExportSpecifier(r))return n.source?{kind:"re-export",name:r.local.name,source:n.source.value}:{kind:"local-binding",name:r.local.name}}}return null}function YE(e){let{resolveExternalExpression:t,resolveCollectionCallTarget:n,evaluateStaticExpression:r,resolveSourceInfoProvenance:o,buildExpressionSourceInfo:i}=e;async function s(m){let{currentFile:y,binding:x,readFile:S,exists:b,fileCache:E,visited:k}=m,I=`${y}::${x.kind}::${x.identifier.name}`;if(k.has(I))return null;k.add(I);try{let v=await a({currentFile:y,binding:x,readFile:S,exists:b,fileCache:E,visited:k});if(v)return v;if(x.path.isImportSpecifier()||x.path.isImportDefaultSpecifier())return await g({currentFile:y,binding:x,readFile:S,exists:b,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,fileCache:E,visited:k});if(x.kind==="param")return null;if(x.path.isVariableDeclarator()){let N=x.path.node.init;if(!N||!Z.isExpression(N))return null;let A=qF(N);if(A&&!x.path.scope.getBinding("Proxy")&&!x.path.scope.getBinding("Reflect")){let B=x.path.scope.getBinding(A),X=B?await s({...m,binding:B}):null;if(X?.kind==="static"&&X.value!==null&&!Array.isArray(X.value)&&typeof X.value=="object")return X}let w=x.path.get("init");if(w&&!Array.isArray(w)&&w.isExpression()){let B=await t({currentFile:y,expressionPath:w,readFile:S,exists:b,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:E,visited:k});if(B)return B;if(w.isCallExpression()){let X=await n({currentFile:y,callPath:w,readFile:S,exists:b,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:E,visited:k});if(X)return X}}let F=await r(N,x.path.scope,y,S,b,E,k);return F===void 0?null:{kind:"static",file:y,root:{kind:"binding",name:x.identifier.name},value:F,sourceKind:"binding"}}if(x.path.isIdentifier()&&x.path.parentPath?.isExportDefaultDeclaration()){let N=x.path.parentPath.node.declaration;if(!Z.isExpression(N))return null;let A=await r(N,x.path.scope,y,S,b,E,k);return A===void 0?null:{kind:"static",file:y,root:{kind:"binding",name:x.identifier.name},value:A,sourceKind:"binding"}}return null}finally{k.delete(I)}}async function a(m){let{currentFile:y,binding:x,readFile:S,exists:b,fileCache:E,visited:k}=m;if(!x.path.isVariableDeclarator()||!x.path.get("id").isArrayPattern())return null;let I=x.path,v=I.node.init;if(!v||!Z.isCallExpression(v))return null;let N=ZF(v);if(!N||!Z.isArrayPattern(I.node.id)||I.node.id.elements.findIndex(X=>Z.isIdentifier(X)&&X.name===x.identifier.name)!==0)return null;let w=N==="useReducer"?1:0,F=v.arguments[w];if(!F||!Z.isExpression(F))return null;let B=await r(F,I.scope,y,S,b,E,k);return B===void 0?null:{kind:"static",file:y,root:{kind:"hook-state",name:x.identifier.name,hook:N},value:B,sourceKind:"binding"}}async function c(m){let y=m.expressionPath.scope.getBinding(m.sourceInfo.base);if(!y||!y.constant||y.kind!=="param"||!m.graph)return null;let x=WE(y,m.sourceInfo);if(!x)return null;let S=[...m.graph.elements.values()].filter(E=>GE(E,m.currentFile,x.componentName,x.exportName));if(!S.length)return null;let b=[];for(let E of S){if(E.sourceFile!==S[0].sourceFile||E.componentName!==S[0].componentName||E.attributeSpreads?.length)return null;let k=await In(E.sourceFile,m.readFile,m.fileCache),I=k.ast?Gc(k.ast,E.sourceRange):null;if(!I)return null;let v=I.parentPath;for(;v&&!v.isFunction();){if(v.isJSXElement()){let $=v.node.openingElement.name;if(!Z.isJSXIdentifier($)||!/^[a-z]/.test($.name))return null}else if(!v.isJSXFragment()&&!v.isReturnStatement()&&!v.isBlockStatement())return null;v=v.parentPath}if(!v)return null;let N=I.get("openingElement").get("attributes").filter($=>$.isJSXAttribute()&&Z.isJSXIdentifier($.node.name,{name:x.propName}));if(N.length!==1)return null;let A=N[0];if(!A?.isJSXAttribute())return null;let w=A.get("value"),F=w.isJSXExpressionContainer()?w.get("expression"):w;if(!F.isExpression())return null;let B=await r(F.node,F.scope,E.sourceFile,m.readFile,m.exists,m.fileCache,m.visited),X=B===void 0?void 0:Pt(B,x.remainingPath);if(X===void 0)return null;b.push(X)}return b}async function l(m){let y=WE(m.binding,m.sourceInfo);if(!y||!m.graph)return null;let x=["component-prop",m.currentFile,m.binding.identifier.start??m.binding.path.node.start??-1,y.componentName,y.propName].join(":");if(m.visited.has(x))return null;m.visited.add(x);try{return await u(m,y,m.graph)}finally{m.visited.delete(x)}}async function u(m,y,x){let S=[...x.elements.values()].filter(A=>GE(A,m.currentFile,y.componentName,y.exportName));if(S.length!==1)return null;let b=S[0],E=b.attributes?.find(A=>A.name===y.propName);if(E&&!E.source){let A=await d({caller:b,propName:y.propName,remainingPath:y.remainingPath,readFile:m.readFile,fileCache:m.fileCache});if(A)return ap(A,{componentName:y.componentName,propName:y.propName,file:b.sourceFile})}if(!E?.source){let A=await f({caller:b,propName:y.propName,remainingPath:y.remainingPath,readFile:m.readFile,exists:m.exists,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:m.fileCache,visited:m.visited});if(A)return ap(A,{componentName:y.componentName,propName:y.propName,file:b.sourceFile});let w=Wx(m.binding,y.componentName,y.propName);if(!w||w.propName!==y.propName)return null;let F=await r(w.expressionPath.node,w.expressionPath.scope,m.currentFile,m.readFile,m.exists,m.fileCache,m.visited);if(F===void 0)return null;let B=y.remainingPath;return B.length>0&&Pt(F,B)===void 0?null:{kind:"value",file:m.currentFile,root:{kind:"binding",name:y.propName},path:B,sourceKind:"binding",semanticKind:"component-prop",displayExpression:w.displayPath,chainPrefix:[{kind:"component-prop",file:m.currentFile,displayName:w.displayPath,canEditHere:!0}],editMode:"upstream",diagnostics:[]}}let k=await In(b.sourceFile,m.readFile,m.fileCache);if(!k.ast)return null;let I=HE(k.ast,k.source,E.source.expression,E.sourceRange)??xs(k.ast,k.source,E.source.expression);if(!I)return null;let v={...E.source,expression:ti(E.source.expression,y.remainingPath),path:[...E.source.path,...y.remainingPath]},N=await o({currentFile:b.sourceFile,expressionPath:I,sourceInfo:v,readFile:m.readFile,exists:m.exists,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:m.fileCache,visited:m.visited});return N?ap(N.kind==="external"?N:{...N,displayExpression:v.expression},{componentName:y.componentName,propName:y.propName,file:b.sourceFile}):null}async function d(m){let y=await In(m.caller.sourceFile,m.readFile,m.fileCache);if(!y.ast)return null;let x=Gc(y.ast,m.caller.sourceRange);if(!x)return null;let S=x.get("openingElement").get("attributes").find(I=>I.isJSXAttribute()&&I.node.name.type==="JSXIdentifier"&&I.node.name.name===m.propName);if(!S?.isJSXAttribute())return null;let b=S.get("value"),E=b.isStringLiteral()?b:b.isJSXExpressionContainer()?b.get("expression"):null;if(!E?.isExpression())return null;let k=ys(E.node);return k?{kind:"value",file:m.caller.sourceFile,root:{kind:"expression",sourceRange:k},path:m.remainingPath,sourceKind:"binding",semanticKind:"component-prop",displayExpression:m.propName,editMode:"upstream",diagnostics:[]}:null}async function f(m){let y=await In(m.caller.sourceFile,m.readFile,m.fileCache);if(!y.ast)return null;let x=Gc(y.ast,m.caller.sourceRange);if(!x)return null;let S=x.get("openingElement");for(let b of S.get("attributes")){if(!b.isJSXSpreadAttribute())continue;let E=b.get("argument");if(!E.isExpression())continue;let k=await i({expression:E.node,scope:E.scope,source:y.source,currentFile:m.caller.sourceFile,readFile:m.readFile,exists:m.exists,fileCache:m.fileCache,visited:m.visited});if(!k)continue;let I=[{kind:"property",name:m.propName},...m.remainingPath],v={...k,expression:ti(k.expression,I),path:[...k.path,...I]},N=await o({currentFile:m.caller.sourceFile,expressionPath:E,sourceInfo:v,readFile:m.readFile,exists:m.exists,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:m.fileCache,visited:m.visited});if(N)return N.kind==="external"?N:{...N,displayExpression:v.expression}}return null}async function g(m){let{currentFile:y,binding:x,readFile:S,exists:b,fileCache:E,visited:k}=m,I=x.path.parentPath;if(!I||!I.isImportDeclaration())return null;let v=I.node.source.value;if(typeof v!="string")return null;let N=await Jr(y,v,b);if(!N)return null;if(x.path.isImportDefaultSpecifier()){let $=await In(N,S,E),G=$.ast?cp($.ast,"default"):null,M=await p({file:N,exportName:"default",readFile:S,exists:b,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:E,visited:k});return!M||M.kind!=="static"?null:{kind:"static",file:G?.kind==="default-expression"?M.file:N,root:G?.kind==="default-expression"?M.root:{kind:"default-export"},value:M.value,sourceKind:"imported-binding"}}if(!x.path.isImportSpecifier())return null;let A=x.path.node.imported,w=Z.isIdentifier(A)?A.name:A.value,F=await In(N,S,E),B=F.ast?cp(F.ast,w):null,X=await p({file:N,exportName:w,readFile:S,exists:b,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:E,visited:k});return X?X.kind==="external"?X:{kind:"static",file:B?.kind==="re-export"?X.file:N,root:B?.kind==="re-export"||X.root.kind==="binding"&&X.root.name!==B?.name?X.root:{kind:"named-export",name:w},value:X.value,sourceKind:"imported-binding"}:null}async function p(m){let{file:y,exportName:x,readFile:S,exists:b,fileCache:E,visited:k}=m,I=`export::${y}::${x}`;if(!k.has(I)){k.add(I);try{let v=await In(y,S,E);if(!v.ast)return;let N=cp(v.ast,x);if(!N)return;if(N.kind==="default-expression"){let B=N.expression;if(!B||!Z.isIdentifier(B))return;let X=bs(v.ast).getBinding(B.name);return X?await s({currentFile:y,binding:X,readFile:S,exists:b,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:E,visited:k})??void 0:void 0}if(N.kind==="re-export"){if(!N.source||!N.name)return;let B=await Jr(y,N.source,b);return B?p({...m,file:B,exportName:N.name}):void 0}let A=N.name;if(!A)return;let w=bs(v.ast).getBinding(A);return w?await s({currentFile:y,binding:w,readFile:S,exists:b,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:E,visited:k})??void 0:void 0}finally{k.delete(I)}}}return{resolveExportValue:p,resolveComponentPropBinding:l,resolveComponentPropValues:c,resolveBindingTarget:s}}import*as se from"@babel/types";function up(e,t){let n=e.scope.getBinding(t);if(!n)return null;let r=n.path.getFunctionParent();if(!r||!r.isArrowFunctionExpression()&&!r.isFunctionExpression())return null;let o=r.node.params[0],i=En(o,t);if(!i)return null;let s=r.parentPath;return!s||!s.isCallExpression()||!eL(s,r)?null:{callPath:s,basePath:i}}function eL(e,t){let n=e.node.callee;return!se.isMemberExpression(n)||!se.isIdentifier(n.property)||n.property.name!=="map"?!1:e.node.arguments.some(r=>r===t.node)}function eS(e,t){let n=e.get("callee");if(!n.isMemberExpression())return null;let r=n.get("object");return Array.isArray(r)||!r.isExpression()?null:gc(r,t)}function ZE(e,t){return e?se.isNumericLiteral(e)&&Number.isInteger(e.value)?e.value:null:t}function qE(e,t,n,r,o){let i=se.isExpression(e.body)?e.body:e.body.body.find(a=>se.isReturnStatement(a))?.argument;if(!i||!se.isExpression(i))return;let s=lp(i,t,n,r,o);return typeof s=="number"?s:void 0}function lp(e,t,n,r,o){if(se.isNumericLiteral(e)||se.isStringLiteral(e)||se.isBooleanLiteral(e))return e.value;if(se.isIdentifier(e))return e.name===t?r:e.name===n?o:void 0;if(se.isMemberExpression(e)){let i=zc(e,t);if(i)return Pt(r,i);let s=zc(e,n);return s?Pt(o,s):void 0}if(se.isBinaryExpression(e)&&e.operator==="-"){let i=se.isExpression(e.left)?lp(e.left,t,n,r,o):void 0,s=se.isExpression(e.right)?lp(e.right,t,n,r,o):void 0;return typeof i=="number"&&typeof s=="number"?i-s:void 0}}function tL(e){if(se.isExpression(e.body))return e.body;for(let t of e.body.body)if(se.isReturnStatement(t)&&t.argument&&se.isExpression(t.argument))return t.argument;return null}function nL(e,t,n){let r=go(e,t,n);return typeof r=="boolean"?r:void 0}function go(e,t,n){if(se.isStringLiteral(e)||se.isNumericLiteral(e)||se.isBooleanLiteral(e))return e.value;if(se.isNullLiteral(e))return null;if(se.isIdentifier(e))return e.name===t?n:void 0;if(se.isMemberExpression(e)){let r=zc(e,t);return r?Pt(n,r):void 0}if(se.isUnaryExpression(e)&&e.operator==="!"){let r=go(e.argument,t,n);return r===void 0?void 0:!r}if(se.isLogicalExpression(e)){let r=go(e.left,t,n);if(r===void 0)return;if(e.operator==="&&")return r&&go(e.right,t,n);if(e.operator==="||")return r||go(e.right,t,n)}if(se.isBinaryExpression(e)){let r=se.isExpression(e.left)?go(e.left,t,n):void 0,o=se.isExpression(e.right)?go(e.right,t,n):void 0;if(r===void 0||o===void 0)return;switch(e.operator){case"===":return r===o;case"!==":return r!==o;case"==":return r==o;case"!=":return r!=o;default:return}}}function tS(e){let t=[],n=e;for(;se.isMemberExpression(n)||se.isOptionalMemberExpression(n);){let r=n.property;if(n.computed)if(se.isNumericLiteral(r))t.unshift({kind:"index",index:r.value});else if(se.isStringLiteral(r))t.unshift({kind:"property",name:r.value});else if(se.isExpression(r))t.unshift({kind:"dynamic",expression:r});else return null;else if(se.isIdentifier(r))t.unshift({kind:"property",name:r.name});else return null;n=n.object}return se.isIdentifier(n)?{base:n.name,segments:t}:null}function nS(e){return e.some(t=>t.kind==="dynamic")}function QE(e){return typeof e=="string"?{kind:"property",name:e}:Number.isInteger(e)?{kind:"index",index:e}:null}function rS(e,t){if(!Array.isArray(e.value))return null;let n=e.collectionPathMap?.length?e.collectionPathMap:e.value.map((r,o)=>[...e.pathPrefix??[],{kind:"index",index:e.collectionIndexMap?.[o]??o}]);return n.length>0?n.map(r=>[...r,...t]):null}function rL(e,t){let n=[],r=[];for(let o of t){let i=Pt(e,o);if(!Array.isArray(i))return null;for(let[s,a]of i.entries())n.push(a),r.push([...o,{kind:"index",index:s}])}return{value:n,collectionPathMap:r}}function oS(e){let{resolveBindingTarget:t,evaluateStaticExpression:n,buildExpressionSourceInfo:r,resolveSourceInfoProvenance:o,resolveComponentPropValues:i}=e;async function s(p){let{currentFile:m,callPath:y,readFile:x,exists:S,fileCache:b,visited:E}=p,k=y.node.callee;if(!se.isMemberExpression(k)||!se.isIdentifier(k.property)||k.property.name!=="map")return null;let I=y.get("callee");if(!I.isMemberExpression())return null;let v=I.get("object");if(Array.isArray(v)||!v.isExpression())return null;let N=await a({currentFile:m,expressionPath:v,readFile:x,exists:S,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:b,visited:E});return!N||!Array.isArray(N.value)||N.value.length===0?null:N}async function a(p){let{currentFile:m,expressionPath:y,readFile:x,exists:S,fileCache:b,visited:E}=p;if(y.isIdentifier()){let k=y.scope.getBinding(y.node.name);if(!k)return null;let I=await t({currentFile:m,binding:k,readFile:x,exists:S,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:b,visited:E});return I?.kind==="static"?I:null}if(y.isCallExpression())return l({currentFile:m,callPath:y,readFile:x,exists:S,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:b,visited:E});if(y.isTSAsExpression()||y.isTSSatisfiesExpression()||y.isTSNonNullExpression()){let k=y.get("expression");if(!Array.isArray(k)&&k.isExpression())return a({...p,expressionPath:k})}if(y.isArrayExpression()){let k=ys(y.node);if(!k)return null;let I=await n(y.node,y.scope,m,x,S,b,E);return Array.isArray(I)?{kind:"static",file:m,root:{kind:"expression",sourceRange:k},value:I,sourceKind:"binding"}:null}if(y.isMemberExpression()){let k=await r({expression:y.node,scope:y.scope,currentFile:m,readFile:x,exists:S,fileCache:b,visited:E});if(!k)return null;let I=await o({currentFile:m,expressionPath:y,sourceInfo:k,readFile:x,exists:S,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:b,visited:E});if(!I||I.kind==="external")return null;let v=await c({currentFile:m,expressionPath:y,provenance:I,readFile:x,exists:S,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:b,visited:E});if(!v||v.kind!=="static")return null;if(I.collectionPathMap?.length){let A=rL(v.value,I.collectionPathMap);if(A)return{kind:"static",file:I.file,root:I.root,value:A.value,sourceKind:I.sourceKind,collectionPathMap:A.collectionPathMap}}let N=Pt(v.value,I.path);return Array.isArray(N)?{kind:"static",file:I.file,root:I.root,value:N,sourceKind:I.sourceKind,pathPrefix:I.path,collectionIndexMap:I.collectionIndexMap,collectionPathMap:I.collectionPathMap}:null}return null}async function c(p){let{provenance:m}=p;if(m.root.kind==="binding"){let b=p.expressionPath.scope.getBinding(m.root.name);if(!b&&m.file!==p.currentFile){let E=await In(m.file,p.readFile,p.fileCache);b=E.ast?bs(E.ast).getBinding(m.root.name):void 0}return b?await t({currentFile:m.file,binding:b,readFile:p.readFile,exists:p.exists,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:p.fileCache,visited:p.visited}):null}if(m.root.kind!=="expression")return null;let y=await In(m.file,p.readFile,p.fileCache);if(!y.ast)return null;let x=XE(y.ast,m.root.sourceRange);if(!x)return null;let S=await n(x.node,x.scope,m.file,p.readFile,p.exists,p.fileCache,p.visited);return S===void 0?null:{kind:"static",file:m.file,root:m.root,value:S,sourceKind:m.sourceKind}}async function l(p){return await u(p)??await d(p)??await f(p)}async function u(p){let{callPath:m}=p,y=m.node.callee;if(!se.isMemberExpression(y)||!se.isIdentifier(y.property)||y.property.name!=="filter")return null;let x=m.get("callee");if(!x.isMemberExpression())return null;let S=x.get("object");if(Array.isArray(S)||!S.isExpression())return null;let b=await a({currentFile:p.currentFile,expressionPath:S,readFile:p.readFile,exists:p.exists,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:p.fileCache,visited:p.visited});if(!b||!Array.isArray(b.value))return null;let[E]=m.node.arguments;if(!se.isArrowFunctionExpression(E)&&!se.isFunctionExpression(E))return null;let k=E.params[0];if(!se.isIdentifier(k))return null;let I=tL(E);if(!I)return null;let v=[],N=[],A=[];for(let[w,F]of b.value.entries()){let B=nL(I,k.name,F);if(typeof B!="boolean")return null;if(B){v.push(F),N.push(b.collectionIndexMap?.[w]??w);let X=b.collectionPathMap?.[w];X&&A.push(X)}}return{...b,value:v,pathPrefix:b.pathPrefix,collectionIndexMap:N,...A.length>0?{collectionPathMap:A}:{}}}async function d(p){let{callPath:m}=p,y=m.node.callee;if(!se.isMemberExpression(y)||!se.isIdentifier(y.property)||y.property.name!=="slice")return null;let x=m.get("callee");if(!x.isMemberExpression())return null;let S=x.get("object");if(Array.isArray(S)||!S.isExpression())return null;let b=await a({currentFile:p.currentFile,expressionPath:S,readFile:p.readFile,exists:p.exists,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:p.fileCache,visited:p.visited});if(!b||!Array.isArray(b.value))return null;let[E,k]=m.node.arguments,I=ZE(E,0),v=ZE(k,b.value.length);if(I===null||v===null)return null;let N=Math.max(0,I<0?b.value.length+I:I),A=Math.max(0,v<0?b.value.length+v:v),w=b.value.map((B,X)=>b.collectionIndexMap?.[X]??X).slice(N,A),F=b.collectionPathMap?.slice(N,A);return{...b,value:b.value.slice(N,A),pathPrefix:b.pathPrefix,collectionIndexMap:w,...F?{collectionPathMap:F}:{}}}async function f(p){let{callPath:m}=p,y=m.node.callee;if(!se.isMemberExpression(y)||!se.isIdentifier(y.property)||y.property.name!=="sort"&&y.property.name!=="toSorted")return null;let x=m.get("callee");if(!x.isMemberExpression())return null;let S=x.get("object");if(Array.isArray(S)||!S.isExpression())return null;let b=await a({currentFile:p.currentFile,expressionPath:S,readFile:p.readFile,exists:p.exists,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:p.fileCache,visited:p.visited});if(!b||!Array.isArray(b.value))return null;let[E]=m.node.arguments;if(!se.isArrowFunctionExpression(E)&&!se.isFunctionExpression(E))return null;let[k,I]=E.params;if(!se.isIdentifier(k)||!se.isIdentifier(I))return null;let v=b.value.map((A,w)=>({value:A,sourceIndex:b.collectionIndexMap?.[w]??w,originalIndex:w})),N=[...v];for(let A of v)for(let w of v)if(qE(E,k.name,I.name,A.value,w.value)===void 0)return null;return N.sort((A,w)=>{let F=qE(E,k.name,I.name,A.value,w.value)??0;return F===0?A.originalIndex-w.originalIndex:F}),{...b,value:N.map(A=>A.value),pathPrefix:b.pathPrefix,collectionIndexMap:N.map(A=>A.sourceIndex),...b.collectionPathMap?{collectionPathMap:N.map(A=>b.collectionPathMap?.[A.originalIndex]).filter(A=>!!A)}:{}}}async function g(p){let m=null,y=!1,x,S=[];for(let E of p.segments){if(E.kind!=="dynamic")continue;let k=await r({expression:E.expression,scope:p.expressionPath.scope,source:p.fileCache.get(p.currentFile)?.source,currentFile:p.currentFile,readFile:p.readFile,exists:p.exists,fileCache:p.fileCache,visited:p.visited});if(!k)return null;let I=up(p.expressionPath,k.base),v;if(I){y=!0;let N=await s({currentFile:p.currentFile,callPath:I.callPath,readFile:p.readFile,exists:p.exists,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:p.fileCache,visited:p.visited});if(!N||!Array.isArray(N.value))return null;v=N.value.map((A,w)=>{let F=Pt(N.value,[{kind:"index",index:w},...I.basePath,...k.path]);return QE(F)}),x??=N.collectionIndexMap}else{let N=await i({...p,sourceInfo:k});if(!N)return null;v=N.map(QE)}if(v.some(N=>N===null)||m!==null&&m!==v.length)return null;m=v.length,S.push(v)}if(m===null||m===0)return null;let b=[];for(let E=0;E<m;E+=1){let k=[...p.rootPath],I=0;for(let v of p.segments){if(v.kind==="dynamic"){let N=S[I]?.[E];if(!N)return null;k.push(N),I+=1;continue}k.push({...v})}b.push(k)}return{sourceKind:y||m>1?"repeat-template":"binding",...x?{collectionIndexMap:x}:{},collectionPathMap:b}}return{resolveRepeatCollectionTarget:s,resolveCollectionCallTarget:l,resolveDynamicMemberPathMap:g}}var{normalizeExpressionWithScope:oL,evaluateStaticExpression:Yc}=BE({resolveBindingTarget:e=>Zc(e)}),{resolveRepeatCollectionTarget:iL,resolveCollectionCallTarget:sL,resolveDynamicMemberPathMap:aL}=oS({resolveBindingTarget:e=>Zc(e),evaluateStaticExpression:Yc,buildExpressionSourceInfo:$n,resolveSourceInfoProvenance:fn,resolveComponentPropValues:e=>uL(e)}),{resolveExportValue:cL,resolveComponentPropBinding:lL,resolveComponentPropValues:uL,resolveBindingTarget:Zc}=YE({resolveExternalExpression:yp,resolveCollectionCallTarget:sL,evaluateStaticExpression:Yc,resolveSourceInfoProvenance:fn,buildExpressionSourceInfo:$n});function pS(e){return new Map([...e].map(t=>[t.file,{source:t.source,ast:t.ast}]))}var iS=new WeakMap;function dL(e){let t=iS.get(e);return t||(t=new WeakMap,iS.set(e,t)),t}function sS(e,t,n){return{kind:"external",file:e,sourceType:"api-field",sourceId:t,displayPath:n,editMode:"readonly",diagnostics:[{code:"external-source-readonly",message:"Dynamic API data is read-only for content edits"}]}}async function mS(e){let{file:t,source:n,segment:r,readFile:o,exists:i}=e,s=e.fileCache??new Map,a=Hc(s,t,n);if(!a)return null;let c=Wc(a,r.sourceRange);if(!c)return null;let l=await $n({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:o,exists:i,fileCache:s,visited:new Set});if(!l){let f=await Sp({currentFile:t,expressionPath:c,readFile:o,exists:i,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:s,visited:new Set});return f?pp(f,ei(c.node,n)):null}let u=new Set,d=await OL({currentFile:t,expressionPath:c,segment:{...r,source:l},readFile:o,exists:i,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:s,visited:u});return d?pp(d,l.expression):null}async function ni(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=Hc(i,t,n);if(!s)return null;let a=e.sourceRange?Wc(s,e.sourceRange):e.expression!==void 0?xs(s,n,e.expression):null;if(!a)return null;let c=qc(a);if(!c.isIdentifier()&&!c.isMemberExpression())return null;let l=new Set,u=await $n({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:r,exists:o,fileCache:i,visited:l}),d=u?await fn({currentFile:t,expressionPath:c,sourceInfo:u,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:l}):await IS({currentFile:t,expressionPath:c,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:l});return pp(d,e.expression??ei(c.node,n))}async function hp(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=Hc(i,t,n);if(!s)return Yt("unsupported-expression","Unable to parse source for provenance resolution");let a=new Set;return e.target.kind==="text-segment"?fL({file:t,source:n,ast:s,segment:e.target.segment,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:a}):pL({file:t,source:n,ast:s,candidate:e.target.candidate,readFile:r,exists:o,graph:e.graph,fileCache:i,visited:a})}async function $n(e){if(de.isIdentifier(e.expression))return{kind:"identifier",expression:e.expression.name,base:e.expression.name,path:[]};if(!de.isMemberExpression(e.expression))return null;let t=await oL(e.expression,e.scope,e.currentFile,e.readFile,e.exists,e.fileCache,e.visited);return t?{kind:t.path.some(n=>n.kind==="index")?"index-expression":"member-expression",expression:ei(e.expression,e.source),base:t.base,path:t.path}:null}function pp(e,t){if(!e||e.kind==="value"&&e.editMode==="readonly")return null;if(e.kind==="external")return{kind:"external-entry",file:e.file,sourceType:e.sourceType,sourceId:e.sourceId,adapterId:e.adapterId,displayExpression:e.displayPath};let n={kind:"value",root:e.root,path:e.path.length>0?e.path:[]};return{kind:"value-binding",file:e.file,locator:n,root:e.root,path:e.path,displayExpression:e.displayExpression??t,sourceKind:e.sourceKind,...e.collectionIndexMap?{collectionIndexMap:e.collectionIndexMap}:{},...e.collectionPathMap?{collectionPathMap:e.collectionPathMap}:{}}}async function fL(e){let{file:t,source:n,ast:r,segment:o,readFile:i,exists:s,fileCache:a,visited:c}=e,l=Wc(r,o.sourceRange),u=l?await $n({expression:l.node,scope:l.scope,source:n,currentFile:t,readFile:i,exists:s,fileCache:a,visited:c}):null;if(!u){if(!l||l.isStringLiteral()||l.isTemplateLiteral()&&l.node.expressions.length===0)return aS(t,o.value);let f=await Sp({currentFile:t,expressionPath:l,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:c});return f?f.kind==="external"?fS(t,f):gp(t,ei(l.node,n),f):mL({expression:l.node,scope:l.scope,currentFile:t,source:n,readFile:i,exists:s,fileCache:a,visited:c,functionCallContracts:e.functionCallContracts})}if(!l)return Yt("unsupported-expression","Unable to locate text expression for provenance resolution");let d=await fn({currentFile:t,expressionPath:l,sourceInfo:u,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:c});if(!d){let f=mp(l.node);if(f)return Yt(f.code,f.message);let g=l.scope.getBinding(u.base);if(g?.path.isVariableDeclarator()){let p=mp(g.path.node.init);if(p)return Yt(p.code,p.message)}return g?.path.isVariableDeclarator()&&de.isCallExpression(g.path.node.init)?gL("unsupported-expression",bS(g.path.node.init,e.functionCallContracts)):Yt("unsupported-expression",`Unable to resolve provenance for expression "${u.expression}"`)}return d.kind==="external"?fS(t,d):gp(t,u.expression,d)}async function pL(e){let{file:t,source:n,ast:r,candidate:o,readFile:i,exists:s,fileCache:a,visited:c}=e;if(!o.conditionSource)return Yt("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let l=xs(r,n,o.conditionExpression);if(!l)return Yt("conditional-branch-unresolved",`Unable to locate conditional expression "${o.conditionExpression}"`);let u=await fn({currentFile:t,expressionPath:l,sourceInfo:o.conditionSource,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:c});if(!u)return Yt("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);if(u.kind==="external")return Yt("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let d=gp(t,o.conditionExpression,u);return d.finalSource?{...d,finalSource:{...d.finalSource,kind:"conditional-branch",displayPath:o.conditionExpression},chain:[...d.chain,{kind:"conditional-branch",file:u.file,displayName:o.conditionExpression,canEditHere:!0}]}:d}function aS(e,t){return{finalSource:{kind:"jsx-literal",file:e,locator:null,displayPath:t},chain:[{kind:"jsx-literal",file:e,displayName:t,canEditHere:!0}],confidence:"exact",editMode:"direct",diagnostics:[]}}async function mL(e){let t=await hS(e);if(t.length===0)return Yt("unsupported-expression",`Unsupported expression type: ${e.expression.type}`);if(hL(e.expression))return gS(t);if(xS(e.expression))return Yt("unsupported-expression","i18n helpers require a static message id string");if(de.isMemberExpression(e.expression)&&e.expression.computed&&!de.isNumericLiteral(e.expression.property)&&!de.isStringLiteral(e.expression.property))return Yt("dynamic-key","Computed member expressions are not supported for provenance resolution");let[n]=t;return Yt(n.code,n.message)}function Yt(e,t){return{finalSource:null,chain:[],confidence:"unknown",editMode:"unsupported",diagnostics:[{code:e,message:t}]}}function gL(e,t){return gS([{code:e,message:t}])}function gS(e){return{finalSource:null,chain:[],confidence:"partial",editMode:"readonly",diagnostics:e}}function hL(e){return de.isCallExpression(e)||de.isConditionalExpression(e)||de.isLogicalExpression(e)||de.isBinaryExpression(e)}function Ss(e){let t=new Set;return e.filter(n=>{let r=`${n.code}:${n.message}`;return t.has(r)?!1:(t.add(r),!0)})}async function hS(e){let{expression:t,scope:n,currentFile:r,readFile:o,exists:i,fileCache:s,visited:a,functionCallContracts:c}=e,l=mp(t);if(l)return[l];if(de.isCallExpression(t))return[{code:"unsupported-expression",message:bS(t,c)}];if(de.isMemberExpression(t)&&t.computed){let u=t.property;if(!de.isNumericLiteral(u)&&!de.isStringLiteral(u)){if(!de.isExpression(u))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}];let f=await Yc(u,n,r,o,i,s,a);if(typeof f!="string"&&!Number.isInteger(f))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}]}}return de.isBinaryExpression(t)?Ss([...await dp(t.left,t.right,e),{code:"unsupported-expression",message:"Mixed expressions are recognized but remain readonly until a safer composition editing strategy is available"}]):de.isLogicalExpression(t)?Ss([...await dp(t.left,t.right,e),{code:"unsupported-expression",message:t.operator==="??"||t.operator==="||"?"Fallback expressions are recognized but remain readonly until a safer composition editing strategy is available":"Complex conditional expressions are recognized but remain readonly until a safer editing strategy is available"}]):de.isConditionalExpression(t)?Ss([...await dp(t.test,t.consequent,t.alternate,e),{code:"unsupported-expression",message:"Complex conditional expressions are recognized but remain readonly until a safer editing strategy is available"}]):[]}function mp(e){return xS(e)?cS("i18n helpers require a static message id string"):SL(e)?cS("CMS helpers require static entry id and field path string arguments"):null}async function dp(...e){let t=e[e.length-1],n=e.slice(0,-1),r=[];for(let o of n)r.push(...await hS({...t,expression:o}));return r}function yL(e,t){let n=(t??[]).filter(r=>r.sourceType===e.sourceType&&(r.capabilities===void 0||r.capabilities.includes("write-text")));if(e.adapterId){let r=n.find(o=>o.adapterId===e.adapterId);if(r)return{adapterId:r.adapterId,editMode:"proxy",diagnostics:[]}}else if(n.length>0)return{adapterId:n[0]?.adapterId,editMode:"proxy",diagnostics:[]};return{adapterId:void 0,editMode:"readonly",diagnostics:[xL(e.sourceType)]}}async function yp(e){for(let n of _L){if(!lS(e.expressionPath,n.helperNames))continue;let r=await n.resolve(e);if(r)return dS(uS(r),e.externalAdapters)}let t={currentFile:e.currentFile,expressionPath:e.expressionPath,readFile:e.readFile,exists:e.exists,graph:e.graph};for(let n of e.externalSourceResolvers??[]){if(!lS(e.expressionPath,n.helperNames))continue;let r=await n.resolve(t);if(r)return dS(uS(r),e.externalAdapters)}return null}function xL(e){return{code:"missing-adapter",message:`No external adapter is registered for ${e}`}}function bL(e){return{code:"external-source-readonly",message:e}}function cS(e){return{code:"unsupported-expression",message:e}}function xp(e){return!e||!de.isCallExpression(e)?null:de.isIdentifier(e.callee)?e.callee.name:de.isMemberExpression(e.callee)&&!e.callee.computed&&de.isIdentifier(e.callee.object)&&de.isIdentifier(e.callee.property)?`${e.callee.object.name}.${e.callee.property.name}`:null}function lS(e,t){if(!t||t.length===0)return!0;let n=xp(e.node);return n?t.includes(n):!1}function uS(e){return"match"in e?{match:e.match,editMode:e.editMode,diagnostics:Ss(e.diagnostics??[])}:{match:e,diagnostics:[]}}function dS(e,t){let n=yL(e.match,t);return{kind:"external",file:e.match.file,sourceType:e.match.sourceType,sourceId:e.match.sourceId,adapterId:e.match.adapterId??n.adapterId,displayPath:e.match.displayPath,editMode:e.editMode==="readonly"?"readonly":n.editMode,diagnostics:Ss([...e.diagnostics,...e.editMode==="readonly"||n.editMode==="readonly"?n.diagnostics:[]])}}function EL(e){if(!e.isCallExpression())return null;let t=e.node.callee;if(!de.isIdentifier(t)||t.name!=="getCmsField")return null;let[n,r]=e.node.arguments;if(!n||!r||!de.isStringLiteral(n)||!de.isStringLiteral(r))return null;let o=n.value,i=r.value;return{sourceType:"cms-field",sourceId:`${o}:${i}`,file:`cms://${o}/${i.replace(/\./g,"/")}`,displayPath:`${o}.${i}`}}function SL(e){return!!e&&de.isCallExpression(e)&&de.isIdentifier(e.callee)&&e.callee.name==="getCmsField"&&(e.arguments.length<2||!de.isStringLiteral(e.arguments[0])||!de.isStringLiteral(e.arguments[1]))}function yS(e){if(!(!e||!de.isCallExpression(e))){if(de.isIdentifier(e.callee)&&e.callee.name==="t"){let[t]=e.arguments;return t&&de.isStringLiteral(t)?t.value:null}if(de.isMemberExpression(e.callee)&&!e.callee.computed&&de.isIdentifier(e.callee.object)&&e.callee.object.name==="intl"&&de.isIdentifier(e.callee.property)&&e.callee.property.name==="formatMessage"){let[t]=e.arguments;if(!t||!de.isObjectExpression(t))return null;for(let n of t.properties)if(de.isObjectProperty(n)&&!n.computed&&(de.isIdentifier(n.key)&&n.key.name==="id"||de.isStringLiteral(n.key)&&n.key.value==="id")&&de.isStringLiteral(n.value))return n.value.value;return null}}}function xS(e){return yS(e)===null}async function IL(e,t,n){let r=new Set,o=Es.posix.dirname(e);for(;r.add(o),!(o==="."||o==="/");){let i=Es.posix.dirname(o);if(i===o){r.add(".");break}o=i}r.add("src"),r.add(".");for(let i of r){let s=i==="."?["locales","messages"]:[Es.posix.join(i,"locales"),Es.posix.join(i,"messages")];for(let a of s){let c=Es.posix.join(a,`${t}.json`);if(await n(c))return c}}return null}async function vL(e){let t=yS(e.expressionPath.node);if(typeof t!="string"||t.length===0)return null;let n="en",r=await IL(e.currentFile,n,e.exists);return r?{sourceType:"i18n-message",sourceId:`${n}:${t}`,file:r,displayPath:t}:null}async function kL(e){if(!e.expressionPath.isCallExpression())return null;let t=e.expressionPath.node.callee;if(!de.isIdentifier(t)||t.name!=="apiField")return null;let[n,r]=e.expressionPath.node.arguments;if(!n||!de.isExpression(n))return null;let o=await Yc(n,e.expressionPath.scope,e.currentFile,e.readFile,e.exists,e.fileCache,e.visited);if(typeof o!="string"||o.length===0)return null;let i={sourceType:"api-field",sourceId:o,file:`api://${o}`,displayPath:o};return r?{match:i,editMode:"readonly",diagnostics:[bL("API mapping transforms must stay readonly until a reversible mapping strategy is registered")]}:i}var _L=[{helperNames:["getCmsField"],resolve:({expressionPath:e})=>EL(e)},{helperNames:["apiField"],resolve:e=>kL(e)},{helperNames:["t","intl.formatMessage"],resolve:({currentFile:e,expressionPath:t,exists:n})=>vL({currentFile:e,expressionPath:t,exists:n})}];function bp(e){return{...e,editMode:"readonly",diagnostics:[{code:"unsupported-expression",message:"Derived display values are readonly because no identity-preserving write target exists"}]}}function fS(e,t){return{finalSource:{kind:t.sourceType,file:t.file,locator:null,displayPath:t.displayPath,externalSource:{sourceType:t.sourceType,sourceId:t.sourceId,adapterId:t.adapterId}},chain:[...t.chainPrefix??[],{kind:t.sourceType,file:t.file,displayName:t.displayPath,canEditHere:t.editMode!=="readonly"}],confidence:"exact",editMode:t.editMode==="direct"?t.file===e?"direct":"proxy":t.editMode,diagnostics:t.diagnostics}}function gp(e,t,n){let r={kind:"value",root:n.root,path:n.path.length>0?n.path:[]},o=n.path.some(l=>l.kind==="index"),i=wL(n),s;n.semanticKind?s=n.semanticKind:i?s="config-entry":n.sourceKind==="repeat-template"?s="repeat-template":n.path.length===0?s=n.sourceKind==="imported-binding"?"imported-binding":"binding":s=o?"array-item":"object-field";let a=n.displayExpression??t,c=[...n.chainPrefix??[]];return n.sourceKind==="binding"?c.push({kind:"binding",file:n.file,displayName:n.root.kind==="binding"?n.root.name:a,canEditHere:n.editMode!=="readonly"}):n.sourceKind==="imported-binding"?c.push({kind:"imported-binding",file:n.file,displayName:n.root.kind==="named-export"?n.root.name:"default",canEditHere:n.editMode!=="readonly"}):n.sourceKind==="repeat-template"&&c.push({kind:"repeat-template",file:n.file,displayName:t,canEditHere:n.editMode!=="readonly"}),n.path.length>0&&n.sourceKind!=="repeat-template"&&c.push({kind:o?"array-item":"object-field",file:n.file,displayName:a,canEditHere:n.editMode!=="readonly"}),i&&c.push({kind:"config-entry",file:n.file,displayName:i.displayPath,canEditHere:n.editMode!=="readonly"}),{finalSource:{kind:s,file:n.file,locator:r,root:n.root,path:n.path,displayPath:a,externalSource:i?{sourceType:"config-entry",sourceId:i.sourceId}:void 0},chain:n.editMode==="readonly"?c.map(l=>({...l,canEditHere:!1})):c,confidence:n.sourceKind==="repeat-template"?"safe-derived":"exact",editMode:n.editMode??(n.file===e?"direct":"proxy"),diagnostics:n.diagnostics??[]}}var CL=[{helperName:"formatPrice",purity:"pure",sourceArgIndex:0},{helperName:"formatDate",purity:"pure",sourceArgIndex:0},{helperName:"pickLabel",purity:"pure",sourceArgIndex:0}];function Ep(e,t){let n=[...CL,...t??[]];for(let r=n.length-1;r>=0;r-=1){let o=n[r];if(o?.helperName===e)return o}return null}function bS(e,t){let n=e.callee;return de.isIdentifier(n)&&Ep(n.name,t)?.purity==="side-effect"?`Helper "${n.name}" is registered as side-effectful and remains readonly`:"Function calls remain readonly because purity does not establish an identity-preserving write target"}async function Sp(e){let t=await yp(e);if(t)return t;let n=await ES({...e,expressionPath:e.expressionPath});if(n)return n;if(e.expressionPath.isTemplateLiteral()){let r=e.expressionPath.node.expressions[0],o=e.expressionPath.get("expressions.0");if(e.expressionPath.node.expressions.length===1&&r&&o&&!Array.isArray(o)&&o.isExpression()){let i=await $n({expression:o.node,scope:o.scope,source:e.fileCache.get(e.currentFile)?.source,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(i){let s=await fn({...e,expressionPath:o,sourceInfo:i});if(s&&s.kind==="value")return{...s,displayExpression:i.expression,editMode:"readonly",diagnostics:[{code:"unsupported-expression",message:"Mixed expressions are recognized but remain readonly until a safer composition editing strategy is available"}]}}}}return await AL(e)}async function ES(e){let t=await vn({...e,allowComposed:!1});if(t?.kind!=="source")return null;let n=qc(e.expressionPath);return n.isIdentifier()||n.isMemberExpression()?t.provenance:bp(t.provenance)}async function vn(e){let t=qc(e.expressionPath),n=PL(e.currentFile,t.node);if(n&&e.visited.has(n))return null;n&&e.visited.add(n);try{if(t.isStringLiteral()||t.isNumericLiteral()||t.isBooleanLiteral()||t.isNullLiteral())return{kind:"none"};if(t.isIdentifier()){let r=await $n({expression:t.node,scope:t.scope,source:e.fileCache.get(e.currentFile)?.source,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(!r)return null;let o=await fn({currentFile:e.currentFile,expressionPath:t,sourceInfo:r,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});return!o||o.kind==="external"?null:{kind:"source",provenance:o}}if(t.isMemberExpression()){let r=await $n({expression:t.node,scope:t.scope,source:e.fileCache.get(e.currentFile)?.source,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(!r)return null;let o=await fn({currentFile:e.currentFile,expressionPath:t,sourceInfo:r,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});return!o||o.kind==="external"?null:{kind:"source",provenance:o}}if(t.isConditionalExpression()){let r=t.get("test"),o=t.get("consequent"),i=t.get("alternate");if(Array.isArray(r)||Array.isArray(o)||Array.isArray(i)||!r.isExpression()||!o.isExpression()||!i.isExpression())return null;let s=await vn({...e,expressionPath:r,allowComposed:!0}),a=await vn({...e,expressionPath:o,allowComposed:!1}),c=await vn({...e,expressionPath:i,allowComposed:!1});return fp(s,a,c)}if(t.isCallExpression())return RL({...e,expressionPath:t});if(!e.allowComposed)return null;if(t.isBinaryExpression()){let r=t.get("left"),o=t.get("right");if(Array.isArray(r)||Array.isArray(o)||!r.isExpression()||!o.isExpression())return null;let i=await vn({...e,expressionPath:r,allowComposed:!0}),s=await vn({...e,expressionPath:o,allowComposed:!0});return fp(i,s)}if(t.isLogicalExpression()){let r=t.get("left"),o=t.get("right");if(Array.isArray(r)||Array.isArray(o)||!r.isExpression()||!o.isExpression())return null;let i=await vn({...e,expressionPath:r,allowComposed:!0}),s=await vn({...e,expressionPath:o,allowComposed:!0});return fp(i,s)}if(t.isUnaryExpression()){let r=t.get("argument");return Array.isArray(r)||!r.isExpression()?null:vn({...e,expressionPath:r,allowComposed:!0})}return null}finally{n&&e.visited.delete(n)}}function qc(e){let t=e;for(;t.isParenthesizedExpression()||t.isTSAsExpression()||t.isTSSatisfiesExpression()||t.isTSNonNullExpression()||t.isTSTypeAssertion();){let n=t.get("expression");if(Array.isArray(n)||!n.isExpression())return t;t=n}return t}async function RL(e){let t=xp(e.expressionPath.node);if(t==="Math.round"||t==="Math.floor"||t==="Math.ceil"||t==="Math.trunc"||t==="useCountUp"){let r=e.expressionPath.get("arguments.0");return!r||Array.isArray(r)||!r.isExpression()?null:vn({...e,expressionPath:r,allowComposed:!1})}let n=e.expressionPath.get("callee");if(n.isMemberExpression()&&!n.node.computed){let r=n.node.property;if(de.isIdentifier(r)&&(r.name==="toFixed"||r.name==="toString")){let o=n.get("object");return Array.isArray(o)||!o.isExpression()?null:vn({...e,expressionPath:o,allowComposed:!1})}}return null}function fp(...e){let t=null;for(let n of e){if(!n)return null;if(n.kind!=="none"){if(!t){t=n.provenance;continue}if(!NL(t,n.provenance))return null}}return t?{kind:"source",provenance:t}:{kind:"none"}}function NL(e,t){return e.file===t.file&&e.sourceKind===t.sourceKind&&JSON.stringify(e.root)===JSON.stringify(t.root)&&JSON.stringify(e.path)===JSON.stringify(t.path)&&JSON.stringify(e.collectionIndexMap??null)===JSON.stringify(t.collectionIndexMap??null)&&JSON.stringify(e.collectionPathMap??null)===JSON.stringify(t.collectionPathMap??null)}function PL(e,t){return t.start==null||t.end==null?null:`safe-derived:${e}:${t.start}:${t.end}`}async function AL(e){if(!e.expressionPath.isCallExpression())return null;let t=xp(e.expressionPath.node);if(!t)return null;let n=Ep(t,e.functionCallContracts);if(!n||n.purity!=="pure")return null;let r=n.sourceArgIndex??0,o=e.expressionPath.get(`arguments.${r}`);if(!o||Array.isArray(o)||!o.isExpression())return null;let i=await SS({currentFile:e.currentFile,argumentPath:o,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});return i?bp(i):null}async function SS(e){let t=await yp({currentFile:e.currentFile,expressionPath:e.argumentPath,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(t)return t;let n=await $n({expression:e.argumentPath.node,scope:e.argumentPath.scope,source:e.fileCache.get(e.currentFile)?.source,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(n){let r=await fn({currentFile:e.currentFile,expressionPath:e.argumentPath,sourceInfo:n,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});return!r||r.kind==="external"?r:{...r,displayExpression:n.expression}}return await Sp({currentFile:e.currentFile,expressionPath:e.argumentPath,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited})}async function TL(e){if(!e.binding.path.isVariableDeclarator())return null;let t=e.binding.path.node.init;if(!t||!de.isCallExpression(t))return null;let n=t.callee;if(!de.isIdentifier(n))return null;let r=Ep(n.name,e.functionCallContracts);if(!r||r.purity!=="pure")return null;let o=r.sourceArgIndex??0,i=e.binding.path.get("init");if(!i||Array.isArray(i)||!i.isCallExpression())return null;let s=i.get(`arguments.${o}`);if(!s||Array.isArray(s)||!s.isExpression())return null;let a=await SS({currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited,argumentPath:s});return a?bp(a):null}function wL(e){if(e.sourceKind!=="imported-binding")return null;let t=e.root.kind==="binding"||e.root.kind==="named-export"?e.root.name:e.root.kind==="default-export"?"default":null;if(!t)return null;let n=/(^|[\/.-])(config|settings)([\/.-]|$)/i.test(e.file),r=/config|settings/i.test(t);if(!n&&!r)return null;let o=ti(t,e.path);return{sourceId:o,displayPath:o}}async function OL(e){let t=e.segment.source;return t?fn({currentFile:e.currentFile,expressionPath:e.expressionPath,sourceInfo:t,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited}):null}async function fn(e){let t=e.sourceInfo,n=up(e.expressionPath,t.base);if(n){let l=await iL({currentFile:e.currentFile,callPath:n.callPath,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,fileCache:e.fileCache,visited:e.visited});if(!l){let m=eS(n.callPath,[...n.basePath,...t.path]);return os(m)?sS(e.currentFile,m.sourceId,m.displayPath):null}let u=rS(l,[...n.basePath,...t.path]),d=l.collectionIndexMap?.[0]??0,f=[...l.pathPrefix??[],{kind:"index",index:d},...n.basePath,...t.path],g=[{kind:"index",index:0},...n.basePath,...t.path];return Pt(l.value,g)===void 0?null:{kind:"value",file:l.file,root:l.root,path:u?.[0]??f,sourceKind:"repeat-template",collectionIndexMap:l.collectionIndexMap,...u?{collectionPathMap:u}:{}}}let r=e.expressionPath.scope.getBinding(t.base);if(!r)return null;if(r.path.isImportNamespaceSpecifier()){let l=t.path[0],u=r.path.parentPath;if(!l||l.kind!=="property"||!u?.isImportDeclaration())return null;let d=await Jr(e.currentFile,u.node.source.value,e.exists);if(!d)return null;let f=await cL({file:d,exportName:l.name,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(!f||f.kind==="external")return null;let g=t.path.slice(1);return Pt(f.value,g)===void 0?null:{kind:"value",file:f.file,root:f.root,path:g,sourceKind:"imported-binding",collectionIndexMap:f.collectionIndexMap}}let o=zx(r);if(o){let l=o.expressionPath,u=await $n({expression:l.node,scope:l.scope,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(u){let d=await fn({...e,expressionPath:l,sourceInfo:{...u,expression:ti(u.expression,t.path),path:[...u.path,...t.path]}});if(d)return d}else if(r.constant){let d=`dynamic-alias:${e.currentFile}:${l.node.start}`;if(e.visited.has(d))return null;e.visited.add(d);try{let f=await IS({...e,expressionPath:qc(l),memberSuffix:t.path});if(f?.kind==="value")return f}finally{e.visited.delete(d)}}if(t.path.length===0){let d=await ES({currentFile:e.currentFile,expressionPath:l,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(d)return d}}if(r.kind==="param")return lL({currentFile:e.currentFile,binding:r,sourceInfo:t,graph:e.graph,readFile:e.readFile,exists:e.exists,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});let i=await TL({currentFile:e.currentFile,binding:r,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(i)return i;let s=pc(r,t.path,dL(e.fileCache));if(os(s))return sS(e.currentFile,s.sourceId,s.displayPath);let a=await Zc({currentFile:e.currentFile,binding:r,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});return a?a.kind==="external"?t.path.length===0?a:null:Pt(a.value,t.path)===void 0?null:{kind:"value",file:a.file,root:a.root,path:t.path,sourceKind:a.sourceKind,collectionIndexMap:a.collectionIndexMap}:null}async function IS(e){let t=tS(e.expressionPath.node);if(!t||!nS(t.segments))return null;let n=await fn({currentFile:e.currentFile,expressionPath:e.expressionPath,sourceInfo:{kind:"identifier",expression:t.base,base:t.base,path:[]},readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(!n||n.kind==="external")return n;let r=await aL({...e,rootPath:n.path,segments:t.segments});if(!r)return null;let o=r.collectionPathMap.map(i=>[...i,...e.memberSuffix??[]]);if(e.memberSuffix){let i=e.expressionPath.scope.getBinding(t.base),s=i?await Zc({...e,binding:i}):null;if(s?.kind!=="static"||o.some(a=>Pt(s.value,a.slice(n.path.length))===void 0))return null}return{...n,path:o[0]??n.path,sourceKind:r.sourceKind,displayExpression:ei(e.expressionPath.node,e.fileCache.get(e.currentFile)?.source),...r.collectionIndexMap?{collectionIndexMap:r.collectionIndexMap}:{},collectionPathMap:o}}async function vS(e){let t=FL(e.propertyName);if(t.owner==="blocked")return Or(t.owner,t.diagnostic);if(t.owner==="class-name-source"||t.owner==="style")return Or(t.owner,{code:"owner-delegated",message:`Property '${e.propertyName}' is owned by ${t.owner}`});let n=e.element.attributes?.filter(l=>l.name===e.propertyName)??[];if(n.length>1)return Or("generic",{code:"duplicate-property-source",message:`Property '${e.propertyName}' has multiple explicit sources`});let r=n[0],o=[];r&&o.push({kind:"attribute",order:r.order??e.element.attributes.indexOf(r),attribute:r});let i=e.element.attributeSpreads??[];for(let l of i)o.push({kind:"spread",order:l.order,spread:l,target:await DL(e,l)});o.sort((l,u)=>l.order-u.order);let s=o.at(-1);if(!s)return{status:"missing",owner:"generic"};if(o.filter(l=>l.kind==="spread"&&l.order>s.order).some(l=>!l.target))return Or("generic",{code:"ambiguous-property-source",message:`A spread may provide or override property '${e.propertyName}'`});if(s.kind==="spread")return s.target?{status:"binding",owner:"generic",target:s.target}:Or("generic",{code:"ambiguous-property-source",message:`The final spread source for '${e.propertyName}' is not provably writable`});let c=o.filter(l=>l.kind==="spread"&&l.order<s.order);return e.operation==="remove"&&c.length>0?Or("generic",{code:"remove-exposes-spread",message:`Removing '${e.propertyName}' would expose an earlier spread source`}):LL(e,s.attribute)}async function LL(e,t){if(t.resolution&&t.resolution.status!=="resolved"&&!t.source){let r=await ni({file:e.file,source:e.source,sourceRange:t.sourceRange,expression:t.value,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache});return r&&r.kind!=="external-entry"?{status:"binding",owner:"generic",attribute:t,target:{kind:"value-binding",target:r}}:Or("generic",{code:"unsupported-property-source",message:`Property '${e.propertyName}' has an unresolved value source`})}if(!t.source?.expression)return{status:"direct",owner:"generic",attribute:t,target:{kind:"jsx-attribute",file:e.file,sourceRange:t.sourceRange}};let n=await ni({file:e.file,source:e.source,sourceRange:t.sourceRange,expression:t.source.expression,sourceInfo:t.source,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache});return!n||n.kind==="external-entry"?Or("generic",{code:"unsupported-property-source",message:`Property '${e.propertyName}' does not have a local writable source`}):{status:"binding",owner:"generic",attribute:t,target:{kind:"value-binding",target:n}}}async function DL(e,t){let n=t.source?.expression;if(!n)return;let r=await ni({file:e.file,source:e.source,sourceRange:t.sourceRange,expression:n,sourceInfo:t.source,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache});if(!(!r||r.kind==="external-entry"))return{kind:"value-binding",target:ML(r,e.propertyName)}}function ML(e,t){let n=[...e.path??[],{kind:"property",name:t}];return{...e,path:n,locator:e.locator?{...e.locator,path:n}:{kind:"value",root:e.root??{kind:"binding",name:t},path:n}}}function Or(e,t){return{status:"blocked",owner:e,...t?{diagnostic:t}:{}}}function kS(e){let t=new Map;for(let r of e.elements.values()){if(r.importedFrom===void 0)continue;let o=t.get(r.importedFrom);o||(o={candidates:[],keys:new Map},t.set(r.importedFrom,o)),o.candidates.push(r)}let n=r=>{if(ho(r.tag))return r.identity.key;let o=t.get(r.sourceFile);if(!o)return null;if(o.keys.has(r.componentName))return o.keys.get(r.componentName);let i=o.candidates.filter(a=>VL(a,r.componentName)),s=i.length===1?i[0].identity.key:null;return o.keys.set(r.componentName,s),s};return r=>BL({...r,graph:e},n)}function BL(e,t){let{key:n,element:r,graph:o,provenances:i}=e,s=$L(n,r,o,t),a=s?.tag??(ho(r.tag)?r.tag:r.componentName),c=s?.identity.key??t(r,o)??n,l=KL(s),u=JL(n,r,o,i,s),d=jL(n,r,o,i,c);return{componentName:a,instanceKey:c,templateOwner:UL(s??r,a),...l.length>0?{variantKeys:l}:{},...u.length>0?{slotKeys:u}:{},editableStrategy:d,impactScope:XL(d),alternativeStrategies:zL(d)}}function jL(e,t,n,r,o){for(let i of r.values())if(i?.editMode==="upstream")return"upstream";return Ip(e,n)?"instance":!ho(t.tag)&&t.sourceFile!==n.routeId&&o!==e?"template":"instance"}function $L(e,t,n,r){if(ho(t.tag))return t;let o=Ip(e,n);if(o)return o;let i=r(t,n);return i?n.elements.get(i)??null:null}function VL(e,t){return e.exportName===t||e.tag===t||e.exportName==="default"}function UL(e,t){return ho(e.tag)&&e.importedFrom?`${e.importedFrom}#${t}`:`${e.sourceFile}#${t}`}function KL(e){if(!e?.attributes)return[];let t=new Set(["variant","size","tone"]);return e.attributes.filter(n=>t.has(n.name)).map(n=>n.name)}function JL(e,t,n,r,o){let i=new Set,s=Ip(e,n);s&&o?.identity.key===s.identity.key&&i.add("children");for(let a of r.values()){let c=a?.chain.find(u=>u.kind==="component-prop");if(!c)continue;let l=c.displayName.split(".").pop();l&&i.add(l)}return i.size===0&&ho(t.tag)&&t.childKeys.length>0&&i.add("children"),[...i]}function Ip(e,t){let n=t.elements.get(e)?.parentKey??null;for(;n;){let r=t.elements.get(n);if(!r)break;if(ho(r.tag))return r;n=r.parentKey}return null}function ho(e){return/^[A-Z]/.test(e)}function XL(e){switch(e){case"template":return"component-template";case"upstream":return"upstream-source";default:return"current-instance"}}function zL(e){switch(e){case"template":return["instance"];case"upstream":return["template"];default:return["template"]}}function RS(e){let t=e.isRepeat??(e.graph?tD(e.element,e.graph):!1),n=e.propertyProvenance??new Map,r=e.repeatTargets??new Map,o=eD(e.element.attributes??[]),i=[...r.values()].some(u=>u.ok),s=o.map(u=>HL({attribute:u,element:e.element,isRepeat:t,selectionRef:e.selectionRef,provenance:n.get(u.name),repeatTarget:r.get(u.name)})),a=(e.element.attributeSpreads?.length??0)>0,c=(e.element.attributeSpreads??[]).slice().sort((u,d)=>u.order-d.order).map(u=>({raw:u.raw,sourceRange:nD(u.sourceRange,e.source),order:u.order,diagnostics:u.source?[]:[{code:"unsupported-spread-source",message:"The spread source cannot be resolved safely, so property ownership is conservative."}]})),l=t&&e.selectionRef?.instanceIndex!==void 0&&i;return{documentVersion:e.documentVersion,...e.selectionRef?{selectionRef:e.selectionRef}:{},items:s,spreads:c,creation:t?{selection:l?"materialize":"unsupported",template:"unsupported"}:{selection:a?"unsupported":"direct",template:a?"unsupported":"direct"}}}function HL(e){let{attribute:t,provenance:n,repeatTarget:r}=e,o=e.selectionRef?.instanceIndex!==void 0&&r?.ok===!0?r:null,i=WL(t,n,e.isRepeat),s=["selection","template"].map(y=>({scope:y,result:Ic({state:n,scope:y,operation:"set",selectionRef:e.selectionRef,isRepeat:e.isRepeat,repeatTarget:r})})),a=s.find(({result:y})=>y.ok)?.result,c=a?.ok?a.target:void 0,l=c?.kind==="value-binding"&&o&&(JSON.stringify(c.locator.root)!==JSON.stringify(o.selectedParentObjectLocator.root)||JSON.stringify(c.locator.path??[])!==JSON.stringify([...o.selectedParentObjectLocator.path??[],{kind:"property",name:t.name}]))?null:o,u=GL(t,n,l,e.isRepeat),d=c?qL(c,e.element,t.name):void 0,f=s.filter(({result:y})=>y.ok).map(({scope:y})=>y),g=f.length>0?ZL(n,o,e.element):"unsupported",p=o?"repeat-item":e.isRepeat?"repeat-template":"node",m=QL(t,n,r);if(f.length===0&&m.length===0){let y=s.find(({result:x})=>!x.ok)?.result;y&&!y.ok&&m.push({code:y.code,message:y.reason})}return{name:t.name,source:i,resolution:u,editMode:g,sourceScope:p,allowedWriteScopes:f,...d?{effectiveWriteTarget:d}:{},diagnostics:m}}function WL(e,t,n){let r;if(n&&t?.status==="binding"){let o=t.target;r=o?.kind==="value-binding"&&o.target.sourceKind==="repeat-template"?"repeat-template":"binding"}else e.syntaxKind==="boolean-shorthand"?r="boolean-shorthand":e.syntaxKind==="literal"||!e.source?r="literal":r="expression";return{kind:r,...e.raw!==void 0?{raw:e.raw}:{}}}function GL(e,t,n,r){return n?_S(n.selectedResolution):t?.status==="blocked"?{status:"unresolved"}:r&&t?.status==="binding"?{status:"unresolved"}:_S(YL(e))}function YL(e){return e.resolution?e.resolution:e.syntaxKind==="boolean-shorthand"?{status:"resolved",value:!0}:e.resolvedValue!==void 0?{status:"resolved",value:e.resolvedValue}:e.source?{status:"unresolved"}:{status:"resolved",value:e.value}}function _S(e){return!e||e.status==="unresolved"?{status:"unresolved"}:e.status==="undefined"?{status:"undefined"}:{status:"resolved",value:e.value}}function ZL(e,t,n){if(t)return"direct";if(!e||e.status==="blocked")return"unsupported";if(e.status==="missing"||e.status==="direct")return"direct";let r=e.target;return r?.kind!=="value-binding"?"unsupported":r.target.file===n.sourceFile?"direct":"proxy"}function qL(e,t,n){return e.kind==="repeat-property"?{kind:"value-path",file:e.target.sourceFile,isProxy:e.target.sourceFile!==t.sourceFile,displayPath:CS({...e.target.selectedParentObjectLocator,path:[...e.target.selectedParentObjectLocator.path??[],{kind:"property",name:n}]})}:e.kind==="value-binding"?{kind:"value-path",file:e.file,isProxy:e.file!==t.sourceFile,displayPath:CS(e.locator)}:{kind:"jsx-node",file:t.sourceFile,isProxy:!1,displayPath:t.componentName+" > "+n}}function QL(e,t,n){let r=[];return t?.diagnostic&&r.push({code:t.diagnostic.code,message:t.diagnostic.message}),n&&!n.ok&&t?.status!=="missing"&&r.push({code:`repeat-${n.errorCode}`,message:n.reason}),e.resolution?.status==="unresolved"&&r.length===0&&r.push({code:"unsupported-property-source",message:`Property '${e.name}' has an unresolved value source`}),r}function eD(e){let t=new Set;return e.filter(n=>t.has(n.name)?!1:(t.add(n.name),!0))}function tD(e,t){let n=t.regions.filter(r=>r.kind==="repeat-region");for(let r of n){let o=e;for(;o;){if(r.childKeys.includes(o.identity.key))return!0;o=o.parentKey?t.elements.get(o.parentKey):void 0}}return!1}function CS(e){return`${e.root.kind==="binding"?e.root.name:e.root.kind==="expression"?e.root.sourceRange?"expression":"value":e.root.kind}${(e.path??[]).map(n=>n.kind==="index"?`[${n.index}]`:`.${n.name}`).join("")}`}function nD(e,t){if(!t)return{start:e.startColumn,end:e.endColumn};let n=t.split(`
7
- `),r=(o,i)=>n.slice(0,Math.max(0,o-1)).reduce((s,a)=>s+a.length+1,0)+i;return{start:r(e.startLine,e.startColumn),end:r(e.endLine,e.endColumn)}}function rD(e){return e==="api-field"||e==="cms-field"||e==="i18n-message"||e==="config-entry"}var oD=160;function NS(e,t,n,r={}){let o=Ro(e),i=[];for(let[s,a]of e.elements){let c=n.get(s),l={canUpdateText:r.canUpdateTextByKey?.get(s)??c?.canUpdateText??!1,canInsertChild:c?.canInsertChild??!1,canMove:c?.canMove??!1,canRemove:c?.canRemove??!1};i.push({key:s,tag:a.tag,label:a.tag===a.componentName?a.tag:`${a.tag} (${a.componentName})`,parentKey:a.parentKey,childKeys:[...a.childKeys],operationSummary:l,...r.dynamicDataSummaryByKey?.get(s)?{dynamicDataSummary:r.dynamicDataSummaryByKey.get(s)}:{}})}return{composition:o,routeId:e.routeId,version:e.version,rootKeys:[...e.rootKeys],entries:i}}function PS(e,t,n,r,o,i,s,a,c,l,u){let d=Ro(t),f=t.elements.get(e),g=n.nodes.get(e),p=r.get(e);if(!f||!g||!p)throw new Error(`Node not found: ${e}`);let m=FS(f.textSegments,s),y=LS(e,t,f,p,m),x=m?cD(m):void 0,S=lD(i,m),b=f.textSegments.map(v=>({index:v.index,value:v.value,editable:DS(v,p,s?.get(v.index)??null),source:o.get(v.index)??null})),E=wS(f,t),k=f.childKeys.map(v=>{let N=t.elements.get(v);return N?{key:v,tag:N.tag,label:N.tag}:null}).filter(v=>v!==null),I=[];if(f.parentKey){let v=t.elements.get(f.parentKey);if(v)for(let N of v.childKeys){if(N===e)continue;let A=t.elements.get(N);A&&I.push({key:N,tag:A.tag,label:A.tag})}}return{composition:d,key:e,tag:f.tag,componentName:f.componentName,sourceFile:f.sourceFile,sourceLocator:TS(f),label:f.tag,capabilities:y,writeTarget:i,effectiveWriteTarget:S,provenanceChain:x,componentSemantic:c,styleSource:l,conditional:a,...u?{dynamicData:u}:{},textSegments:b,boundaryKind:f.boundaryKind,isOpaque:f.isOpaque,ancestors:E,children:k,siblings:I}}function AS(e,t,n,r,o,i,s,a){let c=Ro(t),l=t.elements.get(e),u=n.nodes.get(e),d=r.get(e);if(!l||!u||!d)throw new Error(`Node not found: ${e}`);let f=FS(l.textSegments,i),g=iD(l);return{composition:c,key:e,tag:l.tag,...g?{linkSourceKind:g}:{},componentName:l.componentName,sourceFile:l.sourceFile,sourceLocator:TS(l),label:l.tag,capabilities:LS(e,t,l,d,f),provenanceChain:f?{editMode:f.editMode,diagnostics:f.diagnostics.map(p=>({code:p.code,message:p.message}))}:void 0,...s?{dynamicData:s}:{},...a?{properties:a}:{},textSegments:l.textSegments.map(p=>{let m=o.get(p.index);return{index:p.index,editable:DS(p,d,i?.get(p.index)??null),source:m?{kind:m.kind}:null}}),boundaryKind:l.boundaryKind,isOpaque:l.isOpaque,ancestors:wS(l,t)}}function iD(e){if(e.tag==="a")return"native-anchor";if(e.importedFrom==="next/link"&&e.exportName==="default")return"next-link";if(e.tag==="Link")return"unsupported"}function TS(e){return{sourceFile:e.sourceFile,componentName:e.componentName,openingElementRange:sD(e.sourceRange),structuralPath:e.identity.structuralPath,...aD(e.textSegments)}}function wS(e,t){let n=[],r=e.parentKey;for(;r;){let o=t.elements.get(r);if(!o)break;n.push({key:r,tag:o.tag,label:o.tag}),r=o.parentKey}return n.reverse(),n}function sD(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function aD(e){let t=e.map(n=>n.value.trim()).filter(Boolean).join(" ").replace(/\s+/g," ").trim();return t?{textPreview:t.slice(0,oD)}:{}}function OS(e,t){let n=t.find(r=>r.editable&&r.source&&r.source.kind!=="literal");return n?.source?{kind:"value-binding",file:n.source.file,componentName:e.componentName,isProxy:n.source.file!==e.file}:{kind:"jsx-node",file:e.file,componentName:e.componentName,isProxy:e.isProxy}}function FS(e,t){if(!t)return null;for(let n of e){let r=t.get(n.index);if(r)return r}return null}function LS(e,t,n,r,o){let i=n.identity.structuralPath.includes("#repeat:"),s=t.regions.some(u=>u.kind==="repeat-region"&&u.childKeys.includes(e)),a=o?.diagnostics.find(u=>u.code==="missing-adapter"||u.code==="external-source-readonly")?.code,c=r.canUpdateText?{mode:o?.editMode??"direct",reasonCode:a??(o?.editMode==="upstream"?"component-prop":o?.finalSource?.kind==="repeat-template"?"repeat-item-data":void 0)}:{mode:"unsupported",reasonCode:"capability-denied"},l=r.canUpdateText&&MS(c.mode);return{...r,canUpdateText:l,editModes:{updateText:c,insertChild:r.canInsertChild?{mode:"direct",reasonCode:i||s?"repeat-template":void 0}:{mode:"unsupported",reasonCode:"capability-denied"},move:r.canMove?{mode:s?"proxy":"direct",reasonCode:s?"repeat-collection":void 0}:{mode:"unsupported",reasonCode:"capability-denied"},remove:r.canRemove?{mode:s?"proxy":"direct",reasonCode:s?"repeat-collection":void 0}:{mode:"unsupported",reasonCode:"capability-denied"}}}}function DS(e,t,n){return!e.editable||!t.canUpdateText?!1:n?MS(n.editMode):!0}function MS(e){return e==="direct"||e==="proxy"||e==="upstream"}function cD(e){return{finalSource:e.finalSource?{kind:e.finalSource.kind,file:e.finalSource.file,displayPath:e.finalSource.displayPath,externalSource:e.finalSource.externalSource}:null,chain:e.chain.map(t=>({kind:t.kind,file:t.file,displayName:t.displayName,canEditHere:t.canEditHere})),confidence:e.confidence,editMode:e.editMode,diagnostics:e.diagnostics.map(t=>({code:t.code,message:t.message}))}}function lD(e,t){return t?.finalSource?t.finalSource.kind==="jsx-literal"?{kind:"jsx-node",file:e.file,isProxy:e.isProxy}:t.finalSource.kind==="config-entry"&&t.finalSource.locator?{kind:"value-path",file:t.finalSource.file,isProxy:t.finalSource.file!==e.file,displayPath:t.finalSource.displayPath}:rD(t.finalSource.kind)?{kind:"external-entry",file:t.finalSource.file,isProxy:!1,displayPath:t.finalSource.displayPath,sourceType:t.finalSource.externalSource?.sourceType,sourceId:t.finalSource.externalSource?.sourceId}:{kind:"value-path",file:t.finalSource.file,isProxy:t.finalSource.file!==e.file,displayPath:t.finalSource.displayPath}:{kind:e.kind==="route-export"?"route-export":"jsx-node",file:e.file,isProxy:e.isProxy}}var vp=["set-class-name-source","apply-style-draft"];function BS(e){let t=e.attributes?.find(n=>n.name==="className");if(!t)return{kind:"class-name-source",className:"",sourceKind:"missing",editable:!0,operationBoundary:vp,diagnostics:[{code:"missing-class-name",message:"No className attribute is present on this element"}]};if(t.resolution&&t.resolution.status!=="resolved")return{kind:"class-name-source",className:"",sourceKind:"dynamic-expression",editable:!1,operationBoundary:[],sourcePath:t.source?.expression,diagnostics:[{code:"dynamic-binding",message:"Style binding is unresolved and cannot be edited"}]};if(t.source?.expression){let n=t.source.expression,r=typeof t.resolvedValue=="string"?t.resolvedValue:t.value!==n?t.value:void 0;return typeof r!="string"?{kind:"class-name-source",className:"",sourceKind:"dynamic-expression",editable:!1,operationBoundary:[],sourcePath:n,diagnostics:[{code:t.resolvedValue===void 0?"dynamic-binding":"non-string-binding",message:t.resolvedValue===void 0?"Style binding is dynamic and cannot be edited":"Style binding must resolve to a static string before it can be edited"}]}:{kind:"class-name-source",className:r,sourceKind:"static-expression",editable:!0,operationBoundary:vp,sourcePath:n}}return{kind:"class-name-source",className:t.value,sourceKind:t.resolvedValue===void 0?"static-attribute":"static-expression",editable:!0,operationBoundary:vp}}import jS from"node:path";function _p(){let e=Promise.resolve();return{async runExclusive(t){let n,r=new Promise(i=>{n=i}),o=e;e=o.then(()=>r,()=>r),await o;try{return await t()}finally{n()}}}}async function VS(e,t,n){let r=[],o=new Set;for(let i of e.intents){let s=pD(i.path);if(!s.ok)return s;let a=s.path;if(o.has(a))return{ok:!1,code:"duplicate-target",path:a,reason:`Duplicate file target: ${a}`};if(o.add(a),i.kind==="create-only"){let c=t.has(a),l=n?await n(a):!1;if(c||l)return{ok:!1,code:"create-only-exists",path:a,reason:`Create-only file already exists: ${a}`}}r.push({...i,path:a})}return{ok:!0,plan:{operationId:e.operationId,intents:r}}}async function Qc(e){let t=()=>uD(e);return e.mutex?e.mutex.runExclusive(t):t()}async function uD(e){let t=await VS(e.plan,e.overlay,e.exists);if(!t.ok)return{ok:!1,stage:"precheck",reason:t.reason,error:t,recoveryRequired:!1};let n=dD(e.overlay,t.plan),r;try{r=await e.buildCandidate({overlay:n,plan:t.plan})}catch(l){return{ok:!1,stage:"build",reason:"Candidate build failed.",error:l,recoveryRequired:!1}}let o,i;try{o=await e.prepareHistory?.({candidate:r,plan:t.plan}),await e.reverify?.({candidate:r,plan:t.plan,history:o}),i=await e.writeCandidate({candidate:r,plan:t.plan}),await e.markCandidateWritten?.({candidate:r,plan:t.plan,history:o,receipt:i})}catch(l){return kp({candidate:r,plan:t.plan,failedStage:"commit",error:l,history:o,receipt:i,rollbackCandidate:e.rollbackCandidate})}let s=r;try{let l=await e.validateCandidate({candidate:r,plan:t.plan,receipt:i});l!==void 0&&(s=l)}catch(l){return kp({candidate:r,plan:t.plan,failedStage:"validate",error:l,history:o,receipt:i,rollbackCandidate:e.rollbackCandidate})}let a;try{a=await e.publishCandidate({candidate:s,plan:t.plan,history:o,receipt:i})}catch(l){return kp({candidate:s,plan:t.plan,failedStage:"publish",error:l,history:o,receipt:i,rollbackCandidate:e.rollbackCandidate})}let c={candidate:s,plan:t.plan,history:o,receipt:i,published:a};try{await e.swapCandidate?.(c)}catch(l){return $S("swap",l,"Live state swap failed after durable publish.")}try{await e.finalizeCandidate?.(c)}catch(l){return $S("finalize",l,"Transaction finalization failed after live state swap.")}try{e.emitCommitted?.({candidate:s,plan:t.plan,published:a})}catch{}return{ok:!0,stage:"publish",published:a,plan:t.plan}}function dD(e,t){let n=new Map(e);for(let r of t.intents)r.kind==="delete"?n.delete(r.path):n.set(r.path,r.content);return n}function kp(e){return e.rollbackCandidate({candidate:e.candidate,plan:e.plan,failedStage:e.failedStage,error:e.error,...e.history===void 0?{}:{history:e.history},...e.receipt===void 0?{}:{receipt:e.receipt}}).then(()=>({ok:!1,stage:e.failedStage,reason:fD(e.failedStage),error:e.error,recoveryRequired:!1})).catch(t=>({ok:!1,stage:"rollback",reason:"Rollback failed after candidate commit/validation/publish failure.",error:t,recoveryRequired:!0,cause:e.error}))}function $S(e,t,n){return{ok:!1,stage:e,reason:n,error:t,recoveryRequired:!0}}function fD(e){switch(e){case"commit":return"Candidate write or commit verification failed.";case"validate":return"Candidate validation failed.";case"publish":return"Candidate publish failed."}}function pD(e){if(e.length===0)return{ok:!1,code:"unsafe-path",path:e,reason:"File path must not be empty."};if(e.includes("\0")||e.includes("\\"))return{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`};if(/^[a-zA-Z]:/.test(e)||jS.isAbsolute(e))return{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`};let t=jS.posix.normalize(e);return t==="."||t===".."||t.startsWith("../")||t.includes("/../")?{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`}:t.startsWith("./")||t.includes("/./")?{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`}:{ok:!0,path:t}}var mD=50,gD=8*1024*1024;function XS(e,t={}){let n=[],r=[],o=t.externalAdapters??[],i=Math.max(0,t.maxUndoEntries??mD),s=Math.max(0,t.maxUndoBytes??gD);return{prepareRewritePlan:a,execute:c,executeFilePlan:l,undo:u,redo:d};async function a(v){let N=[...v.steps].sort(($,G)=>$.order-G.order),A=N.filter($=>$.type!=="invoke-external-adapter");if(A.length!==N.length)return{ok:!1,errorCode:"unsupported-operation",reason:"External adapter writes require a transactional prepare/commit/rollback contract."};let w=new Set(A.map($=>$.file)),F=await S(w),B=new Map(F.map($=>[$.file,$.exists===!1?"":$.content])),X;for(let $ of A){let G=JS($,B.get($.file)??"");if(!G.ok)return{ok:!1,errorCode:G.errorCode,reason:G.reason};B.set($.file,G.source),X=G.selectionRef??X}return{ok:!0,filePlan:{operationId:v.operationId,kind:"source-edit",target:v.target,documentVersion:v.documentVersion,conflictPolicy:"compare-and-swap",edits:[...B].map(([$,G])=>({operation:"upsert",file:$,content:G,baseContentHash:F.find(M=>M.file===$)?.sha256??null}))},...X?{selectionRef:X}:{}}}async function c(v){let N=[...v.steps].sort((M,fe)=>M.order-fe.order),A=N.filter(M=>M.type!=="invoke-external-adapter"),w=N.filter(M=>M.type==="invoke-external-adapter"),F=new Set(A.map(M=>M.file));if(A.length>0&&w.length>0)return{ok:!1,operationId:v.operationId,errorCode:"unsupported-operation",reason:"Mixed local file rewrites and external adapter writes require an explicit compensation contract.",rolledBack:!1};if(A.length===0)return y(v,w);let B=await S(F),X=new Map;for(let M of B)X.set(M.file,M.exists===!1?"":M.content);let $;for(let M of A){let fe=X.get(M.file)??"",Fe=JS(M,fe);if(!Fe.ok)return{ok:!1,operationId:v.operationId,errorCode:Fe.errorCode,reason:Fe.reason,rolledBack:!1};X.set(M.file,Fe.source),Fe.selectionRef&&($=Fe.selectionRef)}let G=await E([...X].map(([M,fe])=>({file:M,content:fe,exists:!0,version:0,sha256:ke(fe)})),B);return G.ok===!1?{ok:!1,operationId:v.operationId,errorCode:G.rolledBack?"writeback-failed":"rollback-failed",reason:G.reason,rolledBack:G.rolledBack}:(n.push({operationId:v.operationId,preSnapshots:B,postSnapshots:G.snapshots,plan:v}),f(),r.length=0,{ok:!0,operationId:v.operationId,kind:v.kind,target:v.target,resultVersion:Math.max(...G.snapshots.map(M=>M.version)),affectedFiles:[...F],...$?{selectionRef:$}:{}})}async function l(v){let N=new Set(v.edits.map(G=>G.file)),A=await S(N),w=x(v,A);if(w)return{ok:!1,operationId:v.operationId,errorCode:"stale-version",reason:w.reason,affectedFiles:[w.file],rolledBack:!1};let F=new Map(A.map(G=>[G.file,G])),B=v.edits.find(G=>G.operation==="create-only"&&F.get(G.file)?.exists!==!1);if(B)return{ok:!1,operationId:v.operationId,errorCode:"stale-version",reason:`MATERIALIZATION_INSTANCE_CONFLICT: create-only target already exists: ${B.file}`,affectedFiles:[B.file],rolledBack:!1};let X=v.edits.map(G=>G.operation==="delete"?{file:G.file,content:"",exists:!1,version:0}:{file:G.file,content:G.content,exists:!0,version:0,sha256:ke(G.content)}),$=await E(X,A,new Set(v.edits.filter(G=>G.operation==="create-only").map(G=>G.file)));return $.ok===!1?{ok:!1,operationId:v.operationId,errorCode:$.rolledBack?"writeback-failed":"rollback-failed",reason:$.reason,rolledBack:$.rolledBack}:(n.push({operationId:v.operationId,preSnapshots:A,postSnapshots:$.snapshots,plan:{operationId:v.operationId,kind:v.kind,target:v.target,documentVersion:v.documentVersion,steps:[],preSnapshots:A}}),f(),r.length=0,{ok:!0,operationId:v.operationId,kind:v.kind,target:v.target,resultVersion:Math.max(...$.snapshots.map(G=>G.version)),affectedFiles:[...N]})}async function u(){let v=n.at(-1);if(!v)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to undo"};let N=await E(v.preSnapshots,v.postSnapshots);return N.ok===!1?{ok:!1,operationId:v.operationId,errorCode:N.rolledBack?"writeback-failed":"rollback-failed",reason:N.reason,rolledBack:N.rolledBack}:(n.pop(),r.push(v),{ok:!0,operationId:v.operationId,kind:v.plan.kind,target:v.plan.target,resultVersion:Math.max(...N.snapshots.map(A=>A.version)),affectedFiles:v.preSnapshots.map(A=>A.file)})}async function d(){let v=r.at(-1);if(!v)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to redo"};let N=await E(v.postSnapshots,v.preSnapshots);return N.ok===!1?{ok:!1,operationId:v.operationId,errorCode:N.rolledBack?"writeback-failed":"rollback-failed",reason:N.reason,rolledBack:N.rolledBack}:(r.pop(),n.push(v),f(),{ok:!0,operationId:v.operationId,kind:v.plan.kind,target:v.plan.target,resultVersion:Math.max(...N.snapshots.map(A=>A.version)),affectedFiles:v.postSnapshots.map(A=>A.file)})}function f(){for(;n.length>i;)n.shift();for(;n.length>0&&g()>s;)n.shift()}function g(){return n.reduce((v,N)=>v+p(N),0)}function p(v){return m(v.preSnapshots)+m(v.postSnapshots)}function m(v){return v.reduce((N,A)=>N+A.file.length+A.content.length,0)}async function y(v,N){let A=[];for(let w of N){let F=w.capability??"write-text",B=o.find($=>$.sourceType===w.sourceType&&(w.adapterId===void 0||$.adapterId===w.adapterId)&&($.capabilities===void 0||$.capabilities.includes(F)));if(!B)return{ok:!1,operationId:v.operationId,errorCode:"unsupported-operation",reason:`No external adapter registered for ${w.sourceType}`,rolledBack:!1};let X=await B.execute(w);if(!X.ok)return{ok:!1,operationId:v.operationId,errorCode:"writeback-failed",reason:X.reason??`External adapter failed for ${w.sourceType}`,rolledBack:!1};A.push(w.file)}return{ok:!0,operationId:v.operationId,kind:v.kind,target:v.target,resultVersion:0,affectedFiles:A}}function x(v,N){if(v.conflictPolicy!=="compare-and-swap")return null;let A=new Map(N.map(w=>[w.file,w]));for(let w of v.edits){if(w.operation==="create-only")continue;if(w.baseContentHash===void 0)return{file:w.file,reason:`Source file ${w.file} is missing baseContentHash. Reopen the file before saving.`};let F=A.get(w.file),B=w.baseContentHash;if(B===null){if(F?.exists!==!1)return{file:w.file,reason:`Source file ${w.file} was created or changed before save.`};continue}if(!B)return{file:w.file,reason:`Source file ${w.file} is missing baseContentHash. Reopen the file before saving.`};if(F?.exists===!1||F?.sha256!==B)return{file:w.file,reason:`Source file ${w.file} changed before save. Reload or explicitly overwrite the newer version.`}}return null}async function S(v){let N=[];for(let A of v)N.push(await b(A));return N}async function b(v){if(!await e.exists(v))return{file:v,content:"",version:0,exists:!1};let A=Math.max(1,e.getVersion(v)),w=await e.readFile(v);return{file:v,content:w,version:A,exists:!0,sha256:ke(w)}}async function E(v,N,A=new Set){let w=[];try{for(let F of v){if(A.has(F.file)){if(!e.createExclusive)throw new Error("Create-only write requires atomic exclusive-create support.");await e.createExclusive(F.file,F.content)}else await k(F);let B=e.bumpVersion(F.file);w.push(F.file),F.version=B}}catch(F){let B=await I(N.filter($=>w.includes($.file)));if(B.ok===!1)return{ok:!1,reason:`Writeback failed, then rollback failed for ${B.failedFiles.join(", ")}: ${KS(F)}`,rolledBack:!1,instanceConflict:US(F)};let X=US(F);return{ok:!1,reason:`${X?"MATERIALIZATION_INSTANCE_CONFLICT: ":""}Writeback failed and committed files were restored: ${KS(F)}`,rolledBack:!0,instanceConflict:X}}return{ok:!0,snapshots:v.map(hD)}}async function k(v){if(v.exists===!1){await e.deleteFile(v.file);return}await e.writeFile(v.file,v.content)}async function I(v){let N=[];for(let A of v)try{await k(A),e.bumpVersion(A.file)}catch{N.push(A.file)}return N.length===0?{ok:!0}:{ok:!1,failedFiles:N}}}function US(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="EEXIST"}function hD(e){let t=e.exists!==!1;return{file:e.file,content:t?e.content:"",version:e.version,exists:t,...t?{sha256:ke(e.content)}:{}}}function KS(e){return e instanceof Error?e.message:String(e)}function JS(e,t){switch(e.type){case"invoke-external-adapter":return{ok:!1,reason:"External adapter steps must be executed asynchronously",errorCode:"unsupported-operation"};case"add-import":return It(sn({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-import":return It(Co({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-node":return It(qr({source:t,locator:e.locator,removeWhitespace:e.removeWhitespace}));case"insert-child":return It(on({source:t,locator:e.parentLocator,node:e.node,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"update-text":return It(ra({source:t,locator:e.locator,segmentIndex:e.segmentIndex,newText:e.newText}));case"update-value":return It(ki({source:t,locator:e.locator,next:e.value}));case"update-array-item":return It(ki({source:t,locator:e.locator,next:e.value}));case"insert-bound-array-item":return It(la({source:t,locator:e.locator,index:e.index,value:e.value}));case"insert-jsx-expression-child":return It(oa({source:t,locator:e.parentLocator,expression:e.expression,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"remove-bound-array-item":return It(ua({source:t,locator:e.locator,index:e.index}));case"move-array-item":return It(da({source:t,locator:e.locator,fromIndex:e.fromIndex,toIndex:e.toIndex}));case"move-node":return It(eo({source:t,locator:e.locator,targetParentLocator:e.targetParentLocator,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"move-repeat-template-child":return It(ia({source:t,locator:e.locator,targetParentLocator:e.targetParentLocator,placement:e.placement,anchorLocator:e.anchorLocator,repeatExpression:e.repeatExpression,selectionContext:e.selectionContext}));case"set-class-name-source":return yD(e,t);case"set-property-changes":return It(sa({source:t,locator:e.locator,changes:e.changes}));case"set-link-target":return It(aa({source:t,locator:e.locator,link:e.link,changes:e.changes}));case"set-property-binding":return It(ca({source:t,locator:e.locator,name:e.name,object:e.object,property:e.property}));case"upsert-object-property":return It(pa({source:t,objectLocator:e.locator,name:e.name,value:e.value}));default:return{ok:!1,reason:`Unknown step type: ${e.type}`,errorCode:"unknown"}}}function yD(e,t){let{request:n}=e;if(n.newAttrRaw!==null&&!rh(n.newAttrRaw))return{ok:!1,reason:"newAttrRaw must be a valid JSX className attribute.",errorCode:"invalid-params"};let r=n.oldAttrRange!==null&&n.oldAttrRaw!==null,o=n.openingElementRange.start,i=n.openingElementRange.end,s=t.slice(o,i);if(!(Number.isInteger(o)&&Number.isInteger(i)&&o>=0&&i>o&&i<=t.length&&s.startsWith("<")&&s.endsWith(">")&&!s.startsWith("</")&&(n.oldAttrRange===null||n.oldAttrRange.start>=o&&n.oldAttrRange.end<=i)))return{ok:!1,reason:"The opening element range changed before className save.",errorCode:"stale-version"};if(!r&&n.expectedVersion.contentHash!==ke(t))return{ok:!1,reason:"The source file changed before className save.",errorCode:"stale-version"};if(n.oldAttrRange){if(t.slice(n.oldAttrRange.start,n.oldAttrRange.end)!==n.oldAttrRaw)return{ok:!1,reason:"The className attribute changed before save.",errorCode:"stale-version"}}else if(n.oldAttrRaw!==null)return{ok:!1,reason:"The className attribute range no longer matches.",errorCode:"stale-version"};return{ok:!0,source:nh({source:t,oldAttrRange:n.oldAttrRange,openingElementRange:n.openingElementRange,newAttrRaw:n.newAttrRaw})}}function It(e){if(e.ok)return{ok:!0,source:e.source,...e.selectionRef?{selectionRef:e.selectionRef}:{}};switch(e.diagnostic.code){case"locator-miss":return{ok:!1,reason:e.diagnostic.message,errorCode:"locator-miss"};case"unsupported-syntax":case"binding-not-found":case"export-not-found":case"property-not-found":case"array-index-out-of-range":case"directive-conflict":case"metadata-shape-unsupported":return{ok:!1,reason:e.diagnostic.message,errorCode:"unsupported-operation"};case"invalid-parent-child-relation":case"self-closing-element":return{ok:!1,reason:e.diagnostic.message,errorCode:"invalid-target"};case"parse-failed":case"printer-failed":return{ok:!1,reason:e.diagnostic.message,errorCode:"ast-error"};default:return{ok:!1,reason:e.diagnostic.message,errorCode:"writeback-failed"}}}import{computeSiteEditCompositionKey as el,SiteEditCompositionContextSchema as xD,SiteEditCompositionSelectorSchema as bD}from"@vcp-dev/contracts";var At=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="SiteEditCompositionError"}};function zS(e,t){throw new At("INVALID_COMPOSITION",e,{value:t})}function tl(e){let t=xD.safeParse(e);return t.success?t.data:zS("Invalid SiteEditCompositionContext.",e)}function HS(e){let t=[],n=new Map,r=new Map;for(let l of e.compositions){let u=tl(l?.context);if(typeof l.entryFile!="string"||!l.entryFile)throw new At("INVALID_COMPOSITION","A registered composition must have a non-empty entryFile.");let d=el(u);if(n.has(d))throw new At("DUPLICATE_COMPOSITION",`Composition key ${d} is registered more than once.`,{key:d,context:u});let f=r.get(l.entryFile);if(f)throw new At("DUPLICATE_COMPOSITION",`Entry file ${l.entryFile} is registered more than once.`,{entryFile:l.entryFile,context:f});let g={context:u,entryFile:l.entryFile,key:d};t.push(g),n.set(d,g),r.set(l.entryFile,d)}if(t.length===0)throw new At("INVALID_COMPOSITION","At least one composition must be registered.");let o=new Map;for(let l of e.initialDocumentVersions??[]){let u=tl(l?.composition);if(!Number.isInteger(l?.version)||(l?.version??-1)<0)throw new At("INVALID_INITIAL_DOCUMENT_VERSION","Initial document version must be a non-negative integer.",{context:u,version:l?.version});let d=el(u);if(!n.has(d))throw new At("UNKNOWN_COMPOSITION","Initial document version references an unregistered composition.",{context:u,key:d});if(o.has(d))throw new At("DUPLICATE_COMPOSITION","Initial document versions must contain each composition at most once.",{context:u,key:d});o.set(d,l.version)}function i(l){let u=bD.safeParse(l);if(!u.success)return zS("Invalid SiteEditCompositionSelector.",l);let d=t.filter(({context:f})=>f.routeId===u.data.routeId&&(u.data.templateId===void 0?f.effectiveTemplateId===void 0:f.effectiveTemplateId===u.data.templateId));if(d.length===1)return d[0];throw d.length>1?new At("AMBIGUOUS_COMPOSITION","The composition selector matches multiple registered contexts.",{selector:u.data}):new At("UNKNOWN_COMPOSITION","The composition selector is not registered.",{selector:u.data})}function s(l){let u=tl(l),d=el(u),f=n.get(d);if(!f)throw new At("UNKNOWN_COMPOSITION","The composition context is not registered.",{context:u,key:d});return f}function a(l){let u=tl(l?.context);if(typeof l.entryFile!="string"||!l.entryFile)throw new At("INVALID_COMPOSITION","A registered composition must have a non-empty entryFile.");let d=el(u),f=n.get(d);if(f){if(f.entryFile===l.entryFile)return f;throw new At("DUPLICATE_COMPOSITION",`Composition key ${d} is registered more than once.`,{key:d,context:u})}let g=[...n.values()].find(m=>m.entryFile===l.entryFile);if(g)throw new At("DUPLICATE_COMPOSITION",`Entry file ${l.entryFile} is registered more than once.`,{entryFile:l.entryFile,context:g.context});let p={context:u,entryFile:l.entryFile,key:d};return t.push(p),n.set(d,p),p}function c(l){let u=n.get(l);if(!u)return;n.delete(l);let d=t.findIndex(f=>f.key===l);return d>=0&&t.splice(d,1),o.delete(l),u}return{entries:t,byKey:n,initialVersions:o,register:a,unregister:c,resolveSelector:i,resolveContext:s,getByKey:l=>n.get(l),routeIds:()=>[...new Set(t.map(({context:l})=>l.routeId))]}}function Cp(e){let t=new Map,n=new Map;return{readFile(r){let o=t.get(r);return o||(o=e.readFile(r),t.set(r,o)),o},exists(r){let o=n.get(r);return o||(o=e.exists(r),n.set(r,o)),o}}}async function WS(e,t){if(e.length===0)return[];if(e.length===1)return[await t(e[0])];let n=new Array(e.length),r=[],o=0,i=Array.from({length:Math.min(4,e.length)},async()=>{for(;o<e.length&&r.length===0;){let c=o++;try{n[c]=await t(e[c])}catch(l){r.push({index:c,error:l})}}}),s=await Promise.allSettled(i),a=r.sort((c,l)=>c.index-l.index)[0];if(a)throw a.error;for(let c of s)if(c.status==="rejected")throw c.reason;return n}import{composeSiteEditRepeatInstanceKey as ED,stripSiteEditRepeatInstanceKeys as GS}from"@vcp-dev/contracts";function YS(e){let t=new Map,n=new Map,r=new Map;for(let o of e.entries){t.set(o.key,o);let i=GS(o.key)??o.key;if(i===o.key)continue;let s=n.get(i)??0;r.set(o.key,s),n.set(i,s+1)}return{entriesByKey:t,repeatOccurrenceIndexByKey:r}}function SD(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 nl(e){return e?.map(t=>({...t}))}function Rp(e,t){if(t===null||e?.kind!=="value-binding"||e.sourceKind!=="repeat-template")return e;let n=e.collectionIndexMap?.[t]??t,r=nl(e.collectionPathMap?.[t])??nl(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:nl(e.path),locator:e.locator?{...e.locator,path:r}:e.locator,collectionIndexMap:e.collectionIndexMap?[...e.collectionIndexMap]:void 0,collectionPathMap:e.collectionPathMap?.map(o=>nl(o)??[])}}function ZS(e,t,n){let r=new Set;for(let g of t.regions)if(g.kind==="repeat-region")for(let p of g.childKeys)r.add(p);if(r.size===0)return e;let o=new Map(e.entries.map(g=>[g.key,g])),i=[],s=new Map,a=(g,p)=>ED(g,p),c=(g,p,m)=>{let y=o.get(g);if(!y)return a(g,m);let x=a(g,m),S={...y,key:x,parentKey:p,childKeys:[]};return i.push(S),S.childKeys=y.childKeys.flatMap(b=>l(b,m,x)),x},l=(g,p,m)=>{if(!r.has(g))return[c(g,m,p)];let y=d(g,p),x=[];for(let S=0;S<y;S+=1)x.push(c(g,m,[...p,S]));return x},u=Array.from(new Set([...e.rootKeys,...e.entries.filter(g=>g.parentKey===null).map(g=>g.key)]));for(let g of u){if(!r.has(g)){c(g,null,[]);continue}let p=d(g,[]);for(let m=0;m<p;m+=1)c(g,null,[m])}return{...e,rootKeys:[...e.rootKeys],entries:i};function d(g,p){let m=new Set;for(let y of f(g)){let x=n.get(y);if(x){for(let S of[...x.textTargets.values(),...x.elementPropertyTargets.values()])if(!(S?.kind!=="value-binding"||S.sourceKind!=="repeat-template"))for(let b of ID(S))b.length<=p.length||vD(b,p)&&m.add(b[p.length])}}return m.size>0?m.size:SD(n.get(g))}function f(g){let p=s.get(g);if(p)return p;let m=[g],y=o.get(g);for(let x of y?.childKeys??[])m.push(...f(x));return s.set(g,m),m}}function qS(e){let t=e.parts.at(-1);return typeof t?.repeatIndex=="number"?t.repeatIndex:null}function QS(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((GS(s.key)??s.key)===n){if(s.key===t)return i;i+=1}return null}function ID(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 vD(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 eI(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 tI(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}}function nI(e){return{path:e.path,code:e.code,message:e.message,...e.details?{details:JSON.parse(JSON.stringify(e.details))}:{}}}function kD(e){return e.map(t=>`${t.code} (${t.path}): ${t.message}`).join("; ")}var Is=class extends Error{constructor(t){let n=t.map(nI);super(kD(n)),this.name="RouteBuildDiagnosticsError",this.diagnostics=n}};function rI(e,t){let n=t instanceof Error&&t.message?t.message:String(t);return t instanceof Is?{routeId:e,message:n,diagnostics:t.diagnostics.map(nI)}:{routeId:e,message:n}}function Np(e){return e.map(({routeId:t,message:n})=>`${t}: ${n}`).join("; ")}function Pp(e,t){let n=new Map(e);for(let r of t)n.delete(r);return n}function vs(e,t){e.clear();for(let[n,r]of t)e.set(n,r)}function oI(e,t){for(let n of t){if(n.exists===!1){e.delete(n.file);continue}e.set(n.file,n.content)}}function rl(e,t,n,r){if(!e.has(t)&&e.size>=r){let o=e.keys().next().value;o&&e.delete(o)}e.set(t,n)}function iI(e){let{journal:t,index:n,observedFileDigests:r}=e;if(r.length!==t.files.length)return"ambiguous";let o=t.files.every((l,u)=>l.preDigest===r[u]),i=t.files.every((l,u)=>l.postDigest===r[u]),s=t.historyTransition,a=n.digest===s.expectedIndexDigest,c=n.digest===s.publishedIndexDigest&&n.cursor===s.publishedCursor&&n.currentId===s.publishedCurrentId;return o&&a?"safely-uncommitted":i&&c?"durably-committed":"ambiguous"}var wD=/^(?:src\/)?app\/.*\/?page\.[cm]?[jt]sx?$/,OD=["layout.tsx","layout.ts","layout.jsx","layout.js","layout.mjs","layout.cjs"],sI=32,il=256;function FD(e){return{expectedIndexDigest:e.digest,publishedIndexDigest:e.digest,publishedCursor:e.cursor,publishedCurrentId:e.currentId}}var aI={maxEntries:50,maxBytes:8*1024*1024};function LD(){let e=new Map;return{async readFile(t){return(await import("node:fs/promises")).readFile(t,"utf-8")},async readFileBytes(t){return(await import("node:fs/promises")).readFile(t)},async getFileInfo(t){let n=await import("node:fs/promises");try{let r=await n.lstat(t);return!r.isFile()||r.isSymbolicLink()?null:{path:t,sizeBytes:r.size}}catch{return null}},async writeFile(t,n){await ha(t,n)},async deleteFile(t){await(await import("node:fs/promises")).rm(t,{force:!0})},async exists(t){let n=await import("node:fs/promises");try{return await n.access(t),!0}catch{return!1}},getVersion(t){return e.get(t)??1},bumpVersion(t){let n=(e.get(t)??1)+1;return e.set(t,n),n}}}async function cI(e,t){if(t.length===0)return[];let n;try{n=JSON.parse(await e.readFile("package.json"))}catch{return[]}if(!n||typeof n!="object")return[];let r=n.dependencies;return!r||typeof r!="object"||Array.isArray(r)?[]:t.filter(o=>{if(!Object.prototype.hasOwnProperty.call(r,o))return!1;let i=r[o];return typeof i=="string"&&i.trim().length>0})}function DD(){let e=[],t=[];return{prepareAppend(r){return{kind:"append",entry:r}},prepareUndo(){let r=e.at(-1);return r?{kind:"undo",entry:r}:null},prepareRedo(){let r=t.at(-1);return r?{kind:"redo",entry:r}:null},publishPrepared(r){if(r.kind==="append"){e.push(r.entry),n(),t.length=0;return}if(r.kind==="undo"){if(e.at(-1)!==r.entry)throw new Error("undo history changed before publish");e.pop(),t.push(r.entry);return}if(t.at(-1)!==r.entry)throw new Error("redo history changed before publish");t.pop(),e.push(r.entry),n()},peekUndo(){return e.at(-1)??null},pushUndo(r){e.push(r),n(),t.length=0},popUndo(){return e.pop()??null},peekRedo(){return t.at(-1)??null},pushRedo(r){t.push(r)},popRedo(){return t.pop()??null},clearRedo(){t.length=0},getStatus(){return{canUndo:e.length>0,canRedo:t.length>0,undoDepth:e.length,redoDepth:t.length,recoveryRequired:!1}}};function n(){for(;e.length>aI.maxEntries||MD(e)>aI.maxBytes;)e.shift()}}function MD(e){return e.reduce((t,n)=>t+BD(n),0)}function BD(e){return lI(e.preSnapshots)+lI(e.postSnapshots)+jD(e.provenance)}function jD(e){return e?new TextEncoder().encode(JSON.stringify(e)).byteLength:0}function lI(e){return e.reduce((t,n)=>t+n.file.length+n.content.length,0)}function uI(e,t){return{key:CD(e),composition:e,routeId:e.routeId,entryFile:t,graph:null,topology:null,capabilities:null,document:null,pageBlockIndex:null,pageComposition:null,pageCompositionProjection:null,documentIndex:null,pagePlacementByKey:null,pagePlacementUnitByKey:null,pageUnitByKey:null,pagePlacementsByUnitKey:null,dependencyFiles:new Set([t]),detailProjections:null,fileVersions:new Map,styleContext:null}}var sl=class extends Error{constructor(t){super(t.reason),this.result=t}},yo=class extends Error{constructor(t){super(Np(t)),this.failedRoutes=t}};function dI(e,t){if(!e)return;let n=[...t];if(n.some(o=>o?.entries.some(i=>i.key===e.key)))return e;let r=$t(e.key)??e.key;for(let o of n){let i=o?.entries.find(s=>($t(s.key)??s.key)===r);if(i)return{...e,key:i.key}}return e}function $D(e,t,n){if(!n)return;let r=$t(n.key)??n.key;if(n.key!==e&&n.key!==t&&r!==t)throw new Error(`Selection reference '${n.key}' does not match selected key '${e}'`);if(n.instanceIndex!==void 0&&(!Number.isInteger(n.instanceIndex)||n.instanceIndex<0))throw new Error("Selection reference instanceIndex must be non-negative");if(n.instanceCount!==void 0&&(!Number.isInteger(n.instanceCount)||n.instanceCount<=0))throw new Error("Selection reference instanceCount must be positive");if(n.instanceIndex!==void 0&&n.instanceCount!==void 0&&n.instanceIndex>=n.instanceCount)throw new Error("Selection reference instanceIndex must be smaller than instanceCount");return{...n,key:t}}var VD=/\.(?:[cm]?[jt]sx?)$/i,UD=/\.json$/i,KD=/\.(?:css|scss|sass)$/i,JD=/\.mdx$/i,XD=/\.ya?ml$/i;function zD(e){if(!e||e.kind!=="value-binding")return null;let t="path"in e?e.path:void 0,n=e.root,r=n&&(n.kind==="binding"||n.kind==="named-export")?n.name:void 0;return{kind:e.sourceKind,file:e.file,expression:e.displayExpression,bindingName:r,path:t?.map(o=>o.kind==="property"?o.name:o.index)}}function HD(e){return{kind:e.isProxy?"component-proxy":"jsx-node",file:e.file,componentName:e.componentName,isProxy:e.isProxy}}function WD(e,t){let n=new Map;for(let i of t)n.set(i.path,i.operation==="delete"?{exists:!1}:{exists:!0,content:i.content});let r=new Map,o=new Map;return{async readFile(i){let s=n.get(i);if(s){if(!s.exists)throw new Error(`Source file not found: ${i}`);return s.content}let a=r.get(i);return a||(a=e.readFile(i),r.set(i,a)),a},async writeFile(){throw new Error("Source edit preflight overlay is read-only.")},async deleteFile(){throw new Error("Source edit preflight overlay is read-only.")},async exists(i){let s=n.get(i);if(s)return s.exists;let a=o.get(i);return a||(a=e.exists(i),o.set(i,a)),a},async getFileInfo(i){let s=n.get(i);return s?s.exists?{path:i,sizeBytes:Buffer.byteLength(s.content,"utf8")}:null:e.getFileInfo?.(i)??null},async listFiles(i={}){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let s=yI(await e.listFiles(i)),a=new Map(s.files.map(l=>[l.path,l]));for(let[l,u]of n)if(GD(l,i.roots??[])){if(!u.exists){a.delete(l);continue}a.set(l,{path:l,sizeBytes:Buffer.byteLength(u.content,"utf8")})}let c=[...a.values()].sort((l,u)=>l.path.localeCompare(u.path));return s.truncated?{files:c,truncated:s.truncated}:c},getVersion(i){return e.getVersion(i)},bumpVersion(i){return e.getVersion(i)}}}function GD(e,t){return t.length===0?!0:t.some(n=>e===n||e.startsWith(`${n}/`))}function yI(e){return Array.isArray(e)?{files:e}:e}function YD(e){if(!ND(e.path))return{ok:!1,errorCode:"invalid-params",message:`Source file is read-only: ${e.path}`,details:{path:e.path}};if(e.operation==="upsert"&&e.content.includes("\0"))return{ok:!1,errorCode:"invalid-params",message:`Source file content must be valid text: ${e.path}`,details:{path:e.path}};if(e.operation==="delete"){if(e.capability!==AD||e.confirmDelete!==!0||e.confirmPath!==e.path)return{ok:!1,errorCode:"capability-denied",message:`Source file delete requires explicit confirmation: ${e.path}`,details:{path:e.path}};let t=RD(e.path);return t?{ok:!1,errorCode:"capability-denied",message:`Protected source file cannot be deleted: ${e.path}`,details:{path:e.path,protectionReason:t}}:{ok:!0}}if(VD.test(e.path)){let t=Rn({source:e.content,profile:zr({filePath:e.path,source:e.content})});if(!t.ok)return{ok:!1,errorCode:"ast-error",message:t.diagnostic.message,details:{path:e.path}}}if(UD.test(e.path))try{JSON.parse(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`JSON parse failed: ${Ot(t)}`,details:{path:e.path}}}if(KD.test(e.path)){let t=fI({content:e.content,path:e.path,profile:"css"});if(!t.ok)return t}if(JD.test(e.path)){let t=fI({content:e.content,path:e.path,profile:"mdx"});if(!t.ok)return t}if(XD.test(e.path))try{TD(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`YAML parse failed: ${Ot(t)}`,details:{path:e.path}}}return{ok:!0}}function fI({content:e,path:t,profile:n}){let r=[],o=null,i=!1,s=!1,a=!1,c=!1,l=!0;for(let d=0;d<e.length;d+=1){let f=e[d]??"",g=e[d+1]??"";if(n==="mdx"&&l&&e.startsWith("```",d)){c=!c;let p=e.indexOf(`
6
+ `,i.index),g=e.slice(n[d]??0,f===-1?void 0:f).trim();o.push({token:a,variant:u?.[1]??"",alpha:c?Number(c[1]):null,line:d+1,snippet:g.length>ay?`${g.slice(0,ay-1)}\u2026`:g})}return o}function ja(e){return[...new Set(e)]}var kP=["@/components/site/","@/lib/generated/","@/lib/cms","@/lib/cms/"],_P=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),dy=new Set(["require","module","exports","__dirname","__filename"]),id=SP,CP=typeof id=="function"?id:id.default;function ad(e,t={}){let n=[],r=RP(t.hostCapabilities),o=od(e,t.style??cy),i;try{i=EP(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return{ok:!1,violations:[{code:"parse-failed",message:"Generated source failed Babel parsing."}],styleViolations:o}}t.themeStyleMode==="reject"&&PP(o)&&n.push({code:"style-forbidden",message:"Generated source must use public semantic design tokens instead of raw colors, hard-coded surfaces, or private tokens."});let s=u=>{n.some(f=>f.code===u.code&&f.name===u.name&&f.source===u.source)||n.push(u)};return CP(i,{ImportDeclaration(u){a(u.node.source.value)},ExportNamedDeclaration(u){let d=u.node.source?.value;d&&a(d)},ExportAllDeclaration(u){a(u.node.source.value)},CallExpression(u){let d=u.node.callee;if(d.type==="Import"){s({code:"dynamic-import-forbidden",message:"Generated source cannot use dynamic import()."});return}d.type==="Identifier"&&(d.name==="require"?s({code:"commonjs-forbidden",message:"Generated source cannot use CommonJS require().",name:d.name}):(d.name==="eval"||d.name==="Function")&&s({code:"dynamic-code-forbidden",message:`Generated source cannot execute dynamic code through ${d.name}().`,name:d.name}))},NewExpression(u){u.node.callee.type==="Identifier"&&u.node.callee.name==="Function"&&s({code:"dynamic-code-forbidden",message:"Generated source cannot construct functions dynamically through Function().",name:"Function"})},MetaProperty(u){u.node.meta.type==="Identifier"&&u.node.meta.name==="import"&&s({code:"import-meta-forbidden",message:"Generated source cannot use import.meta."})},MemberExpression(u){l(sd(u.node))},OptionalMemberExpression(u){l(sd(u.node))},Identifier(u){u.isReferencedIdentifier()&&l(u.node.name)},JSXAttribute(u){t.rejectInlineStyles&&u.node.name.type==="JSXIdentifier"&&u.node.name.name==="style"&&s({code:"inline-style-forbidden",message:"Generated source cannot use inline style attributes."})},JSXOpeningElement(u){t.rejectStyleElements&&u.node.name.type==="JSXIdentifier"&&u.node.name.name.toLowerCase()==="style"&&s({code:"inline-style-forbidden",message:"Generated source cannot declare style elements."})}}),{ok:n.length===0,violations:n,styleViolations:o};function a(u){if(!(t.trustedManagedImports?.includes(u)&&vP.safeParse(/^@\/components\/site\/generated\/forms\/form-([^/]+)$/u.exec(u)?.[1]).success)&&!(u.startsWith("./")||u.startsWith("../"))){if(t.allowSiteOwnedImports&&kP.some(d=>d.endsWith("/")?u.startsWith(d):u===d)){c(u);return}r?NP(u,r)||s({code:"import-forbidden",message:`Generated source imports a package or public path outside the trusted host capabilities: ${u}.`,source:u}):s({code:t.hostCapabilities===void 0?"host-capabilities-unavailable":"host-capabilities-invalid",message:"Generated code cannot use an external import without trusted host capabilities.",source:u}),c(u)}}function c(u){t.protectedImportPrefixes?.some(d=>u.startsWith(d))&&s({code:"protected-import-forbidden",message:`Generated source cannot import protected host output directly: ${u}.`,source:u})}function l(u){if(!(!u||!_P.has(u))){if(u==="eval"||u==="Function"){s({code:"dynamic-code-forbidden",message:`Generated source cannot execute dynamic code through ${u}.`,name:u});return}s({code:dy.has(u)?"commonjs-forbidden":"browser-global-forbidden",message:dy.has(u)?`Generated source cannot depend on the CommonJS global ${u}.`:`Generated source cannot depend on the restricted global ${u}.`,name:u})}}}function RP(e){if(e==null)return null;let t=IP.safeParse(e);return t.success?t.data:null}function NP(e,t){if(t.runtime_dependencies.some(({name:r})=>e===r||e.startsWith(`${r}/`)))return!0;if(!e.startsWith("@/"))return!1;let n=e.slice(2);return t.public_paths.some(r=>{let[o]=r.split("#",1);return o.endsWith("/*")?n.startsWith(o.slice(0,-1)):fy(n)===fy(o)})}function fy(e){return e.replace(/\.(?:jsx?|tsx?|json)$/i,"")}function PP(e){return e.hardCodedSurfaceHits.length>0||e.rawColorHits.length>0||e.privateTokenHits.length>0}function sd(e){return e.type==="Identifier"?e.name:e.type==="MemberExpression"||e.type==="OptionalMemberExpression"?sd(e.object):null}var by="components/site/generated",my="{{$INSTANCE}}",Va=5,DP=/^[a-z][a-z0-9-]{0,48}$/,BP=/^[a-f0-9]{8}$/,gy=/\.tsx?$/,jP=/\.json$/,$P=/\.(?:tsx?|json)$/,VP=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,cd=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),ld=wP,UP=typeof ld=="function"?ld:ld.default;function KP(e){let t=Array.isArray(e.manifest.files)?e.manifest.files:[];if(t.length>py)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file count exceeds the reusable limit."}};let n=oA(t);if(n)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Static prefab resolves duplicate target path: ${n}`,path:n}};let r=LP.safeParse(e.manifest);if(!r.success)return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab manifest failed schema validation."}};let o=tA(e.generatedRoot);if(!o)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Generated root must be ${by}.`,path:e.generatedRoot}};if(!Ey(r.data.instanceBaseName))return{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_INVALID",message:"Static prefab instanceBaseName must contain at least one safe word.",path:r.data.instanceBaseName}};let i=yy(r.data.files),s=yy(e.controlledFiles);if(!iA(i,s))return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Controlled file list must exactly match the manifest file templates."}};if(i.size>py)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file count exceeds the reusable limit."}};let a=0;for(let[c,l]of r.data.files.entries()){let u=Buffer.byteLength(l.content,"utf8");if(u>OP)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file exceeds the per-file content limit.",file:l.pathTemplate,path:`files[${c}]`}};a+=u}return a>FP?{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab exceeds the reusable total content limit."}}:{ok:!0,data:{kind:"static-prefab-materialization",instanceName:"",generatedRoot:o,instanceRoot:"",entry:{path:"",export:r.data.entry.export},files:[]}}}async function JP(e){let t=KP(e);if(!t.ok)return t;let n=t.data.generatedRoot,r=Ey(e.manifest.instanceBaseName),o=Math.max(1,Math.min(Va,e.maxAttempts??Va));for(let i=0;i<o;i+=1){let s=nA(e.instanceNameGenerator?.()??AP(4).toString("hex"));if(!s)return{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_INVALID",message:"Static prefab instance suffix must be 8 lowercase hex chars."}};let a=`${r}-${s}`,c=Iy(n,a),l=XP({manifest:e.manifest,generatedRoot:n,instanceName:a,instanceRoot:c,hostCapabilities:e.hostCapabilities??null,availableHostDependencies:e.availableHostDependencies});if(!l.ok)return l;if(!await HP(e.exists,c,l.data.files))return{ok:!0,data:l.data}}return{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:"Unable to allocate a create-only static prefab instance after repeated conflicts."}}}async function ud(e){let t=Math.max(1,Math.min(Va,e.maxAttempts??Va));for(let n=0;n<t;n+=1){let r=await JP({...e,maxAttempts:1});if(!r.ok){if(r.error.code==="MATERIALIZATION_INSTANCE_CONFLICT")continue;return r}let o=await e.commit(r.data);if(o.ok)return{ok:!0,plan:r.data,data:o.data};if(o.error.code!=="MATERIALIZATION_INSTANCE_CONFLICT")return o}return{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:"Unable to commit a complete static prefab instance after repeated conflicts."}}}function XP(e){let t=zP(e);if(t)return{ok:!1,error:t};let n=[],r=new Set;for(let s of e.manifest.files){let a=Mi({pathTemplate:s.pathTemplate,generatedRoot:e.generatedRoot,instanceName:e.instanceName,instanceRoot:e.instanceRoot});if(!a.ok)return a;if(r.has(a.data))return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Static prefab resolves duplicate target path: ${a.data}`,path:a.data}};r.add(a.data),n.push({kind:"create-only",path:a.data,content:s.content,...s.role?{role:s.role}:{},sourcePathTemplate:s.pathTemplate})}n.sort((s,a)=>s.path.localeCompare(a.path));let o=Mi({pathTemplate:e.manifest.entry.pathTemplate,generatedRoot:e.generatedRoot,instanceName:e.instanceName,instanceRoot:e.instanceRoot});if(!o.ok)return o;if(!n.some(s=>s.path===o.data))return{ok:!1,error:{code:"MATERIALIZATION_ENTRY_INVALID",message:"Entry path must match one of the static prefab files.",path:o.data}};let i=dd({files:n,instanceRoot:e.instanceRoot,entries:[{path:o.data,export:e.manifest.entry.export}],hostCapabilities:e.hostCapabilities,declaredProjectDependencies:Object.keys(e.manifest.projectDependencies??{}),availableHostDependencies:e.availableHostDependencies});return i.ok?{ok:!0,data:{kind:"static-prefab-materialization",instanceName:e.instanceName,generatedRoot:e.generatedRoot,instanceRoot:e.instanceRoot,entry:{path:o.data,export:e.manifest.entry.export},files:n}}:i}function zP(e){if(e.availableHostDependencies===void 0)return null;let t=new Set(Object.keys(e.manifest.projectDependencies??{})),n=new Set(e.availableHostDependencies);return n.size!==e.availableHostDependencies.length||[...n].some(r=>!t.has(r))?{code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Target host dependency evidence must match declared materialization dependencies."}:[...t].some(r=>!n.has(r))?{code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"The target host does not provide every declared materialization dependency."}:[...t].some(r=>!e.hostCapabilities?.runtime_dependencies.some(({name:o})=>o===r))?{code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Materialization dependencies exceed the trusted host capability contract."}:null}async function HP(e,t,n){if(await e(t))return!0;for(let r of n)if(await e(r.path))return!0;return!1}function Mi(e){if(e.pathTemplate.split(my).length!==2)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:"Static prefab path templates must include the instance placeholder exactly once.",path:e.pathTemplate}};let t=e.pathTemplate.replaceAll(my,e.instanceName),n=rA(t);return n?Iy(e.generatedRoot,e.instanceName)!==e.instanceRoot?{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:"Static prefab instance root normalization failed.",path:e.pathTemplate}}:n!==e.instanceRoot&&!n.startsWith(`${e.instanceRoot}/`)?{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:"Static prefab path must stay under components/site/generated/<instance>.",path:n}}:n!==t?{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:"Static prefab path template cannot rely on path normalization semantics.",path:e.pathTemplate}}:n===e.instanceRoot||!$P.test(n)||VP.test(n)?{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:"Static prefab files must be .ts/.tsx/.json files and cannot be config, layout, provider, or global source files.",path:n}}:{ok:!0,data:n}:{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:"Static prefab path template resolves to an unsafe path.",path:e.pathTemplate}}}function dd(e){let{files:t,instanceRoot:n,entries:r,hostCapabilities:o}=e,i=new Set(e.declaredProjectDependencies??[]),s=e.availableHostDependencies===void 0?null:new Set(e.availableHostDependencies),a=new Set(t.map(g=>g.path)),c=new Map,l=new Map(t.map(g=>[g.path,new Set])),u=new Map;for(let g of t){if(jP.test(g.path)){if(g.path.endsWith($a)){let x=MP(g.content);if(!x.success)return Yn("MATERIALIZATION_DATA_UNSUPPORTED",x.error.message,g.path);u.set(g.path,new Set)}else try{JSON.parse(g.content)}catch{return Yn("MATERIALIZATION_DATA_UNSUPPORTED","Static prefab JSON file must contain valid JSON.",g.path)}continue}let p;try{p=TP(g.content,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files must parse as plain module source.",file:g.path}}}let m=ad(g.content,{hostCapabilities:o,protectedImportPrefixes:["@/components/site/generated/"],trustedManagedImports:e.trustedManagedImports,rejectInlineStyles:!1,rejectStyleElements:!0,themeStyleMode:e.preserveCapturedStyles?"report":"ignore",style:{colorMixPolicy:"always",includeExtendedColorFunctions:!0,includeRgbBackgroundImage:!0,rejectAnyRawColorLiteral:!1,rejectPrivateTokens:!1,rejectTailwindPalette:!1}}),y=GP(m.violations,g.path);if(y)return{ok:!1,error:y};c.set(g.path,p)}for(let g of t){if(!gy.test(g.path))continue;let p=c.get(g.path),m=null;if(UP(p,{ImportDeclaration(y){let x=hy({importer:g.path,source:y.node.source.value,instanceRoot:n,filePaths:a});if(!x.allowed)m??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab imports must resolve within the controlled instance or match the starter allowlist.",file:g.path},y.stop();else if(!x.internalPath&&!YP(y.node.source.value,i,s))m??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"External prefab imports must be declared and available in the target host.",file:g.path},y.stop();else if(x.internalPath&&(l.get(g.path).add(x.internalPath),x.internalPath.endsWith($a))){let S=qP({importer:g.path,imported:x.internalPath,source:y.node.source.value,ast:p});S.ok?u.get(x.internalPath).add(g.path):(m??=S.error,y.stop())}},ExportAllDeclaration(y){m??={code:"MATERIALIZATION_ENTRY_INVALID",message:"Static prefab files cannot use export-star declarations.",file:g.path},y.stop()},ExportNamedDeclaration(y){if(y.node.source){let x=hy({importer:g.path,source:y.node.source.value,instanceRoot:n,filePaths:a});!x.allowed||!x.internalPath&&!e.trustedManagedImports?.includes(y.node.source.value)?(m??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab re-exports must resolve within the controlled instance.",file:g.path},y.stop()):x.internalPath&&l.get(g.path).add(x.internalPath)}},CallExpression(y){if(y.node.callee.type==="Import"){m??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab files cannot use dynamic import().",file:g.path},y.stop();return}y.node.callee.type==="Identifier"&&y.node.callee.name==="require"&&(m??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab files cannot use require().",file:g.path},y.stop())},NewExpression(y){y.node.callee.type==="Identifier"&&y.node.callee.name==="Function"&&(m??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot construct functions dynamically.",file:g.path},y.stop())},MetaProperty(y){y.node.meta.type==="Identifier"&&y.node.meta.name==="import"&&(m??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot use import.meta.",file:g.path},y.stop())},MemberExpression(y){let x=xy(y.node);x&&cd.has(x)&&(m??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${x}.`,file:g.path},y.stop())},OptionalMemberExpression(y){let x=xy(y.node);x&&cd.has(x)&&(m??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${x}.`,file:g.path},y.stop())},Identifier(y){y.isReferencedIdentifier()&&cd.has(y.node.name)&&(m??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${y.node.name}.`,file:g.path},y.stop())},JSXAttribute(y){!e.preserveCapturedStyles||y.node.name.type!=="JSXIdentifier"||y.node.name.name!=="style"||WP(y.node.value)||(m??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot use inline style attributes.",file:g.path},y.stop())},JSXOpeningElement(y){y.node.name.type==="JSXIdentifier"&&y.node.name.name.toLowerCase()==="style"&&(m??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot declare style elements.",file:g.path},y.stop())},StringLiteral(y){e.preserveCapturedStyles&&Ua(y.node.value)&&(m??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Captured styles cannot load URLs or execute CSS expressions.",file:g.path},y.stop())},TemplateElement(y){e.preserveCapturedStyles&&Ua(y.node.value.cooked??y.node.value.raw)&&(m??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Captured styles cannot load URLs or execute CSS expressions.",file:g.path},y.stop())},JSXElement(y){let x=y.node.openingElement.name;e.preserveCapturedStyles&&x.type==="JSXIdentifier"&&["script","iframe","object","embed"].includes(x.name.toLowerCase())&&(m??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Captured components cannot embed executable external documents.",file:g.path},y.stop())}}),m)return{ok:!1,error:m}}if(r.length===0)return Yn("MATERIALIZATION_ENTRY_INVALID","Static prefab requires at least one source entry.");let d=new Set;for(let g of r){if(d.has(g.path))return Yn("MATERIALIZATION_PATH_INVALID",`Static prefab contains duplicate source entries: ${g.path}`,g.path);if(d.add(g.path),!gy.test(g.path))return Yn("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must be a .ts/.tsx source module.",g.path);let p=c.get(g.path);if(!p)return Yn("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must resolve to a controlled source file.",g.path);if(!QP(p,g.export))return Yn("MATERIALIZATION_EXPORT_MISSING","Static prefab entry does not declare the manifest export.",g.path)}for(let[g,p]of u)if(p.size!==1)return Yn("MATERIALIZATION_IMPORT_FORBIDDEN","Each component .i18n.json file must have exactly one same-name Client Component static importer.",g);let f=new Set;for(let g of r)for(let p of eA(g.path,l))f.add(p);return f.size!==t.length?Yn("MATERIALIZATION_ENTRY_INVALID","Every controlled source file must be reachable from the entry module.",r[0]?.path):{ok:!0}}function Ua(e){return/(?:url|expression)\s*\(|@import|javascript:|-moz-binding|\\/iu.test(e)}function WP(e){return e?.type!=="JSXExpressionContainer"||e.expression.type!=="ObjectExpression"?!1:e.expression.properties.every(t=>{if(t.type!=="ObjectProperty"||t.computed)return!1;let n=t.key.type==="Identifier"?t.key.name:t.key.type==="StringLiteral"?t.key.value:null;if(!n||n==="__proto__"||n==="constructor"||n==="prototype"||Ua(n))return!1;let r=t.value;return r.type==="StringLiteral"&&!Ua(r.value)||r.type==="NumericLiteral"||r.type==="NullLiteral"||r.type==="UnaryExpression"&&["-","+"].includes(r.operator)&&r.argument.type==="NumericLiteral"})}function GP(e,t){let n=e[0];if(!n)return null;let r=new Set(["host-capabilities-unavailable","host-capabilities-invalid","import-forbidden","protected-import-forbidden","dynamic-import-forbidden","commonjs-forbidden"]),o=new Set(["inline-style-forbidden","style-forbidden"]);return{code:r.has(n.code)?"MATERIALIZATION_IMPORT_FORBIDDEN":o.has(n.code)?"MATERIALIZATION_STYLE_FORBIDDEN":"MATERIALIZATION_DATA_UNSUPPORTED",message:n.message,file:t}}function hy(e){if(!e.source.startsWith("./")&&!e.source.startsWith("../"))return{allowed:!0};if(e.source.includes("\\")||e.source.includes("\0"))return{allowed:!1};let t=Zn.posix.normalize(Zn.posix.join(Zn.posix.dirname(e.importer),e.source));if(t===e.instanceRoot||!t.startsWith(`${e.instanceRoot}/`))return{allowed:!1};let r=[t,`${t}.ts`,`${t}.tsx`,`${t}.json`,...["ts","tsx","json"].map(o=>`${t}/index.${o}`)].find(o=>e.filePaths.has(o));return r?{allowed:!0,internalPath:r}:{allowed:!1}}function YP(e,t,n){if(n===null)return!0;let r=ZP(e);return r===null||t.has(r)&&n.has(r)}function ZP(e){if(e.startsWith("@/")||e.startsWith("./")||e.startsWith("../")||e.startsWith("/"))return null;if(e.startsWith("@")){let[t,n]=e.split("/");return t&&n?`${t}/${n}`:e}return e.split("/")[0]||null}function qP(e){let t=Zn.posix.dirname(e.importer),n=Zn.posix.dirname(e.imported),r=Zn.posix.basename(e.importer).replace(/\.tsx?$/,""),o=Zn.posix.basename(e.imported).slice(0,-$a.length),i=`./${r}${$a}`;return!e.importer.endsWith(".tsx")||t!==n||r!==o||e.source!==i?{ok:!1,error:{code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Component i18n resources must use an explicit same-directory, same-name import from a .tsx file.",file:e.importer}}:e.ast.program.directives.some(a=>a.value.value==="use client")?{ok:!0}:{ok:!1,error:{code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:'A component that imports .i18n.json must declare the top-level "use client" directive.',file:e.importer}}}function QP(e,t){for(let n of e.program.body){if(t.kind==="default"&&n.type==="ExportDefaultDeclaration"||t.kind==="default"&&n.type==="ExportNamedDeclaration"&&n.exportKind!=="type"&&n.specifiers.some(o=>o.type==="ExportSpecifier"&&o.exportKind!=="type"&&o.exported.type==="Identifier"&&o.exported.name==="default"))return!0;if(t.kind!=="named"||n.type!=="ExportNamedDeclaration")continue;if(n.specifiers.some(o=>o.exported.type==="Identifier"&&o.exported.name===t.name))return!0;let r=n.declaration;if((r?.type==="FunctionDeclaration"||r?.type==="ClassDeclaration")&&r.id?.name===t.name||r?.type==="VariableDeclaration"&&r.declarations.some(o=>o.id.type==="Identifier"&&o.id.name===t.name))return!0}return!1}function eA(e,t){let n=new Set,r=[e];for(;r.length>0;){let o=r.pop();n.has(o)||(n.add(o),r.push(...t.get(o)??[]))}return n}function Yn(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{file:n}:{}}}}function tA(e){let t=Sy(e);return t===by?t:null}function nA(e){let t=e.trim().toLowerCase();return BP.test(t)?t:null}function Ey(e){let t=e.trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,49).replace(/-+$/g,"");return DP.test(t)?t:null}function Sy(e){if(!e||e.startsWith("/")||e.includes("\\"))return null;let t=Zn.posix.normalize(e);return t==="."||t.startsWith("../")||t.includes("/../")||t.includes("//")?null:t}function rA(e){let t=Sy(e);return!t||t!==e?null:t}function Iy(...e){return Zn.posix.join(...e)}function yy(e){return new Set(e.map(t=>t.pathTemplate))}function oA(e){let t=new Set;for(let n of e){if(t.has(n.pathTemplate))return n.pathTemplate;t.add(n.pathTemplate)}return null}function iA(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function xy(e){let t=e;for(;;){if(!t||typeof t!="object"||!("type"in t))return null;if(t.type==="Identifier"&&"name"in t&&typeof t.name=="string")return t.name;if(t.type==="MemberExpression"||t.type==="OptionalMemberExpression"){t=t.object;continue}return null}}import{createHash as Bd}from"node:crypto";import Td from"@babel/traverse";function fd(e){let t=new Map,n=new Map;for(let s of e){if(t.has(s.placementKey))throw new Error(`Duplicate placement key in page composition projection: ${s.placementKey}`);t.set(s.placementKey,s);let a=n.get(s.placementUnitKey)??[];a.push(s),n.set(s.placementUnitKey,a)}let r=new Map,o=new Map,i=new Map;for(let[s,a]of n){let c=Object.freeze([...a]),l=c.find(u=>u.anchorSourceRange!==null&&u.members.length>0)??c.find(u=>u.members.length>0)??c[0];l&&(o.set(s,c),i.set(s,l),r.set(s,Object.freeze({placementUnitKey:s,placementKeys:Object.freeze(c.map(u=>u.placementKey)),sourcePlacementKey:l.placementKey})))}return{placementByKey:t,unitByKey:r,placementsByUnitKey:o,sourcePlacementByUnitKey:i}}function Ka(e){if(e.node.alternate||!sA(e.get("test")))return!1;let t=e.get("consequent"),n=t.isBlockStatement()?t.get("body"):[t];if(n.length!==1)return!1;let r=n[0];if(r.isThrowStatement())return!0;if(!r.isExpressionStatement())return!1;let o=r.get("expression");if(!o.isCallExpression()||o.node.arguments.length!==0)return!1;let i=o.get("callee");if(!i.isIdentifier())return!1;let s=i.scope.getBinding(i.node.name);if(!s?.constant||s.constantViolations.length>0||!s.path.isImportSpecifier()||s.path.node.importKind==="type")return!1;let a=s.path.node.imported,c=a.type==="Identifier"?a.name:a.value,l=s.path.parentPath;return!!(c==="notFound"&&l?.isImportDeclaration()&&l.node.importKind!=="type"&&l.node.source.value==="next/navigation")}function sA(e){let t=vy(e);return e.traverse({enter(n){vy(n)||(t=!1,n.stop())}}),t}function vy(e){if(e.isAssignmentExpression()||e.isUpdateExpression()||e.isAwaitExpression()||e.isYieldExpression()||e.isNewExpression()||e.isTaggedTemplateExpression()||e.isOptionalCallExpression()||e.isJSXElement()||e.isJSXFragment()||e.isFunction()||e.isUnaryExpression({operator:"delete"}))return!1;if(!e.isCallExpression())return!0;let t=e.get("callee"),n=e.get("arguments");if(!t.isMemberExpression()||t.node.computed||n.length!==1)return!1;let r=t.get("object"),o=t.get("property");if(!r.isIdentifier()||!o.isIdentifier())return!1;if(r.node.name==="Object"&&o.node.name==="keys"&&!r.scope.getBinding("Object"))return!n[0].isSpreadElement();let i=r.scope.getBinding(r.node.name);return!!(o.node.name==="includes"&&n[0].isStringLiteral()&&i?.constant&&i.path.isVariableDeclarator()&&i.path.parentPath?.isVariableDeclaration({kind:"const"}))}import{createHash as AA}from"node:crypto";import Fy from"node:path";import*as Fo from"@babel/parser";import Sd from"@babel/traverse";import Id from"@babel/generator";import*as ue from"@babel/types";import yd from"@babel/generator";import{parse as yA}from"@babel/parser";import xd from"@babel/traverse";import*as Re from"@babel/types";import{PortableInvocationBindingSchema as xA}from"@vcp-dev/contracts";import pd from"@babel/traverse";import*as Ne from"@babel/types";var ky=typeof pd=="function"?pd:pd.default;function hn(e){let t=Cy(e.module,e.exportName,e.parsedModules??new Map([[e.module.file,e.module]]),new Set);return t?_y(t,e.allowNonRenderingGuards):mr("component-export-unresolved","The requested local component export is not a statically resolvable function.",e.module.file)}function gr(e){let t=aA(e.module,e.componentName,e.callSourceRange);return t.kind==="local"?_y(t.definition):t.kind==="imported"?!e.imported?.module&&!nt(t.specifier)?mr("component-external-module-opaque","External package components are opaque to the local source graph.",t.specifier):e.imported?e.imported.module?hn({module:e.imported.module,exportName:e.imported.exportName,parsedModules:e.imported.parsedModules}):mr("component-module-unavailable","The component source module is unavailable in the parsed graph.",e.imported.file):mr("component-local-binding-unresolved","The JSX call does not resolve to a statically declared local component function.",e.module.file):mr("component-local-binding-unresolved","The JSX call does not resolve to a statically declared local component function.",e.module.file)}function _y(e,t=!1){let n=fA(e.module.ast,e.node);if(!n)return mr("component-function-unresolved","The component function has no source AST path.",e.module.file);let r=Ry(n,t);if(!r){let s=mA(n);return s?{ok:!0,componentName:e.name,sourceFile:e.module.file,metadataOnly:!1,roots:[s[0]],returnAlternatives:s}:mr("component-control-flow-unsupported","Component roots require an expression body or one direct return.",e.module.file)}let o=[],i=Ny(r);return Xa(r,o)?{ok:!0,componentName:e.name,sourceFile:e.module.file,metadataOnly:i,roots:o}:mr("component-root-dynamic","Component return contains an unsupported dynamic or spread root.",e.module.file)}function aA(e,t,n){let r={kind:"unresolved"};return ky(e.ast,{JSXElement(o){if(!uA(o.node.loc,n))return;let i=o.node.openingElement.name;if(!Ne.isJSXIdentifier(i)||i.name!==t)return;let s=o.scope.getBinding(t);if(!s||s.constantViolations.length>0){o.stop();return}if(cA(s.path)){let c=s.path.parentPath;c?.isImportDeclaration()&&(r={kind:"imported",specifier:c.node.source.value}),o.stop();return}let a=lA(s.path);a&&(r={kind:"local",definition:{node:a,name:t,module:e}}),o.stop()}}),r}function cA(e){return e.isImportSpecifier()||e.isImportDefaultSpecifier()||e.isImportNamespaceSpecifier()}function lA(e){if(e.isFunctionDeclaration())return e.node;if(!e.isVariableDeclarator())return null;let t=e.get("init");return!Array.isArray(t)&&hd(t.node)?t.node:null}function uA(e,t){return e!=null&&e.start.line===t.startLine&&e.start.column===t.startColumn&&e.end.line===t.endLine&&e.end.column===t.endColumn}function Cy(e,t,n,r){let o=`${e.file}#${t}`;if(r.has(o))return null;let i=new Set(r).add(o),s=(u,d)=>{let f=sr(e.file,u,n),g=f?n.get(f):void 0;return g?Cy(g,d,n,i):null},a=u=>{let d=dA(e,u);if(d)return{...d,module:e};for(let f of e.ast.program.body)if(!(!Ne.isImportDeclaration(f)||f.importKind==="type")){for(let g of f.specifiers)if(g.local.name===u){if(Ne.isImportDefaultSpecifier(g))return s(f.source.value,"default");if(Ne.isImportSpecifier(g)&&g.importKind!=="type")return s(f.source.value,Ja(g.imported))}}return null};for(let u of e.ast.program.body){if(Ne.isExportDefaultDeclaration(u)&&t==="default"){let d=u.declaration;if(hd(d))return{node:d,name:hA(d)??"default",module:e};if(Ne.isIdentifier(d))return a(d.name)}if(!(!Ne.isExportNamedDeclaration(u)||u.exportKind==="type")){if(u.declaration){let d=gA(u.declaration,t);if(d)return a(d)}for(let d of u.specifiers)if(Ne.isExportSpecifier(d)&&d.exportKind!=="type"&&Ja(d.exported)===t)return u.source?s(u.source.value,Ja(d.local)):a(Ja(d.local))}}let c=e.ast.program.body.flatMap(u=>{if(!Ne.isExportAllDeclaration(u)||u.exportKind==="type"||t==="default")return[];let d=s(u.source.value,t);return d?[d]:[]}),l=c.filter((u,d)=>c.findIndex(f=>f.node===u.node&&f.module.file===u.module.file)===d);return l.length===1?l[0]:null}function dA(e,t){for(let n of e.ast.program.body){let r=Ne.isExportNamedDeclaration(n)?n.declaration:n;if(Ne.isFunctionDeclaration(r)&&r.id?.name===t)return{node:r,name:t};if(Ne.isVariableDeclaration(r)){for(let o of r.declarations)if(Ne.isIdentifier(o.id)&&o.id.name===t&&hd(o.init))return{node:o.init,name:t}}}return null}function fA(e,t){let n=null;return ky(e,{Function(r){r.node===t&&(n=r,r.stop())}}),n}function Ry(e,t=!1){let n=e.get("body");if(!n.isBlockStatement())return n;let r=n.get("body"),o=r.at(-1);return!o?.isReturnStatement()||!o.get("argument").node||!r.slice(0,-1).every(i=>i.isVariableDeclaration()||i.isFunctionDeclaration()||pA(i)||t&&i.isIfStatement()&&Ka(i))?null:o.get("argument")}function pA(e){if(!e.isExpressionStatement())return!1;let t=e.get("expression");if(!t.isCallExpression())return!1;let n=t.get("callee");if(!n.isIdentifier())return!1;let r=n.scope.getBinding(n.node.name);if(!r?.constant||!r.path.isImportSpecifier())return!1;let o=r.path.node.imported,i=r.path.parentPath;if(!Ne.isIdentifier(o,{name:"useEffect"})||!i?.isImportDeclaration()||i.node.source.value!=="react"||i.node.importKind==="type"||r.path.node.importKind==="type")return!1;let s=t.get("arguments")[0];return!!(s&&(s.isArrowFunctionExpression()||s.isFunctionExpression()))}function mA(e){let t=e.get("body");if(!t.isBlockStatement())return null;let n=md(t.get("body"));if(!n||n.length<2)return null;let r=[],o=null;for(let i of n){if(!i.isJSXElement())return null;let s=i.node.openingElement.name;if(!Ne.isJSXIdentifier(s)||!/^[A-Z]/.test(s.name))return null;let a=i.scope.getBinding(s.name);if(!a||a.constantViolations.length>0||o&&o!==a.path.node||(o=a.path.node,i.node.children.some(c=>!Ne.isJSXText(c)||c.value.trim()!=="")||i.node.openingElement.attributes.some(c=>Ne.isJSXSpreadAttribute(c)||Ne.isJSXAttribute(c)&&Ne.isJSXIdentifier(c.name,{name:"children"}))))return null;r.push(i)}return r}function md(e){for(let[t,n]of e.entries()){if(n.isVariableDeclaration()||n.isFunctionDeclaration())continue;if(n.isReturnStatement()){let a=n.get("argument");return a.node&&t===e.length-1?[a]:null}if(!n.isIfStatement())return null;let r=a=>md(a.isBlockStatement()?a.get("body"):[a]),o=r(n.get("consequent")),i=n.get("alternate"),s=i.node?t===e.length-1?r(i):null:md(e.slice(t+1));return o&&s?[...o,...s]:null}return null}function Xa(e,t){if(Ny(e))return!0;if(e.isJSXFragment()||e.isJSXElement()&&Ye(e)){let n=e.get("children");for(let r of Array.isArray(n)?n:[n])if(!r.isJSXText()&&(r.isJSXSpreadChild()||!Xa(r,t)))return!1;return!0}if(e.isJSXElement())return t.push(e),!0;if(e.isJSXExpressionContainer()){let n=e.get("expression");return n.isJSXEmptyExpression()||n.isNullLiteral()||Xa(n,t)}return e.isParenthesizedExpression()||e.isTSAsExpression()||e.isTSTypeAssertion()||e.isTSNonNullExpression()||e.isTypeCastExpression()?Xa(e.get("expression"),t):e.isNullLiteral()||e.isStringLiteral()||e.isNumericLiteral()||e.isBooleanLiteral()}function gd(e){return["base","link","meta","script","style","title"].includes(e)}function Ny(e){let t=!1,n=r=>{if(r.isJSXElement()){let o=r.node.openingElement.name;return Ne.isJSXIdentifier(o)&&gd(o.name)?(t=!0,!0):Ye(r)?r.get("children").every(i=>n(i)):!1}if(r.isJSXFragment())return r.get("children").every(o=>n(o));if(r.isJSXText())return r.node.value.trim()==="";if(r.isNullLiteral()||r.isBooleanLiteral()||r.isJSXEmptyExpression())return!0;if(r.isJSXExpressionContainer()||r.isParenthesizedExpression()||r.isTSAsExpression()||r.isTSTypeAssertion()||r.isTSNonNullExpression())return n(r.get("expression"));if(r.isConditionalExpression())return n(r.get("consequent"))&&n(r.get("alternate"));if(r.isArrayExpression())return r.get("elements").every(o=>!o.node||n(o));if(r.isCallExpression()){let o=r.get("callee"),i=r.get("arguments");if(!o.isMemberExpression()||o.node.computed||!Ne.isIdentifier(o.node.property,{name:"map"})||i.length!==1)return!1;let s=i[0];if(!s.isArrowFunctionExpression()&&!s.isFunctionExpression())return!1;let a=Ry(s);return a!==null&&n(a)}return!1};return n(e)&&t}function gA(e,t){return Ne.isFunctionDeclaration(e)?e.id?.name===t?t:null:Ne.isVariableDeclaration(e)&&e.declarations.some(n=>Ne.isIdentifier(n.id)&&n.id.name===t)?t:null}function hd(e){return Ne.isFunctionDeclaration(e)||Ne.isFunctionExpression(e)||Ne.isArrowFunctionExpression(e)}function hA(e){return"id"in e&&e.id&&Ne.isIdentifier(e.id)?e.id.name:null}function Ja(e){return Ne.isIdentifier(e)?e.name:e.value}function mr(e,t,n){return{ok:!1,diagnostic:{code:e,message:t,file:n}}}var bd=typeof yd=="function"?yd:yd.default,Py=typeof xd=="function"?xd:xd.default,Ty=new Set(["sourceBlockId","source_block_id","originalBlockId","original_block_id"]),bA=new Set(["sourceOrder","source_order","originalOrder","original_order"]),EA=new Set(["data-site-block-id","data-site-block-order","data-vcp-block-id","data-vcp-edit-key","data-vcp-order","sourceBlockId","source_block_id","originalBlockId","original_block_id","sourceOrder","source_order","originalOrder","original_order"]),SA=/^[A-Za-z_$][A-Za-z0-9_$]*$/u,IA=/^[A-Za-z_$][A-Za-z0-9_$]*(?:\.[A-Za-z_$][A-Za-z0-9_$]*)*$/u;function yr(e){if(!Oy(e)||!Array.isArray(e.bindings))return hr("INVOCATION_INPUT_INVALID","bindings must be an array in a portable invocation.","bindings");let t=CA(e);if(!t||!IA.test(t))return hr("INVOCATION_COMPONENT_INVALID","Portable invocation requires a safe JSX component local name.","component");let n=wy(e.targetBlockId);if(!n.ok)return n;let r=RA(e.targetOrder);if(!r.ok)return r;let o=e.searchParamsIdentifier??"searchParams";if(!SA.test(o))return hr("INVOCATION_VALUE_UNRESOLVED","The route searchParams binding requires a safe local identifier.","searchParamsIdentifier");let i=[],s=[],a=new Set,c=!1,l=0;for(let[d,f]of e.bindings.entries()){let g=xA.safeParse(f);if(!g.success)return hr("INVOCATION_VALUE_UNRESOLVED","Portable invocation values must use the closed JSON/server/identity contract.",`bindings.${d}`);let p=g.data;if(a.has(p.propName))return hr("INVOCATION_DUPLICATE_PROP",`Portable invocation contains duplicate prop ${p.propName}.`,`bindings.${d}.propName`);if(a.add(p.propName),bA.has(p.propName))return hr("INVOCATION_SOURCE_METADATA","Source block order cannot be copied or rebound as a component prop.",`bindings.${d}`);if(Ty.has(p.propName)&&p.value.kind!=="target-block-id")return hr("INVOCATION_SOURCE_METADATA","Source block identity/order cannot be copied as a business prop.",`bindings.${d}`);if(p.value.kind==="target-block-id"&&(l+=1,l>1))return hr("INVOCATION_DUPLICATE_PROP","A portable invocation may bind the target block identity only once.",`bindings.${d}`);p.value.kind==="route-search-params"&&(c=!0),s.push(p),i.push(Re.jsxAttribute(Re.jsxIdentifier(p.propName),Re.jsxExpressionContainer(kA(p.value,n.value,o))))}let u=Re.jsxElement(Re.jsxOpeningElement(_A(t),i,!0),null,[],!0);return{ok:!0,plan:{kind:"portable-invocation",component:t,jsx:bd(u,{jsescOption:{minimal:!0}}).code,bindings:s,targetBlockId:n.value,targetOrder:r.value,requiresRouteSearchParams:c,searchParamsIdentifier:c?o:null}}}function vA(e){if(!Oy(e)||e.jsx===void 0==(e.source===void 0))return wo("BLOCK_METADATA_INPUT_INVALID","Provide exactly one JSX expression or full source module.","input");let t=wy(e.targetBlockId);if(!t.ok)return wo("BLOCK_METADATA_TARGET_INVALID",t.error.message,"targetBlockId");if(!Number.isSafeInteger(e.targetOrder)||e.targetOrder<0)return wo("BLOCK_METADATA_TARGET_INVALID","targetOrder must be a non-negative safe integer.","targetOrder");let n=e.jsx!==void 0,r,o;try{if(!n&&e.entryExport){let g=je("portable-entry.tsx",e.source);if(!g.ok)throw new Error(g.diagnostic.message);o=g.module,r=o.ast}else r=yA(n?e.jsx:e.source,{sourceType:"module",plugins:["jsx","typescript"]})}catch(g){return wo("BLOCK_METADATA_PARSE_FAILED",g instanceof Error?g.message:String(g),n?"jsx":"source")}let i=[],s;if(o&&e.entryExport){let g=hn({module:o,exportName:e.entryExport.kind==="default"?"default":e.entryExport.name});g.ok&&g.roots.length===1&&(s=g.roots[0],i.push(s.node))}else Py(r,{JSXElement(g){Ay(g)||i.push(g.node)},JSXFragment(g){Ay(g)||i.push(g.node)}});if(i.length!==1)return wo("BLOCK_METADATA_ROOT_AMBIGUOUS","Portable block metadata requires exactly one JSX root.",n?"jsx":"source");let a=i[0],c=NA(a);if(!c)return wo("BLOCK_METADATA_ROOT_AMBIGUOUS","Portable block metadata requires exactly one direct JSX element root.",n?"jsx":"source");let l=0,u=0,d=g=>{let p=PA(g.node.name);!p||!EA.has(p)||(p==="data-site-block-id"||p==="data-vcp-block-id"||Ty.has(p)?l+=1:u+=1,g.remove())};s?s.traverse({JSXAttribute:d}):Py(r,{JSXAttribute:d}),c.openingElement.attributes.push(Re.jsxAttribute(Re.jsxIdentifier("data-site-block-id"),Re.stringLiteral(t.value)),Re.jsxAttribute(Re.jsxIdentifier("data-site-block-order"),Re.jsxExpressionContainer(Re.numericLiteral(e.targetOrder))));let f=n?bd(a,{jsescOption:{minimal:!0}}).code:bd(r,{jsescOption:{minimal:!0}}).code;return{ok:!0,plan:{kind:"portable-block-metadata",source:f,jsx:f,targetBlockId:t.value,targetOrder:e.targetOrder,removedSourceBlockIdCount:l,removedSourceOrderCount:u}}}function kA(e,t,n){return e.kind==="route-search-params"?Re.identifier(n):e.kind==="target-block-id"?Re.stringLiteral(t):Ed(e.value)}function Ed(e){return e===null?Re.nullLiteral():typeof e=="string"?Re.stringLiteral(e):typeof e=="number"?Re.numericLiteral(e):typeof e=="boolean"?Re.booleanLiteral(e):Array.isArray(e)?Re.arrayExpression(e.map(t=>Ed(t))):Re.objectExpression(Object.entries(e).map(([t,n])=>Re.objectProperty(Re.stringLiteral(t),Ed(n))))}function _A(e){let t=e.split("."),n=Re.jsxIdentifier(t[0]);for(let r of t.slice(1))n=Re.jsxMemberExpression(n,Re.jsxIdentifier(r));return n}function CA(e){return typeof e.componentName=="string"?e.componentName:typeof e.component=="string"?e.component:e.component&&typeof e.component=="object"?e.component.localName:null}function wy(e){return typeof e!="string"||e.length===0||e.trim()!==e||e.length>256?{ok:!1,error:{code:"INVOCATION_TARGET_BLOCK_INVALID",path:"targetBlockId",message:"targetBlockId must be a non-blank stable identity."}}:{ok:!0,value:e}}function RA(e){return e!=null?!Number.isSafeInteger(e)||e<0?{ok:!1,error:{code:"INVOCATION_TARGET_ORDER_INVALID",path:"targetOrder",message:"targetOrder must be a non-negative safe integer."}}:{ok:!0,value:e}:{ok:!0,value:null}}function NA(e){if(Re.isJSXElement(e))return e;let t=e.children.filter(Re.isJSXElement),n=e.children.some(r=>Re.isJSXText(r)&&r.value.trim().length>0);return t.length===1&&!n?t[0]??null:null}function Ay(e){let t=e.parentPath;for(;t;){if(t.isJSXElement()||t.isJSXFragment())return!0;t=t.parentPath}return!1}function PA(e){return Re.isJSXIdentifier(e)?e.name:null}function Oy(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function hr(e,t,n){return{ok:!1,error:{code:e,path:n,message:t}}}function wo(e,t,n){return{ok:!1,error:{code:e,path:n,message:t}}}var kd=typeof Id=="function"?Id:Id.default,TA=typeof Sd=="function"?Sd:Sd.default;function $i(e){let t=$y(e);if(t)return{ok:!1,error:t};let n=e.projection,r=Ad(n,e.placementKey,e.expectedDocumentVersion);if(!r.ok)return{ok:!1,error:{code:r.diagnostic.code==="DOCUMENT_VERSION_STALE"?"VERSION_STALE":"RUNTIME_ANCHOR_UNRESOLVED",message:r.diagnostic.message,diagnostics:[r.diagnostic]}};let o=r.placement,i=FA(n,o),s=JA(e);if(!s.ok)return s;let a={jsx:s.invocation?.jsx??`<${e.component.localName} />`},c=wA(e);if(i){let p=_d(e);return p.ok?{ok:!0,plan:{kind:"route-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:e.placementKey,placementUnitKey:o.placementUnitKey,importStep:c,...s.invocation?{invocation:s.invocation}:{},...s.serverParamsStep?{serverParamsStep:s.serverParamsStep}:{},returnStep:{kind:"insert-return",node:a,placement:o.relation,replaceOriginal:n.container.kind==="starter-placeholder"},rewriteStep:{kind:"insert-root-expression",locator:p.locator,sourceHash:p.sourceHash,node:a,placement:o.relation,replaceOriginal:n.container.kind==="starter-placeholder"}}}:p.result}let l=o.containerSourceRange??n.container.sourceRange,u=o.containerSourceHash??(za(l,n.container.sourceRange)?n.container.sourceHash:null);if(!l||!u)return Di("Route page composition does not expose a verifiable container boundary.");let d=ji(l),f=My(e.source,d,u,"Route page composition container");if(!f.ok)return f.result;let g=o.anchorSourceRange?ji(o.anchorSourceRange):void 0;if(g){if(!o.anchorSourceHash)return Di("Route page composition placement does not expose a verifiable anchor boundary.");let p=My(e.source,g,o.anchorSourceHash,"Route page composition anchor");if(!p.ok)return p.result}return{ok:!0,plan:{kind:"route-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:e.placementKey,placementUnitKey:o.placementUnitKey,importStep:c,...s.invocation?{invocation:s.invocation}:{},...s.serverParamsStep?{serverParamsStep:s.serverParamsStep}:{},insertStep:{kind:"insert-child",parentLocator:d,node:a,placement:o.relation,...g?{anchorLocator:g}:{}},rewriteStep:{kind:"insert-child",parentLocator:d,node:a,placement:o.relation,...g?{anchorLocator:g}:{}}}}}function Nd(e){let t=je(e.entryFile,e.source);if(!t.ok)return xr("PORTABLE_ROUTE_SOURCE_INVALID",t.diagnostic.message);let n=yn({route:e.routeId,composition:e.composition??{routeId:e.routeId},entryFile:e.entryFile,version:e.documentVersion,source:e.source,ast:t.module.ast});if(!n.ok)return xr("PORTABLE_ROUTE_UNSUPPORTED","Portable route does not expose a supported page-composition boundary.",n.projection.diagnostics);let r=n.projection.placements.flatMap(l=>{if(l.relation!==e.anchor.relation)return[];if(e.anchor.sourceRange)return l.anchorSourceRange&&za(l.anchorSourceRange,e.anchor.sourceRange)?[{placement:l,matchCount:1}]:[];let u=l.members.reduce((d,f)=>d+By(f,e.anchor.componentName),0);return u===0?[]:[{placement:l,matchCount:u}]}),o=r.reduce((l,u)=>l+u.matchCount,0);if(o===0)return xr("PORTABLE_ROUTE_ANCHOR_MISSING","Portable route anchor was not found in the canonical page composition.");if(o!==1||r.length!==1)return xr("PORTABLE_ROUTE_ANCHOR_AMBIGUOUS","Portable route anchor does not identify exactly one page-composition gap.");let i=$i({routeId:e.routeId,entryFile:e.entryFile,currentDocumentVersion:e.documentVersion,expectedDocumentVersion:e.documentVersion,source:e.source,projection:n.projection,placementKey:r[0].placement.placementKey,component:e.component,invocation:e.invocation});if(!i.ok)return i;let s=e.source,a=i.plan.rewriteStep;if(a.kind==="insert-root-expression"){let l=Vi({source:s,locator:a.locator,expectedSourceHash:a.sourceHash,action:{kind:"insert",jsx:a.node.jsx,placement:a.placement,replaceOriginal:a.replaceOriginal}});if(!l.ok)return xr("PORTABLE_ROUTE_PATCH_FAILED",l.diagnostic.message);s=l.source}else{let l=on({source:s,locator:a.parentLocator,node:a.node,placement:a.placement,...a.anchorLocator?{anchorLocator:a.anchorLocator}:{}});if(!l.ok)return xr("PORTABLE_ROUTE_PATCH_FAILED",l.diagnostic.message);s=l.source}if(i.plan.serverParamsStep){let l=Vy({source:s,step:i.plan.serverParamsStep});if(!l.ok)return xr("PORTABLE_ROUTE_PATCH_FAILED",l.diagnostic.message);s=l.source}let c=sn({source:s,moduleSpecifier:i.plan.importStep.moduleSpecifier,imports:i.plan.importStep.imports});return c.ok?{ok:!0,plan:i.plan,patch:{kind:"portable-route-composition-patch",path:e.entryFile,expectedSourceHash:t.module.sourceHash,source:c.source}}:xr("PORTABLE_ROUTE_PATCH_FAILED",c.diagnostic.message)}function By(e,t){return(e.label===t?1:0)+e.children.reduce((n,r)=>n+By(r,t),0)}function xr(e,t,n=[]){return{ok:!1,error:{code:e,message:t,diagnostics:n}}}function wA(e){let t=BA(e.entryFile,e.component.source);return e.component.exportName==="default"?{kind:"add-import",moduleSpecifier:t,imports:[{kind:"default",local:e.component.localName}]}:{kind:"add-import",moduleSpecifier:t,imports:[{kind:"named",imported:e.component.exportName,local:e.component.localName===e.component.exportName?void 0:e.component.localName}]}}function Vi(e){if(e.locator.root.kind!=="expression"||e.locator.path?.length)return no(e.source,"Root expression rewrite requires an exact expression locator.");let t=pi(e.source,"value");if(!t.ok)return no(e.source,t.diagnostic.message);let n=Ie(t.ast,e.locator);if(!n.ok)return no(e.source,n.diagnostic.message);let r=n.match.path;if(!r.isExpression())return no(e.source,"Resolved value locator does not point to an expression.");let o=Oo(e.source,r.node.start??null,r.node.end??null);if(!o||o!==e.expectedSourceHash)return no(e.source,"Root expression hash no longer matches the current source.");if(e.action.kind==="remove")return r.replaceWith(ue.nullLiteral()),{ok:!0,source:kd(t.ast,{}).code};let i;try{i=Fo.parseExpression(e.action.jsx,{plugins:["jsx","typescript"]})}catch(s){return no(e.source,s instanceof Error?s.message:String(s))}return!ue.isJSXElement(i)&&!ue.isJSXFragment(i)?no(e.source,"Root expression rewrite requires a JSX insertion expression."):(e.action.kind==="replace"?r.replaceWith(i):r.replaceWith(OA(r.node,i,e.action.placement,e.action.replaceOriginal)),{ok:!0,source:kd(t.ast,{}).code})}function OA(e,t,n,r){if(ue.isNullLiteral(e)||r)return t;let o=ue.isJSXFragment(e)?[...e.children]:[ue.isJSXElement(e)?e:ue.jsxExpressionContainer(e)],s=n==="before"||n==="prepend"?[t,...o]:[...o,t];return ue.jsxFragment(ue.jsxOpeningFragment(),ue.jsxClosingFragment(),s)}function no(e,t){return{ok:!1,source:e,diagnostic:{message:t}}}function Pd(e){let t=$y(e);if(t)return{ok:!1,error:t};let n=e.projection,r=Hy(n,e.placementUnitKey,e.expectedDocumentVersion);if(!r.ok)return{ok:!1,error:{code:r.diagnostic.code==="DOCUMENT_VERSION_STALE"?"VERSION_STALE":"NO_SAFE_PAGE_PLACEMENT",message:r.diagnostic.message,diagnostics:[r.diagnostic]}};let o=r.placement;if(!o.sourceRange||!o.sourceHash)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Route page composition source placement does not expose a safe boundary.",diagnostics:[]}};if(LA(n,o)){let m=_d(e);return m.ok?e.operation==="remove-node"&&!Ly(n,o.placementUnitKey)?Di("The last editable page unit cannot be deleted."):e.operation==="move-node"?Di("A singleton root expression cannot be moved without a safe parent boundary."):{ok:!0,plan:{kind:"page-unit-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:o.placementKey,placementUnitKey:o.placementUnitKey,sourceHash:m.sourceHash,rewriteStep:{kind:e.operation==="remove-node"?"remove-root-expression":"replace-root-expression",locator:m.locator,sourceHash:m.sourceHash}}}:m.result}let s=ji(o.sourceRange),a=Pn(e.source,s);if(!a.ok||!a.match.node)return{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:a.ok===!1?a.diagnostic.message:"Route page composition source anchor could not be resolved.",diagnostics:a.ok?[]:[Bi(a.diagnostic)]}};if(Oo(e.source,a.match.node.start??null,a.match.node.end??null)!==o.sourceHash)return{ok:!1,error:{code:"VERSION_STALE",message:"Route page composition source placement hash no longer matches the current source.",diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:"Route page composition source placement hash no longer matches the current source."}]}};if(e.operation==="remove-node"){let m=_d(e);return m.ok?Ly(n,o.placementUnitKey)?{ok:!0,plan:{kind:"page-unit-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:o.placementKey,placementUnitKey:o.placementUnitKey,sourceHash:o.sourceHash,rewriteStep:{kind:"remove-node",locator:s}}}:Di("The last editable page unit cannot be deleted."):m.result}if(e.operation==="replace-node")return{ok:!0,plan:{kind:"page-unit-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:o.placementKey,placementUnitKey:o.placementUnitKey,sourceHash:o.sourceHash,rewriteStep:{kind:"replace-node",locator:s}}};if(!e.targetPlacement)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Page-unit move requires a target placement.",diagnostics:[]}};if(e.targetPlacement.composition.routeId!==e.routeId||!DA(e.targetPlacement.composition,e.composition))return{ok:!1,error:{code:"CROSS_PAGE_MOVE_UNSUPPORTED",message:"Page-unit move across routes or composition templates is not supported.",diagnostics:[]}};if(e.targetPlacement.documentVersion!==e.expectedDocumentVersion)return{ok:!1,error:{code:"VERSION_STALE",message:"Page-unit target placement belongs to a different document version.",diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:"Page-unit target placement belongs to a different document version."}]}};let l=Ad(n,e.targetPlacement.placementKey,e.expectedDocumentVersion);if(!l.ok)return{ok:!1,error:{code:l.diagnostic.code==="DOCUMENT_VERSION_STALE"?"VERSION_STALE":"NO_SAFE_PAGE_PLACEMENT",message:l.diagnostic.message,diagnostics:[l.diagnostic]}};let u=l.placement;if(u.placementUnitKey!==e.targetPlacement.placementUnitKey||u.relation!==e.targetPlacement.relation)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Page-unit target placement metadata does not match the cached projection.",diagnostics:[]}};let d=u.containerSourceRange;if(!d||!u.containerSourceHash)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Route page composition target placement does not expose a verifiable container boundary.",diagnostics:[]}};let f=ji(d),g=Pn(e.source,f);if(!g.ok||!g.match.node)return{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:g.ok===!1?g.diagnostic.message:"Route page composition target container could not be resolved.",diagnostics:g.ok?[]:[Bi(g.diagnostic)]}};if(Oo(e.source,g.match.node.start??null,g.match.node.end??null)!==u.containerSourceHash)return Dy("Route page composition target container hash no longer matches the current source.");if(u.relation==="before"||u.relation==="after"){let m=u.anchorSourceRange,y=u.anchorSourceHash;if(!m||!y)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Route page composition target placement does not expose a verifiable anchor boundary.",diagnostics:[]}};let x=ji(m),S=Pn(e.source,x);return!S.ok||!S.match.node?{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:S.ok===!1?S.diagnostic.message:"Route page composition target anchor could not be resolved.",diagnostics:S.ok?[]:[Bi(S.diagnostic)]}}:Oo(e.source,S.match.node.start??null,S.match.node.end??null)!==y?Dy("Route page composition target anchor hash no longer matches the current source."):{ok:!0,plan:{kind:"page-unit-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:o.placementKey,placementUnitKey:o.placementUnitKey,sourceHash:o.sourceHash,rewriteStep:{kind:"move-node",locator:s,targetParentLocator:f,anchorLocator:x,placement:u.relation}}}}return{ok:!0,plan:{kind:"page-unit-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:o.placementKey,placementUnitKey:o.placementUnitKey,sourceHash:o.sourceHash,rewriteStep:{kind:"move-node",locator:s,targetParentLocator:f,placement:u.relation}}}}function Ly(e,t){for(let n of e.placementUnitByKey.values())if(n.placementUnitKey!==t&&n.members.length>0)return!0;return!1}function FA(e,t){let n=e.placementUnitByKey.get(t.placementUnitKey);return n&&e.container.kind!=="jsx-container"&&za(n.sourceRange,e.mutationTarget.sourceRange)&&n.sourceHash===e.mutationTarget.sourceHash?!0:e.container.sourceRange===null&&(e.container.kind==="virtual-route-root"||e.container.kind==="starter-placeholder")}function LA(e,t){return e.container.kind!=="jsx-container"&&za(t.sourceRange,e.mutationTarget.sourceRange)&&t.sourceHash===e.mutationTarget.sourceHash}function _d(e){let t=e.projection.mutationTarget,n={kind:"value",root:{kind:"expression",sourceRange:t.sourceRange}},r=Pn(e.source,n);return!r.ok||!r.match.node?{ok:!1,result:{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:r.ok===!1?r.diagnostic.message:"Route mutation target could not be resolved.",diagnostics:r.ok?[]:[Bi(r.diagnostic)]}}}:Oo(e.source,r.match.node.start??null,r.match.node.end??null)!==t.sourceHash?{ok:!1,result:jy("Route mutation target hash no longer matches the current source.")}:{ok:!0,locator:n,sourceHash:t.sourceHash}}function My(e,t,n,r){let o=Pn(e,t);return!o.ok||!o.match.node?{ok:!1,result:{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:o.ok===!1?o.diagnostic.message:`${r} could not be resolved.`,diagnostics:o.ok?[]:[Bi(o.diagnostic)]}}}:Oo(e,o.match.node.start??null,o.match.node.end??null)!==n?{ok:!1,result:jy(`${r} hash no longer matches the current source.`)}:{ok:!0}}function jy(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function Di(e){return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:e,diagnostics:[]}}}function Dy(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function Bi(e){return{code:"UNSUPPORTED_PAGE_SHAPE",message:e.message,details:{astCode:e.code}}}function $y(e){let{projection:t}=e;return t.route!==e.routeId||t.entryFile!==e.entryFile?{code:"VERSION_STALE",message:"Cached page composition projection belongs to a different route.",diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:"Cached page composition projection belongs to a different route.",details:{expectedRouteId:e.routeId,projectedRouteId:t.route,expectedEntryFile:e.entryFile,projectedEntryFile:t.entryFile}}]}:e.composition&&!MA(t.composition,e.composition)?{code:"VERSION_STALE",message:"Cached page composition projection belongs to a different composition.",diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:"Cached page composition projection belongs to a different composition.",details:{expectedComposition:e.composition,projectedComposition:t.composition}}]}:e.currentDocumentVersion!==e.expectedDocumentVersion||t.documentVersion!==e.currentDocumentVersion?{code:"VERSION_STALE",message:"Route page composition version is stale.",diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:"Route page composition version is stale.",details:{expectedDocumentVersion:e.expectedDocumentVersion,currentDocumentVersion:e.currentDocumentVersion,projectedDocumentVersion:t.documentVersion}}]}:null}function MA(e,t){return e.routeId===t.routeId&&e.effectiveTemplateId===t.effectiveTemplateId}function DA(e,t){return e.routeId===t.routeId&&e.templateId===t.effectiveTemplateId}function BA(e,t){let n=Fy.posix.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=Fy.posix.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function ji(e){return{kind:"jsx-node",strategy:"source-range",sourceRange:e}}function Oo(e,t,n){return t==null||n==null?null:`sha256:${AA("sha256").update(e.slice(t,n)).digest("hex")}`}function za(e,t){return e===null||t===null?e===t:e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function Vy(e){let t;try{t=Fo.parse(e.source,{sourceType:"module",plugins:["jsx","typescript"]})}catch(r){return{ok:!1,source:e.source,diagnostic:{message:r instanceof Error?r.message:String(r)}}}let n=jA(t,e.step);return n.ok?{ok:!0,source:kd(t,{}).code}:{ok:!1,source:e.source,diagnostic:{message:n.message}}}function jA(e,t){let n=Xy(e);if(!n)return{ok:!1,message:"Route default function could not be resolved for searchParams wiring."};let r=Rd(n.node.params[0]);if(t.action==="reuse")return n.node.params.length!==1||!r?{ok:!1,message:"Existing route searchParams binding no longer matches the plan."}:Ky(r)!==t.identifier?{ok:!1,message:"Existing route searchParams binding no longer matches the plan."}:{ok:!0};let o=Uy(n.node.params,t.typescript);if(!o.ok||o.action!=="add"||o.identifier!==t.identifier)return{ok:!1,message:"Route searchParams signature changed before the patch was applied."};if(n.node.params.length===0)return n.node.params.push(t.typescript?Cd():$A()),{ok:!0};let i=n.node.params[0],s=Rd(i);return s?(VA(s,t.typescript),{ok:!0}):{ok:!1,message:"Route page parameter is not a supported object pattern."}}function $A(){return ue.objectPattern([ue.objectProperty(ue.identifier("searchParams"),ue.identifier("searchParams"),!1,!0)])}function Cd(){let t=Fo.parse("function __PortablePage({ searchParams }: { searchParams?: Promise<Record<string, string | string[] | undefined>> }) {}",{sourceType:"module",plugins:["typescript"]}).program.body[0];if(!ue.isFunctionDeclaration(t))throw new Error("Failed to construct the canonical searchParams type.");let n=t.params[0];if(!ue.isObjectPattern(n))throw new Error("Failed to construct the canonical searchParams pattern.");return ue.cloneNode(n,!0)}function VA(e,t){let n=ue.objectProperty(ue.identifier("searchParams"),ue.identifier("searchParams"),!1,!0),r=e.properties.findIndex(ue.isRestElement);if(r<0?e.properties.push(n):e.properties.splice(r,0,n),!t)return;let o=Jy(e);if(!o){e.typeAnnotation=Cd().typeAnnotation;return}if(!ue.isTSTypeLiteral(o.typeAnnotation))return;let i=Cd().typeAnnotation;if(!i||!ue.isTSTypeAnnotation(i)||!ue.isTSTypeLiteral(i.typeAnnotation))return;let s=i.typeAnnotation.members[0];s&&!UA(o.typeAnnotation)&&o.typeAnnotation.members.push(ue.cloneNode(s,!0))}function UA(e){return e.members.some(t=>!("key"in t)||!t.key?!1:zy(t.key)==="searchParams")}function KA(e,t){if(t.isFunctionDeclaration()||t.isFunctionExpression()||t.isArrowFunctionExpression())return t;if(!t.isIdentifier())return null;let n=e.scope.getBinding(t.node.name);if(!n)return null;let r=n.path;if(r.isFunctionDeclaration()||r.isFunctionExpression())return r;if(r.isVariableDeclarator()){let o=r.get("init");if(o.isArrowFunctionExpression()||o.isFunctionExpression())return o}return null}function JA(e){if(!e.invocation)return{ok:!0};let t=yr({component:e.component.localName,bindings:e.invocation.bindings,targetBlockId:e.invocation.targetBlockId,targetOrder:e.invocation.targetOrder});if(!t.ok)return vd(t.error.message);let n;if(t.plan.requiresRouteSearchParams){let r=XA(e.source,e.entryFile);if(!r.ok)return vd(r.message,"UNSUPPORTED_ROUTE_PARAMS");if(n=r.step,r.step.identifier!==t.plan.searchParamsIdentifier&&(t=yr({component:e.component.localName,bindings:e.invocation.bindings,targetBlockId:e.invocation.targetBlockId,targetOrder:e.invocation.targetOrder,searchParamsIdentifier:r.step.identifier}),!t.ok))return vd(t.error.message)}return{ok:!0,invocation:t.plan,...n?{serverParamsStep:n}:{}}}function vd(e,t="PORTABLE_INVOCATION_INVALID"){return{ok:!1,error:{code:t,message:e,diagnostics:[]}}}function XA(e,t){let n;try{n=Fo.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch(s){return{ok:!1,message:s instanceof Error?s.message:String(s)}}if(n.program.directives.some(s=>s.value.value==="use client"))return{ok:!1,message:"Portable route searchParams wiring cannot cross a use client boundary."};let r=Xy(n);if(!r)return{ok:!1,message:"Portable route searchParams wiring requires a default server function."};let o=/\.(?:ts|tsx)$/iu.test(t),i=Uy(r.node.params,o);return i.ok?{ok:!0,step:{kind:"ensure-search-params",action:i.action,identifier:i.identifier,typescript:o}}:i}function Uy(e,t){if(e.length===0)return{ok:!0,action:"add",identifier:"searchParams"};if(e.length!==1)return{ok:!1,message:"Portable route searchParams wiring rejects a default page with multiple parameters."};let n=Rd(e[0]);if(!n)return{ok:!1,message:"Portable route searchParams wiring requires an object page parameter or an empty signature."};let r=Ky(n);return r==="unsupported"?{ok:!1,message:"Portable route searchParams wiring cannot prove the existing searchParams binding."}:r?{ok:!0,action:"reuse",identifier:r}:t&&!zA(n)?{ok:!1,message:"Portable route searchParams wiring cannot safely extend this typed page signature."}:{ok:!0,action:"add",identifier:"searchParams"}}function Rd(e){return!e||ue.isTSParameterProperty(e)?null:ue.isObjectPattern(e)?e:ue.isAssignmentPattern(e)&&ue.isObjectPattern(e.left)?e.left:null}function Ky(e){for(let t of e.properties)if(!(!ue.isObjectProperty(t)||t.computed||zy(t.key)!=="searchParams"))return ue.isIdentifier(t.value)?t.value.name:ue.isAssignmentPattern(t.value)&&ue.isIdentifier(t.value.left)?t.value.left.name:"unsupported";return null}function zA(e){let t=Jy(e);return t?ue.isTSTypeLiteral(t.typeAnnotation):e.properties.length===0}function Jy(e){return e.typeAnnotation&&ue.isTSTypeAnnotation(e.typeAnnotation)?e.typeAnnotation:null}function Xy(e){let t=null;return TA(e,{ExportDefaultDeclaration(n){if(t)return;let r=KA(n,n.get("declaration"));r&&(t=r)}}),t}function zy(e){return ue.isIdentifier(e)?e.name:ue.isStringLiteral(e)?e.value:null}var HA=typeof Td=="function"?Td:Td.default;function yn(e){if(!e.ast)return xn(e,[mt("UNSUPPORTED_PAGE_SHAPE","SourceGraph entry AST is required",{reason:"parsed-ast-required"})]);let t=tT(e.ast);if(!t)return xn(e,[mt("UNSUPPORTED_PAGE_SHAPE","Route default export must resolve to a local function component",{reason:"default-export-unresolved"})]);let n=rT(t);if(!n.ok)return xn(e,[n.diagnostic]);let r=n.expression;if(r.isIdentifier()){let o=iT(r,t);if(o.status==="resolved")r=o.expression;else if(o.status==="invalid")return xn(e,[mt("UNSUPPORTED_PAGE_SHAPE","Route default export local binding is not a supported JSX root")])}if(aT(r,t))return xn(e,[mt("INDIRECT_RETURN_ONLY","Route default export only returns through an indirect function boundary")]);if(r.isNullLiteral())return Od(e,t,"virtual-route-root",r);if(sT(r)){let o=dT({input:e,source:e.source,expression:r});return wd(e,t,o,{kind:"virtual-route-root",sourceKind:"atomic-expression"},r)}if(r.isConditionalExpression())return xn(e,[mt("UNSUPPORTED_PAGE_SHAPE","Route conditional root contains an unsupported branch shape",{reason:"ambiguous-placement"})]);if(r.isJSXElement()&&!Ye(r)&&!Ki(r)){let o=Md(r),i=Yy({input:e,containerKind:"virtual-route-root",sourceKind:"jsx-element",source:e.source,containerPath:r,members:[o]});return wd(e,t,i,{kind:"virtual-route-root",sourceKind:"jsx-element"},r)}if(r.isJSXElement()||r.isJSXFragment()){let o=lT(r);if(!o.ok)return xn(e,[o.diagnostic]);let i=Lo(o.path);if(i.unsupported)return xn(e,[mt("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);if(cT(e.source,r,i.members))return Od(e,t,"starter-placeholder",r);let s=r.isJSXFragment()||Ye(r);if(i.members.length===0&&s)return Od(e,t,"virtual-route-root",r);let a=o.path===r&&s?"virtual-route-root":"jsx-container",c=o.path.isJSXFragment()?"jsx-fragment":"jsx-element",l=Yy({input:e,containerKind:a,sourceKind:c,source:e.source,containerPath:o.path,members:i.members});return wd(e,t,l,{kind:a,sourceKind:c},r)}return xn(e,[mt("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")])}function Ad(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:mt("DOCUMENT_VERSION_STALE","Placement lookup is stale for the requested document version",{expectedDocumentVersion:e.documentVersion,requestedDocumentVersion:n})};let r=e.placementByKey.get(t)??null;return r?{ok:!0,placement:r}:{ok:!1,diagnostic:mt("PLACEMENT_KEY_NOT_FOUND","Placement key was not found in the projected page composition",{placementKey:t})}}function Hy(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:mt("DOCUMENT_VERSION_STALE","Placement lookup is stale for the requested document version",{expectedDocumentVersion:e.documentVersion,requestedDocumentVersion:n})};let r=e.placementUnitByKey.get(t)??null;return r?{ok:!0,placement:r}:{ok:!1,diagnostic:mt("PLACEMENT_KEY_NOT_FOUND","Placement unit key was not found in the projected page composition",{placementUnitKey:t})}}function Zy(e){return e.ok?WA(e.projection):GA(e.projection)}function WA(e){let t=new Map,n=[];for(let l of e.placements)l.members.length===0&&e.placements.length>1||l.members.length>0&&!l.anchorSourceRange||t.has(l.placementUnitKey)||t.set(l.placementUnitKey,l);let r=new Map,o=new Map;for(let[l,u]of t){let d=u.members.flatMap((m,y)=>qy(e,u,m,y,e.container.placementKey)),f=d.filter(({member:m})=>m.isBusinessMember).map(({sourceMember:m})=>ZA(l,m,u.independent)),g=d.length>0?d:[{sourceMember:{key:`source:${l}:empty`,kind:e.container.kind==="starter-placeholder"?"starter-placeholder":"null-return",containerKey:e.container.placementKey,label:"empty-page",sourceFile:e.entryFile,isAtomic:!0},member:null}];r.set(l,g.map(({sourceMember:m})=>m)),o.set(l,f);let p=g[0]?.sourceMember.key??l;n.push({key:l,containerKey:p,businessMemberKeys:f.map(m=>m.key),isMultiMember:u.memberCount>1})}let i=[...r.values()].flat(),s=[...o.values()].flat(),a=i[0]?.key??null,c=e.placements.map(l=>({kind:"page-composition",placementKey:l.placementKey,documentVersion:e.documentVersion,composition:e.composition,placementUnitKey:l.placementUnitKey,relation:l.relation}));return{status:"supported",version:e.version,composition:e.composition,container:YA(e,a),sourceMembers:i,businessMembers:s,placementUnits:n,placements:c}}function GA(e){let t=e.diagnostics.map(qA);return{status:"unsupported",version:e.version,composition:e.composition,reason:QA(e.diagnostics),diagnostics:t}}function YA(e,t){switch(e.container.kind){case"jsx-container":return{kind:"jsx-container",key:e.container.placementKey,sourceMemberKey:t??e.container.placementKey,sourceFile:e.entryFile,componentName:e.defaultExportName??void 0};case"starter-placeholder":return{kind:"starter-placeholder",key:e.container.placementKey,sourceFile:e.entryFile};case"virtual-route-root":return{kind:"virtual-route-root",key:e.container.placementKey}}}function qy(e,t,n,r,o){let i=`source:${t.placementUnitKey}:${r}:${n.memberKey}`;return[{sourceMember:{key:i,kind:n.kind==="jsx-element"?"jsx-element":"jsx-expression",containerKey:o,label:n.label,sourceFile:e.entryFile,isAtomic:n.kind!=="jsx-element"},member:n},...n.children.flatMap((a,c)=>qy(e,t,a,c,i))]}function ZA(e,t,n){return{key:`business:${e}:${t.key}`,sourceMemberKey:t.key,containerKey:e,label:t.label,isIndependent:n}}function qA(e){return{code:eT(e),message:e.message}}function QA(e){let t=e[0];if(!t)return"UNSUPPORTED_ROUTE_STRUCTURE";switch(t.code){case"ROUTE_RETURN_NOT_FOUND":return"ROUTE_RETURN_NOT_FOUND";case"MULTIPLE_PAGE_RETURNS":return"MULTIPLE_PAGE_RETURNS";case"INDIRECT_RETURN_ONLY":return"INDIRECT_RETURN_ONLY";case"PLACEMENT_KEY_NOT_FOUND":return"RUNTIME_ANCHOR_UNRESOLVED";case"DOCUMENT_VERSION_STALE":return"VERSION_STALE";case"UNSUPPORTED_PAGE_SHAPE":return t.details?.reason==="ambiguous-placement"?"PAGE_CONTAINER_AMBIGUOUS":"UNSUPPORTED_ROUTE_STRUCTURE";default:return"UNSUPPORTED_ROUTE_STRUCTURE"}}function eT(e){switch(e.code){case"PLACEMENT_KEY_NOT_FOUND":return"RUNTIME_ANCHOR_UNRESOLVED";case"DOCUMENT_VERSION_STALE":return"VERSION_STALE";case"UNSUPPORTED_PAGE_SHAPE":return e.details?.reason==="ambiguous-placement"?"PAGE_CONTAINER_AMBIGUOUS":"UNSUPPORTED_ROUTE_STRUCTURE";default:return e.code}}function tT(e){let t=null;return HA(e,{ExportDefaultDeclaration(n){let r=n.get("declaration");if(r.isArrowFunctionExpression()||r.isFunctionDeclaration()||r.isFunctionExpression()){t=r,n.stop();return}if(!r.isIdentifier())return;let o=n.scope.getBinding(r.node.name);if(!o)return;let i=nT(o.path);i&&(t=i,n.stop())}}),t}function nT(e){if(e.isArrowFunctionExpression()||e.isFunctionDeclaration()||e.isFunctionExpression())return e;if(e.isVariableDeclarator()){let t=e.get("init");if(t.isArrowFunctionExpression()||t.isFunctionExpression())return t}return null}function rT(e){let t=e.get("body");if(!t.isBlockStatement()){let s=Ui(t);return s?{ok:!0,expression:s}:{ok:!1,diagnostic:mt("ROUTE_RETURN_NOT_FOUND","Route default export does not contain a proven return boundary")}}let n=t.get("body"),r=n.at(-1);if(!r)return{ok:!1,diagnostic:mt("ROUTE_RETURN_NOT_FOUND","Route default export does not contain a proven return boundary")};if(!r.isReturnStatement())return{ok:!1,diagnostic:mt("UNSUPPORTED_PAGE_SHAPE","Route default export must end with a direct terminal return",{reason:"terminal-return-required"})};for(let s of n.slice(0,-1)){if(s.isIfStatement()){if(!oT(s)&&!Ka(s))return{ok:!1,diagnostic:mt("UNSUPPORTED_PAGE_SHAPE","Route guard return shape is not statically safe",{reason:"guard-shape"})};continue}if(Qy(s)||ex(s))return{ok:!1,diagnostic:mt("UNSUPPORTED_PAGE_SHAPE","Route default export contains unsupported control flow before the terminal return",{reason:"control-flow-return"})}}let o=r.get("argument"),i=Ui(o);return i?{ok:!0,expression:i}:{ok:!1,diagnostic:mt("ROUTE_RETURN_NOT_FOUND","Route default export returns without a boundary expression",{reason:"bare-return"})}}function oT(e){if(e.node.alternate)return null;let t=e.get("consequent");if(t.isReturnStatement())return t;if(!t.isBlockStatement())return null;let n=t.get("body"),r=n.at(-1);if(!r?.isReturnStatement())return null;for(let o of n.slice(0,-1))if(Qy(o)||ex(o))return null;return r}function Qy(e){return e.isForStatement()||e.isForInStatement()||e.isForOfStatement()||e.isWhileStatement()||e.isDoWhileStatement()||e.isSwitchStatement()||e.isTryStatement()||e.isWithStatement()}function ex(e){let t=!1;return e.traverse({Function(n){n.skip()},ReturnStatement(){t=!0}}),t}function iT(e,t){let n=t.scope.getBinding(e.node.name);if(!n||n.scope.path.node!==t.node)return{status:"not-local"};if(!n.path.isVariableDeclarator())return{status:"not-local"};let r=n.path.parentPath;if(!r?.isVariableDeclaration()||r.node.kind!=="const")return{status:"invalid"};let o=n.path.get("init");if(Array.isArray(o)||!o.node)return{status:"invalid"};let i=Ui(o);return!i||!i.isJSXElement()&&!i.isJSXFragment()?{status:"invalid"}:n.referencePaths.length!==1||n.referencePaths[0]?.node!==e.node||n.constantViolations.length!==0?{status:"invalid"}:{status:"resolved",expression:i}}function sT(e){return e.isConditionalExpression()?Wy(Ui(e.get("consequent")))&&Wy(Ui(e.get("alternate"))):!1}function Wy(e){return!!(e&&(e.isJSXElement()||e.isJSXFragment()||e.isNullLiteral()))}function Ui(e){if(!e.node)return null;let t=e;for(;;){if(t.isParenthesizedExpression()){t=t.get("expression");continue}if(t.isTSAsExpression()||t.isTSTypeAssertion()){t=t.get("expression");continue}if(t.isTSNonNullExpression()||t.isTypeCastExpression()){t=t.get("expression");continue}break}return t.isExpression()?t:null}function aT(e,t){if(e.isIdentifier())return Gy(e.node.name,t);if(e.isCallExpression()){let n=e.get("callee");if(n.isIdentifier())return Gy(n.node.name,t)}return!1}function Gy(e,t){let n=t.scope.getBinding(e);if(!n)return!1;let r=n.path;if(r.isFunctionDeclaration()||r.isFunctionExpression()||r.isArrowFunctionExpression())return!0;if(r.isVariableDeclarator()){let o=r.get("init");return o.isFunctionExpression()||o.isArrowFunctionExpression()}return!1}function cT(e,t,n){return e.includes("DESIGN_PLAN_REPLACE_ME")&&t.isJSXElement()&&n.length>0&&Ld(t)}function Ld(e){for(let t of e.get("children")){if(t.isJSXText()){if(t.node.value.trim())return!1;continue}if(t.isJSXExpressionContainer()){let n=t.get("expression");if(n.isJSXEmptyExpression()||n.isNullLiteral())continue;return!1}if(t.isJSXFragment()){if(!Ld(t))return!1;continue}if(t.isJSXElement()&&!Ld(t))return!1}return!0}function lT(e){return{ok:!0,path:e}}function Lo(e){let t=[],n=!1;for(let r of e.get("children")){if(r.isJSXText()){if(!r.node.value.trim())continue;t.push({memberKey:Dd(r.node.type,r.node.start,r.node.end),kind:"text",nodeType:r.node.type,sourceRange:ln(r.node.loc),businessMemberCount:0,parentSourceRange:ln(e.node.loc),children:[],isBusinessMember:!1,label:"text"});continue}if(r.isJSXExpressionContainer()){let o=r.get("expression");if(o.isJSXEmptyExpression()||o.isNullLiteral())continue;if(o.isJSXFragment()){let i=Lo(o);n||=i.unsupported,t.push(...i.members);continue}if(o.isJSXElement()){let i=Ki(o)?Lo(o):null;n||=i?.unsupported??!1,t.push({...Md(o,i?.members),sourceRange:ln(r.node.loc),parentSourceRange:ln(e.node.loc)});continue}if(o.isJSXSpreadChild()){n=!0;continue}t.push({memberKey:Dd(o.node.type,o.node.start,o.node.end),kind:"atomic-expression",nodeType:o.node.type,sourceRange:ln(r.node.loc),businessMemberCount:1,parentSourceRange:ln(e.node.loc),children:[],isBusinessMember:!0,label:"atomic-expression"});continue}if(r.isJSXFragment()||r.isJSXElement()&&Ye(r)){let o=Lo(r);n||=o.unsupported,t.push(...o.members);continue}if(r.isJSXElement()){let o=Ki(r)?Lo(r):null;n||=o?.unsupported??!1,t.push({...Md(r,o?.members),parentSourceRange:ln(e.node.loc)})}}return{members:t,unsupported:n}}function Md(e,t){let n=e.isJSXElement()&&Ki(e)?t??Lo(e).members:[],r=e.isJSXElement()&&!Ki(e)&&!Ye(e);return{memberKey:Dd(e.node.type,e.node.start,e.node.end),kind:"jsx-element",nodeType:e.node.type,sourceRange:ln(e.node.loc),businessMemberCount:r?1:tx(n),parentSourceRange:ln(e.parentPath?.node.loc),children:n,isBusinessMember:r,label:uT(e)}}function Ki(e){let t=e.node.openingElement.name;return t.type==="JSXIdentifier"&&t.name[0]===t.name[0]?.toLowerCase()}function uT(e){if(e.isJSXFragment())return"Fragment";let t=e.node.openingElement.name;if(t.type==="JSXIdentifier")return t.name;if(t.type==="JSXMemberExpression"){let n=t.object;return`${n.type==="JSXIdentifier"?n.name:"member"}.${t.property.name}`}return t.name.name}function tx(e){return e.reduce((t,n)=>t+n.businessMemberCount,0)}function Ha(e){return e.length===0?0:Math.max(1,tx(e))}function Yy(e){let t=ln(e.containerPath.node.loc),n=jd(e.source,e.containerPath.node.start,e.containerPath.node.end),r=un(e.input,e.containerKind,e.sourceKind,t),o=un(e.input,e.containerKind,"placement-unit",t);return{placementKey:r,placementUnitKey:o,version:e.input.version,containerKey:r,independent:Ha(e.members)<=1,memberCount:Ha(e.members),sourceRange:t,sourceHash:n,relation:"append",containerSourceRange:t,containerSourceHash:n,anchorSourceRange:null,anchorSourceHash:null,members:e.members}}function dT(e){let t=ln(e.expression.node.loc),n=jd(e.source,e.expression.node.start,e.expression.node.end),r=un(e.input,"virtual-route-root","atomic-expression",t),o=un(e.input,"virtual-route-root","placement-unit",t);return{placementKey:r,placementUnitKey:o,version:e.input.version,containerKey:r,independent:!0,memberCount:1,sourceRange:t,sourceHash:n,relation:"append",containerSourceRange:t,containerSourceHash:n,anchorSourceRange:null,anchorSourceHash:null,members:[{memberKey:un(e.input,"virtual-route-root","atomic-member",t),kind:"atomic-expression",nodeType:e.expression.node.type,sourceRange:t,businessMemberCount:1,parentSourceRange:null,children:[],isBusinessMember:!0,label:e.expression.node.type}]}}function nx(e,t){let n=ln(t.node.loc),r=jd(e.source,t.node.start,t.node.end);return!n||!r?null:{kind:"expression",documentVersion:e.version,sourceRange:n,sourceHash:r}}function wd(e,t,n,r,o){let i=nx(e,o);if(!i)return xn(e,[mt("UNSUPPORTED_PAGE_SHAPE","Route default export does not provide an exact mutation target",{reason:"mutation-target-unavailable"})]);let s=n.containerSourceRange??n.sourceRange,a=fT(e,n,s),c=fd(a),l={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:ox(t),container:{kind:r.kind,placementKey:n.placementKey,placementUnitKey:n.placementUnitKey,version:e.version,isEmptyPage:n.memberCount===0,sourceKind:r.sourceKind,sourceRange:s,sourceHash:n.sourceHash},placements:a,diagnostics:[],placementByKey:new Map,unitByKey:new Map,placementsByUnitKey:new Map,placementUnitByKey:new Map,mutationTarget:i};return Object.defineProperties(l,{placementByKey:{value:c.placementByKey,enumerable:!1},unitByKey:{value:c.unitByKey,enumerable:!1},placementsByUnitKey:{value:c.placementsByUnitKey,enumerable:!1},placementUnitByKey:{value:c.sourcePlacementByUnitKey,enumerable:!1}}),{ok:!0,projection:l}}function fT(e,t,n){if(t.members.length===0)return[t];let r=[],o=(l,u,d,f,g,p,m=n)=>({...t,placementKey:u,placementUnitKey:d,containerKey:t.placementKey,independent:Ha(p)<=1,memberCount:Ha(p),sourceRange:f,sourceHash:f?Fd(e.source,f):null,relation:l,containerSourceRange:m,containerSourceHash:m?Fd(e.source,m):null,anchorSourceRange:g,anchorSourceHash:g?Fd(e.source,g):null,members:p}),i=t.placementKey,s=t.members.map(l=>un(e,i,"placement-unit",l.sourceRange)),a=s[0]??t.placementUnitKey,c=s.at(-1)??t.placementUnitKey;r.push(o("prepend",un(e,i,"prepend",n),a,n,null,[]));for(let l of t.members){let u=l.parentSourceRange??n,d=un(e,i,"placement-unit",l.sourceRange);r.push(o("before",un(e,d,"before",l.sourceRange),d,l.sourceRange,l.sourceRange,[l],u)),r.push(o("after",un(e,d,"after",l.sourceRange),d,l.sourceRange,l.sourceRange,[l],u))}return r.push(o("append",i,c,n,null,[])),r}function Od(e,t,n,r){let o=nx(e,r);if(!o)return xn(e,[mt("UNSUPPORTED_PAGE_SHAPE","Route default export does not provide an exact mutation target",{reason:"mutation-target-unavailable"})]);let i=un(e,n,"empty-container",void 0),s=un(e,n,"empty-unit",void 0),a={placementKey:i,placementUnitKey:s,version:e.version,containerKey:i,independent:!0,memberCount:0,sourceRange:null,sourceHash:null,relation:"append",containerSourceRange:null,containerSourceHash:null,anchorSourceRange:null,anchorSourceHash:null,members:[]},c=fd([a]),l={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:ox(t),container:{kind:n,placementKey:i,placementUnitKey:s,version:e.version,isEmptyPage:!0,sourceKind:n==="starter-placeholder"?"starter-placeholder":"jsx-fragment",sourceRange:null,sourceHash:null},placements:[a],diagnostics:[],placementByKey:new Map,unitByKey:new Map,placementsByUnitKey:new Map,placementUnitByKey:new Map,mutationTarget:o};return Object.defineProperties(l,{placementByKey:{value:c.placementByKey,enumerable:!1},unitByKey:{value:c.unitByKey,enumerable:!1},placementsByUnitKey:{value:c.placementsByUnitKey,enumerable:!1},placementUnitByKey:{value:c.sourcePlacementByUnitKey,enumerable:!1}}),{ok:!0,projection:l}}function xn(e,t){return{ok:!1,projection:{status:"unsupported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,diagnostics:t}}}function mt(e,t,n){return n===void 0?{code:e,message:t}:{code:e,message:t,details:n}}function un(e,t,n,r){return rx([e.route,e.entryFile,String(e.version),t,n,r?`${r.startLine}:${r.startColumn}-${r.endLine}:${r.endColumn}`:"no-range"])}function Dd(e,t,n){return rx(["member",e,String(t??-1),String(n??-1)])}function rx(e){return`pc_${Bd("sha256").update(e.join("\0")).digest("hex").slice(0,24)}`}function jd(e,t,n){return t==null||n==null?null:`sha256:${Bd("sha256").update(e.slice(t,n)).digest("hex")}`}function Fd(e,t){let n=[0];for(let i=0;i<e.length;i+=1)e.charCodeAt(i)===10&&n.push(i+1);let r=n[t.startLine-1],o=n[t.endLine-1];return r===void 0||o===void 0?null:`sha256:${Bd("sha256").update(e.slice(r+t.startColumn,o+t.endColumn)).digest("hex")}`}function ln(e){return e?{startLine:e.start.line,startColumn:e.start.column,endLine:e.end.line,endColumn:e.end.column}:null}function ox(e){if(e.isFunctionDeclaration())return e.node.id?.name??null;let t=e.parentPath;return t?.isVariableDeclarator()&&t.node.id.type==="Identifier"?t.node.id.name:null}import{createHash as kT}from"node:crypto";import*as bn from"@babel/types";function ix(e){if(!e.path.isIdentifier())return{kind:"not-alias"};let t=e.path.scope.getBinding(e.path.node.name);if(!t)return{kind:"unbound"};if(t.constantViolations.length>0)return{kind:"reassigned"};let n=t.path;if(!n.isVariableDeclarator())return{kind:"not-alias"};if(e.aliases.has(n.node)||e.aliases.size>=(e.maxDepth??32))return{kind:"guard"};let r=n.get("init");return Array.isArray(r)||!r.node?{kind:"not-alias"}:{kind:"initializer",initializer:r,aliases:new Set(e.aliases).add(n.node)}}import $d from"@babel/traverse";import*as Mo from"@babel/types";var mT=typeof $d=="function"?$d:$d.default,gT=32;function br(e,t,n,r=new Set){if(r.has(e.ast)||r.size>=gT)return null;let o=new Set(r).add(e.ast),i;if(mT(e.ast,{Program(d){i=d,d.stop()}}),!i)return null;let s=(d,f)=>{let g=sr(e.file,d,n),p=g?n.get(g):void 0;return p?br(p,f,n,o):null},a=d=>{let f=i.scope.getBinding(d);if(!f||f.constantViolations.length)return null;let g=f.path.parentPath;return g?.isImportDeclaration()?g.node.importKind==="type"?null:f.path.isImportDefaultSpecifier()?s(g.node.source.value,"default"):f.path.isImportSpecifier()&&f.path.node.importKind!=="type"?s(g.node.source.value,Wa(f.path.node.imported)):null:f.path.isVariableDeclarator()?f.path.get("init"):f.path},c=[],l=[];for(let d of i.get("body"))if(d.isExportDefaultDeclaration()&&t==="default"){let f=d.get("declaration");c.push(f.isIdentifier()?a(f.node.name):f)}else if(d.isExportNamedDeclaration()&&d.node.exportKind!=="type"){let f=d.get("declaration");f.node&&Object.hasOwn(Mo.getBindingIdentifiers(f.node),t)&&c.push(a(t));for(let g of d.node.specifiers)Mo.isExportSpecifier(g)&&g.exportKind!=="type"&&Wa(g.exported)===t&&c.push(d.node.source?s(d.node.source.value,Wa(g.local)):a(Wa(g.local)))}else d.isExportAllDeclaration()&&d.node.exportKind!=="type"&&t!=="default"&&l.push(d.node.source.value);if(c.length)return c.length===1?c[0]:null;let u=l.map(d=>s(d,t)).filter(d=>d!==null);return u.length===1?u[0]:null}function Wa(e){return Mo.isIdentifier(e)?e.name:e.value}import*as be from"@babel/types";var hT=32;function Kt(e,t=new Map,n=new Set){if(n.has(e.node)||n.size>=hT)return null;let r=new Set(n).add(e.node),o=t.get(e.node);if(o)return Ji(o,t,r);if(e.isTSAsExpression()||e.isTSTypeAssertion()||e.isTSNonNullExpression()||e.isTSSatisfiesExpression()||e.isParenthesizedExpression())return Kt(e.get("expression"),t,r);if(e.isIdentifier()){let i=e.scope.getBinding(e.node.name);return!i||i.constantViolations.length?null:Ud(i,t,r)}if(e.isMemberExpression()||e.isOptionalMemberExpression()){let i=Jt(e.node.property,e.node.computed),s=e.get("object"),a=Kt(s,t,r);return i!==null&&a?Za(a,i,t,r):null}if(e.isConditionalExpression())return Ji([e.get("consequent"),e.get("alternate")],t,r);if(e.isLogicalExpression())return Ji([e.get("left"),e.get("right")],t,r);if(e.isSequenceExpression()){let i=e.get("expressions").at(-1);return i?Kt(i,t,r):null}if(e.isCallExpression()&&be.isIdentifier(e.node.callee)){let i=e.scope.getBinding(e.node.callee.name);if(!i||!Do(i))return null;let s=i.path.isFunctionDeclaration()?i.path:i.path.isVariableDeclarator()?i.path.get("init"):null;if(!s||!(s.isFunctionDeclaration()||s.isFunctionExpression()||s.isArrowFunctionExpression())||s.node.async||s.node.generator)return null;let a=s,c=new Map(t),l=e.get("arguments");for(let[g,p]of a.get("params").entries()){if(!p.isIdentifier())return null;let m=l[g];if(!m?.isExpression())return null;let y=Kt(m,t,r);if(!y)return null;let x=p.scope.getBinding(p.node.name);if(!x)return null;c.set(x.identifier,y)}let u=a.get("body"),d=u.isBlockStatement()?u.get("body")[0]:u;if(!d)return null;let f=d.isReturnStatement()?d.get("argument"):d;return f.node?Kt(f,c,r):null}return[e]}function Ud(e,t=new Map,n=new Set){if(e.constantViolations.length)return null;let r=t.get(e.identifier);if(r)return Ji(r,t,n);if(!e.path.isVariableDeclarator())return null;let o=e.path.get("init");if(!o.node)return null;let i=Kt(o,t,n);if(!i)return null;let s=Vd(e.path.node.id,e.identifier.name);return s?s.reduce((a,c)=>a&&Za(a,c,t,n),i):null}function Ga(e){if(!e.params.every(n=>be.isIdentifier(n)||be.isAssignmentPattern(n)&&be.isIdentifier(n.left)&&ro(n.right)))return!1;if(!be.isBlockStatement(e.body))return ro(e.body);if(e.body.body.length!==1)return!1;let t=e.body.body[0];return be.isReturnStatement(t)&&!!t.argument&&ro(t.argument)}function Do(e){if(e.constantViolations.length>0)return!1;if(e.path.isFunctionDeclaration())return Ga(e.path.node);let t=e.path.isVariableDeclarator()?e.path:e.path.findParent(r=>r.isVariableDeclarator()),n=t?.isVariableDeclarator()?t.node.init:null;return be.isArrowFunctionExpression(n)||be.isFunctionExpression(n)?Ga(n):!1}function ro(e){let t=!0;return be.traverseFast(e,n=>{(be.isCallExpression(n)&&!Ya(n)||be.isOptionalCallExpression(n)||be.isNewExpression(n)||be.isAwaitExpression(n)||be.isAssignmentExpression(n)||be.isUpdateExpression(n)||be.isUnaryExpression(n,{operator:"delete"})||be.isYieldExpression(n)||be.isTaggedTemplateExpression(n))&&(t=!1)}),t}function Ya(e){return be.isIdentifier(e.callee,{name:"useTranslations"})&&e.arguments.length===1&&be.isStringLiteral(e.arguments[0])}function Ji(e,t,n){let r=[];for(let o of e){let i=Kt(o,t,n);if(!i)return null;r.push(...i)}return r.length?r:null}function Za(e,t,n,r=new Set){let o=[];for(let i of e)if(i.isObjectExpression()){let s=i.get("properties");if(s.some(c=>!c.isObjectProperty()||c.node.computed))return null;let a=s.filter(c=>c.isObjectProperty()&&Jt(c.node.key,!1)===t);if(a.length!==1||!a[0].isObjectProperty())return null;o.push(a[0].get("value"))}else if(i.isArrayExpression()&&/^(?:0|[1-9]\d*)$/u.test(t)){if(i.node.elements.some(a=>be.isSpreadElement(a)))return null;let s=i.get("elements")[Number(t)];if(!s?.node||s.isSpreadElement())return null;o.push(s)}else return null;return Ji(o,n,r)}function Kd(e,t){let n=Kt(e,t);return!!(n?.length&&n.every(r=>be.isLiteral(r.node)&&!r.isRegExpLiteral()||r.isTemplateLiteral()||r.isBinaryExpression()||r.isUnaryExpression()))}function Jt(e,t){return!t&&be.isIdentifier(e)?e.name:be.isStringLiteral(e)||be.isNumericLiteral(e)?String(e.value):null}function Vd(e,t){if(be.isIdentifier(e))return e.name===t?[]:null;if(be.isObjectPattern(e))for(let n of e.properties){if(!be.isObjectProperty(n)||n.computed)continue;let r=Jt(n.key,!1),o=Vd(n.value,t);if(r!==null&&o)return[r,...o]}if(be.isArrayPattern(e))for(let[n,r]of e.elements.entries()){if(!r)continue;let o=Vd(r,t);if(o)return[String(n),...o]}return null}function sx(e,t=new Set,n){return ax(e.get("callee"),t,n)}function ax(e,t,n){if(t.has(e.node)||t.size>=32)return{kind:"guard"};if(e.isIdentifier()){let r=e.scope.getBinding(e.node.name);if(!r)return{kind:"unknown"};if(t.has(r.path.node))return{kind:"guard"};let o=new Set(t).add(r.path.node),i=r.path.parentPath;if(i?.isImportDeclaration()&&n){let l=i.node.source.value;if(!(l.startsWith(".")||l.startsWith("@/")))return{kind:"unknown"};let u=r.path.scope.getProgramParent().path.node,d=[...n.values()].find(y=>y.ast.program===u),f=d&&sr(d.file,l,n),g=f?n.get(f):void 0,p=r.path.isImportDefaultSpecifier()?"default":r.path.isImportSpecifier()&&r.path.node.importKind!=="type"?Jt(r.path.node.imported,!1):null,m=g&&p&&i.node.importKind!=="type"?br(g,p,n):null;return m?Bo(m,o,n):{kind:"guard"}}let s=r.path.isVariableDeclarator()?r.path.get("init"):r.path;if(!s.node)return{kind:"unknown"};let a=Bo(s,o,n);if(a.kind!=="sources")return a;let c=[...a.sources];for(let l of r.constantViolations){if(!l.isAssignmentExpression({operator:"="}))return{kind:"guard"};let u=Bo(l.get("right"),o,n);if(u.kind!=="sources")return{kind:"guard"};c.push(...u.sources)}return{kind:"sources",sources:c,aliases:a.aliases}}if(e.isMemberExpression()||e.isOptionalMemberExpression()){let r=Jt(e.node.property,e.node.computed),o=e.get("object"),i=Kt(o);if(!i)return{kind:"unknown"};let s=[],a=new Set(t).add(e.node);for(let c of i){if(!c.isObjectExpression())return{kind:"unknown"};if(r===null||c.node.properties.some(d=>d.type!=="ObjectProperty"))return{kind:"guard"};let l=c.get("properties").filter(d=>d.isObjectProperty()&&Jt(d.node.key,d.node.computed)===r);if(l.length!==1||!l[0].isObjectProperty())return{kind:"guard"};let u=Bo(l[0].get("value"),a,n);if(u.kind!=="sources")return{kind:"guard"};s.push(...u.sources),a=u.aliases}return{kind:"sources",sources:s,aliases:a}}return Bo(e,new Set(t).add(e.node),n)}function Bo(e,t,n){if(e.isIdentifier())return ax(e,t,n);if(e.isTSAsExpression()||e.isTSTypeAssertion()||e.isTSNonNullExpression()||e.isParenthesizedExpression())return Bo(e.get("expression"),t,n);if(!(e.isFunctionDeclaration()||e.isFunctionExpression()||e.isArrowFunctionExpression()))return{kind:"unknown"};let r=e,o=[];for(let s of r.get("params"))s.isAssignmentPattern()&&o.push(s.get("right")),s.traverse({AssignmentPattern(a){o.push(a.get("right"))}});let i=r.get("body");return i.isBlockStatement()?i.traverse({Function(s){s.skip()},ReturnStatement(s){let a=s.get("argument");a.node&&o.push(a),s.skip()}}):o.push(i),{kind:"sources",sources:o,aliases:t}}function Qa(e,t){return JSON.stringify([t,e])}var xT=new Set;function fx(e,t){let n=new Map,r=[],o=new Map,i=(p,m)=>JSON.stringify([p,m.loc?.start.line,m.loc?.start.column,m.loc?.end.line,m.loc?.end.column]);for(let p of e.graph.elements.values()){let m=p.sourceRange;o.set(JSON.stringify([p.sourceFile,m.startLine,m.startColumn,m.endLine,m.endColumn]),p)}let s=p=>r.push({code:"render-occurrence-unproven",message:"A block render occurrence cannot be proven statically.",file:p}),a=(p,m)=>!dx(m)&&[...t].some(y=>e.graph.elements.get(y)?.sourceFile===p);function c(p,m,y,x,S,b=xT){if(p.isIdentifier())return x&&qa(p,x)?x.children.some(k=>c(k.path,k.file,y,k.substitution,S,b)):u({path:p,file:m,active:y,substitution:x,unknownIsRelevant:S,aliases:b});if(p.isCallExpression()||p.isOptionalCallExpression()){let k=p,I=sx(k,b,e.parsedModules);return I.kind==="guard"||I.kind==="sources"&&I.sources.some(v=>c(v,[...e.parsedModules.values()].find(N=>N.ast.program===v.scope.getProgramParent().path.node)?.file??m,y,x,S,I.aliases))?!0:k.get("arguments").some(v=>c(v,m,y,x,S,b))||I.kind==="unknown"&&S}if(p.isJSXElement()){if(Ye(p))return p.get("children").some(F=>c(F,m,y,x,S,b));let k=o.get(i(m,p.node));if(k){if(t.has(k.identity.key))return!0;if(k.boundaryKind==="component-boundary"&&!k.isPublicUiComponent){let F=e.parsedModules.get(k.sourceFile);if(!F)return!1;let B=gr({module:F,componentName:k.tag,callSourceRange:k.sourceRange,...k.importedFrom?{imported:{file:k.importedFrom,module:e.parsedModules.get(k.importedFrom),exportName:k.exportName??k.tag,parsedModules:e.parsedModules}}:{}});return B.ok?B.metadataOnly?!1:l(B,p,k.sourceFile,y,x,b):B.diagnostic.code==="component-external-module-opaque"?Xi(p).some(X=>c(X,m,y,x,!1,b)):a(F.file,B.diagnostic.code)}return p.get("children").some(F=>c(F,m,y,x,S,b))}let I=p.node.openingElement.name;if(!bn.isJSXIdentifier(I))return!1;if(/^[a-z]/.test(I.name))return p.get("children").some(F=>c(F,m,y,x,S,b));let v=e.parsedModules.get(m),N=p.node.loc;if(!v||!N)return!1;let A=vT({path:p,file:m,componentName:I.name,parsedModules:e.parsedModules}),w=gr({module:v,componentName:I.name,callSourceRange:{startLine:N.start.line,startColumn:N.start.column,endLine:N.end.line,endColumn:N.end.column},...A?{imported:A}:{}});return w.ok?w.metadataOnly?!1:l(w,p,m,y,x,b):w.diagnostic.code==="component-external-module-opaque"?Xi(p).some(F=>c(F,m,y,x,!1,b)):a(v.file,w.diagnostic.code)}if(p.isJSXFragment())return p.get("children").some(k=>c(k,m,y,x,S,b));if(p.isJSXExpressionContainer()||p.isParenthesizedExpression()||p.isTSAsExpression()||p.isTSNonNullExpression()||p.isTSTypeAssertion())return c(p.get("expression"),m,y,x,S,b);let E=!1;return p.traverse({"CallExpression|OptionalCallExpression"(k){c(k,m,y,x,S,b)&&(E=!0),k.skip(),E&&k.stop()},ReferencedIdentifier(k){c(k,m,y,x,S,b)&&(E=!0),E&&k.stop()},JSXElement(k){c(k,m,y,x,S,b)&&(E=!0),k.skip(),E&&k.stop()},JSXFragment(k){c(k,m,y,x,S,b)&&(E=!0),k.skip(),E&&k.stop()}}),E?!0:S&&!oo(p)}function l(p,m,y,x,S,b){let E=`${p.sourceFile}#${p.componentName}`;if(x.has(E))return!1;let k=new Set(x).add(E);return p.returnAlternatives?.some(I=>Xi(I).some(v=>c(v,p.sourceFile,k,null,!1,b)))||p.roots.some(I=>c(I,p.sourceFile,k,null,!1,b))?!0:cx(p.roots).kind==="none"?!1:ux(m).some(I=>c(I,y,k,S,!0,b))}function u(p){if(!p.path.isIdentifier())return p.unknownIsRelevant;let m=ix({path:p.path,aliases:p.aliases});return m.kind==="unbound"?p.unknownIsRelevant&&p.path.node.name!=="undefined":m.kind==="guard"||m.kind==="reassigned"?!0:m.kind==="not-alias"?p.unknownIsRelevant:c(m.initializer,p.file,p.active,p.substitution,p.unknownIsRelevant,m.aliases)?!0:Jd(m.initializer).isIdentifier()?!1:p.unknownIsRelevant&&!oo(m.initializer)}let d=(p,m,y,x,S,b)=>{if(p.isIdentifier()){c(p,m,x,b,!1)&&s(m);return}if(p.isJSXElement()){if(Ye(p)){for(let I of p.get("children"))d(I,m,y,x,S,b);return}let E=o.get(i(m,p.node));if(!E)return;let k=E.identity.key;if(t.has(k)){S||s(m);let I=n.get(k)??[];I.push(Qa(k,y)),n.set(k,I)}if(E.boundaryKind==="component-boundary"&&!E.isPublicUiComponent){let I=e.parsedModules.get(E.sourceFile);if(!I)return;let v=gr({module:I,componentName:E.tag,callSourceRange:E.sourceRange,...E.importedFrom?{imported:{file:E.importedFrom,module:e.parsedModules.get(E.importedFrom),exportName:E.exportName??E.tag,parsedModules:e.parsedModules}}:{}});if(!v.ok){if(v.diagnostic.code==="component-external-module-opaque"){Xi(p).some(X=>c(X,m,x,b,!1))&&s(m);return}[...t].some(X=>e.graph.elements.get(X)?.sourceFile===I.file)&&!dx(v.diagnostic.code)&&s(I.file);return}if(v.metadataOnly)return;let N=`${v.sourceFile}#${v.componentName}`;if(x.has(N)){s(I.file);return}let A=new Set(x).add(N);v.returnAlternatives?.some(X=>Xi(X).some($=>c($,v.sourceFile,A,b,!1)))&&s(v.sourceFile);let w=cx(v.roots),F=IT(p);if(w.kind==="unproven"||w.kind==="supported"&&F){for(let X of ux(p))if(c(X,m,A,b,!0)){s(m);break}}let B=w.kind==="supported"&&!F?{bindingNode:w.bindingNode,children:p.get("children").map(X=>({path:X,file:m,substitution:b}))}:null;for(let X of v.roots)d(X,v.sourceFile,[...y,k],A,S,B);return}for(let I of p.get("children"))d(I,m,y,x,S,b);return}if(p.isJSXFragment()){for(let E of p.get("children"))d(E,m,y,x,S,b);return}if(p.isJSXExpressionContainer()){let E=p.get("expression");if(b&&!E.isJSXEmptyExpression()){let k=Jd(E);if(qa(k,b)){for(let I of b.children)d(I.path,I.file,y,x,S,I.substitution);return}if(bT(E,b))for(let I of b.children)d(I.path,I.file,y,x,!1,I.substitution)}d(E,m,y,x,S,b);return}if(p.isParenthesizedExpression()||p.isTSAsExpression()||p.isTSNonNullExpression()||p.isTSTypeAssertion()){d(p.get("expression"),m,y,x,S,b);return}c(p,m,x,b,!1)&&s(m),p.traverse({JSXElement(E){d(E,m,y,x,!1,b),E.skip()}})},f=e.parsedModules.get(e.entryFile);if(!f)return{occurrences:n,diagnostics:r};let g=hn({module:f,exportName:"default",allowNonRenderingGuards:!0});if(!g.ok)return s(e.entryFile),{occurrences:n,diagnostics:r};for(let p of g.roots)d(p,f.file,[],new Set,!0,null);return{occurrences:n,diagnostics:r}}function Jd(e){let t=e;for(;t.isParenthesizedExpression()||t.isTSAsExpression()||t.isTSNonNullExpression()||t.isTSTypeAssertion();)t=t.get("expression");return t}function oo(e){let t=Jd(e);return t.isStringLiteral()||t.isNumericLiteral()||t.isBooleanLiteral()||t.isNullLiteral()||t.isBigIntLiteral()||t.isJSXElement()||t.isJSXFragment()?!0:t.isIdentifier()?t.node.name==="undefined"&&!t.scope.getBinding("undefined"):t.isTemplateLiteral()?t.node.expressions.length===0:t.isArrayExpression()?t.get("elements").every(n=>!n.node||oo(n)):t.isConditionalExpression()?oo(t.get("consequent"))&&oo(t.get("alternate")):t.isLogicalExpression()?oo(t.get("left"))&&oo(t.get("right")):!1}function qa(e,t){if(!e.isIdentifier())return!1;let n=e.scope.getBinding(e.node.name);return!!(n&&(n.path.node===t.bindingNode||n.identifier===t.bindingNode))}function bT(e,t){if(qa(e,t))return!0;let n=!1;return e.traverse({Identifier(r){qa(r,t)&&(n=!0,r.stop())}}),n}function cx(e){let t=e[0]?.getFunctionParent();if(!t)return{kind:"none"};let n=t.get("params")[0];return n?n.isAssignmentPattern()?lx(n.get("left"),!0):lx(n,!1):{kind:"none"}}function lx(e,t){if(e.isObjectPattern()){let n=[],r=!1;for(let i of e.get("properties")){if(i.isObjectProperty()){if(i.node.computed){wn(i.get("value"))&&(r=!0);continue}let s=i.node.key;(bn.isIdentifier(s)?s.name:bn.isStringLiteral(s)?s.value:null)==="children"&&n.push(i);continue}i.isRestElement()&&wn(i.get("argument"))&&(r=!0)}if(n.length>1)return r||n.some(i=>wn(i.get("value")))?{kind:"unproven"}:{kind:"none"};if(n.length===0)return r?{kind:"unproven"}:{kind:"none"};if(r)return{kind:"unproven"};let o=n[0].get("value");if(o.isIdentifier()){let i=o.scope.getBinding(o.node.name);return!i||i.path.node!==o.node&&i.identifier!==o.node?{kind:"unproven"}:i.constantViolations.length>0?{kind:"unproven"}:i.referencePaths.length===0?{kind:"none"}:i.referencePaths.every(s=>ET(s))?t?{kind:"unproven"}:{kind:"supported",bindingNode:o.node}:{kind:"unproven"}}return wn(o)?{kind:"unproven"}:{kind:"none"}}if(e.isIdentifier()){let n=e.scope.getBinding(e.node.name);return!n||n.referencePaths.length===0?{kind:"none"}:n.referencePaths.every(r=>ST(r))?{kind:"none"}:{kind:"unproven"}}return wn(e)?{kind:"unproven"}:{kind:"none"}}function wn(e){if(e.isIdentifier()){let t=e.scope.getBinding(e.node.name);return!!(t&&t.referencePaths.length>0)}return e.isAssignmentPattern()?wn(e.get("left")):e.isRestElement()?wn(e.get("argument")):e.isObjectPattern()?e.get("properties").some(t=>t.isObjectProperty()?wn(t.get("value")):t.isRestElement()?wn(t.get("argument")):!0):e.isArrayPattern()?e.get("elements").some(t=>t.node?wn(t):!1):!0}function ET(e){let t=e.parentPath;for(;t&&(t.isParenthesizedExpression()||t.isTSAsExpression()||t.isTSNonNullExpression()||t.isTSTypeAssertion());)t=t.parentPath;if(!t||!t.isJSXExpressionContainer())return!1;let n=t.parentPath;return!!(n&&(n.isJSXElement()||n.isJSXFragment()))}function ST(e){let t=e.parentPath;if(!t||!t.isMemberExpression()&&!t.isOptionalMemberExpression()||t.node.object!==e.node)return!1;let n=t.node.property;return t.node.computed?bn.isStringLiteral(n)&&n.value!=="children":bn.isIdentifier(n)&&n.name!=="children"}function IT(e){for(let t of e.get("openingElement").get("attributes")){if(t.isJSXAttribute()){let n=t.node.name;if(bn.isJSXIdentifier(n)&&n.name==="children")return!0;continue}if(t.isJSXSpreadAttribute()&&px(t.get("argument")))return!0}return!1}function ux(e){let t=e.get("children").map(n=>n);for(let n of e.get("openingElement").get("attributes")){if(n.isJSXAttribute()){let r=n.node.name;if(!bn.isJSXIdentifier(r)||r.name!=="children")continue;let o=n.get("value");o&&!Array.isArray(o)&&t.push(o);continue}if(n.isJSXSpreadAttribute()){let r=n.get("argument");px(r)&&t.push(r)}}return t}function Xi(e){let t=e.get("children").map(n=>n);for(let n of e.get("openingElement").get("attributes"))if(n.isJSXSpreadAttribute())t.push(n.get("argument"));else if(n.isJSXAttribute()){let r=n.get("value");r&&!Array.isArray(r)&&t.push(r)}return t}function px(e){if(e.isJSXElement()||e.isJSXFragment())return!0;let t=!1;return e.traverse({JSXElement(n){t=!0,n.stop()},JSXFragment(n){t=!0,n.stop()}}),t}function vT(e){let t=e.path.scope.getBinding(e.componentName);if(!t)return;let n=t.path;if(!n.isImportDefaultSpecifier()&&!n.isImportSpecifier())return;let r=n.parentPath;if(!r?.isImportDeclaration())return;let o=sr(e.file,r.node.source.value,e.parsedModules);if(!o)return;let i=n.isImportDefaultSpecifier()?"default":bn.isIdentifier(n.node.imported)?n.node.imported.name:n.node.imported.value;return{file:o,module:e.parsedModules.get(o),exportName:i,parsedModules:e.parsedModules}}function dx(e){return e==="component-export-unresolved"||e==="component-local-binding-unresolved"}function hx(e){let t=[],n=[];return yx(e.element,e,[],e.ownerNode,e.element,[],new Set,t,n),{roots:t,diagnostics:n}}function yx(e,t,n,r,o,i,s,a,c,l=[]){if(l.length>1&&(e.boundaryKind!=="component-boundary"||e.isPublicUiComponent)){c.push({code:"conditional-component-root-unproven",message:"Conditional returns require one proven local component definition.",file:e.sourceFile});return}if(e.boundaryKind!=="component-boundary"||e.isPublicUiComponent){if(gd(e.tag))return;a.push({element:e,callChain:n,ownerNode:r,ownerMember:o,ownerCallChain:i});return}let u=t.parsedModules.get(e.sourceFile);if(!u){c.push({code:"component-module-unavailable",message:"The component source module is unavailable in the parsed graph.",file:e.sourceFile,structuralPath:e.identity.structuralPath});return}let d=gr({module:u,componentName:e.tag,callSourceRange:e.sourceRange,...e.importedFrom?{imported:{file:e.importedFrom,module:t.parsedModules.get(e.importedFrom),exportName:e.exportName??e.tag,parsedModules:t.parsedModules}}:{}});if(!d.ok){c.push({...d.diagnostic,structuralPath:e.identity.structuralPath});return}if(d.metadataOnly)return;let f=d.sourceFile,g=`${f}#${d.componentName}`;if(s.has(g)){c.push({code:"component-call-cycle",message:"A component call cycle cannot be expanded safely.",file:e.sourceFile,structuralPath:e.identity.structuralPath});return}if(d.roots.length===0){c.push({code:"component-root-empty",message:"A component call has no statically addressable JSX root.",file:f,structuralPath:e.identity.structuralPath});return}let p=[...n,{sourceFile:e.sourceFile,component:e.tag,exportName:e.exportName??e.tag,callLocator:{key:e.identity.key,structuralPath:e.identity.structuralPath,sourceRange:e.sourceRange},...l.length>1?{alternativeLocators:l.map(S=>({key:S.identity.key,structuralPath:S.identity.structuralPath,sourceRange:S.sourceRange}))}:{}}],m=d.roots.length>1?{kind:"component-definition",key:g}:r,y=new Set(s);y.add(g);let x=[];for(let S of d.returnAlternatives??[]){let b=gx(S),E=b?mx(t.graph,f,b):[];if(E.length!==1){c.push({code:"conditional-component-root-unproven",message:"A conditional call site is absent or ambiguous in the source graph.",file:f});return}x.push(E[0])}for(let S of d.roots){let b=gx(S),E=b?mx(t.graph,f,b):[];if(E.length!==1){c.push({code:E.length?"component-root-ambiguous":"component-root-unresolved",message:"The component root could not be matched to one source graph node.",file:f,structuralPath:e.identity.structuralPath});continue}yx(E[0],t,p,m,d.roots.length>1?E[0]:o,d.roots.length>1?p:i,y,a,c,x)}}function mx(e,t,n){return(e.fileIndex.get(t)??[]).map(r=>e.elements.get(r)).filter(r=>!!r&&r.sourceRange.startLine===n.startLine&&r.sourceRange.startColumn===n.startColumn&&r.sourceRange.endLine===n.endLine&&r.sourceRange.endColumn===n.endColumn)}function gx(e){let t=e.node.loc;return t?{startLine:t.start.line,startColumn:t.start.column,endLine:t.end.line,endColumn:t.end.column}:null}function ec(e){let t=[],n=[];if(e.projection.entryFile!==e.entryFile||!bx(e.projection.composition,e.composition)||e.graph.composition&&!bx(e.graph.composition,e.composition))return{roots:[],diagnostics:[zi("composition-mismatch",e.entryFile)]};if(!e.parsedModules.has(e.entryFile))return{roots:[],diagnostics:[zi("entry-module-unavailable",e.entryFile)]};for(let i of e.graph.diagnostics??[])t.push({code:`source-graph-${i.code}`,message:i.message,file:i.path});let r=e.projection.placements.filter(i=>i.relation==="before").flatMap(i=>i.members);for(let i of r){if(i.kind==="text")continue;if(i.kind!=="jsx-element"||!i.sourceRange){t.push(zi("route-member-not-addressable",e.entryFile));continue}let s=CT(e.graph,e.entryFile,i.sourceRange);if(s.length!==1){t.push(zi(s.length?"route-root-ambiguous":"route-root-unresolved",e.entryFile));continue}let a=s[0],c=hx({element:a,graph:e.graph,parsedModules:e.parsedModules,ownerNode:{kind:"route-member",key:a.parentKey??`${e.entryFile}#${e.projection.container.placementKey}`}});t.push(...c.diagnostics);for(let l of c.roots){let u=l.ownerMember;n.push({...l,parentStructuralPath:u.parentKey?e.graph.elements.get(u.parentKey)?.identity.structuralPath??null:null})}}let o=fx(e,new Set(n.map(i=>i.element.identity.key)));t.push(...o.diagnostics);for(let i of n){let s=i.element.identity.key,a=Qa(s,i.callChain.map(c=>c.callLocator.key));o.occurrences.get(s)?.filter(c=>c===a).length!==1&&t.push(zi("render-occurrence-unproven",i.element.sourceFile))}return{roots:_T(n,e.composition,o.occurrences),diagnostics:t}}function _T(e,t,n){let r=e.map(i=>{let s=i.element,a=n.get(s.identity.key)??[],c=i.callChain.map(l=>l.callLocator.key);return{rootKey:kT("sha256").update(JSON.stringify([t,c,s.identity.key])).digest("hex"),rootRef:{key:s.identity.key,...a.length>1?{instanceIndex:a.indexOf(Qa(s.identity.key,c)),instanceCount:a.length}:{}},sourceFile:s.sourceFile,structuralPath:s.identity.structuralPath,sourceRange:s.sourceRange,callChain:i.callChain,ownerNode:i.ownerNode,ownerMemberKey:i.ownerMember.identity.key,ownerCallKeys:i.ownerCallChain.map(l=>l.callLocator.key),parentStructuralPath:i.parentStructuralPath,siblingRootKeys:[],siblingIndex:0}}),o=new Map;for(let i of r){let s=xx(i);o.set(s,[...o.get(s)??[],i])}return r.map(i=>{let s=o.get(xx(i))??[i];return{...i,siblingIndex:s.indexOf(i),siblingRootKeys:s.filter(a=>a!==i).map(a=>a.rootKey)}})}function xx(e){return JSON.stringify([e.ownerNode.kind,e.ownerNode.key,e.parentStructuralPath,e.ownerCallKeys])}function CT(e,t,n){return(e.fileIndex.get(t)??[]).map(r=>e.elements.get(r)).filter(r=>!!r&&r.sourceRange.startLine===n.startLine&&r.sourceRange.startColumn===n.startColumn&&r.sourceRange.endLine===n.endLine&&r.sourceRange.endColumn===n.endColumn)}function bx(e,t){return e.routeId===t.routeId&&e.effectiveTemplateId===t.effectiveTemplateId}function zi(e,t){return{code:e,message:"Page block roots could not be proven from the current source graph.",file:t}}import{SiteEditPageBlockDirectorySchema as RT,SiteEditPageBlockDescriptorSchema as NT,SiteEditSourcePathSchema as Sx}from"@vcp-dev/contracts";function tc(e){let t=new Map;for(let[n,r]of e.elements){let o=/^[A-Z]/.test(r.tag),i={file:r.sourceFile,componentName:r.componentName,isProxy:o},s=r.boundaryKind,a=[];r.isOpaque&&a.push({kind:"opaque-region",reason:`Component '${r.tag}' is opaque: internal structure not editable`}),o&&!r.isOpaque&&a.push({kind:"component-boundary",reason:`Component '${r.tag}' boundary: editing requires source file access`});let c={key:n,writeTarget:i,boundaryKind:s,parentKey:r.parentKey,childKeys:[...r.childKeys],constraints:a};t.set(n,c)}for(let n of e.regions){let r=n.kind==="repeat-region"?"repeat-region":n.kind==="conditional-region"?"conditional-region":n.kind==="opaque-region"?"opaque-region":"component-boundary",o=n.kind==="repeat-region"?"Node is inside a repeat region: operations affect the template, not individual instances":n.kind==="conditional-region"?"Node is inside a conditional region: visibility depends on runtime condition":`Node is inside a ${n.kind}`;for(let i of n.childKeys){let s=t.get(i);s&&s.constraints.push({kind:r,reason:o}),Ex(i,r,o,t,e)}}return{nodes:t,rootKeys:[...e.rootKeys]}}function Ex(e,t,n,r,o){let i=o.elements.get(e);if(i)for(let s of i.childKeys){let a=r.get(s);a&&!a.constraints.some(c=>c.kind===t)&&(a.constraints.push({kind:t,reason:n}),Ex(s,t,n,r,o))}}function Hi(e){let t=[],n={...e.graph,composition:e.composition},r=ma(tc(n),n),o=[],i=new Map;for(let a of e.roots){let c=e.graph.elements.get(a.rootRef.key),l=e.graph.elements.get(a.ownerMemberKey),u=e.parsedModules.get(a.sourceFile),d=TT(a,e.graph),f=d?e.parsedModules.get(d):void 0;if(!c||!l||l.sourceFile!==d||!u||!Sx.safeParse(a.sourceFile).success||!d||!f||!Sx.safeParse(d).success){t.push(Xd("root-source-unavailable",a.sourceFile));continue}if(i.has(a.rootKey)){t.push(Xd("block-key-ambiguous",a.sourceFile));continue}let g=ke(u.source),p=NT.safeParse({blockKey:a.rootKey,rootRef:a.rootRef,definitionKey:a.rootRef.key,source:{file:a.sourceFile,structuralPath:a.structuralPath,contentHash:g},owner:a.ownerNode,siblingBlockKeys:a.siblingRootKeys,placementUnitKey:wT(a,e),capabilities:PT(c,r),...AT(c,r)});if(!p.success){t.push(Xd("page-block-descriptor-invalid",a.sourceFile));continue}let m=p.data;o.push(m),i.set(a.rootKey,{blockKey:a.rootKey,composition:e.composition,documentVersion:e.documentVersion,descriptor:m,root:a,ownerFile:d,ownerSourceHash:ke(f.source),ownerSourceContent:f.source,sourceHash:g,sourceContent:u.source,ownerLocator:{kind:"jsx-element",file:l.sourceFile,sourceRange:l.sourceRange,structuralPath:l.identity.structuralPath,componentName:l.componentName},rootLocator:{kind:"jsx-element",file:c.sourceFile,sourceRange:c.sourceRange,structuralPath:c.identity.structuralPath,componentName:c.componentName}})}let s=RT.safeParse(o);return s.success?{composition:e.composition,documentVersion:e.documentVersion,descriptors:s.data,bindings:i,diagnostics:t}:{composition:e.composition,documentVersion:e.documentVersion,descriptors:[],bindings:new Map,diagnostics:[...t,{code:"page-block-directory-invalid",message:"The proven page block directory failed its strict contract."}]}}function PT(e,t){let n=t.get(e.identity.key),r=e.parentKey?t.get(e.parentKey):void 0;return{insert:r?r.canInsertChild:!0,replace:!!(n?.canRemove&&(!r||r.canInsertChild)),move:n?.canMove??!1,remove:n?.canRemove??!1,save:!0}}function AT(e,t){let n=t.get(e.identity.key),r={},o=n?.constraints[0]?.message??"The existing Engine capability check denied this operation.";return(!n||!n.canRemove)&&(r.replace={code:n?"CAPABILITY_DENIED":"CAPABILITY_UNAVAILABLE",reason:o},r.remove={code:n?"CAPABILITY_DENIED":"CAPABILITY_UNAVAILABLE",reason:o}),(!n||!n.canMove)&&(r.move={code:n?"CAPABILITY_DENIED":"CAPABILITY_UNAVAILABLE",reason:o}),Object.keys(r).length?{unavailableReasons:r}:{}}function TT(e,t){if(e.ownerNode.kind==="component-definition"){let n=e.ownerNode.key.lastIndexOf("#");return n>0?e.ownerNode.key.slice(0,n):null}return t.elements.get(e.ownerMemberKey)?.sourceFile??null}function wT(e,t){let n=e.callChain[0]?.callLocator.key??e.rootRef.key,r=t.graph.elements.get(n);if(r)return t.projection.placements.find(o=>o.members.some(i=>i.sourceRange!==null&&i.sourceRange.startLine===r.sourceRange.startLine&&i.sourceRange.startColumn===r.sourceRange.startColumn&&i.sourceRange.endLine===r.sourceRange.endLine&&i.sourceRange.endColumn===r.sourceRange.endColumn))?.placementUnitKey}function Xd(e,t){return{code:e,message:"The page block source binding could not be proven.",file:t}}import zd from"@babel/traverse";import{BlockRenderRefSchema as OT,SiteEditPageBlockPositionSchema as FT,SiteEditPageBlockTargetSchema as LT}from"@vcp-dev/contracts";var MT=typeof zd=="function"?zd:zd.default;function jo(e,t,n,r){if(!LT.safeParse(t).success)return Bt("INVALID_PARAMS","Invalid page block target.");if(n!==e.documentVersion)return Bt("VERSION_STALE","The page block index is stale.");if(t.composition.routeId!==e.composition.routeId||t.composition.templateId!==e.composition.effectiveTemplateId)return Bt("INVALID_TARGET","The target belongs to another composition.");let o=e.bindings.get(t.blockKey);return o?r&&(!OT.safeParse(r).success||r.key!==o.descriptor.rootRef.key||r.instanceIndex!==o.descriptor.rootRef.instanceIndex||r.instanceCount!==o.descriptor.rootRef.instanceCount)?Bt("INVALID_TARGET","The render occurrence does not match the target."):{ok:!0,binding:o}:Bt("INVALID_TARGET","The page block target was not found.")}function nc(e,t){if(!FT.safeParse(t).success)return Bt("INVALID_PARAMS","Invalid page block boundary.");if(t.documentVersion!==e.documentVersion)return Bt("VERSION_STALE","The page block boundary is stale.");if(t.composition.routeId!==e.composition.routeId||t.composition.templateId!==e.composition.effectiveTemplateId)return Bt("INVALID_TARGET","The boundary belongs to another composition.");let n=e.bindings.get(t.anchorBlockKey);if(!n)return Bt("INVALID_TARGET","The boundary anchor was not found.");let r=[n,...n.descriptor.siblingBlockKeys.map(u=>e.bindings.get(u))];if(r.some(u=>!u))return Bt("INVALID_TARGET","A verified sibling binding is unavailable.");let o=r.sort((u,d)=>u.root.siblingIndex-d.root.siblingIndex),i=Ix(n);if(!i)return Bt("INVALID_TARGET","The operation owner call site is unavailable.");let s=vx(n,i);if(s===void 0)return Bt("INVALID_TARGET","The boundary parent source range is ambiguous.");for(let u of o)if(u.ownerFile!==n.ownerFile||u.root.ownerNode.kind!==n.root.ownerNode.kind||u.root.ownerNode.key!==n.root.ownerNode.key||!DT(vx(u,Ix(u)),s))return Bt("INVALID_TARGET","Siblings do not share one proven source boundary.");let a=o.findIndex(u=>u.blockKey===n.blockKey);if(a<0)return Bt("INVALID_TARGET","Anchor order is ambiguous.");let c=t.placement==="before"?o[a-1]:n,l=t.placement==="before"?n:o[a+1];return{ok:!0,boundary:{ownerFile:n.ownerFile,parentLocator:s,anchorLocator:i,sourceHash:n.ownerSourceHash,placement:t.placement,beforeBlockKey:c?.blockKey??null,afterBlockKey:l?.blockKey??null}}}function Ix(e){return e.ownerLocator.file===e.ownerFile?e.ownerLocator:null}function vx(e,t){if(!t)return;let n=je(t.file,e.ownerSourceContent);if(!n.ok)return;let r=[];if(MT(n.module.ast,{JSXElement(i){let s=Hd(i.node);s&&s.startLine===t.sourceRange.startLine&&s.startColumn===t.sourceRange.startColumn&&s.endLine===t.sourceRange.endLine&&s.endColumn===t.sourceRange.endColumn&&r.push(i)}}),r.length!==1)return;let o=r[0].parentPath;for(;o;){if(o.isJSXFragment()){let i=Hd(o.node);return i?{kind:"jsx-fragment",file:t.file,sourceRange:i}:void 0}if(o.isJSXElement()){let i=Hd(o.node),s=t.structuralPath?.lastIndexOf("/")??-1,a=s<0?void 0:t.structuralPath.slice(0,s);return i?{kind:"jsx-element",file:t.file,sourceRange:i,...a?{structuralPath:a}:{},...t.componentName?{componentName:t.componentName}:{}}:void 0}o=o.parentPath}return null}function DT(e,t){return e===void 0||t===void 0||e===null||t===null?e===t:e.file===t.file&&e.kind===t.kind&&e.sourceRange.startLine===t.sourceRange.startLine&&e.sourceRange.startColumn===t.sourceRange.startColumn&&e.sourceRange.endLine===t.sourceRange.endLine&&e.sourceRange.endColumn===t.sourceRange.endColumn}function Hd(e){let t=e.loc;return t?{startLine:t.start.line,startColumn:t.start.column,endLine:t.end.line,endColumn:t.end.column}:null}function Bt(e,t){return{ok:!1,code:e,message:t}}import Cx from"node:path";import{SiteEditSourcePathSchema as WT}from"@vcp-dev/contracts";import rc from"node:path";import Wd from"@babel/traverse";import*as Er from"@babel/types";import{SiteEditSourcePathSchema as kx,SiteEditPageBlockTargetSchema as BT}from"@vcp-dev/contracts";var jT=typeof Wd=="function"?Wd:Wd.default;function _x(e){if(!e.operationId)return st("INVALID_PARAMS","An operationId is required.");if(!BT.safeParse(e.target).success)return st("INVALID_PARAMS","Invalid page block target.");if(e.target.kind!=="page-block"||e.target.blockKey!==e.binding.blockKey||e.target.composition.routeId!==e.binding.composition.routeId||e.target.composition.templateId!==e.binding.composition.effectiveTemplateId)return st("INVALID_TARGET","The request target does not match its resolved block binding.");if(e.documentVersion!==e.binding.documentVersion)return st("VERSION_STALE","The resolved block belongs to a stale document version.");if(e.operation==="move-node"||e.operation==="remove-node")return st("UNSUPPORTED_OPERATION","Move and remove are planned by the structural operation task.");if(!e.node)return st("INVALID_PARAMS","An insert/replacement node is required.");let t=e.operation==="insert-child"?e.boundary?.ownerFile:e.binding.ownerFile;if(!t||!kx.safeParse(t).success)return st("INVALID_TARGET","The exact owner source file is unavailable.");let n=e.files.get(t);if(n===void 0)return st("INVALID_TARGET","The exact owner source is absent from the fixed file map.");if(ke(n)!==e.binding.ownerSourceHash)return st("VERSION_STALE","The owner source hash changed after target resolution.");let r=e.files.get(e.binding.descriptor.source.file);if(r===void 0||ke(r)!==e.binding.descriptor.source.contentHash)return st("VERSION_STALE","The block source hash changed after target resolution.");let o;if(e.operation==="insert-child"){if(o=e.boundary,!o||o.ownerFile!==e.binding.ownerFile||o.sourceHash!==e.binding.ownerSourceHash||o.anchorLocator.file!==t||o.parentLocator?.file!==t)return st("INVALID_TARGET","The insertion boundary is not in the resolved source owner.");let l=o.placement==="before"?o.afterBlockKey:o.beforeBlockKey;if(l!==e.binding.blockKey&&!e.binding.descriptor.siblingBlockKeys.includes(l??""))return st("INVALID_TARGET","The boundary anchor is not a verified same-owner sibling.");if(!o.parentLocator)return st("UNSUPPORTED_OPERATION","A root without a source parent has no safe sibling insertion boundary.")}let i=VT(e.node,t,n,e.files);if(!i.ok)return i;let s=e.operation==="replace-node"?ko({source:n,locator:$T(e.binding),node:{jsx:i.value.jsx}}):on({source:n,locator:Gd(o.parentLocator),anchorLocator:Gd(o.anchorLocator),placement:o.placement,node:{jsx:i.value.jsx}});if(!s.ok)return st("UNSUPPORTED_OPERATION",s.diagnostic.message);let a=s.source;if(i.value.import){let l=sn({source:a,moduleSpecifier:i.value.import.moduleSpecifier,imports:i.value.import.specifiers});if(!l.ok)return st("UNSUPPORTED_OPERATION",l.diagnostic.message);a=l.source}return{ok:!0,plan:{operationId:e.operationId,kind:"source-edit",target:e.target,documentVersion:e.documentVersion,conflictPolicy:"compare-and-swap",edits:[{operation:"upsert",file:t,content:a,baseContentHash:e.binding.ownerSourceHash}]}}}function $T(e){return Gd(e.ownerLocator)}function Gd(e){return{kind:"jsx-node",strategy:"source-range",sourceRange:e.sourceRange,...e.structuralPath&&e.componentName?{expectedIdentity:{file:e.file,component:e.componentName,structuralPath:e.structuralPath}}:{}}}function VT(e,t,n,r){if(e.kind==="native-tag")return/^[A-Za-z][A-Za-z0-9:_-]*$/.test(e.tag)?{ok:!0,value:{jsx:e.text===void 0?`<${e.tag} />`:`<${e.tag}>{${JSON.stringify(e.text)}}</${e.tag}>`}}:st("INVALID_PARAMS","The native JSX tag is invalid.");if(!e.component)return st("UNSUPPORTED_OPERATION","A materialized component entry is resolved by the materialization task.");let o=UT(t,e.component.source,r);if(!o)return st("INVALID_TARGET","The component source is not in the safe fixed file map.");let i=je(t,n);if(!i.ok)return st("UNSUPPORTED_OPERATION",i.diagnostic.message);let s=KT(i.module.ast.program.body,e.component.source,e.component.exportName),a=s??XT(zT(e.component.exportName,o),JT(i.module.ast)),c=HT(e.props??{});if(!c.ok)return c;let l=`<${a}${c.value?` ${c.value}`:""} />`;if(s)return{ok:!0,value:{jsx:l}};let u=e.component.exportName==="default"?{kind:"default",local:a}:{kind:"named",imported:e.component.exportName,...a!==e.component.exportName?{local:a}:{}};return{ok:!0,value:{jsx:l,import:{moduleSpecifier:e.component.source,specifiers:[u]}}}}function UT(e,t,n){let r=t.startsWith("@/")?t.slice(2):t.startsWith("./")||t.startsWith("../")?rc.posix.normalize(rc.posix.join(rc.posix.dirname(e),t)):null;return r?(/\.(?:tsx?|jsx?)$/i.test(r)?[r]:[".tsx",".ts",".jsx",".js"].map(i=>`${r}${i}`).concat([".tsx",".ts",".jsx",".js"].map(i=>`${r}/index${i}`))).find(i=>kx.safeParse(i).success&&n.has(i))??null:null}function KT(e,t,n){for(let r of e)if(!(!Er.isImportDeclaration(r)||r.source.value!==t)){for(let o of r.specifiers)if(n==="default"&&Er.isImportDefaultSpecifier(o)||n!=="default"&&Er.isImportSpecifier(o)&&(Er.isIdentifier(o.imported)?o.imported.name:o.imported.value)===n)return o.local.name}return null}function JT(e){let t=new Set;return jT(e,{Program(n){n.scope.crawl(),t=new Set(Object.keys(n.scope.bindings)),n.stop()}}),t}function XT(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n+=1;return`${e}${n}`}function zT(e,t){let r=(e==="default"?rc.posix.basename(t).replace(/\.(?:tsx?|jsx?)$/i,""):e).replace(/[^A-Za-z0-9_$]/g,""),o=r?r[0].toUpperCase()+r.slice(1):"Component";return/^[A-Za-z_$][\w$]*$/.test(o)?o:"Component"}function HT(e){let t=[];for(let[n,r]of Object.entries(e)){if(!/^[A-Za-z_][A-Za-z0-9_:.-]*$/.test(n))return st("INVALID_PARAMS","A component prop name is invalid.");let o;try{o=JSON.stringify(r)}catch{return st("INVALID_PARAMS","Component props must be JSON serializable.")}if(o===void 0)return st("INVALID_PARAMS","Component props must be JSON serializable.");t.push(`${n}={${o}}`)}return{ok:!0,value:t.join(" ")}}function st(e,t){return{ok:!1,code:e,message:t}}function Rx(e){if(e.materialization.kind!=="static-prefab-materialization"||!e.materialization.files.some(i=>i.path===e.materialization.entry.path))return oc("MATERIALIZATION_ENTRY_INVALID","The materialization entry must identify one controlled create-only file.");if(!e.materialization.files.every(i=>i.kind==="create-only"&&WT.safeParse(i.path).success))return oc("MATERIALIZATION_PATH_INVALID","Every materialized output must remain a safe create-only Snapshot source.");if(e.materialization.files.some(i=>e.files.has(i.path)))return oc("MATERIALIZATION_INSTANCE_CONFLICT","A generated materialization path already exists in the fixed Snapshot source map.");let t=e.operation==="insert-child"?e.boundary?.ownerFile:e.binding.ownerFile;if(!t||!e.files.has(t))return oc("INVALID_TARGET","The exact page-block owner source is missing from the fixed file map.");let n=YT(t,e.materialization.entry.path),r=_x({operationId:e.operationId,documentVersion:e.documentVersion,target:e.target,binding:e.binding,...e.boundary?{boundary:e.boundary}:{},operation:e.operation,node:{kind:"component-call",component:{source:n,exportName:e.materialization.entry.export.kind==="default"?"default":e.materialization.entry.export.name},props:{}},files:GT(e.files,e.materialization)});if(!r.ok)return r;let o=e.materialization.files.map(i=>({operation:"create-only",file:i.path,content:i.content}));return{ok:!0,plan:{...r.plan,target:e.target,edits:[...o,...r.plan.edits]}}}function GT(e,t){let n=new Map(e);for(let r of t.files)n.set(r.path,r.content);return n}function YT(e,t){let n=Cx.posix.relative(Cx.posix.dirname(e),t);return n.startsWith(".")?n:`./${n}`}function oc(e,t){return{ok:!1,code:e,message:t}}import{PageTemplateIdSchema as aw}from"@vcp-dev/contracts";import k1 from"node:fs";import C1 from"node:path";var ZT=/^page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function Wi(e){let t=e.map(r=>sw(r.path)),n=qT(t);return n?t.filter(r=>ew(n,r)).map(r=>({routeId:tw(n,r),entryFile:r})).sort((r,o)=>r.routeId.localeCompare(o.routeId)):[]}function Yd(e,t=""){let r=((e??"/").trim()||"/").split(/[?#]/,1)[0]||"/",o=r.startsWith("/")?r:`/${r}`,i=iw(t),s=i&&(o===i||o.startsWith(`${i}/`))?o.slice(i.length)||"/":o,a=s.startsWith("/")?s:`/${s}`;return a==="/"?"/":a.replace(/\/+$/,"")}function qT(e){return e.some(r=>r.startsWith("app/")&&!QT(r))?"app":e.some(r=>r.startsWith("src/app/"))?"src/app":null}function QT(e){return/^(?:src\/)?app\/(?:_vcp|\.vcp)/.test(e)}function ew(e,t){if(!t.startsWith(`${e}/`))return!1;let n=t.slice(t.lastIndexOf("/")+1);return ZT.test(n)?t.slice(e.length+1,-n.length-1).split("/").filter(Boolean).every(r=>!r.startsWith("_")&&!r.startsWith(".")):!1}function tw(e,t){let n=t.slice(e.length+1).split("/").slice(0,-1).map(rw).filter(r=>!!r);return n.length===0?"/":`/${n.join("/")}`}function nw(e){return e.startsWith("(")&&e.endsWith(")")}function rw(e){return!e||e.startsWith("@")||e.startsWith("_")||nw(e)?null:ow(e)}function ow(e){return e.replace(/^\((?:\.|\.\.|\.\.\.)\)/,"")}function iw(e){let t=e.trim();return!t||t==="/"?"":(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"")}function sw(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}var Gi=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="PageTemplateManagedSourceError"}};function jt(e,t={}){throw new Gi("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Invalid page-template source (${e}): ${t.path??t.routeId??t.templateId??""}`,{reason:e,...t})}function Zd(e){return aw.safeParse(e).success||jt("invalid-template-id",{templateId:e}),Buffer.from(e,"utf8").toString("base64url")}function Nx(e){/^[A-Za-z0-9_-]{1,255}$/.test(e)||jt("invalid-template-key",{path:e});let t;try{t=new TextDecoder("utf-8",{fatal:!0}).decode(Buffer.from(e,"base64url"))}catch{return jt("invalid-template-key",{path:e})}return Zd(t)!==e&&jt("noncanonical-template-key",{path:e}),t}function cw(e){let t=Yd(e),n=t.slice(1).split("/");return(!e.startsWith("/")||/[?#\\%\u0000-\u001f]/.test(e)||t.startsWith("/.vcp")||t!=="/"&&n.some(r=>!r||r==="."||r===".."||r.startsWith("@")||r.startsWith("_")||r.startsWith("(")||lw(r)&&!Px(r)))&&jt("invalid-public-route",{routeId:e}),t}function lw(e){return e.includes("[")||e.includes("]")}function Px(e){return/^\[\[\.\.\.[^\[\]]+\]\]$|^\[[^\[\]]+\]$/.test(e)}function Ax(e){return e.some(Px)}function Tx(e,t,n="app"){n!=="app"&&n!=="src/app"&&jt("invalid-app-root");let r=cw(e),o=Zd(t),i=Ax(r.slice(1).split("/")),s=i?`${n}/.vcp/page-templates/${o}${r}`:`${n}/.vcp/page-templates${r==="/"?"":r}`,a=i?`${s}/page.tsx`:`${s}/${o}/page.tsx`;return(Buffer.byteLength(a,"utf8")>4095||a.split("/").some(c=>Buffer.byteLength(c,"utf8")>255))&&jt("path-too-long",{path:a}),{appRoot:n,routeRoot:s,templateKey:o,templateEntryFile:a}}function wx(e){return/^(?:src\/)?app\/\.vcp\/page-templates\//.test(e)}function Ox(e){let t=Array.isArray(e)?e.map(r=>[r.path,r.content]):[...e],n=new Map;for(let[r,o]of t){let i=r.replace(/\\/g,"/").replace(/^\.\//,"");i.split("/").some(s=>s===".."||s===".")&&jt("invalid-file-path",{path:i}),n.has(i)&&jt("duplicate-file-path",{path:i}),n.set(i,o)}return n}function sc(e){let t=Ox(e.files),n=Wi([...t.keys()].map(i=>({path:i}))),r=new Map;for(let i of n){if(r.has(i.routeId))throw new Gi("PAGE_TEMPLATE_ROUTE_AMBIGUOUS",`Multiple canonical entries for ${i.routeId}`,{reason:"duplicate-route-id",routeId:i.routeId,candidates:n.filter(s=>s.routeId===i.routeId).map(s=>s.entryFile)});r.set(i.routeId,i.entryFile)}let o=[];for(let i of t.keys()){if(!wx(i))continue;let s=/^(app|src\/app)\/\.vcp\/page-templates\/(.+)\/page\.tsx$/.exec(i);s||jt("candidate-must-be-single-page",{path:i});let a=s[1],c=s[2].split("/"),l=Ax(c),u=l?c[0]:c.pop(),d=l?c.slice(1):c,f=Nx(u),g=d.length?`/${d.join("/")}`:"/";Tx(g,f,a).templateEntryFile!==i&&jt("candidate-path-mismatch",{path:i,routeId:g});let m=r.get(g);(!m||!m.startsWith(`${a}/`))&&jt("canonical-entry-missing",{path:i,routeId:g}),o.push({routeId:g,templateId:f,entryFile:i,canonicalEntryFile:m,appRoot:a})}return o.sort((i,s)=>ic(i.routeId,s.routeId)||ic(i.templateId,s.templateId))}function ac(e){let t=Ox(e.files),n=sc({files:t}),r=Wi([...t.keys()].map(o=>({path:o}))).map(o=>({context:{routeId:o.routeId},entryFile:o.entryFile}));return r.push(...n.map(o=>({context:{routeId:o.routeId,effectiveTemplateId:o.templateId},entryFile:o.entryFile}))),r.sort((o,i)=>ic(o.context.routeId,i.context.routeId)||(o.context.effectiveTemplateId===void 0?-1:i.context.effectiveTemplateId===void 0?1:ic(o.context.effectiveTemplateId,i.context.effectiveTemplateId)))}function uw(e){let t=Yd(e.selector.routeId),n=ac({files:e.files}),r=n.find(i=>i.context.routeId===t&&i.context.effectiveTemplateId===void 0);(!r||r.entryFile!==e.canonicalEntryFile)&&jt("canonical-entry-mismatch",{routeId:t,path:e.canonicalEntryFile});let o=e.selector.templateId===void 0?r:n.find(i=>i.context.routeId===t&&i.context.effectiveTemplateId===e.selector.templateId);return o||jt("template-selection-not-found",{routeId:t,templateId:e.selector.templateId}),{...o,mode:e.selector.templateId===void 0?"direct":"candidate",effectiveEntryFile:o.entryFile}}function ic(e,t){return e<t?-1:e>t?1:0}import{HOME_PAGE_URL_PATH as ww}from"@vcp-dev/contracts";import{parse as kw}from"@babel/parser";import{parse as U1}from"@babel/parser";import{FormBlockIdSchema as J1,FormSpecV1Schema as X1}from"@vcp-dev/contracts";import{posix as L1}from"node:path";import dw from"@babel/traverse";var qd=dw,D1=typeof qd=="function"?qd:qd.default,B1=Symbol("unknown-member");var Yi="components/site/generated/forms",H1=`${Yi}/vcp-form-runtime.tsx`,cc="[A-Za-z0-9][A-Za-z0-9_-]{0,127}",W1=new RegExp(`^${Yi}/form-(${cc})\\.spec\\.ts$`),G1=new RegExp(`^${Yi}/form-(${cc})\\.tsx$`),Y1=new RegExp(`^@/${Yi}/form-(${cc})$`),Z1=new RegExp(`(?:^|/)${Yi}/form-(${cc})(?:\\.tsx?)?$`);var q1=Symbol("invalid-literal");import{createHash as tX}from"node:crypto";import{posix as rX}from"node:path";import{parse as iX}from"@babel/parser";import{FormSpecV1Schema as aX}from"@vcp-dev/contracts";var cX=Symbol("dynamic");import{parse as fw}from"@babel/parser";function lc(e){return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&typeof t.type=="string"):[]}var pw=/^(?:src\/)?app\/(.*)page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function Fx(e){let t=pw.exec(e);if(!t)return null;let r=(t[1]??"").split("/").filter(o=>o.length>0&&!/^\(.+\)$/.test(o));return r.length===0?"/":`/${r.join("/")}`}function mw(e){let t=e;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function Lx(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function gw(e){let t=e;for(;t&&(t.type==="TSAsExpression"||t.type==="TSSatisfiesExpression"||t.type==="ParenthesizedExpression");)t=t.expression??null;return t}function Qd(e){let t=e;if(t?.type==="StringLiteral"||t?.type==="NumericLiteral"||t?.type==="BooleanLiteral")return t.value;if(t?.type==="NullLiteral")return null;if(t?.type==="ArrayExpression")return(t.elements??[]).map(Qd);if(t?.type==="ObjectExpression"){let n={};for(let r of lc(t.properties)){if(r.type!=="ObjectProperty"||r.computed)throw new Error("dynamic object property");let o=Lx(r.key);if(!o)throw new Error("unsupported object key");n[o]=Qd(r.value)}return n}throw new Error(`unsupported static value: ${t?.type??"unknown"}`)}function ef(e,t){let n=[],r=Fx(t);if(r===null)return{found:!1,seo:null,diagnostics:n};let o;try{o=fw(e,{sourceType:"module",plugins:["typescript","jsx"]})}catch(l){return n.push({code:"page-seo.parse-failed",message:l instanceof Error?l.message:String(l)}),{found:!1,seo:null,diagnostics:n}}let i;for(let l of lc(o.program.body)){let u=l.type==="ExportNamedDeclaration"?l.declaration:l;if(u?.type==="VariableDeclaration")for(let d of lc(u.declarations)){let f=d.id;f?.type==="Identifier"&&f.name==="PAGE_SEO"&&(i=d.init)}}if(i==null)return{found:!1,seo:null,diagnostics:n};let s=gw(i);if(!s)return{found:!1,seo:null,diagnostics:n};if(s.type!=="ObjectExpression")return n.push({code:"page-seo.dynamic-declaration",message:"PAGE_SEO is not a static object literal"}),{found:!1,seo:null,diagnostics:n};let a={};for(let l of lc(s.properties)){if(l.type!=="ObjectProperty"||l.computed)continue;let u=Lx(l.key);if(!(u!=="path"&&u!=="title"&&u!=="description"&&u!=="keywords"&&u!=="meta_tags_json"&&u!=="schema_json"&&u!=="breadcrumbs_json")){if(u==="path"||u==="title"||u==="description"||u==="keywords"){let d=mw(l.value);if(d===void 0){n.push({code:"page-seo.dynamic-field",message:`PAGE_SEO.${u} is not a static string; skipped`});continue}a[u]=d;continue}try{let d=Qd(l.value);u==="meta_tags_json"&&d!==null&&typeof d=="object"&&!Array.isArray(d)?a.meta_tags_json=d:u==="schema_json"&&d!==null&&typeof d=="object"?a.schema_json=d:u==="breadcrumbs_json"&&Array.isArray(d)?a.breadcrumbs_json=d:n.push({code:"page-seo.dynamic-field",message:`PAGE_SEO.${u} has unsupported static shape; skipped`})}catch(d){n.push({code:"page-seo.dynamic-field",message:`PAGE_SEO.${u} is not a static JSON-like value; skipped: ${d instanceof Error?d.message:String(d)}`})}}}let c=r;return a.path!==void 0&&(a.path!==r&&n.push({code:"page-seo.path-mismatch",message:`PAGE_SEO.path "${a.path}" != derived "${r}"; using PAGE_SEO.path`}),c=a.path),{found:!0,seo:{path:c,...a.title!==void 0?{title:a.title}:{},...a.description!==void 0?{description:a.description}:{},...a.keywords!==void 0?{keywords:a.keywords}:{},...a.meta_tags_json!==void 0?{meta_tags_json:a.meta_tags_json}:{},...a.schema_json!==void 0?{schema_json:a.schema_json}:{},...a.breadcrumbs_json!==void 0?{breadcrumbs_json:a.breadcrumbs_json}:{}},diagnostics:n}}import{parse as hw}from"@babel/parser";var Mx=["page","anchor","external","email","phone","group","file"],yw=["link","cta"],Bx=["description","badge","iconKey"],tf=["label","targetType","href","role","openInNewTab","nofollow","children",...Bx],xw=new Set(tf);function qi(e){return Array.isArray(e)?e:[]}function Zi(e){let t=e;return t?.type==="StringLiteral"&&typeof t.value=="string"?t.value:void 0}function bw(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function Dx(e){let t=e;return t?.type==="BooleanLiteral"&&typeof t.value=="boolean"?t.value:void 0}function nf(e){let t=[],n;try{n=hw(e,{sourceType:"module",plugins:["typescript","jsx"]})}catch(i){return{items:[],diagnostics:[{severity:"fatal",path:"NAV_ITEMS",message:`parse failed: ${String(i)}`}]}}let r;for(let i of qi(n.program.body)){let s=i.type==="ExportNamedDeclaration"?i.declaration:i;if(s?.type==="VariableDeclaration")for(let a of qi(s.declarations)){let c=a.id;c?.type==="Identifier"&&c.name==="NAV_ITEMS"&&(r=a.init)}}for(;r&&(r.type==="TSAsExpression"||r.type==="TSSatisfiesExpression"||r.type==="TSInstantiationExpression");)r=r.expression;if(!r||r.type!=="ArrayExpression")return{items:[],diagnostics:[{severity:"fatal",path:"NAV_ITEMS",message:"missing top-level NAV_ITEMS array literal"}]};let o=[];return qi(r.elements).forEach((i,s)=>{let a=jx(i,`NAV_ITEMS[${s}]`,t);a&&o.push(a)}),{items:o,diagnostics:t}}function jx(e,t,n){if(e?.type!=="ObjectExpression")return n.push({severity:"fatal",path:t,message:"nav item must be an object literal"}),null;let r={};for(let l of qi(e.properties)){if(l.type!=="ObjectProperty"||l.computed)continue;let u=bw(l.key);u&&(r[u]=l.value)}let o=Zi(r.label),i=Zi(r.targetType);if(!o)return n.push({severity:"fatal",path:`${t}.label`,message:"label must be a static string"}),null;if(!i||!Mx.includes(i))return n.push({severity:"fatal",path:`${t}.targetType`,message:`targetType must be one of ${Mx.join("/")}`}),null;r.group!==void 0&&n.push({severity:"warning",code:"leaf-group-field",path:`${t}.group`,message:'unsupported leaf group field ignored; use a canonical targetType: "group" node with children'});let s={label:o,targetType:i};for(let l of Bx){if(r[l]===void 0)continue;let u=Zi(r[l]);u!==void 0?s[l]=u:n.push({severity:"warning",path:`${t}.${l}`,message:`${l} ignored: not a static string`})}r.icon!==void 0&&n.push({severity:"warning",path:`${t}.icon`,message:"icon component ref ignored; use static iconKey"});for(let l of Object.keys(r))xw.has(l)||l==="group"||l==="icon"||n.push({severity:"warning",code:"unknown-field",path:`${t}.${l}`,message:`unsupported field \`${l}\` ignored; NAV_ITEMS only carries ${tf.join("/")}`});if(r.children!==void 0){if(r.children.type!=="ArrayExpression")return n.push({severity:"fatal",path:`${t}.children`,message:"children must be a static array"}),null;let l=[];qi(r.children.elements).forEach((u,d)=>{let f=jx(u,`${t}.children[${d}]`,n);f&&l.push(f)}),s.children=l}if(i==="group")return s.children?s:(n.push({severity:"fatal",path:`${t}.children`,message:"group item requires children"}),null);let a=Zi(r.href);if(!a)return n.push({severity:"fatal",path:`${t}.href`,message:"href must be a static string for non-group item"}),null;s.href=a;let c=Zi(r.role);if(c!==void 0&&(yw.includes(c)?s.role=c:n.push({severity:"warning",path:`${t}.role`,message:"role ignored: not link/cta"})),r.openInNewTab!==void 0){let l=Dx(r.openInNewTab);l!==void 0?s.openInNewTab=l:n.push({severity:"warning",path:`${t}.openInNewTab`,message:"openInNewTab ignored: not a static boolean"})}if(r.nofollow!==void 0){let l=Dx(r.nofollow);l!==void 0?s.nofollow=l:n.push({severity:"warning",path:`${t}.nofollow`,message:"nofollow ignored: not a static boolean"})}return s}import{parse as Ew}from"@babel/parser";function Qi(e){return Array.isArray(e)?e:[]}function $x(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression";)t=t.expression;return t?.type==="ArrayExpression"?t:void 0}function Sw(e){let t;try{t=Ew(e,{sourceType:"module",plugins:["typescript","jsx"],tokens:!0})}catch{return{status:"unsupported"}}let n=[];for(let o of Qi(t.program.body)){let i=o.type==="ExportNamedDeclaration"?o.declaration:o;if(i?.type==="VariableDeclaration")for(let s of Qi(i.declarations)){let a=s.id;a?.type==="Identifier"&&a.name==="NAV_ITEMS"&&n.push(s)}}if(n.length===0)return{status:"navigation_not_found"};if(n.length!==1)return{status:"unsupported"};let r=$x(n[0]?.init);return!r||typeof r.start!="number"||typeof r.end!="number"?{status:"unsupported"}:{status:"ok",array:r,start:r.start,end:r.end}}function rf(e,t){let n=Vx(t);if(!n)return{status:"unsupported",source:e};let r=Sw(e);if(r.status!=="ok")return{status:r.status,source:e};let o=r.array;if(nf(e).diagnostics.some(({severity:l})=>l==="fatal"))return{status:"unsupported",source:e};let s=[],a=l=>{let u=Qi(l.elements);for(let[d,f]of u.entries()){if(vw(f,n)){let p=u[d+1],m=u[d-1],y=f.start,x=f.end;if(typeof y!="number"||typeof x!="number")continue;if(p&&typeof p.start=="number")s.push({start:y,end:p.start});else if(m&&typeof m.end=="number")s.push({start:m.end,end:x});else{let S=/^\s*,/.exec(e.slice(x));s.push({start:y,end:S?x+S[0].length:x})}continue}let g=Iw(f);g&&a(g)}};if(a(o),s.length===0)return{status:"not_found",source:e};let c=e;for(let l of s.sort((u,d)=>d.start-u.start))c=c.slice(0,l.start)+c.slice(l.end);return{status:"removed",source:c,removedCount:s.length}}function Iw(e){if(e.type==="ObjectExpression")for(let t of Qi(e.properties)){if(t.type!=="ObjectProperty")continue;let n=t.key;if((n?.name??n?.value)==="children")return $x(t.value)}}function Vx(e){let t=e.trim();return t.startsWith("/")?t==="/"?t:t.replace(/\/+$/,""):null}function vw(e,t){if(e.type!=="ObjectExpression")return!1;let n,r;for(let o of Qi(e.properties)){if(o.type!=="ObjectProperty")continue;let i=o.key,s=o.value,a=i?.name??i?.value;s?.type==="StringLiteral"&&(a==="href"&&(n=String(s.value)),a==="targetType"&&(r=String(s.value)))}return r==="page"&&Vx(n??"")===t}import{estimateNavLabelWidth as xX}from"@vcp-dev/contracts";import{parse as SX}from"@babel/parser";function qn(e,t){let n;try{n=kw(e,{sourceType:"module",sourceFilename:t.filePath,plugins:["jsx","typescript"]})}catch(N){let A=N.loc;return{form_codes:[],components:[],uncertain_components:[],rendered_component_openings:[],renders_native_form:!1,diagnostics:[{code:"rendered-module.parse-failed",message:N instanceof Error?N.message:"Rendered module failed Babel parsing.",file_path:t.filePath??"",line:A?.line??1}]}}let r=n.program,o=Xt(r?.body),i=new Map,s=new Map,a=new Map,c=new Map,l=N=>{if(N?.type==="FunctionDeclaration"){let A=N.id;A?.type==="Identifier"&&typeof A.name=="string"&&s.set(A.name,N);return}if(N?.type==="VariableDeclaration")for(let A of Xt(N.declarations)){let w=A.id,F=A.init;w?.type==="Identifier"&&typeof w.name=="string"&&F&&(Sr(F)?s.set(w.name,F):F.type==="Identifier"&&typeof F.name=="string"&&a.set(w.name,F.name))}};for(let N of o){if(N.type==="ImportDeclaration"){let A=N.source?.value;if(typeof A!="string")continue;for(let w of Xt(N.specifiers)){let F=w.local;if(!(F?.type!=="Identifier"||typeof F.name!="string")){if(w.type==="ImportDefaultSpecifier")i.set(F.name,{source:A,exportName:"default"});else if(w.type==="ImportNamespaceSpecifier")i.set(F.name,{source:A,exportName:"*"});else if(w.type==="ImportSpecifier"){let B=w.imported,X=B?.type==="Identifier"&&typeof B.name=="string"?B.name:B?.type==="StringLiteral"&&typeof B.value=="string"?B.value:"";X&&i.set(F.name,{source:A,exportName:X})}}}continue}N.type==="ExportNamedDeclaration"?l(N.declaration):l(N)}for(let N of o){if(N.type==="ExportDefaultDeclaration"){let F=N.declaration;F&&Sr(F)?c.set("default",F):F?.type==="Identifier"&&typeof F.name=="string"&&c.set("default",F.name);continue}if(N.type!=="ExportNamedDeclaration")continue;let A=N.declaration;if(A?.type==="FunctionDeclaration"){let F=A.id;F?.type==="Identifier"&&typeof F.name=="string"&&c.set(F.name,F.name)}else if(A?.type==="VariableDeclaration")for(let F of Xt(A.declarations)){let B=F.id;B?.type==="Identifier"&&typeof B.name=="string"&&c.set(B.name,B.name)}let w=N.source?.value;for(let F of Xt(N.specifiers)){let B=Jx(F.local),X=Jx(F.exported);if(!(!B||!X))if(typeof w=="string"){let $=`#re-export:${X}`;i.set($,{source:w,exportName:B}),c.set(X,$)}else c.set(X,B)}}let u=new Set,d=[],f=new Set,g=[],p=new Set,m=[],y=new Map,x=!1,S=[],b=new Map,E=new Map,k=(N,A="rendered")=>{let w=Kx(N,i);if(!w)return!1;let F=`${w.source}\0${w.exportName}`;if(A==="uncertain")return!f.has(F)&&!p.has(F)&&(p.add(F),g.push({source:w.source,export_name:w.exportName})),!0;if(!f.has(F)&&(f.add(F),d.push({source:w.source,export_name:w.exportName}),p.delete(F))){let B=g.findIndex(X=>X.source===w.source&&X.export_name===w.exportName);B>=0&&g.splice(B,1)}return!0},I=(N,A="rendered",w=[])=>{let F=`${A}\0${sf(w)}`,B=b.get(N)??new Set,X=E.get(N)??new Set;if(B.has(F)||X.has(A))return;B.add(F),b.set(N,B),X.add(A),E.set(N,X);let $=new Map(s),G=new Map,D=[],fe=(Ee,lt=!1)=>{if(uc(Ee)){if(!lt&&Sr(Ee)){if(Ee.type==="FunctionDeclaration"){let Le=Ee.id;Le?.type==="Identifier"&&typeof Le.name=="string"&&$.set(Le.name,Ee)}return}if(Ee.type==="VariableDeclarator"){let Le=Ee.id,pe=Ee.init;Le?.type==="Identifier"&&typeof Le.name=="string"&&pe&&(Sr(pe)?$.set(Le.name,pe):G.set(Le.name,pe))}else if(Ee.type==="ReturnStatement"){let Le=Ee.argument;Le&&D.push(Le)}if(Ee.type==="CallExpression"){let Le=Ee.callee;if(Le?.type==="Import"&&S.push({code:"rendered-module.dynamic-import",message:"Rendered component graph must use static imports.",file_path:t.filePath??"",line:Ee.loc?.start.line??1}),es(Le)==="cms.forms.getConfig"){let pe=Xt(Ee.arguments)[0];pe?.type==="StringLiteral"&&typeof pe.value=="string"&&pe.value.trim()?A==="rendered"?u.add(pe.value.trim()):S.push({code:"rendered-module.unresolved-export",message:"Unable to prove whether a CMS form inside a JSX prop is rendered.",file_path:t.filePath??"",line:Ee.loc?.start.line??1}):S.push({code:"rendered-module.dynamic-form-code",message:"Rendered cms.forms.getConfig() requires a non-empty string literal.",file_path:t.filePath??"",line:Ee.loc?.start.line??1})}}for(let[Le,pe]of Object.entries(Ee))if(Le!=="loc")if(Array.isArray(pe))for(let $e of pe)fe($e);else fe(pe)}};fe(N,!0);let Fe=new Set,ot=new Set,Tt=(Ee,lt=A,Le=w)=>{if(!(!uc(Ee)||Sr(Ee))){if(Ee.type==="Identifier"&&typeof Ee.name=="string"){let pe=G.get(Ee.name),$e=`${lt}\0${Ee.name}\0${sf(Le)}`;pe&&!Fe.has($e)&&!ot.has(Ee.name)?(Fe.add($e),ot.add(Ee.name),Tt(pe,lt,Le),ot.delete(Ee.name)):k(Ee.name,lt);return}if(Ee.type==="CallExpression"){let pe=Ee.callee,$e=Xt(Ee.arguments),kt=es(pe),pn=pe?.type==="Identifier"&&typeof pe.name=="string"?i.get(pe.name):void 0;if(lt==="rendered"&&(kt==="createElement"||kt.endsWith(".createElement")||pn?.source==="react"&&pn.exportName==="createElement")&&$e[0]?.type==="StringLiteral"&&$e[0].value==="form"&&(x=!0),pe?.type==="Identifier"&&typeof pe.name=="string"){let _t=$.get(pe.name);if(_t){I(_t,lt,Le);return}}if(pe&&Sr(pe)){I(pe,lt,Le);return}if(Rw(pe)){for(let _t of $e)if(Sr(_t))I(_t,lt,Le);else if(_t.type==="Identifier"&&typeof _t.name=="string"){let Fs=$.get(_t.name);Fs&&I(Fs,lt,Le)}return}for(let _t of $e)Nw(_t)&&S.push({code:"rendered-module.unresolved-export",message:"Unable to prove whether a JSX-producing call argument is rendered.",file_path:t.filePath??"",line:_t.loc?.start.line??1});return}if(Ee.type==="JSXElement"){let pe=Ee.openingElement,$e=pe?Ux(Le,_w(pe)):Le;Tt(pe,lt,$e);for(let kt of Xt(Ee.children))Tt(kt,lt,$e);return}if(Ee.type==="JSXOpeningElement"){let pe=dc(Ee.name);lt==="rendered"&&pe==="form"&&(x=!0);let $e=pe?Kx(pe,i):void 0;if(lt==="rendered"&&$e&&typeof Ee.start=="number"){let kt=`${$e.source}\0${$e.exportName}\0${Ee.start}`,pn=y.get(kt);if(!pn){let _t=Pw(Ee).get("formBlockId");pn={source:$e.source,export_name:$e.exportName,start_offset:Ee.start,...typeof _t=="string"?{static_form_block_id:_t}:{}},y.set(kt,pn),m.push(pn)}Le.length>0&&(pn.static_render_blockers=Ux(pn.static_render_blockers??[],Le))}if(pe&&!k(pe,lt)){let kt=$.get(pe);kt?I(kt,lt,Le):G.has(pe)?Tt(G.get(pe),lt,Le):Cw(pe)||/^[A-Z]/.test(pe)&&S.push({code:"rendered-module.dynamic-import",message:`Unable to resolve rendered component ${pe} from a static import.`,file_path:t.filePath??"",line:Ee.loc?.start.line??1})}for(let kt of Xt(Ee.attributes))Tt(kt,"uncertain",Le);return}if(Ee.type==="JSXAttribute"){let pe=Ee.value,$e=pe?.type==="JSXExpressionContainer"?pe.expression:pe;$e&&Sr($e)?I($e,"uncertain",Le):Tt($e,"uncertain",Le);return}for(let[pe,$e]of Object.entries(Ee))if(!(pe==="loc"||pe==="closingElement"))if(Array.isArray($e))for(let kt of $e)Tt(kt,lt,Le);else Tt($e,lt,Le)}},Vr=N.body;Vr&&Vr.type!=="BlockStatement"&&D.push(Vr);for(let Ee of D)Tt(Ee);X.delete(A)},v=c.get(t.exportName);if(typeof v=="string"){let N=v,A=new Set;for(;a.has(N)&&!A.has(N);)A.add(N),N=a.get(N);if(!k(N)){let w=s.get(N);w?I(w):S.push(Xx(t))}}else v?I(v):S.push(Xx(t));return{form_codes:[...u],components:d,uncertain_components:g,rendered_component_openings:m,renders_native_form:x,diagnostics:S}}function sf(e){return e.map(t=>`${t.start_offset}:${t.reason}`).join("|")}function Ux(e,t){return[...new Map([...e,...t].map(r=>[sf([r]),r])).values()]}function _w(e){let t=new Map;for(let a of Xt(e.attributes)){if(a.type==="JSXSpreadAttribute"){t.clear();continue}let c=zx(a.name);if(!c)continue;let l=a.value;t.set(c,l?.type==="JSXExpressionContainer"?l.expression:l)}let n=dc(e.name)??"unknown",r=[],o=a=>{r.push({element_name:n,line:e.loc?.start.line??1,start_offset:Tw(e.start),reason:a})};for(let a of["hidden","inert","aria-hidden","disabled"]){if(!t.has(a)||a==="disabled"&&n!=="fieldset")continue;let c=of(t.get(a));(c===!0||(a==="aria-hidden"?c==="true":typeof c=="string"))&&o(a)}let i=t.get("style");if(i?.type==="ObjectExpression"){let a=new Map;for(let l of Xt(i.properties)){let u=l.key,d=!l.computed&&u?.type==="Identifier"?u.name:u?.type==="StringLiteral"?u.value:void 0;l.type!=="ObjectProperty"||typeof d!="string"?a.clear():a.set(d,of(l.value))}a.get("display")==="none"&&o("style.display=none"),a.get("visibility")==="hidden"&&o("style.visibility=hidden");let c=a.get("opacity");(c===0||typeof c=="string"&&c.trim()==="0")&&o("style.opacity=0")}let s=of(t.get("className"));if(typeof s=="string"){let a=s.split(/\s+/).filter(Boolean),l={hidden:new Set(["block","inline","inline-block","flex","inline-flex","grid","inline-grid","table","inline-table","table-row","table-cell","flow-root","contents","list-item"]),invisible:new Set(["visible"]),"sr-only":new Set(["not-sr-only"])};for(let[u,d]of Object.entries(l))a.includes(u)&&!a.some(f=>d.has(f.split(":").at(-1)))&&o(`className=${u}`)}return r}function of(e){if(e===null)return!0;if(e){if(e.type==="StringLiteral"||e.type==="BooleanLiteral"||e.type==="NumericLiteral")return e.value;if(e.type==="TemplateLiteral"&&Xt(e.expressions).length===0)return Xt(e.quasis)[0]?.value?.cooked}}function Kx(e,t){let n=t.get(e);if(n)return n;let[r,...o]=e.split(".");if(!r||o.length===0)return;let i=t.get(r);if(i?.exportName==="*")return{source:i.source,exportName:o.join(".")}}function Cw(e){return e.endsWith(".Provider")||e.endsWith(".Consumer")}function Sr(e){return e?.type==="FunctionDeclaration"||e?.type==="FunctionExpression"||e?.type==="ArrowFunctionExpression"}function Rw(e){let t=es(e),n=e?.type==="MemberExpression"&&e.computed!==!0?e.property:void 0;return t==="Array.from"||t==="React.Children.map"||n?.type==="Identifier"&&(n.name==="map"||n.name==="flatMap")}function Nw(e){let t=!1;return af(e,n=>{if(!t){if(n.type==="JSXOpeningElement"){t=!0;return}n.type==="CallExpression"&&es(n.callee)==="cms.forms.getConfig"&&(t=!0)}}),t}function Jx(e){return e?.type==="Identifier"&&typeof e.name=="string"?e.name:e?.type==="StringLiteral"&&typeof e.value=="string"?e.value:""}function Xx(e){return{code:"rendered-module.unresolved-export",message:`Unable to resolve rendered export ${e.exportName}.`,file_path:e.filePath??"",line:1}}function es(e){if(!e)return"";if(e.type==="Identifier"&&typeof e.name=="string")return e.name;if(e.type!=="MemberExpression"||e.computed===!0)return"";let t=es(e.object),n=e.property;return!t||n?.type!=="Identifier"||typeof n.name!="string"?"":`${t}.${n.name}`}function Pw(e){let t=new Map,n=Array.isArray(e.attributes)?e.attributes:[];for(let r of n){let o=r;if(o.type!=="JSXAttribute")continue;let i=zx(o.name);i&&t.set(i,Aw(o.value))}return t}function Aw(e){if(e==null)return!0;let t=e;if(t.type==="StringLiteral")return t.value;if(t.type!=="JSXExpressionContainer")return;let n=t.expression;if(n&&(n.type==="StringLiteral"||n.type==="NumericLiteral"))return n.value}function zx(e){let t=e;if(t?.type==="JSXIdentifier")return typeof t.name=="string"?t.name:void 0}function Tw(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function af(e,t){if(uc(e)){t(e);for(let[n,r]of Object.entries(e))if(n!=="loc"){if(Array.isArray(r)){for(let o of r)af(o,t);continue}af(r,t)}}}function uc(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}function dc(e){let t=e;if(!t)return"";if(t.type==="JSXIdentifier")return typeof t.name=="string"?t.name:"";if(t.type==="JSXMemberExpression"){let n=dc(t.object),r=dc(t.property);return n&&r?`${n}.${r}`:r||n}return""}function Xt(e){return Array.isArray(e)?e.filter(t=>uc(t)):[]}var Ow="components/site/generated/",ts=[".tsx",".ts",".jsx",".js"];function Hx(e){if(e.expectedUrlPath===ww)return{ok:!1,code:"HOME_PAGE_LOCKED",message:"The homepage source is protected from deletion."};let t=new Set(Wi(Object.keys(e.files).map(m=>({path:m}))).map(m=>m.entryFile)),n=Object.entries(e.files).filter(([m,y])=>{let x=m.replace(/\\/g,"/");if(!t.has(x))return!1;let S=ef(y,x);return S.found&&S.seo?.path===e.expectedUrlPath});if(n.length===0)return{ok:!1,code:"ROUTE_NOT_FOUND",message:"No route uniquely matches the requested page identity."};if(n.length>1)return{ok:!1,code:"ROUTE_AMBIGUOUS",message:"Multiple routes match the requested page identity."};let[r]=n[0],o=new Set([r]);try{let m=sc({files:new Map(Object.entries(e.files))});for(let y of m)y.canonicalEntryFile===r&&o.add(y.entryFile)}catch(m){return{ok:!1,code:"SOURCE_DEPENDENCY_UNSAFE",message:m instanceof Error?m.message:"Invalid page template source."}}let i=Fw(e.files);if(!i.ok)return i.error;let s=i.graph,a=Bw(o,s),c=jw(o,a,s),l=[...a].filter(m=>!c.has(m)).sort((m,y)=>m.localeCompare(y)),u=[...o,...[...c].sort((m,y)=>m.localeCompare(y))],d=new Set(u),f=u.map(m=>({operation:"delete",file:m})),g=[],p=[];for(let[m,y]of Object.entries(e.files))if(!d.has(m)){if(y.includes("NAV_ITEMS")){let x=rf(y,e.expectedUrlPath);x.status==="removed"?(f.push({operation:"upsert",file:m,content:x.source}),g.push(m)):x.status==="unsupported"&&p.push(`unsupported_navigation:${m}`)}y.includes(e.expectedUrlPath)&&!y.includes("NAV_ITEMS")&&p.push(`preserved_link:${m}`)}return{ok:!0,edits:f,deletedFiles:u,updatedFiles:g,preservedSharedFiles:l,warnings:p}}function Fw(e){let t=new Set(Object.keys(e)),n=new Map;for(let[r,o]of Object.entries(e)){let i=r.replace(/\\/g,"/");if(i==="next-env.d.ts"||i.endsWith("/next-env.d.ts")||!Lw(r))continue;let s=je(r,o);if(!s.ok)return{ok:!1,error:{ok:!1,code:"SOURCE_DEPENDENCY_UNSAFE",message:`Page source dependencies could not be proven safe: ${r} (parse-failed).`}};let a=new Set;for(let{specifier:c}of s.module.imports){if(Mw(c))continue;let l=Cn(r,c),u=Dw(l,t);if(!u)return{ok:!1,error:{ok:!1,code:"SOURCE_DEPENDENCY_UNSAFE",message:`Page source dependencies could not be proven safe: ${r} -> ${c} (import-not-found).`}};a.add(u)}n.set(r,a)}return{ok:!0,graph:n}}function Lw(e){let t=e.toLowerCase();return ts.some(n=>t.endsWith(n))}function Mw(e){return!!(/\.([a-z0-9]+)$/i.exec(e)&&!ts.some(n=>e.endsWith(n)))}function Dw(e,t){let n=e.replace(/\\/g,"/");return(ts.some(o=>n.endsWith(o))?[n]:[...ts.map(o=>`${n}${o}`),...ts.map(o=>`${n}/index${o}`)]).find(o=>t.has(o))??null}function Bw(e,t){let n=new Set,r=[...e].flatMap(o=>[...t.get(o)??[]]);for(;r.length>0;){let o=r.pop();!o.startsWith(Ow)||n.has(o)||(n.add(o),r.push(...t.get(o)??[]))}return n}function jw(e,t,n){let r=new Set(t),o=!0;for(;o;){o=!1;for(let i of[...r])[...n].some(([a,c])=>!e.has(a)&&!r.has(a)&&c.has(i))&&(r.delete(i),o=!0)}return r}import*as Wb from"@babel/parser";import*as Oe from"@babel/types";import*as Pc from"node:path";import*as Ue from"@babel/types";function Wx(e){if(e.path.isVariableDeclarator()){let n=e.path.get("init");return n?.isExpression()?{expressionPath:n}:null}if(!e.path.isIdentifier()||!e.path.parentPath?.isVariableDeclarator())return null;let t=e.path.parentPath.get("init");return t?.isExpression()?{expressionPath:t}:null}function On(e){if(e.path.isObjectPattern()||e.path.isArrayPattern())return io(e.path.node,e.identifier.name);if(e.path.isVariableDeclarator()){let n=e.path.node.id;if(Ue.isObjectPattern(n)||Ue.isArrayPattern(n))return io(n,e.identifier.name)}if(!e.path.isIdentifier())return!1;let t=e.path.parentPath;for(;t;){if(t.isAssignmentPattern()){let n=t.get("left");if(Vw(e.path,n))return!0}if(t.isFunction()||t.isVariableDeclarator())return!1;t=t.parentPath}return!1}function io(e,t,n=!1){return Ue.isIdentifier(e)?e.name===t&&n:Ue.isObjectPattern(e)?e.properties.some(r=>Ue.isObjectProperty(r)?io(r.value,t,n):io(r.argument,t,n)):Ue.isArrayPattern(e)?e.elements.some(r=>{if(!r)return!1;let o=Ue.isRestElement(r)?r.argument:r;return io(o,t,n)}):Ue.isAssignmentPattern(e)?io(e.left,t,!0):Ue.isRestElement(e)?io(e.argument,t,n):!1}function $o(e,t){if(e.path.isObjectPattern()){if(t){let r=En(e.path.node,t.base),[o,...i]=r??[];if(o?.kind==="property")return{propName:o.name,remainingPath:[...i,...t.path],hasDefault:On(e)}}return t?{propName:t.base,remainingPath:t.path,hasDefault:On(e)}:null}if(e.path.isVariableDeclarator()){let r=e.path.get("init");if(r?.isExpression()){let o=Gx(r),i=!1,s=o?o.initBinding&&cf(o.initBinding)?(i=On(o.initBinding),[...o.initPathPrefix]):o.initBinding?(()=>{let c=$o(o.initBinding,{kind:"identifier",expression:o.initBinding.identifier.name,base:o.initBinding.identifier.name,path:[]});return i=c?.hasDefault??!1,c?[{kind:"property",name:c.propName},...c.remainingPath,...o.initPathPrefix]:null})():null:null,a=En(e.path.node.id,e.identifier.name);if(s&&a){let c=[...s,...a],[l,...u]=c;return!l||l.kind!=="property"?null:{propName:l.name,remainingPath:[...u,...t?.path??[]],hasDefault:i||On(e)}}}}let n=Jw(e);if(n){let r=$w(n,e);if(r){let[s,...a]=r.path;return!s||s.kind!=="property"?null:{propName:s.name,remainingPath:[...a,...t?.path??[]],hasDefault:r.hasDefault||On(e)}}if(n.findParent(s=>s.isVariableDeclarator()))return null;let o=Uw(e);if(o){let[s,...a]=o;return!s||s.kind!=="property"?null:{propName:s.name,remainingPath:[...a,...t?.path??[]],hasDefault:On(e)}}let i=ns(n.node);return i?{propName:i,remainingPath:t?.path??[],hasDefault:On(e)}:null}if(cf(e)){let[r,...o]=t?.path??[];return!r||r.kind!=="property"?null:{propName:r.name,remainingPath:o,hasDefault:On(e)}}return null}function $w(e,t){let n=e.findParent(u=>u.isVariableDeclarator());if(!n?.isVariableDeclarator())return null;let r=n.get("init");if(!r?.isExpression())return null;let o=Gx(r);if(!o)return null;let{initBinding:i,initPathPrefix:s}=o;if(!i)return null;let a=!1,c=cf(i)?(a=On(i),[...s]):(()=>{let u=$o(i,{kind:"identifier",expression:i.identifier.name,base:i.identifier.name,path:[]});return a=u?.hasDefault??!1,u?[{kind:"property",name:u.propName},...u.remainingPath,...s]:null})();if(!c)return null;let l=En(n.node.id,t.identifier.name);return l?{path:[...c,...l],hasDefault:a||On(t)}:null}function Gx(e){if(e.isIdentifier())return{initBinding:e.scope.getBinding(e.node.name),initPathPrefix:[]};if(!e.isMemberExpression())return null;let t=Xw(e.node);return t?{initBinding:e.scope.getBinding(t.base),initPathPrefix:t.path}:null}function cf(e){return e.path.isIdentifier()&&e.path.key===0&&Array.isArray(e.path.container)&&e.path.parentPath?.isFunction()===!0}function Vw(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function Uw(e){let t=e.identifier.name,n=e.path.getFunctionParent();if(!n)return null;let r=n.get("params"),o=Array.isArray(r)?r:[r];for(let i of o){let a=En(i.node,t);if(a)return a}return null}function Yx(e,t,n){if(e.path.isVariableDeclarator()){let a=e.path.get("id");if(!Array.isArray(a)&&(a.isObjectPattern()||a.isArrayPattern())){let c=fc(a,e.identifier.name);if(c&&(!n||c.propName===n))return{propName:c.propName,componentName:t,expressionPath:c.expressionPath,displayPath:`${t}.${c.propName}.default`}}}if(e.path.isObjectPattern())for(let a of e.path.get("properties")){if(!a.isObjectProperty())continue;let c=ns(a.node);if(!c||n&&c!==n)continue;let l=a.get("value");if(!l.isAssignmentPattern())continue;let u=l.get("right");if(u.isExpression())return{propName:c,componentName:t,expressionPath:u,displayPath:`${t}.${c}.default`}}let r=Kw(e);if(!r)return null;let o=r.parentPath;if(!o?.isObjectProperty())return null;let i=ns(o.node);if(!i||n&&i!==n)return null;let s=r.get("right");return s.isExpression()?{propName:i,componentName:t,expressionPath:s,displayPath:`${t}.${i}.default`}:null}function fc(e,t){if(e.isObjectPattern()){for(let n of e.get("properties"))if(n.isObjectProperty()){let r=ns(n.node),o=n.get("value");if(o.isAssignmentPattern()){let i=o.get("left"),s=o.get("right");if(r&&!Array.isArray(i)&&En(i.node,t)&&!Array.isArray(s)&&s.isExpression())return{propName:r,expressionPath:s}}if(!Array.isArray(o)&&(o.isObjectPattern()||o.isArrayPattern())){let i=fc(o,t);if(i)return i}}else if(n.isRestElement()){let r=n.get("argument");if(!Array.isArray(r)&&(r.isObjectPattern()||r.isArrayPattern())){let o=fc(r,t);if(o)return o}}}if(e.isArrayPattern())for(let n of e.get("elements")){if(!n)continue;let r=n.isRestElement()&&!Array.isArray(n.get("argument"))?n.get("argument"):n;if(!Array.isArray(r)&&(r.isObjectPattern()||r.isArrayPattern())){let o=fc(r,t);if(o)return o}}return null}function En(e,t,n=[]){if(Ue.isIdentifier(e))return e.name===t?n:null;if(Ue.isObjectPattern(e)){for(let r of e.properties)if(Ue.isObjectProperty(r)){let o=ns(r);if(!o)continue;let i=En(r.value,t,[...n,{kind:"property",name:o}]);if(i)return i}else if(Ue.isRestElement(r)){let o=En(r.argument,t,n);if(o)return o}}if(Ue.isArrayPattern(e))for(let r=0;r<e.elements.length;r+=1){let o=e.elements[r];if(!o)continue;let i=Ue.isRestElement(o)?o.argument:o,s=En(i,t,[...n,{kind:"index",index:r}]);if(s)return s}return Ue.isAssignmentPattern(e)?En(e.left,t,n):null}function Kw(e){if(!e.path.isIdentifier())return null;let t=e.path.parentPath;return t?.isAssignmentPattern()&&t.node.left===e.path.node?t:null}function Jw(e){if(!e.path.isIdentifier())return null;let t=e.path.parentPath;if(t?.isObjectProperty()&&t.parentPath?.isObjectPattern())return t;let n=t?.isAssignmentPattern()?t.parentPath:null;return n?.isObjectProperty()&&n.parentPath?.isObjectPattern()?n:null}function ns(e){return e.computed?null:Ue.isIdentifier(e.key)?e.key.name:Ue.isStringLiteral(e.key)?e.key.value:null}function Xw(e){let t=[],n=e;for(;Ue.isMemberExpression(n);){if(n.computed)if(Ue.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(Ue.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(Ue.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return Ue.isIdentifier(n)?{base:n.name,path:t}:null}import*as nb from"@babel/parser";import df from"@babel/traverse";import*as Vo from"@babel/types";import*as _e from"@babel/types";var Zx=new WeakMap;function gc(e,t=[]){if(e.isIdentifier()){let n=e.scope.getBinding(e.node.name);return n?pc(n,t):null}if(e.isMemberExpression()){let n=Zw(e.node),r=zw(e.node);if(!n||r===null)return null;let o=e.scope.getBinding(n);return o?pc(o,[...r,...t]):null}return e.isAwaitExpression()||uf(e.node)?Ir(Qw(e.node),t,"awaited or fetched expression"):null}function zw(e){let t=[],n=e;for(;_e.isMemberExpression(n);){if(n.computed)if(_e.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(_e.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(_e.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return _e.isIdentifier(n)?t:null}function pc(e,t=[],n){let r=Hw(e,t);if(r)return r;let o=Ww(e,t,n);if(o)return o;let i=Gw(e,t,n);return i||null}function os(e){return e?.kind==="api-source"}function Hw(e,t){if(e.path.isVariableDeclarator()&&_e.isIdentifier(e.path.node.id)){let s=e.path.get("init");if(s?.isCallExpression()&&lf(s.node)&&t[0]?.kind==="property"&&t[0].name==="data")return Ir(e.identifier.name,t,"query hook result.data binding")}if(e.path.isVariableDeclarator()&&_e.isObjectPattern(e.path.node.id)){let s=e.path.node.id.properties.find(c=>_e.isObjectProperty(c)&&eb(c)==="data"&&rs(c.value,e.identifier.name)),a=e.path.get("init");if(s&&a?.isCallExpression()&&lf(a.node))return Ir(e.identifier.name,t,"query hook data binding")}let n=Yw(e);if(!n||eb(n.node)!=="data")return null;let o=n.findParent(s=>s.isVariableDeclarator());if(!o?.isVariableDeclarator())return null;let i=o.get("init");return!i?.isCallExpression()||!lf(i.node)?null:Ir(e.identifier.name,t,"query hook data binding")}function Ww(e,t,n){if(e.path.isVariableDeclarator()&&_e.isArrayPattern(e.path.node.id)){let c=e.path.get("init");if(!c?.isCallExpression()||!Qx(c.node))return null;let[l,u]=e.path.node.id.elements;return!_e.isIdentifier(l)||l.name!==e.identifier.name||!_e.isIdentifier(u)?null:qx(e,u.name,n)?Ir(e.identifier.name,t,"state setter is updated by API data"):null}if(!e.path.isIdentifier())return null;let r=e.path.parentPath;if(!r?.isArrayPattern())return null;let o=r.parentPath;if(!o?.isVariableDeclarator())return null;let i=o.get("init");if(!i?.isCallExpression()||!Qx(i.node)||r.node.elements.findIndex(c=>c===e.path.node)!==0)return null;let a=r.node.elements[1];return _e.isIdentifier(a)&&qx(e,a.name,n)?Ir(e.identifier.name,t,"state setter is updated by API data"):null}function Gw(e,t,n){let r=e.path.isVariableDeclarator()?e.path:e.path.findParent(i=>i.isVariableDeclarator());if(!r?.isVariableDeclarator())return null;let o=r.get("init");return o?.isExpression()?o.isAwaitExpression()?Ir(e.identifier.name,t,"awaited binding result"):uf(o.node,n)?Ir(e.identifier.name,t,"fetch-backed binding result"):null:null}function Yw(e){if(!e.path.isIdentifier())return null;let t=e.path.parentPath;return t?.isObjectProperty()?t:t?.isAssignmentPattern()&&t.parentPath?.isObjectProperty()?t.parentPath:null}function rs(e,t){return _e.isIdentifier(e)?e.name===t:_e.isAssignmentPattern(e)?rs(e.left,t):_e.isObjectPattern(e)?e.properties.some(n=>_e.isObjectProperty(n)?rs(n.value,t):rs(n.argument,t)):_e.isArrayPattern(e)?e.elements.some(n=>!!n&&rs(_e.isRestElement(n)?n.argument:n,t)):!1}function qx(e,t,n){let r=!1,o=!1,i=e.scope.path,s;if(n){let c=Zx.get(n);c||(c=new WeakMap,Zx.set(n,c)),s=c.get(i.node),s||(s=new Map,c.set(i.node,s));let l=s.get(t);if(l!==void 0)return l}i.traverse({CallExpression(c){uf(c.node)&&(r=!0),(qw(c.node.callee,t)||c.node.arguments.some(l=>_e.isIdentifier(l)&&l.name===t))&&(o=!0)}});let a=r&&o;return s?.set(t,a),a}function lf(e){let t=hc(e.callee);return t==="useQuery"||t==="useSWR"||t==="useSuspenseQuery"}function Qx(e){return hc(e.callee)==="useState"}function uf(e,t){let n=t?.get(e);if(n!==void 0)return n;let r=mc(e,o=>_e.isCallExpression(o)&&hc(o.callee)==="fetch");return t?.set(e,r),r}function Zw(e){let t=e;for(;_e.isMemberExpression(t);)t=t.object;return _e.isIdentifier(t)?t.name:null}function eb(e){return e.computed?null:_e.isIdentifier(e.key)?e.key.name:_e.isStringLiteral(e.key)?e.key.value:null}function hc(e){return _e.isIdentifier(e)?e.name:_e.isMemberExpression(e)&&_e.isIdentifier(e.property)?e.property.name:null}function qw(e,t){return mc(e,n=>_e.isIdentifier(n)&&n.name===t)}function mc(e,t){if(t(e))return!0;let n=_e.VISITOR_KEYS[e.type];if(!n)return!1;for(let r of n){let o=e[r];if(Array.isArray(o)){for(let i of o)if(_e.isNode(i)&&mc(i,t))return!0;continue}if(_e.isNode(o)&&mc(o,t))return!0}return!1}function Qw(e){return _e.isIdentifier(e)?e.name:_e.isCallExpression(e)?hc(e.callee)??"api":_e.isAwaitExpression(e)?"awaited-api":"api"}function Ir(e,t,n){return{kind:"api-source",readonly:!0,sourceId:e,displayPath:eO(e,t),reason:n}}function eO(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}var rb=typeof df=="function"?df:df.default;function ob(e,t){let n=sb(e);if(!n)return{allowed:!0};let r=!1;return rb(n,{CallExpression(o){if(!ab(o.node,t.sourceRange)||!tO(o.node))return;let i=o.get("callee");if(!i.isMemberExpression())return;let s=i.get("object");Array.isArray(s)||!s.isExpression()||os(gc(s))&&(r=!0,o.stop())}}),r?{allowed:!1,reason:"Cannot add data-backed items to a dynamic API list"}:{allowed:!0}}function ib(e,t){let n=sb(e);if(!n)return{allowed:!0};let r=!1;return rb(n,{JSXExpressionContainer(o){ab(o.node,t.sourceRange)&&(Vo.isJSXEmptyExpression(o.node.expression)||(r=!0,o.stop()))}}),r?{allowed:!1,reason:"Cannot move subtree across files because it depends on local binding expressions"}:{allowed:!0}}function sb(e){try{return nb.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function tO(e){let t=e.callee;return Vo.isMemberExpression(t)&&Vo.isIdentifier(t.property)&&t.property.name==="map"}function ab(e,t){let n=e.loc;return n?tb({line:n.start.line,column:n.start.column},{line:t.startLine,column:t.startColumn})>=0&&tb({line:n.end.line,column:n.end.column},{line:t.endLine,column:t.endColumn})<=0:!1}function tb(e,t){return e.line!==t.line?e.line<t.line?-1:1:e.column!==t.column?e.column<t.column?-1:1:0}import*as te from"@babel/types";import*as cb from"@babel/parser";import ff from"@babel/traverse";import*as qe from"@babel/types";import*as Uo from"node:path";var Sn=typeof ff=="function"?ff:ff.default;function yt(e){try{return cb.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function pf(e){return e.computed?qe.isStringLiteral(e.key)||qe.isNumericLiteral(e.key)?String(e.key.value):null:nO(e.key)}function nO(e){return qe.isIdentifier(e)?e.name:qe.isStringLiteral(e)||qe.isNumericLiteral(e)?String(e.value):null}function so(e){return qe.isParenthesizedExpression(e)||qe.isTSAsExpression(e)||qe.isTSSatisfiesExpression(e)||qe.isTSNonNullExpression(e)||qe.isTSTypeAssertion(e)?so(e.expression):qe.isExpression(e)?e:null}function mf(e){if(qe.isIdentifier(e))return[e.name];if((qe.isMemberExpression(e)||qe.isOptionalMemberExpression(e))&&!e.computed&&qe.isIdentifier(e.property)){let t=so(e.object),n=t?mf(t):null;return n?[...n,e.property.name]:null}return null}function ao(e,t){return t.startsWith("@/")?t.slice(2).replace(/\\/g,"/"):t.startsWith(".")?Uo.normalize(Uo.join(Uo.dirname(e),t)).replace(/\\/g,"/"):t}function zt(e,t){return yc(e)===yc(t)}function yc(e){let t=Ko(e);return t.endsWith("/index")?t.slice(0,-6):t}function Ko(e){return e.replace(/\.(tsx|ts|jsx|js)$/,"")}function db(e,t,n){let r=gb(e,t);if(hb(e,r),yb(e,r))return{ok:!1,reason:"Cannot move prop-backed repeat child because the component is referenced through an unsupported value usage"};let o=[];return Sn(e,{JSXElement(s){Sb(s,r)&&o.push(s)}}),o.length!==1?{ok:!1,reason:"Cannot move prop-backed repeat child without a single unambiguous component call site"}:xc(o[0])!==n?{ok:!1,reason:"Cannot move prop-backed repeat child because the call site is outside the target component"}:{ok:!0,path:o[0]}}function fb(e,t){let n=new Map,r=i=>{let s=Jo(i);return n.has(s)?!1:(n.set(s,i),!0)};r(t);let o=!0;for(;o;){o=!1;for(let i of e)for(let s of rO(i,n))o=r(s)||o}return[...n.values()]}function rO(e,t){let n=[],r=oO(e,t);for(let o of e.ast.program.body){if(te.isExportDefaultDeclaration(o)&&te.isIdentifier(o.declaration)&&(r.get(o.declaration.name)?.length??0)>0){let i=r.get(o.declaration.name)??[];for(let s of i){if(s.namespace){let a=is(s.namespace,o.declaration.name,"default");a&&n.push({file:e.file,namespace:a,exportName:s.exportName});continue}n.push({file:e.file,exportName:"default"})}continue}if(te.isExportNamedDeclaration(o)&&o.source&&typeof o.source.value=="string"){let i=ao(e.file,o.source.value);for(let s of o.specifiers){if(te.isExportNamespaceSpecifier(s)){let l=vr(s.exported);for(let u of t.values())zt(u.file,i)&&n.push({file:e.file,namespace:gf(l,u.namespace),exportName:u.exportName});continue}if(!te.isExportSpecifier(s))continue;let a=vr(s.local),c=[...t.values()].filter(l=>zt(l.file,i)&&co(l.namespace,a));if(c.length>0){let l=vr(s.exported);for(let u of c){let d=is(u.namespace,a,l);d&&n.push({file:e.file,namespace:d,exportName:u.exportName})}continue}t.has(Jo({file:i,exportName:a}))&&n.push({file:e.file,exportName:vr(s.exported)})}continue}if(te.isExportNamedDeclaration(o)&&!o.source){for(let i of o.specifiers){if(!te.isExportSpecifier(i))continue;let s=vr(i.local),a=r.get(s)??[];if(a.length>0){let c=vr(i.exported);n.push({file:e.file,exportName:c});for(let l of a){let u=is(l.namespace,s,c);u&&n.push({file:e.file,namespace:u,exportName:l.exportName})}}}continue}if(te.isExportAllDeclaration(o)&&typeof o.source.value=="string"){let i=ao(e.file,o.source.value),s=o.exported;if(s){let a=vr(s);for(let c of t.values())zt(c.file,i)&&n.push({file:e.file,namespace:gf(a,c.namespace),exportName:c.exportName});continue}for(let a of t.values())zt(a.file,i)&&(a.namespace||a.exportName!=="default")&&n.push({file:e.file,namespace:a.namespace,exportName:a.exportName})}}return n}function gf(e,t){return t?`${e}.${t}`:e}function co(e,t){return e===t||e?.startsWith(`${t}.`)===!0}function is(e,t,n){return!co(e,t)||!e?null:e===t?n:`${n}${e.slice(t.length)}`}function oO(e,t){let n=new Map,r=(i,s)=>{let a=n.get(i)??[];a.push(s),n.set(i,a)};for(let i of e.ast.program.body){if(!te.isImportDeclaration(i)||typeof i.source.value!="string")continue;let s=ao(e.file,i.source.value);for(let a of i.specifiers){if(te.isImportDefaultSpecifier(a)){let c=t.get(Jo({file:s,exportName:"default"}));c&&r(a.local.name,c);let l=[...t.values()].filter(u=>zt(u.file,s)&&co(u.namespace,"default"));for(let u of l){let d=is(u.namespace,"default",a.local.name);d&&r(a.local.name,{...u,namespace:d})}continue}if(te.isImportSpecifier(a)){let c=vr(a.imported),l=[...t.values()].filter(d=>zt(d.file,s)&&co(d.namespace,c));for(let d of l)r(a.local.name,d);let u=t.get(Jo({file:s,exportName:c}));u&&r(a.local.name,u);continue}if(te.isImportNamespaceSpecifier(a))for(let c of t.values())zt(c.file,s)&&r(a.local.name,{...c,namespace:gf(a.local.name,c.namespace)})}}let o=!0;for(;o;){o=!1;for(let i of e.ast.program.body)if(te.isVariableDeclaration(i))for(let s of i.declarations){if(!te.isIdentifier(s.id)||!s.init)continue;let a=so(s.init);if(!a||!te.isIdentifier(a))continue;let c=n.get(a.name)??[];if(c.length===0)continue;let l=n.get(s.id.name)??[],u=new Set(l.map(Jo));for(let d of c){let f=is(d.namespace,a.name,s.id.name),g=f?{...d,namespace:f}:d,p=Jo(g);u.has(p)||(r(s.id.name,g),u.add(p),o=!0)}}}return n}function Jo(e){let t=e.namespace?`${e.namespace}.${e.exportName}`:e.exportName;return`${yc(e.file)}#${t}`}function vr(e){return te.isIdentifier(e)?e.name:e.value}function pb(e,t){for(let n of e.program.body){if(te.isExportDefaultDeclaration(n)){let o=n.declaration;if((te.isFunctionDeclaration(o)||te.isClassDeclaration(o))&&o.id?.name===t)return{exportName:"default"};if(te.isIdentifier(o)&&o.name===t)return{exportName:"default"}}if(!te.isExportNamedDeclaration(n))continue;let r=n.declaration;if((te.isFunctionDeclaration(r)||te.isClassDeclaration(r))&&r.id?.name===t)return{exportName:t};if(te.isVariableDeclaration(r)){for(let o of r.declarations)if(te.isIdentifier(o.id,{name:t}))return{exportName:t}}for(let o of n.specifiers){if(!te.isExportSpecifier(o)||o.local.name!==t)continue;return{exportName:te.isIdentifier(o.exported)?o.exported.name:o.exported.value}}}return null}function yf(e){let t=iO(e),n=[],r=yb(e.ast,t);return Sn(e.ast,{JSXElement(o){zt(e.file,e.sourceFile)&&xc(o)===e.sourceComponent||Sb(o,t)&&n.push({file:e.file,path:o})}}),{callSites:n,hasUnsafeReference:r}}function mb(){return{localBindings:new Set,namespaceMembers:new Map,hasUnsupportedAlias:!1}}function gb(e,t){let n=mb();return Sn(e,{Program(r){let o=r.scope.getBinding(t);o&&n.localBindings.add(o),r.stop()}}),n}function iO(e){let t=mb();return zt(e.file,e.sourceFile)&&sO(t,gb(e.ast,e.sourceComponent)),Sn(e.ast,{ImportDeclaration(n){let r=n.node,o=r.source.value;if(typeof o!="string")return;let i=ao(e.file,o),s=e.componentIdentities.filter(a=>zt(a.file,i));if(s.length!==0)for(let a of r.specifiers){let c=n.scope.getBinding(a.local.name);if(c){if(te.isImportDefaultSpecifier(a)&&s.some(l=>l.exportName==="default")&&t.localBindings.add(c),te.isImportDefaultSpecifier(a)){let l=s.filter(u=>co(u.namespace,"default"));if(l.length>0){let u=t.namespaceMembers.get(c)??new Set;for(let d of l){let f=ub(d,"default");f&&u.add(f)}t.namespaceMembers.set(c,u)}continue}if(te.isImportSpecifier(a)){let l=te.isIdentifier(a.imported)?a.imported.name:a.imported.value,u=s.filter(d=>co(d.namespace,l));if(u.length>0){let d=t.namespaceMembers.get(c)??new Set;for(let f of u){let g=ub(f,l);g&&d.add(g)}t.namespaceMembers.set(c,d);continue}s.some(d=>!d.namespace&&d.exportName===l)&&t.localBindings.add(c);continue}if(te.isImportNamespaceSpecifier(a))for(let l of s){let u=l.namespace?`${l.namespace}.${l.exportName}`:l.exportName,d=t.namespaceMembers.get(c)??new Set;d.add(u),t.namespaceMembers.set(c,d)}}}}}),hb(e.ast,t),t}function sO(e,t){e.hasUnsupportedAlias||=t.hasUnsupportedAlias;for(let n of t.localBindings)e.localBindings.add(n);for(let[n,r]of t.namespaceMembers){let o=e.namespaceMembers.get(n)??new Set;for(let i of r)o.add(i);e.namespaceMembers.set(n,o)}}function hb(e,t){Sn(e,{VariableDeclarator(n){if(!n.node.init)return;let r=so(n.node.init);if(r){if(te.isIdentifier(n.node.id)){let o=lo(r,t,n),i=n.scope.getBinding(n.node.id.name);o&&i&&hf(t,i,o);return}if(te.isObjectPattern(n.node.id)){let o=lo(r,t,n);o?.unsupported||o?.local?t.hasUnsupportedAlias=!0:o&&o.namespaceMembers.size>0&&Eb(n.node.id,o.namespaceMembers,t,n)}}}})}function yb(e,t){if(t.hasUnsupportedAlias)return!0;let n=!1;return Sn(e,{ReferencedIdentifier(r){if(n){r.stop();return}aO(r)||!r.isIdentifier()||!xb(r,t)||cO(r,t)||lO(r)||(n=!0,r.stop())}}),n}function aO(e){let t=e;for(;t.parentPath?.isJSXMemberExpression();)t=t.parentPath;let n=t.parentPath;return!!(n?.isJSXOpeningElement()&&n.node.name===t.node||n?.isJSXClosingElement()&&n.node.name===t.node)}function xb(e,t){let n=e.scope.getBinding(e.node.name);if(!n)return null;let r=e;for(;r.parentPath?.isMemberExpression()&&r.parentPath.node.object===r.node&&!r.parentPath.node.computed;)r=r.parentPath;return t.localBindings.has(n)||t.namespaceMembers.has(n)&&lo(r.node,t,r)?r:null}function cO(e,t){let n=e.findParent(c=>c.isVariableDeclarator());if(!n?.isVariableDeclarator())return!1;let r=n.get("init");if(!r?.isExpression()||!lb(e,r))return!1;let o=xb(e,t);if(!o)return!1;if(so(r.node)===o.node)return!!lo(r.node,t,r);let s=e.findParent(c=>c.isObjectProperty());if(!s?.isObjectProperty())return!1;let a=s.get("value");return a.isExpression()&&lb(e,a)&&!!lo(a.node,t,a)}function lO(e){let t=e.parentPath;return t?.isExportDefaultDeclaration()&&t.node.declaration===e.node?!0:!!(t?.isExportSpecifier()&&t.node.local===e.node)}function lb(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function lo(e,t,n){let r=so(e);if(!r)return null;if(te.isIdentifier(r)){let a=n.scope.getBinding(r.name);if(!a)return null;let c=t.namespaceMembers.get(a);return t.localBindings.has(a)?{local:!0,namespaceMembers:new Set,unsupported:!1}:c?{local:!1,namespaceMembers:new Set(c),unsupported:!1}:null}if(te.isObjectExpression(r))return uO(r,t,n);let o=mf(r);if(!o||o.length===0)return null;let i=n.scope.getBinding(o[0]);if(!i)return null;let s=t.namespaceMembers.get(i);return s?bb(s,o.slice(1).join(".")):null}function uO(e,t,n){let r=new Set,o=!1;for(let i of e.properties){if(!te.isObjectProperty(i))continue;let s=pf(i);if(!s||!te.isExpression(i.value)){te.isExpression(i.value)&&(o||=lo(i.value,t,n)!==null);continue}let a=lo(i.value,t,n);if(a){o||=a.unsupported,a.local&&r.add(s);for(let c of a.namespaceMembers)r.add(`${s}.${c}`)}}return r.size>0||o?{local:!1,namespaceMembers:r,unsupported:o}:null}function bb(e,t){if(!t)return{local:!1,namespaceMembers:new Set(e),unsupported:!1};let n=new Set,r=!1;for(let o of e){if(o===t){r=!0;continue}o.startsWith(`${t}.`)&&n.add(o.slice(t.length+1))}return r||n.size>0?{local:r,namespaceMembers:n,unsupported:!1}:null}function hf(e,t,n){if(e.hasUnsupportedAlias||=n.unsupported,n.local&&e.localBindings.add(t),n.namespaceMembers.size>0){let r=e.namespaceMembers.get(t)??new Set;for(let o of n.namespaceMembers)r.add(o);e.namespaceMembers.set(t,r)}}function Eb(e,t,n,r){for(let o of e.properties){if(te.isRestElement(o)){if(te.isIdentifier(o.argument)){let c=r.scope.getBinding(o.argument.name);c&&hf(n,c,{local:!1,namespaceMembers:new Set(t),unsupported:!1})}else n.hasUnsupportedAlias=!0;continue}if(!te.isObjectProperty(o))continue;let i=pf(o);if(!i){n.hasUnsupportedAlias=!0;continue}let s=bb(t,i);if(!s)continue;n.hasUnsupportedAlias||=s.unsupported;let a=te.isAssignmentPattern(o.value)?o.value.left:o.value;if(te.isIdentifier(a)){let c=r.scope.getBinding(a.name);c&&hf(n,c,s);continue}if(te.isObjectPattern(a)&&s.namespaceMembers.size>0){Eb(a,s.namespaceMembers,n,r);continue}n.hasUnsupportedAlias=!0}}function ub(e,t){if(!co(e.namespace,t))return null;if(e.namespace===t)return e.exportName;let n=e.namespace?.slice(t.length+1);return n?`${n}.${e.exportName}`:e.exportName}function Sb(e,t){let n=e.node.openingElement.name;if(te.isJSXIdentifier(n)){let o=e.scope.getBinding(n.name);return!!(o&&t.localBindings.has(o))}let r=Ib(n);if(r&&r.length>1){let o=e.scope.getBinding(r[0]);return o?t.namespaceMembers.get(o)?.has(r.slice(1).join("."))===!0:!1}return!1}function Ib(e){if(te.isJSXIdentifier(e))return[e.name];if(te.isJSXMemberExpression(e)){let t=Ib(e.object);return t?[...t,e.property.name]:null}return null}function xc(e){let t=e.getFunctionParent();if(!t)return null;if(t.isFunctionDeclaration())return t.node.id?.name??null;if(t.isArrowFunctionExpression()||t.isFunctionExpression()){let n=t.parentPath;if(n?.isVariableDeclarator()&&te.isIdentifier(n.node.id))return n.node.id.name}return null}function vb(e,t){let n=yt(e);if(!n||!t.tag||!t.importedFrom||!t.exportName)return Number.POSITIVE_INFINITY;let r=yf({ast:n,file:t.file,sourceFile:t.file,sourceComponent:t.tag,componentIdentities:[{file:t.importedFrom,exportName:t.exportName}]});return r.hasUnsafeReference?Number.POSITIVE_INFINITY:r.callSites.length}function Ve(e){return e.structuralPath.includes("#repeat:")||e.isRepeatItemRoot||e.isRepeatRegion?{kind:"jsx-node",strategy:"source-range",sourceRange:e.sourceRange}:{kind:"jsx-node",strategy:"structural-path",file:e.file,component:e.component,structuralPath:e.structuralPath,expectedRange:e.sourceRange}}function De(e){return typeof e.start=="number"&&typeof e.end=="number"?{start:e.start,end:e.end}:null}function Fn(e,t){let n=De(e);return!!(n&&Ht(t,n))}function Ht(e,t){return t.start>=e.start&&t.end<=e.end}function dn(e,t){let n=Ie(e,Ve(t));return n.ok&&n.match.path.isJSXElement()?n.match.path:bc(e,t)}function Xo(e,t){let n=De(t);return n?e.slice(n.start,n.end):""}function kb(e,t){return e.start===t.start&&e.end===t.end}function bc(e,t){let n=null;return Sn(e,{JSXElement(r){let o=r.node.loc;o&&o.start.line===t.sourceRange.startLine&&o.start.column===t.sourceRange.startColumn&&o.end.line===t.sourceRange.endLine&&o.end.column===t.sourceRange.endColumn&&(n=r,r.stop())}}),n}function Ec(e,t){return xf(e,t).length>0}function Sc(e,t){let n=De(e.node),r=De(t.node);if(!n||!r)return!1;let o=e.parentPath;for(;o;){if((o.isIfStatement()||o.isSwitchCase())&&(!!!t.findParent(s=>s.node===o?.node)||o.isIfStatement()&&!dO(o,n,r)))return!0;o=o.parentPath}return!1}function dO(e,t,n){let r=De(e.node.consequent);if(r&&Ht(r,t)&&!Ht(r,n))return!1;let o=e.node.alternate?De(e.node.alternate):null;return!(o&&Ht(o,t)&&!Ht(o,n))}function xf(e,t){let n=De(e.node);if(!n)return[];let r=[],o=e.parentPath;for(;o;){let i=!!t.findParent(s=>s.node===o?.node);if(!i&&o.isConditionalExpression()){let s=De(o.node.consequent),a=De(o.node.alternate);s&&n.start>=s.start&&n.end<=s.end?r.push({kind:"conditional",path:o,conditionPath:o.get("test"),branch:"consequent"}):a&&n.start>=a.start&&n.end<=a.end&&r.push({kind:"conditional",path:o,conditionPath:o.get("test"),branch:"alternate"})}else if(!i&&o.isLogicalExpression()&&bf(o.node.operator)){let s=De(o.node.right);s&&n.start>=s.start&&n.end<=s.end&&r.push({kind:"logical",path:o,conditionPath:o.get("left"),operator:o.node.operator})}o=o.parentPath}return r}function bf(e){return e==="&&"||e==="||"||e==="??"}function _b(e,t){let n=De(e.consequent);if(n&&Ht(n,t))return n;let r=De(e.alternate);return r&&Ht(r,t)?r:null}function Cb(e){if(!e.knownSourceFiles)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component without project-wide source visibility"};if(!e.routeEntryFiles)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component without registered route visibility"};let t=new Set(e.knownSourceFiles.map(a=>Ko(a.file)));if(!t.has(Ko(e.sourceFile))||!t.has(Ko(e.targetFile)))return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component without source and target file visibility"};for(let a of e.routeEntryFiles)if(!t.has(Ko(a)))return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component until all registered route entries are loaded"};let n=pb(e.sourceAst,e.sourceComponent);if(!n)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component without an exported source component identity"};let r=[];for(let a of e.knownSourceFiles){let c=yt(a.content);if(!c)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component because a loaded source file cannot be parsed"};r.push({file:a.file,ast:c})}let o=fb(r,{file:e.sourceFile,exportName:n.exportName}),i=[];for(let a of r){let c=yf({ast:a.ast,file:a.file,sourceFile:e.sourceFile,sourceComponent:e.sourceComponent,componentIdentities:o});if(c.hasUnsafeReference)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component because the component has unsupported value usages"};i.push(...c.callSites)}if(i.length!==1)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component without a single project-wide component call site"};let[s]=i;return!zt(s.file,e.targetFile)||xc(s.path)!==e.targetComponent?{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component because the only call site is outside the target component"}:{ok:!0,callSitePath:s.path}}import{SiteEditSetPropsParamsSchema as yO}from"@vcp-dev/contracts";function Ic(e){let{state:t,scope:n,operation:r,selectionRef:o,repeatTarget:i}=e;if(!t||t.status==="blocked")return{ok:!1,code:"readonly-property",reason:t?.diagnostic?.message??"No safe property write target is available"};if(t.status==="binding"){let s=t.target;if(s?.kind!=="value-binding"||!s.target.locator||n!=="selection"||r!=="set")return ss();let a=s.target,c=a.locator;if(a.sourceKind==="repeat-template"){let l=o?.instanceIndex;if(l===void 0)return ss();let u=fO(a,l,o?.instanceCount);if(!u)return ss();c=u}return{ok:!0,target:{kind:"value-binding",file:a.file,locator:c}}}return o?.instanceIndex!==void 0?n!=="selection"||!i?.ok?{ok:!1,code:"repeat-target-failed",reason:i&&!i.ok?i.reason:"No safe selected repeat property target is available"}:{ok:!0,target:{kind:"repeat-property",target:i}}:e.isRepeat&&n!=="template"||t.status==="direct"&&t.target?.kind!=="jsx-attribute"?ss():{ok:!0,target:{kind:"jsx-attribute"}}}function ss(){return{ok:!1,code:"unsupported-binding",reason:"Property does not have a safe typed binding write target for this scope and operation"}}function fO(e,t,n){if(!e.locator||!Number.isInteger(t)||t<0)return null;let r=e.collectionPathMap?.length??e.collectionIndexMap?.length;if(r!==void 0&&(t>=r||n!==void 0&&n!==r))return null;let o=e.collectionPathMap?.[t];if(o)return{...e.locator,path:o};let i=e.locator.path??[],s=i.findLastIndex(c=>c.kind==="index");if(s<0)return null;let a=i.map((c,l)=>l===s&&c.kind==="index"?{kind:"index",index:e.collectionIndexMap?.[t]??t}:c);return{...e.locator,path:a}}import*as Ln from"@babel/types";import{SiteEditSetPropsParamsSchema as pO}from"@vcp-dev/contracts";function Rb(e){let t=e.changes??(e.change?[e.change]:[]);if(!pO.safeParse({kind:"set-props",scope:"selection",changes:t}).success)return as("invalid-change","Repeat property changes are invalid");if(t.length!==1||t[0].name!==e.target.propertyName)return as("target-mismatch","A repeat property plan must contain exactly one change for its target property");let r=t[0];if(r.operation==="remove"&&e.target.propertyState==="missing")return{ok:!0,steps:[]};let o=We(e.source,"value");if(!o.ok)return as("invalid-target","Repeat property source could not be parsed");let i=[{type:"set-property-binding",order:0,file:e.target.templateFile,locator:e.target.targetElementLocator,name:r.name,object:e.target.callbackItemName,property:r.name}];for(let[s,a]of e.target.parentObjectLocators.entries()){let c=Ie(o.ast,a);if(!c.ok||!c.match.path.isObjectExpression())return as("unsupported-object",`Repeat item ${s} is not a writable object expression`);let l=s===e.target.sourceItemIndex?mO(r):gO(c.match.path.node,r.name);if(!l)return as("unsupported-property-value",`Repeat item ${s} has an unsupported value for '${r.name}'`);i.push({type:"upsert-object-property",order:i.length,file:e.target.sourceFile,locator:a,name:r.name,value:l})}return{ok:!0,steps:i}}function mO(e){return e.operation==="set"?{kind:"value",value:e.value}:{kind:"undefined"}}function gO(e,t){let n=e.properties.filter(i=>Ln.isObjectProperty(i)&&hO(i.key)===t);if(n.length>1)return null;let r=n[0];if(!r)return{kind:"undefined"};if(!Ln.isExpression(r.value))return null;let o=Tn(r.value);return o.status==="undefined"?{kind:"undefined"}:o.status!=="resolved"?null:{kind:"value",value:o.value}}function hO(e){return Ln.isIdentifier(e)?e.name:Ln.isStringLiteral(e)?e.value:Ln.isNumericLiteral(e)?String(e.value):null}function as(e,t){return{ok:!1,errorCode:e,reason:t}}function Nb(e){if(e.change.name!=="className"&&e.change.name!=="class")return cs("unsupported-owner",`No specialized property owner is available for '${e.change.name}'`);let t=e.classNameSource;if(!t||t.filePath!==e.node.file)return cs("owner-source-unavailable","className source details are unavailable for the selected node");if(e.change.name==="class"&&t.sourceKind==="missing")return cs("owner-source-unavailable","The class alias requires an existing className source");if(t.sourceKind==="expression")return cs("owner-source-dynamic","Dynamic className expressions are not writable by the generic property owner");if(e.change.operation==="set"&&typeof e.change.value!="string")return cs("owner-value-invalid","The className owner accepts only string values");if(e.change.operation==="remove"&&t.sourceKind==="missing")return{ok:!0,steps:[]};let n=t.sourceKind==="missing",r=e.change.operation==="set"?`className=${JSON.stringify(e.change.value)}`:null,o=e.change.operation==="remove"?"remove-attribute":n?"create-attribute":"replace-static-classname";return{ok:!0,steps:[{type:"set-class-name-source",order:0,file:e.node.file,request:{kind:"set-class-name-source",key:e.node.key,filePath:e.node.file,expectedVersion:t.version,oldAttrRaw:t.attrRaw,oldAttrRange:t.attrRange,openingElementRange:t.openingElementRange,newAttrRaw:r,intent:{source:"style-panel",operation:o}}}]}}function cs(e,t){return{ok:!1,errorCode:e,reason:t}}async function Ab(e){let t=yO.safeParse({kind:"set-props",scope:e.scope,changes:e.changes});if(!t.success)return kr("invalid-change","Typed property changes are invalid");if(e.node.importedFrom==="next/link"&&e.node.exportName==="default"){let r=t.data.changes.find(o=>o.name==="href");if(r&&(r.operation==="remove"||typeof r.value!="string"||r.value.trim().length===0))return kr("invalid-change","next/link requires a non-empty href; use the dedicated link-target operation to remove the link")}let n=[];for(let r of t.data.changes){let o=await xO(e,r);if(o){if(!o.ok)return kr("owner-plan-failed",o.reason);Pb(n,o.steps);continue}let i=await e.getPropertyState(e.node.key,r.name,e.selectionRef);if(!i)return kr("missing-property-state",`No authoritative property state is available for '${r.name}'`);if(i.status==="blocked")return kr("readonly-property",i.diagnostic?.message??`Property '${r.name}' is not writable`);if(SO(i,r)||r.operation==="remove"&&i.status==="missing")continue;let s=e.selectionRef?.instanceIndex!==void 0&&i.status!=="binding"?await e.getRepeatPropertyTarget?.(e.node.key,r.name,e.selectionRef):void 0,a=Ic({state:i,scope:e.scope,operation:r.operation,selectionRef:e.selectionRef,repeatTarget:s});if(!a.ok)return kr(a.code,a.reason);let c=a.target;if(c.kind==="value-binding"&&r.operation==="set"){Ef(n,{type:"update-value",order:n.length,file:c.file,locator:c.locator,value:r.value});continue}if(c.kind==="repeat-property"){let l=Rb({source:e.getFileContent(c.target.sourceFile),target:c.target,changes:[r]});if(!l.ok)return kr("repeat-target-failed",l.reason);Pb(n,l.steps);continue}Ef(n,{type:"set-property-changes",order:n.length,file:e.node.file,locator:bO(e.node),scope:e.scope,changes:[r]})}return n.forEach((r,o)=>{r.order=o}),EO(n)?kr("step-conflict","Property changes resolve to conflicting write steps"):{ok:!0,steps:n}}async function xO(e,t){return t.name!=="className"&&t.name!=="class"?null:Nb({node:e.node,change:t,classNameSource:e.classNameSource})}function bO(e){return e.structuralPath.includes("#repeat:")||e.key.includes("::repeat-item#")?{kind:"jsx-node",strategy:"source-range",sourceRange:e.sourceRange}:{kind:"jsx-node",strategy:"structural-path",file:e.file,component:e.component,structuralPath:e.structuralPath,expectedRange:e.sourceRange}}function EO(e){let t=new Set;for(let n of e){let{order:r,...o}=n,i=`${n.file}:${n.type}:${JSON.stringify(o)}`;if(t.has(i))return!0;t.add(i)}return!1}function Pb(e,t){for(let n of t)Ef(e,{...n,order:e.length})}function Ef(e,t){if(t.type==="set-property-changes"){let n=e.find(r=>r.type==="set-property-changes"&&r.file===t.file&&JSON.stringify(r.locator)===JSON.stringify(t.locator)&&r.scope===t.scope);if(n){n.changes.push(...t.changes);return}}e.push(t)}function SO(e,t){if(t.operation!=="set"||e.status!=="direct")return!1;let n=e.attribute?.resolution;return n?.status==="resolved"?Sf(n.value,t.value):e.attribute?.source===null&&e.attribute.value===t.value}function Sf(e,t){if(Object.is(e,t))return!0;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((n,r)=>Sf(n,t[r]));if(e&&t&&typeof e=="object"&&typeof t=="object"){let n=e,r=t,o=Object.keys(n);return o.length===Object.keys(r).length&&o.every(i=>Sf(n[i],r[i]))}return!1}function kr(e,t){return{ok:!1,errorCode:e,reason:t}}import*as Ho from"@babel/types";import*as ae from"@babel/types";function If(e,t,n){let r=dn(t,n);return r?Mn(e,r):null}function Mn(e,t){let n=t.findParent(m=>m.isArrowFunctionExpression()||m.isFunctionExpression());if(!n||!n.isArrowFunctionExpression()&&!n.isFunctionExpression())return null;let r=n,o=r.parentPath;if(!o||!o.isCallExpression()&&!o.isOptionalCallExpression())return null;let i=o;if(i.node.arguments.findIndex(m=>m===r.node)!==0)return null;let a=i.get("callee");if(!a.isMemberExpression()&&!a.isOptionalMemberExpression())return null;let c=a.node,l=c.property;if(!ae.isIdentifier(l)||l.name!=="map"||c.computed)return null;let u=a.get("object"),d=Xo(e,u.node),f=r.node.params.map(m=>Xo(e,m)),g=De(i.node),p=De(r.node);return!d||f.some(m=>m.length===0)||!g||!p?null:{callStart:g.start,callEnd:g.end,callbackStart:p.start,callbackEnd:p.end,collectionExpression:d,callbackParams:f,mapOperator:ae.isOptionalMemberExpression(c)&&c.optional?"?.map":".map",collectionNeedsParens:vc(u.node),callbackPath:r,collectionPath:u}}function ls(e,t){return!!(e&&t&&e.callStart===t.callStart&&e.callEnd===t.callEnd&&e.callbackStart===t.callbackStart&&e.callbackEnd===t.callbackEnd)}function IO(e,t){let n=De(e.node);return n?vO(t).some(r=>{let o=De(r);return r===e.node||!!(o&&o.start===n.start&&o.end===n.end)}):!1}function vO(e){let t=e.callbackPath.node.body;return ae.isBlockStatement(t)?_r(t.body):Cr(t)}function _r(e){let t=[];for(let n of e){if(ae.isReturnStatement(n)){n.argument&&t.push(...Cr(n.argument));continue}if(ae.isBlockStatement(n)){t.push(..._r(n.body));continue}if(ae.isIfStatement(n)){let r=ae.isBlockStatement(n.consequent)?n.consequent.body:[n.consequent];if(t.push(..._r(r)),n.alternate){let o=ae.isBlockStatement(n.alternate)?n.alternate.body:[n.alternate];t.push(..._r(o))}continue}if(ae.isSwitchStatement(n)){for(let r of n.cases)t.push(..._r(r.consequent));continue}ae.isTryStatement(n)&&(t.push(..._r(n.block.body)),n.handler&&t.push(..._r(n.handler.body.body)),n.finalizer&&t.push(..._r(n.finalizer.body)))}return t}function Cr(e){return ae.isJSXElement(e)?kO(e)?Tb(e.children):[e]:ae.isJSXFragment(e)?Tb(e.children):ae.isParenthesizedExpression(e)||ae.isTSAsExpression(e)||ae.isTSSatisfiesExpression(e)||ae.isTSNonNullExpression(e)||ae.isTSTypeAssertion(e)?Cr(e.expression):ae.isConditionalExpression(e)?[...Cr(e.consequent),...Cr(e.alternate)]:ae.isLogicalExpression(e)&&bf(e.operator)?Cr(e.right):[]}function Tb(e){return e.flatMap(t=>ae.isJSXElement(t)||ae.isJSXFragment(t)?Cr(t):ae.isJSXExpressionContainer(t)&&(ae.isJSXElement(t.expression)||ae.isJSXFragment(t.expression)||ae.isConditionalExpression(t.expression)||ae.isLogicalExpression(t.expression))?Cr(t.expression):[])}function kO(e){let t=e.openingElement.name;return ae.isJSXIdentifier(t)?t.name==="Fragment":ae.isJSXMemberExpression(t)&&t.property.name==="Fragment"}function wb(e,t){return!!(e&&t&&e.callbackStart<t.callbackStart&&e.callbackEnd>t.callbackEnd)}function vc(e){return!(ae.isIdentifier(e)||ae.isThisExpression(e)||ae.isMemberExpression(e)||ae.isOptionalMemberExpression(e)||ae.isCallExpression(e)||ae.isOptionalCallExpression(e))}function Ob(e){let t=e.parentPath;if(!t||!t.isCallExpression()&&!t.isOptionalCallExpression()||t.node.arguments[0]!==e.node)return!1;let n=t.node.callee;return(ae.isMemberExpression(n)||ae.isOptionalMemberExpression(n))&&ae.isIdentifier(n.property)&&n.property.name==="map"&&!n.computed}function zo(e,t){let n=yt(e);if(!n)return t.isRepeatItemRoot===!0;let r=Ie(n,Ve(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:bc(n,t);if(!o)return t.isRepeatItemRoot===!0;let i=Mn(e,o);return i?IO(o,i):t.isRepeatItemRoot===!0}function Fb(e,t){let n=yt(e);if(!n)return!1;let r=Ie(n,Ve(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:bc(n,t);return o?!!o.findParent(i=>{if(!i.isCallExpression()&&!i.isOptionalCallExpression())return!1;let s=i.node.callee;return(ae.isMemberExpression(s)||ae.isOptionalMemberExpression(s))&&ae.isIdentifier(s.property)&&s.property.name==="map"}):!1}import*as Xe from"@babel/types";function vf(e){if(Xe.isJSXIdentifier(e))return/^[A-Z]/.test(e.name)?e.name:null;if(Xe.isJSXMemberExpression(e)){let t=e;for(;Xe.isJSXMemberExpression(t);)t=t.object;return t.name}return null}function _O(e,t){let n=De(e.node);if(!n)return[];let r=new Set,o=(i,s)=>{let a=s.scope.getBinding(i);!a||Fn(a.path.node,n)||Rr(a,i,t)||r.add(i)};return e.traverse({ReferencedIdentifier(i){o(i.node.name,i)},JSXOpeningElement(i){let s=vf(i.node.name);s&&o(s,i)}}),[...r].sort()}function kf(e,t,n){let r=yt(e);if(!r)return{ok:!0};let o=Ie(r,Ve(t));if(!o.ok||!o.match.path.isJSXElement())return{ok:!0};let i=Ie(r,Ve(n));if(!i.ok||!i.match.path.isJSXElement())return{ok:!0};let s=Ii(o.match.path,i.match.path);if(Ec(s,i.match.path))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let a=_O(s,i.match.path);return a.length>0?{ok:!1,bindingNames:a}:{ok:!0}}function Mb(e){let t=e;for(;Xe.isTSQualifiedName(t);)t=t.left;return Xe.isIdentifier(t)?t.name:null}function us(e,t){e.isIdentifier()&&e.isReferencedIdentifier()&&t(e),e.traverse({ReferencedIdentifier(n){n.isIdentifier()&&t(n)}})}function kc(e){let t=[],n=r=>{if(r){if(Xe.isIdentifier(r)){t.push(r.name);return}if(Xe.isObjectPattern(r)){for(let o of r.properties){if(Xe.isRestElement(o)){n(o.argument);continue}Xe.isObjectProperty(o)&&n(o.value)}return}if(Xe.isArrayPattern(r)){for(let o of r.elements)n(o);return}if(Xe.isAssignmentPattern(r)){n(r.left);return}if(Xe.isRestElement(r)){n(r.argument);return}Xe.isTSParameterProperty(r)&&n(r.parameter)}};return n(e),t}function _f(e,t){let n=De(e.node),r=De(t.node);if(!n||!r)return{ok:!1,reason:"Cannot move repeat-backed child out of a component without proving the component call-site render scope"};let o=Lb(e),i=Lb(t);if(!o||!i||!kb(o,i))return{ok:!1,reason:"Cannot move repeat-backed child out of a component because the component call site is rendered in a different return branch"};let s=e.parentPath;for(;s;){if(s.isConditionalExpression()){let a=_b(s.node,n);if(a&&!Ht(a,r))return{ok:!1,reason:"Cannot move repeat-backed child out of a component because the component call site is conditionally rendered outside the target scope"}}else if(s.isLogicalExpression()){let a=De(s.node.right);if(a&&Ht(a,n)&&!Ht(a,r))return{ok:!1,reason:"Cannot move repeat-backed child out of a component because the component call site is conditionally rendered outside the target scope"}}else if((s.isArrowFunctionExpression()||s.isFunctionExpression())&&Ob(s)){let a=De(s.node.body)??De(s.node);if(a&&!Ht(a,r))return{ok:!1,reason:"Cannot move repeat-backed child out of a component because the component call site is repeated outside the target scope"}}s=s.parentPath}return{ok:!0}}function Lb(e){let t=e;for(;t;){if(t.isReturnStatement())return t.node.argument?De(t.node.argument):null;if(t.isArrowFunctionExpression()&&(Xe.isJSXElement(t.node.body)||Xe.isJSXFragment(t.node.body)||Xe.isConditionalExpression(t.node.body)||Xe.isLogicalExpression(t.node.body)))return De(t.node.body);t=t.parentPath}return null}function Rr(e,t,n){return n.scope.getBinding(t)===e}function Cf(e,t,n,r={}){if(!r.preserveConditionalBoundary&&Ec(e,t))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let o=De(e.node);if(!o)return{ok:!0};let i=new Set(n.callbackPath.node.params.flatMap(c=>kc(c)).map(c=>n.callbackPath.scope.getBinding(c)?.path.node).filter(Boolean)),s=new Set,a=(c,l)=>{let u=l.scope.getBinding(c);!u||Fn(u.path.node,o)||i.has(u.path.node)||Rr(u,c,t)||s.add(c)};return e.traverse({ReferencedIdentifier(c){a(c.node.name,c)},JSXOpeningElement(c){let l=vf(c.node.name);l&&a(l,c)}}),s.size>0?{ok:!1,bindingNames:[...s].sort()}:{ok:!0}}function Rf(e,t,n){let r=De(e.node);if(!r)return{ok:!0};let o=new Set(n.callbackPath.node.params.flatMap(s=>kc(s)).map(s=>n.callbackPath.scope.getBinding(s)?.path.node).filter(Boolean)),i=new Set;return us(e,s=>{let a=s.scope.getBinding(s.node.name);!a||Fn(a.path.node,r)||o.has(a.path.node)||Rr(a,s.node.name,t)||i.add(s.node.name)}),i.size>0?{ok:!1,bindingNames:[...i].sort()}:{ok:!0}}function Db(e,t){let n=new Set(e.callbackPath.node.params.flatMap(a=>kc(a)).map(a=>e.callbackPath.scope.getBinding(a)?.path.node).filter(Boolean)),r=new Set,o=(a,c)=>{let l=c.scope.getBinding(a);!l||n.has(l.path.node)||Rr(l,a,t)||r.add(a)},i=e.callbackPath.get("params"),s=Array.isArray(i)?i:[i];for(let a of s)a.traverse({ReferencedIdentifier(c){o(c.node.name,c)},TSTypeReference(c){let l=c.node.typeName;if(Ho.isIdentifier(l))o(l.name,c);else{let u=Mb(l);u&&o(u,c)}}});return r.size>0?{ok:!1,bindingNames:[...r].sort()}:{ok:!0}}function Nf(e,t){let n=De(e.node),r=new Set;return us(e,o=>{let i=o.scope.getBinding(o.node.name);i&&(n&&Fn(i.path.node,n)||Rr(i,o.node.name,t)||r.add(o.node.name))}),r.size>0?{ok:!1,bindingNames:[...r].sort(),reason:"Cannot move repeat-backed child because the repeat collection is not visible at the target"}:{ok:!0}}function Bb(e){let t=[];for(let n of e.callbackPath.node.params){if(Ho.isIdentifier(n)){t.push(n.name);continue}if(Ho.isRestElement(n)&&Ho.isIdentifier(n.argument)){t.push(`...${n.argument.name}`);continue}return{ok:!1,reason:"Cannot move cross-file repeat child because the callback parameters are not portable to the target file"}}return{ok:!0,callbackParams:t}}function jb(e,t){return{...e,callbackParams:t}}function Pf(e,t){return`${e.collectionNeedsParens?`(${e.collectionExpression})`:e.collectionExpression}${e.mapOperator}((${e.callbackParams.join(", ")}) => ${t})`}function ds(e,t,n){return n?.finalSource?.kind==="component-prop"?"Cannot edit prop-backed node structure with a generic node operation":t?.kind==="value-binding"&&t.sourceKind==="repeat-template"&&!e.isRepeatItemRoot?"Cannot edit repeat-backed child node structure with a generic node operation":t?.kind==="value-binding"&&t.file!==e.file&&t.sourceKind!=="repeat-template"?"Cannot edit upstream-bound node structure with a generic node operation":null}function $b(e,t,n,r){return e.parentKey===t.key&&e.file===t.file&&n?.kind==="value-binding"&&n.file!==e.file&&n.sourceKind!=="repeat-template"&&r?.finalSource?.kind!=="component-prop"}function uo(e){return{file:e.file,component:e.component}}function CO(e){return e.target.kind==="node"?e.target.key:null}function RO(e){return"kind"in e&&e.kind==="page-composition"}function Rc(e){return typeof e=="object"&&e!==null&&"kind"in e&&e.kind==="block-boundary"}function _c(e){return!RO(e)&&!Rc(e)}function Ff(e,t){let n=Pc.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=Pc.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function Af(e,t){let n=e.getFileContent(t.file);if(!n)return;let r=Pn(n,Ve(t));if(r.ok)return n.slice(r.match.start,r.match.end)}function Mf(e){if(!e.component)return"Component";if(e.component.exportName!=="default")return e.component.exportName;let t=e.component.source.replace(/\\/g,"/").replace(/\/$/,""),n=t.split("/").pop()||"Component",i=(n==="index"?t.split("/").slice(-2,-1)[0]||"Component":n).replace(/\.[^.]+$/,"").split(/[^A-Za-z0-9]+/).filter(Boolean);return i.length===0?"Component":i.map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join("")}function NO(e){if(e.isNumericLiteral())return!0;if(!e.isUnaryExpression({operator:"-"}))return!1;let t=e.get("argument");return!Array.isArray(t)&&t.isNumericLiteral()}function PO(e){let t=e.trim();if(!/^[+-]?(?:(?:\d+\.?\d*)|(?:\.\d+))(?:[eE][+-]?\d+)?$/.test(t))return null;let n=Number(t);return Number.isFinite(n)?n:null}function Tf(e){return e==="Cannot edit repeat-backed child node structure with a generic node operation"}function AO(e){let t=db(e.ast,e.sourceNode.component,e.targetParent.component);if(!t.ok)return{ok:!1,reason:t.reason};let n=_f(t.path,e.targetParentPath);if(!n.ok)return{ok:!1,reason:n.reason};let r=TO({source:e.source,sourceContext:e.sourceContext,callSitePath:t.path,targetParentPath:e.targetParentPath});if(!r.ok)return r;let o=Gb(r.collectionExpression);return{ok:!0,context:{...e.sourceContext,collectionExpression:r.collectionExpression,collectionNeedsParens:o?vc(o):!0}}}function TO(e){let t=De(e.sourceContext.collectionPath.node);if(!t)return{ok:!1,reason:"Cannot move prop-backed repeat child because the collection expression cannot be mapped"};let n=new Map,r=new Set,o=null,i=s=>{if(o)return;let a=s.scope.getBinding(s.node.name);if(!a||Fn(a.path.node,t))return;let c=FO(s,a,t);if(c){if(c.hasDefault){o="Cannot move prop-backed repeat child because the collection prop has a default value that cannot be preserved safely";return}let l=MO(e.callSitePath,c.propName,e.source);if(!l.ok){o=l.reason;return}let u=wO(l.expression,c.remainingPath);if(!u){o="Cannot move prop-backed repeat child because the mapped prop path is not a portable expression";return}let d=Nf(l.expressionPath,e.targetParentPath);if(!d.ok){o=d.reason??`Cannot move prop-backed repeat child because the mapped prop source is not visible at the target: ${d.bindingNames.join(", ")}`;return}n.set(`${c.range.start}:${c.range.end}`,{...c.range,text:u});return}Rr(a,s.node.name,e.targetParentPath)||r.add(s.node.name)};return e.sourceContext.collectionPath.isIdentifier()&&e.sourceContext.collectionPath.isReferencedIdentifier()&&i(e.sourceContext.collectionPath),e.sourceContext.collectionPath.traverse({ReferencedIdentifier(s){s.isIdentifier()&&i(s)}}),o?{ok:!1,reason:o}:r.size>0?{ok:!1,reason:`Cannot move prop-backed repeat child because the collection depends on bindings outside the target scope: ${[...r].sort().join(", ")}`}:n.size===0?{ok:!1,reason:"Cannot move repeat-backed child out of its component without an explicit prop mapping"}:{ok:!0,collectionExpression:DO(e.source,t,[...n.values()])}}function wO(e,t){if(t.length===0)return e;let n=Gb(e);if(!n)return null;let r=vc(n)?`(${e})`:e;for(let o of t){if(o.kind==="property"){r=OO(o.name)?`${r}.${o.name}`:`${r}[${JSON.stringify(o.name)}]`;continue}r=`${r}[${o.index}]`}return r}function OO(e){return/^[$A-Z_a-z][$\w]*$/.test(e)}function FO(e,t,n){let r=LO(e,n),o=r?{kind:"member-expression",expression:e.node.name,base:e.node.name,path:[{kind:"property",name:r.propertyName}]}:{kind:"identifier",expression:e.node.name,base:e.node.name,path:[]},i=$o(t,o);if(!i)return null;let s=r?.range??De(e.node);return s?{propName:i.propName,remainingPath:i.remainingPath,hasDefault:i.hasDefault,range:s}:null}function LO(e,t){let n=e.parentPath;if(!n||!n.isMemberExpression()&&!n.isOptionalMemberExpression()||n.node.object!==e.node||!Fn(n.node,t)||n.node.computed||!Oe.isIdentifier(n.node.property))return null;let r=De(n.node);return r?{propertyName:n.node.property.name,range:r}:null}function MO(e,t,n){let r=e.get("openingElement").get("attributes");if(r.some(c=>c.isJSXSpreadAttribute()))return{ok:!1,reason:"Cannot move prop-backed repeat child through spread props; use an explicit prop mapping"};let o=r.find(c=>c.isJSXAttribute()&&Oe.isJSXIdentifier(c.node.name)&&c.node.name.name===t);if(!o?.isJSXAttribute())return{ok:!1,reason:`Cannot move prop-backed repeat child because prop '${t}' is not passed explicitly`};let i=o.get("value");if(!i.isJSXExpressionContainer())return{ok:!1,reason:`Cannot move prop-backed repeat child because prop '${t}' is not an expression`};let s=i.get("expression");if(!s.isExpression())return{ok:!1,reason:`Cannot move prop-backed repeat child because prop '${t}' is not a usable expression`};let a=Xo(n,s.node);return a?{ok:!0,expression:a,expressionPath:s}:{ok:!1,reason:`Cannot move prop-backed repeat child because prop '${t}' cannot be read`}}function DO(e,t,n){let r=e.slice(t.start,t.end),o=[...n].sort((i,s)=>s.start-i.start);for(let i of o)r=r.slice(0,i.start-t.start)+i.text+r.slice(i.end-t.start);return r}function Gb(e){try{let n=Wb.parse(`const __VD_EXPR__ = (${e});`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0],r=Oe.isVariableDeclaration(n)?n.declarations[0]?.init:null;return r&&Oe.isExpression(r)?r:null}catch{return null}}function BO(e){let t=De(e.sourceContext.collectionPath.node);if(!t)return{ok:!1,reason:"Cannot move cross-file repeat child because the collection expression cannot be inspected"};let n=new Map,r=new Set,o=i=>{let s=i.scope.getBinding(i.node.name);if(!s||Fn(s.path.node,t))return;let a=Vb(s,e.sourceFile,e.targetFile);if(a){let c=e.targetParentPath.scope.getBinding(a.localName);if(c){let u=Vb(c,e.targetFile,e.targetFile);(!u||u.moduleFile!==a.moduleFile||!jO(u.importSpec,a.importSpec))&&r.add(a.localName);return}let l=n.get(a.moduleSpecifier)??[];l.some(u=>JSON.stringify(u)===JSON.stringify(a.importSpec))||l.push(a.importSpec),n.set(a.moduleSpecifier,l);return}r.add(i.node.name)};return us(e.sourceContext.collectionPath,o),r.size>0?{ok:!1,reason:`Cannot move cross-file repeat child because the collection depends on non-importable bindings: ${[...r].sort().join(", ")}`}:{ok:!0,imports:[...n.entries()].map(([i,s])=>({moduleSpecifier:i,imports:s}))}}function jO(e,t){return e.kind!==t.kind?!1:e.kind==="named"&&t.kind==="named"?e.imported===t.imported&&e.local===t.local:e.kind==="default"&&t.kind==="default"||e.kind==="namespace"&&t.kind==="namespace"?e.local===t.local:!1}function Vb(e,t,n){let r=$O(e),o=r?.parentPath;if(!r||!o?.isImportDeclaration())return null;let i=o.node.source.value;if(typeof i!="string")return null;let s=ao(t,i),a=i.startsWith(".")?Ff(n,s):i;if(r.isImportDefaultSpecifier()){let c=r.node.local.name;return{localName:c,moduleFile:s,moduleSpecifier:a,importSpec:{kind:"default",local:c}}}if(r.isImportNamespaceSpecifier()){let c=r.node.local.name;return{localName:c,moduleFile:s,moduleSpecifier:a,importSpec:{kind:"namespace",local:c}}}if(r.isImportSpecifier()){let c=Oe.isIdentifier(r.node.imported)?r.node.imported.name:r.node.imported.value,l=r.node.local.name;return{localName:l,moduleFile:s,moduleSpecifier:a,importSpec:{kind:"named",imported:c,local:l===c?void 0:l}}}return null}function $O(e){let t=e.path;for(;t&&!t.isImportDeclaration();){if(t.isImportSpecifier()||t.isImportDefaultSpecifier()||t.isImportNamespaceSpecifier())return t;t=t.parentPath}return null}function Ub(e,t,n,r){let o=xf(t,n);if(o.length===0)return{sourceJsx:r,conditionPaths:[]};let i=r,s=[];for(let a of o){let c=Xo(e,a.conditionPath.node);if(!c)return{sourceJsx:r,conditionPaths:[]};let l=VO(a.conditionPath,c);if(s.push(a.conditionPath),a.kind==="logical"){i=`${l} ${a.operator} ${KO(i)}`;continue}i=a.branch==="consequent"?`${l} ? ${i} : null`:`${l} ? null : ${i}`}return{sourceJsx:i,conditionPaths:s}}function VO(e,t){return UO(e.node)?t:`(${t})`}function UO(e){return Oe.isIdentifier(e)||Oe.isThisExpression(e)||Oe.isSuper(e)||Oe.isMemberExpression(e)||Oe.isOptionalMemberExpression(e)||Oe.isCallExpression(e)||Oe.isOptionalCallExpression(e)||Oe.isBooleanLiteral(e)||Oe.isNumericLiteral(e)||Oe.isStringLiteral(e)||Oe.isNullLiteral(e)||Oe.isUnaryExpression(e)}function KO(e){return e.trim().startsWith("<")?e:`(${e})`}var JO={table:new Set(["caption","colgroup","thead","tbody","tfoot","tr"]),thead:new Set(["tr"]),tbody:new Set(["tr"]),tfoot:new Set(["tr"]),tr:new Set(["th","td"]),ul:new Set(["li"]),ol:new Set(["li"]),select:new Set(["option","optgroup"]),optgroup:new Set(["option"])};function Cc(e,t){if(t.kind!=="native-tag")return null;let n=e.tag?.toLowerCase();if(!n||n!==e.tag||n.startsWith("component:"))return null;let r=JO[n];if(!r)return null;let o=t.tag.toLowerCase();return r.has(o)?null:`Cannot insert <${t.tag}> into <${e.tag}>; expected ${[...r].map(i=>`<${i}>`).join(", ")}`}function XO(e,t){for(let n of e.program.body){if(!Oe.isImportDeclaration(n)||n.source.value!==t)continue;let r=n.specifiers.find(o=>Oe.isImportDefaultSpecifier(o));if(r&&Oe.isImportDefaultSpecifier(r))return r.local.name}return null}function zO(e,t,n){for(let r of e.program.body){if(!Oe.isImportDeclaration(r)||r.source.value!==t)continue;let o=r.specifiers.find(i=>Oe.isImportSpecifier(i)&&(Oe.isIdentifier(i.imported)?i.imported.name:i.imported.value)===n);if(o&&Oe.isImportSpecifier(o))return o.local.name}return null}function Kb(e){let t=new Set;return Sn(e,{Program(n){for(let r of Object.keys(n.scope.bindings))t.add(r);n.stop()}}),t}function Jb(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n+=1;return`${e}${n}`}function HO(e,t){if(!e.component)return{localName:"Component"};let n=e.component,r=Mf(e),o=yt(t);if(n.exportName!=="default"){let a=o?zO(o,n.source,n.exportName):null;if(a)return{localName:a};let c=o?Jb(r,Kb(o)):r;return{localName:c,importStep:wf(e,c)}}if(!o)return{localName:r,importStep:wf(e,r)};let i=XO(o,n.source);if(i)return{localName:i};let s=Jb(r,Kb(o));return{localName:s,importStep:wf(e,s)}}function WO(e,t){if(e.kind==="native-tag")return e.text?`<${e.tag}>${e.text}</${e.tag}>`:`<${e.tag} />`;let n=t??Mf(e);if(e.props&&Object.keys(e.props).length>0){let r=Object.entries(e.props).map(([o,i])=>typeof i=="string"?`${o}="${i}"`:`${o}={${JSON.stringify(i)}}`).join(" ");return`<${n} ${r} />`}return`<${n} />`}function GO(e){if(e.kind==="native-tag")return e.text===void 0?{kind:e.kind,tag:e.tag}:{kind:e.kind,tag:e.tag,text:e.text};if(!e.component)return{kind:e.kind};let t=e.props?YO(e.props):void 0;return{kind:e.kind,component:{source:e.component.source,exportName:e.component.exportName},...t?{props:t}:{}}}function YO(e){return Object.fromEntries(Object.entries(e).filter(t=>Lf(t[1])))}function Lf(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(Lf):typeof e=="object"?Object.values(e).every(Lf):!1}function wf(e,t=Mf(e)){if(!e.component)throw new Error("Materialized component calls do not have a component import");return{moduleSpecifier:e.component.source,imports:e.component.exportName==="default"?[{kind:"default",local:t}]:[{kind:"named",imported:e.component.exportName,...t!==e.component.exportName?{local:t}:{}}]}}function Xb(e,t){if("kind"in e)return{parentNode:null,anchorNode:null,placement:e.relation};if(e.relation==="prepend"||e.relation==="append"){let o=t.getNode(e.parentKey);return{parentNode:o,anchorNode:null,placement:e.relation,...o?{}:{error:{errorCode:"locator-miss",reason:`Target parent '${e.parentKey}' not found in graph`}}}}if(!("anchorKey"in e))return{parentNode:null,anchorNode:null,placement:e.relation,error:{errorCode:"invalid-target",reason:`Sibling target '${e.relation}' requires an anchor`}};let n=t.getNode(e.anchorKey),r=t.getNode(e.parentKey);return n?r?n.parentKey!==r.key?{parentNode:r,anchorNode:n,placement:e.relation,error:{errorCode:"invalid-target",reason:`Target anchor '${n.key}' belongs to parent '${n.parentKey??"<root>"}', expected '${r.key}'`}}:{parentNode:r,anchorNode:n,placement:e.relation}:{parentNode:null,anchorNode:n,placement:e.relation,error:{errorCode:"locator-miss",reason:`Target parent '${e.parentKey}' not found in graph`}}:{parentNode:r,anchorNode:null,placement:e.relation,error:{errorCode:"locator-miss",reason:`Target anchor '${e.anchorKey}' not found in graph`}}}function ZO(e,t,n){let r=e;for(;r;){if(r===t)return!0;r=n.getNode(r)?.parentKey}return!1}function Wo(e,t){return`Operation kind '${e}' does not match params.kind '${t}'`}function Df(e,t=e.path){return{kind:"value",root:e.root,path:t&&t.length>0?t:void 0,expectedRange:e.expectedRange}}function fs(e){let t=e.path??[];for(let n=t.length-1;n>=0;n-=1){let r=t[n];if(r.kind==="index")return{locator:Df(e,t.slice(0,n)),index:r.index}}return null}function Of(e,t){return e.locator?e.collectionPathMap?.[t]?Df(e.locator,e.collectionPathMap[t]):fs(e.locator)?QO(e.locator,eF(t,e.collectionIndexMap)):null:null}function qO(e,t){let n=e.path??[],r=n.findLastIndex(i=>i.kind==="index");if(r===-1)return;let o=n.slice(r+1);return o.length===0?t:Yb(o,t)}function Yb(e,t){let[n,...r]=e;if(!n)return t;if(n.kind!=="property")return;let o=Yb(r,t);return o===void 0?void 0:{[n.name]:o}}function QO(e,t){let n=e.path??[];for(let r=n.length-1;r>=0;r-=1)if(n[r].kind==="index"){let i=[...n];return i[r]={kind:"index",index:t},Df(e,i)}return null}function eF(e,t){return t?.[e]??e}function zb(e,t){return!t||t.length===0?e:e<=0?t[0]??0:e>=t.length?(t[t.length-1]??t.length-1)+1:t[e]??e}function tF(e,t){return nF(e.root,t.root)&&oF(e.path??[],t.path??[])}function nF(e,t){if(e.kind!==t.kind)return!1;switch(e.kind){case"binding":case"hook-state":case"named-export":return"name"in t&&e.name===t.name;case"default-export":return!0;case"expression":return"sourceRange"in t&&rF(e.sourceRange,t.sourceRange)}}function rF(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function oF(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],o=t[n];if(r.kind!==o.kind)return!1;if(r.kind==="property"){if(o.kind!=="property"||r.name!==o.name)return!1;continue}if(o.kind!=="index"||r.index!==o.index)return!1}return!0}var Nc=class{constructor(t){this.operationCounter=0,this.graph=t}async plan(t){let n=`op-${++this.operationCounter}-${Date.now()}`;switch(t.kind){case"update-text":{if(t.params.kind!=="update-text")return{ok:!1,errorCode:"unknown",reason:Wo(t.kind,t.params.kind)};let r=t,o=this.resolveNodeRequest(t);if(!o.ok)return o.result;let i=o.node,s=this.graph.getFileVersion(i.file);return t.documentVersion!==s?{ok:!1,errorCode:"stale-version",reason:`Document version ${t.documentVersion} is stale or otherwise does not match current version (current: ${s})`}:this.planUpdateText(n,r,i,this.graph.getCapability(i.key),await this.graph.getTextWriteTarget(i.key,r.params.segmentIndex))}case"update-array-item":{if(t.params.kind!=="update-array-item")return{ok:!1,errorCode:"unknown",reason:Wo(t.kind,t.params.kind)};let r=t,o=this.resolveNodeRequest(t);if(!o.ok)return o.result;let i=o.node,s=this.graph.getFileVersion(i.file);return t.documentVersion!==s?{ok:!1,errorCode:"stale-version",reason:`Document version ${t.documentVersion} is stale or otherwise does not match current version (current: ${s})`}:this.planUpdateArrayItem(n,r,this.graph.getCapability(i.key),await this.graph.getTextWriteTarget(i.key,r.params.segmentIndex))}case"remove-node":{if(t.params.kind!=="remove-node")return{ok:!1,errorCode:"unknown",reason:Wo(t.kind,t.params.kind)};let r=t,o=this.resolveNodeRequest(t);if(!o.ok)return o.result;let i=o.node,s=this.graph.getFileVersion(i.file);return t.documentVersion!==s?{ok:!1,errorCode:"stale-version",reason:`Document version ${t.documentVersion} is stale or otherwise does not match current version (current: ${s})`}:this.planRemoveNode(n,r,i,this.graph.getCapability(i.key))}case"insert-child":{if(t.params.kind!=="insert-child")return{ok:!1,errorCode:"unknown",reason:Wo(t.kind,t.params.kind)};let r=t;if(Rc(r.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page-block boundaries require the page-block resolver"};if(!_c(r.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};let o=Xb(r.params.position,this.graph);if(o.error)return{ok:!1,errorCode:o.error.errorCode,reason:o.error.reason};if(!o.parentNode)return{ok:!1,errorCode:"locator-miss",reason:`Insert target parent for request '${t.id}' not found in graph`};let i=this.graph.getFileVersion(o.parentNode.file);return t.documentVersion!==i?{ok:!1,errorCode:"stale-version",reason:`Document version ${t.documentVersion} is stale or otherwise does not match current version (current: ${i})`}:this.planInsertChild(n,r,o.parentNode,this.graph.getCapability(o.parentNode.key),o.anchorNode)}case"move-node":{if(t.params.kind!=="move-node")return{ok:!1,errorCode:"unknown",reason:Wo(t.kind,t.params.kind)};let r=t,o=this.resolveNodeRequest(t);if(!o.ok)return o.result;let i=o.node,s=this.graph.getFileVersion(i.file);return t.documentVersion!==s?{ok:!1,errorCode:"stale-version",reason:`Document version ${t.documentVersion} is stale or otherwise does not match current version (current: ${s})`}:this.planMoveNode(n,r,i,this.graph.getCapability(i.key))}case"set-class-name-source":{let r=this.resolveNodeRequest(t);if(!r.ok)return r.result;let o=this.graph.getFileVersion(r.node.file);return t.documentVersion!==o?{ok:!1,errorCode:"stale-version",reason:`Document version ${t.documentVersion} is stale or otherwise does not match current version (current: ${o})`}:this.planNodeAttributeOperation(n,t,r.node)}case"set-props":{let r=this.resolveNodeRequest(t);if(!r.ok)return r.result;let o=this.graph.getFileVersion(r.node.file);return t.documentVersion!==o?{ok:!1,errorCode:"stale-version",reason:`Document version ${t.documentVersion} is stale or otherwise does not match current version (current: ${o})`}:await this.planSetProps(n,t,r.node)}case"set-link-target":{if(t.params.kind!=="set-link-target")return{ok:!1,errorCode:"invalid-params",reason:Wo(t.kind,t.params.kind)};let r=this.resolveNodeRequest(t);if(!r.ok)return r.result;let o=this.graph.getFileVersion(r.node.file);return t.documentVersion!==o?{ok:!1,errorCode:"stale-version",reason:`Document version ${t.documentVersion} is stale or otherwise does not match current version (current: ${o})`}:this.planSetLinkTarget(n,t,r.node)}case"apply-style-draft":{let r=this.resolveNodeRequest(t);if(!r.ok)return r.result;let o=this.graph.getFileVersion(r.node.file);return t.documentVersion!==o?{ok:!1,errorCode:"stale-version",reason:`Document version ${t.documentVersion} is stale or otherwise does not match current version (current: ${o})`}:await this.planApplyStyleDraft(n,t,r.node)}default:return{ok:!1,errorCode:"unknown",reason:`Unknown operation kind: ${t.kind}`}}}resolveNodeRequest(t){let n=CO(t);if(!n)return{ok:!1,result:{ok:!1,errorCode:"invalid-target",reason:`Operation '${t.kind}' requires a node target`}};let r=this.graph.getNode(n);return r?{ok:!0,node:r}:{ok:!1,result:{ok:!1,errorCode:"locator-miss",reason:`Target key '${n}' not found in graph`}}}planNodeAttributeOperation(t,n,r){let o=r.file,i=this.graph.getCapability(r.key);return n.params.filePath!==o?{ok:!1,errorCode:"stale-version",reason:"The className source file changed before save."}:this.buildPlan(t,n,[{order:0,file:o,type:"set-class-name-source",request:{...n.params,key:r.key}}],i)}async planSetProps(t,n,r){let o=this.graph.getCapability(r.key),i=await this.buildTypedPropertySteps({node:r,scope:n.params.scope,changes:n.params.changes,selectionRef:n.selectionRef});return i.ok?this.buildPlan(t,n,i.steps,o):Hb(i)}async planSetLinkTarget(t,n,r){if(r.tag!=="a"&&!(r.importedFrom==="next/link"&&r.exportName==="default"))return{ok:!1,errorCode:"capability-denied",reason:"Only native anchors and source-verified next/link nodes can be changed"};if(r.structuralPath.includes("#repeat:")||r.isRepeatRegion||r.isRepeatItemRoot)return{ok:!1,errorCode:"capability-denied",reason:"Link target changes are not supported inside repeat templates"};if(n.selectionRef?.instanceIndex!==void 0||(n.selectionRef?.instanceCount??1)>1)return{ok:!1,errorCode:"capability-denied",reason:"Link target changes require a single non-repeated selection"};if(n.params.changes.length>0){let o=await this.buildTypedPropertySteps({node:r,scope:"selection",changes:n.params.changes,selectionRef:n.selectionRef});if(!o.ok)return Hb(o);if(o.steps.some(i=>i.type!=="set-property-changes"||i.file!==r.file))return{ok:!1,errorCode:"capability-denied",reason:"Link descriptions must have a direct, unique source in the selected file"}}return this.buildPlan(t,n,[{type:"set-link-target",order:0,file:r.file,locator:Ve(r),link:n.params.link,changes:n.params.changes}],this.graph.getCapability(r.key))}async planApplyStyleDraft(t,n,r){let o=r.file,i=this.graph.getCapability(r.key),s=[];if(n.params.className){if(n.params.className.filePath!==o)return{ok:!1,errorCode:"stale-version",reason:"The className source file changed before save."};s.push({order:s.length,file:o,type:"set-class-name-source",request:{kind:"set-class-name-source",...n.params.className,key:r.key}})}if(n.params.props){let a=await this.buildStyleDraftPropertySteps({initialOrder:s.length,node:r,props:n.params.props,selectionRef:n.selectionRef});if(!a.ok)return a;s.push(...a.steps)}return this.buildPlan(t,n,s,i)}async buildTypedPropertySteps(t){let n=this.graph.getPropertyState;return n?Ab({node:t.node,scope:t.scope,changes:t.changes,selectionRef:t.selectionRef,getPropertyState:n,getRepeatPropertyTarget:this.graph.getRepeatPropertyTarget,getFileContent:r=>this.graph.getFileContent(r),getFileVersion:r=>this.graph.getFileVersion(r),classNameSource:this.graph.getClassNameSource?.(t.node.key)??void 0}):{ok:!1,errorCode:"missing-property-state",reason:"Typed property planning requires authoritative property provenance"}}async buildStyleDraftPropertySteps(t){let{initialOrder:n,node:r,props:o,selectionRef:i}=t,s=[],a=[];for(let[c,l]of Object.entries(o)){if(l===void 0)continue;let u=await this.graph.getElementPropertyWriteTarget?.(r.key,c),d=r.attributes?.find(g=>g.name===c);if((await this.graph.getPropertyState?.(r.key,c,i))?.status==="blocked"||!u&&d?.source)return{ok:!1,errorCode:"capability-denied",reason:`apply-style-draft cannot overwrite a derived or unresolved property '${c}'`};if(!(typeof d?.resolvedValue=="string"&&d.resolvedValue===l||d?.source===null&&d.value===l)){if(u?.kind==="external-entry")return{ok:!1,errorCode:"capability-denied",reason:`apply-style-draft cannot overwrite readonly external property '${c}'`};if(u?.kind==="value-binding"&&u.locator){let g=u.locator;if(u.sourceKind==="repeat-template"&&typeof i?.instanceIndex=="number"){let p=Of(u,i.instanceIndex);if(!p)return{ok:!1,errorCode:"invalid-params",reason:"apply-style-draft could not resolve the selected repeat item"};g=p}s.push({order:n+s.length,file:u.file,type:"update-value",locator:g,value:l});continue}a.push({operation:"set",name:c,value:l})}}return a.length>0&&s.push({order:n+s.length,file:r.file,type:"set-property-changes",locator:Ve(r),scope:"selection",changes:a}),{ok:!0,steps:s}}buildTextRewriteSteps(t,n,r,o,i){if(o?.kind==="value-binding"&&o.locator){if(o.sourceKind==="repeat-template"&&typeof i?.instanceIndex=="number"){let a=Of(o,i.instanceIndex);if(!a)return{ok:!1,errorCode:"invalid-params",reason:"update-text could not resolve the selected repeat item"};let c=this.coerceTextValueForValueTarget(o.file,a,r);return c.ok?{ok:!0,steps:[{order:0,file:o.file,type:"update-array-item",locator:a,value:c.value}]}:c}let s=this.coerceTextValueForValueTarget(o.file,o.locator,r);return s.ok?{ok:!0,steps:[{order:0,file:o.file,type:"update-value",locator:o.locator,value:s.value}]}:s}return{ok:!0,steps:o?.kind==="external-entry"?[{order:0,file:`external:${o.sourceId}`,type:"invoke-external-adapter",sourceType:o.sourceType,sourceId:o.sourceId,adapterId:o.adapterId,capability:"write-text",value:r}]:[{order:0,file:t.file,type:"update-text",locator:Ve(t),segmentIndex:n,newText:r}]}}coerceTextValueForValueTarget(t,n,r,o="update-text"){let i=this.graph.getFileContent(t),s=yt(i);if(!s)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not inspect the value source`};let a=Ie(s,n);if(!a.ok)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not resolve the value source`};if(!NO(a.match.path))return{ok:!0,value:r};let c=PO(r);return c===null?{ok:!1,errorCode:"invalid-params",reason:`${o} value must be a valid number for numeric source`}:{ok:!0,value:c}}planUpdateArrayItem(t,n,r,o){if(!r.canUpdateText)return{ok:!1,errorCode:"capability-denied",reason:"Cannot update repeated text on this node"};if(o?.kind!=="value-binding"||o.sourceKind!=="repeat-template"||!o.locator)return{ok:!1,errorCode:"invalid-params",reason:"update-array-item requires a writable repeat-template source"};let{index:i,value:s}=n.params,a=o.collectionPathMap?.length??o.collectionIndexMap?.length;if(a!==void 0&&i>=a)return{ok:!1,errorCode:"invalid-params",reason:`update-array-item index ${i} is outside the repeated source`};let c=Of(o,i);if(!c)return{ok:!1,errorCode:"invalid-params",reason:"update-array-item could not resolve the selected repeat item"};let l=this.coerceTextValueForValueTarget(o.file,c,s,"update-array-item");return l.ok?this.isValueTargetUnchanged(o.file,c,l.value)?{ok:!1,errorCode:"invalid-params",reason:"update-array-item value is unchanged"}:this.buildPlan(t,n,[{order:0,file:o.file,type:"update-array-item",locator:c,value:l.value}],r):l}isValueTargetUnchanged(t,n,r){let o=yt(this.graph.getFileContent(t));if(!o)return!1;let i=Ie(o,n);if(!i.ok)return!1;let s=i.match.path;if(s.isStringLiteral())return typeof r=="string"&&s.node.value===r;if(s.isNumericLiteral())return typeof r=="number"&&Object.is(s.node.value,r);if(s.isBooleanLiteral())return typeof r=="boolean"&&s.node.value===r;if(s.isNullLiteral())return r===null;if(s.isUnaryExpression({operator:"-"})){let a=s.get("argument");return typeof r=="number"&&!Array.isArray(a)&&a.isNumericLiteral()&&Object.is(-a.node.value,r)}return!1}planUpdateText(t,n,r,o,i){let s=this.graph.getTextProvenance?.(r.key,n.params.segmentIndex);if(s&&(s.editMode==="readonly"||s.editMode==="unsupported"))return{ok:!1,errorCode:"unsupported-operation",reason:"Text has no identity-preserving write target"};if(!o.canUpdateText)return{ok:!1,errorCode:"capability-denied",reason:"Cannot update text on this node"};let a=this.buildTextRewriteSteps(r,n.params.segmentIndex,n.params.value,i,n.selectionRef);return a.ok?this.buildPlan(t,n,a.steps,o):a}async planRemoveNode(t,n,r,o){if(!o.canRemove)return{ok:!1,errorCode:"capability-denied",reason:"Cannot remove this node"};let i=await this.graph.getTextWriteTarget(r.key,0);if(i?.kind==="external-entry")return this.buildPlan(t,n,[{order:0,file:`external:${i.sourceId}`,type:"invoke-external-adapter",sourceType:i.sourceType,sourceId:i.sourceId,adapterId:i.adapterId,capability:"remove-node",value:{operation:"remove-node"}}],o);if(r.isRepeatItemRoot){let d=i;if(d?.kind==="value-binding"&&d.locator){let f=fs(d.locator);if(f)return this.buildPlan(t,n,[{order:0,file:d.file,type:"remove-bound-array-item",locator:f.locator,index:f.index}],o)}return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed node removal requires a writable array target"}}let s=ds(r,i,this.graph.getTextProvenance?.(r.key,0)??null);if(s)return{ok:!1,errorCode:"unsupported-operation",reason:s};let a=this.getRepeatBackedTemplateStructureReason(r);if(a)return{ok:!1,errorCode:"unsupported-operation",reason:a};let c=await this.getUpstreamBackedDescendantReason(r);if(c)return{ok:!1,errorCode:"unsupported-operation",reason:c};let l=[{order:0,file:r.file,type:"remove-node",locator:Ve(r),removeWhitespace:!0}],u=this.buildRemoveComponentImportStep(r);return u&&l.push({...u,order:l.length}),this.buildPlan(t,n,l,o)}buildRemoveComponentImportStep(t,n=this.graph.getFileContent(t.file)){if(!t.importedFrom||!t.exportName||!t.tag||vb(n,t)>1)return null;let r=Ff(t.file,t.importedFrom);return{order:0,file:t.file,type:"remove-import",moduleSpecifier:r,imports:t.exportName==="default"?[{kind:"default"}]:[{kind:"named",imported:t.exportName}]}}async planInsertChild(t,n,r,o,i){if(!_c(n.params.position))return Rc(n.params.position)?{ok:!1,errorCode:"unsupported-operation",reason:"Page-block boundaries require the page-block resolver"}:{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};if(n.params.node.kind==="component-call"&&!n.params.node.component)return{ok:!1,errorCode:"unsupported-operation",reason:"Materialized component insertion requires the materialization transaction planner"};if(!o.canInsertChild)return{ok:!1,errorCode:"capability-denied",reason:"Cannot insert child into this node"};let s=this.graph.getEditableTextSegmentIndex(r.key),a=s!==null?await this.graph.getTextWriteTarget(r.key,s):null,c=ds(r,a,s!==null?this.graph.getTextProvenance?.(r.key,s)??null:null);if(c)return{ok:!1,errorCode:"unsupported-operation",reason:c};let l=await this.getUpstreamBackedDescendantReason(r);if(l)return{ok:!1,errorCode:"unsupported-operation",reason:l};let u=await this.planExternalBackedInsertChild(t,n,r,o,i,a);if(u)return u;let d=await this.planRepeatBackedInsertChild(t,n,r,o);if(d)return d;let f=this.getRepeatBackedTemplateStructureReason(r);if(f)return{ok:!1,errorCode:"unsupported-operation",reason:f};let g=ob(this.graph.getFileContent(r.file),r);if(!g.allowed)return{ok:!1,errorCode:"unsupported-operation",reason:g.reason??"Cannot insert child into this node"};let p=Cc(r,n.params.node);if(p)return{ok:!1,errorCode:"unsupported-operation",reason:p};let m=[],y=0,x=n.params.node.kind==="component-call"?HO(n.params.node,this.graph.getFileContent(r.file)):void 0,S=x?.importStep;return S&&m.push({order:y++,file:r.file,type:"add-import",moduleSpecifier:S.moduleSpecifier,imports:S.imports}),m.push({order:y++,file:r.file,type:"insert-child",parentLocator:Ve(r),node:{jsx:WO(n.params.node,x?.localName)},placement:n.params.position.relation,anchorLocator:i?Ve(i):void 0}),this.buildPlan(t,n,m,o)}async planExternalBackedInsertChild(t,n,r,o,i,s){if(!_c(n.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};let a=s?.kind==="external-entry"?s:await this.findExternalInsertContext(r,i);if(!a)return null;let c=i?await this.graph.getTextWriteTarget(i.key,0):null;return this.buildPlan(t,n,[{order:0,file:`external:${a.sourceId}`,type:"invoke-external-adapter",sourceType:a.sourceType,sourceId:a.sourceId,adapterId:a.adapterId,capability:"insert-child",value:{operation:"insert-child",relation:n.params.position.relation,parentKey:r.key,anchorSourceId:c?.kind==="external-entry"?c.sourceId:null,node:GO(n.params.node)}}],o)}async findExternalInsertContext(t,n){if(n){let o=await this.graph.getTextWriteTarget(n.key,0);if(o?.kind==="external-entry")return o}if(!this.graph.getChildNodes)return null;let r=[...this.graph.getChildNodes(t.key)];for(;r.length>0;){let o=r.shift();if(!o)continue;let i=await this.graph.getTextWriteTarget(o.key,0);if(i?.kind==="external-entry")return i;let s=this.graph.getTextProvenance?.(o.key,0)?.finalSource?.externalSource;if(s)return{kind:"external-entry",file:`external:${s.sourceId}`,sourceType:s.sourceType,sourceId:s.sourceId,adapterId:s.adapterId,displayExpression:s.sourceId};r.push(...this.graph.getChildNodes(o.key))}return null}async planRepeatBackedInsertChild(t,n,r,o){if(!_c(n.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};if(n.params.position.relation!=="append"&&n.params.position.relation!=="prepend")return null;let i=n.params.node;if(i.kind!=="native-tag"||i.text===void 0||!this.graph.getChildNodes)return null;let s=this.graph.getChildNodes(r.key).find(d=>d.isRepeatItemRoot&&d.tag?.toLowerCase()===i.tag.toLowerCase());if(!s)return null;let a=await this.graph.getTextWriteTarget(s.key,0);if(!a||a.kind!=="value-binding"||!a.locator)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child requires a writable value target"};let c=fs(a.locator);if(!c)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child requires an array-backed target"};let l=qO(a.locator,i.text);if(l===void 0)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child could not infer an item shape from the template"};let u=n.params.position.relation==="prepend"?zb(0,a.collectionIndexMap):zb(a.collectionIndexMap?.length??c.index+1,a.collectionIndexMap);return this.buildPlan(t,n,[{order:0,file:a.file,type:"insert-bound-array-item",locator:c.locator,index:u,value:l}],o)}async getUpstreamBackedDescendantReason(t){if(!this.graph.getChildNodes)return null;let n=[...this.graph.getChildNodes(t.key)];for(;n.length>0;){let r=n.shift();if(!r)continue;let o=this.graph.getEditableTextSegmentIndex(r.key),i=o!==null?await this.graph.getTextWriteTarget(r.key,o):null,s=ds(r,i,o!==null?this.graph.getTextProvenance?.(r.key,o)??null:null);if(s)return s;n.push(...this.graph.getChildNodes(r.key))}return null}getRepeatBackedTemplateStructureReason(t){if(t.isRepeatItemRoot)return zo(this.graph.getFileContent(t.file),t)?"Cannot edit repeat-backed item template structure with a generic node operation":"Cannot edit repeat-backed child node structure with a generic node operation";if(t.structuralPath.includes("#repeat:")||Fb(this.graph.getFileContent(t.file),t))return"Cannot edit repeat-backed child node structure with a generic node operation";let n=t.parentKey;for(;n;){let r=this.graph.getNode(n);if(!r)return null;if(r.isRepeatItemRoot||r.isRepeatRegion)return"Cannot edit repeat-backed child node structure with a generic node operation";n=r.parentKey}return null}planRepeatTemplateInternalMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&zo(this.graph.getFileContent(r.file),r)||r.file!==o.file)return null;let c=this.graph.getFileContent(r.file),l=yt(c);if(!l)return null;let u=dn(l,r),d=dn(l,o);if(!u||!d)return null;let f=Mn(c,u),g=Mn(c,d);if(!ls(f,g))return null;if(a&&(s==="before"||s==="after")){let m=dn(l,a),y=m?Mn(c,m):null;if(!ls(f,y))return null}if(Sc(u,d))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child across statement-level conditional branches"};let p=kf(c,r,o);return p.ok?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:Ve(r),targetParentLocator:Ve(o),placement:s,anchorLocator:a?Ve(a):void 0,selectionContext:uo(o)}],i):{ok:!1,errorCode:"unsupported-operation",reason:p.reason??`Cannot move node because it depends on bindings outside the target scope: ${p.bindingNames.join(", ")}`}}planRepeatTemplateHoistMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&zo(this.graph.getFileContent(r.file),r)||r.file!==o.file)return null;let c=this.graph.getFileContent(r.file),l=yt(c);if(!l)return null;let u=dn(l,r),d=dn(l,o);if(!u||!d)return null;let f=Mn(c,u);if(!f)return null;let g=Mn(c,d);if(ls(f,g))return null;if(g&&!wb(g,f))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child into a different repeat template"};if(a&&(s==="before"||s==="after")){let b=If(c,l,a);if(g&&!ls(g,b)||!g&&b)return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child relative to a repeat-template anchor outside the target scope"}}if(r.tag&&r.tag.toLowerCase()===r.tag){let b=Cc(o,{kind:"native-tag",tag:r.tag});if(b)return{ok:!1,errorCode:"unsupported-operation",reason:b}}let p=Af(this.graph,r);if(!p)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(Sc(u,d))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let m=Ub(c,u,d,p);for(let b of m.conditionPaths){let E=Rf(b,d,f);if(!E.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its condition depends on bindings outside the target scope: ${E.bindingNames.join(", ")}`}}let y=Cf(u,d,f,{preserveConditionalBoundary:m.conditionPaths.length>0});if(!y.ok)return{ok:!1,errorCode:"unsupported-operation",reason:y.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${y.bindingNames.join(", ")}`};let x=Db(f,d);if(!x.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its callback parameters depend on bindings outside the target scope: ${x.bindingNames.join(", ")}`};let S=f;if(r.component!==o.component){let b=AO({source:c,ast:l,sourceContext:f,sourceNode:r,targetParent:o,targetParentPath:d});if(!b.ok)return{ok:!1,errorCode:"unsupported-operation",reason:b.reason};S=b.context}else{let b=Nf(f.collectionPath,d);if(!b.ok)return{ok:!1,errorCode:"unsupported-operation",reason:b.reason??`Cannot move repeat-backed child because the repeat collection is not visible at the target: ${b.bindingNames.join(", ")}`}}return this.buildPlan(t,n,[{order:0,file:r.file,type:"move-repeat-template-child",locator:Ve(r),targetParentLocator:Ve(o),placement:s,anchorLocator:a?Ve(a):void 0,repeatExpression:Pf(S,m.sourceJsx),selectionContext:uo(o)}],i)}planCrossFileRepeatTemplateHoistMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&zo(this.graph.getFileContent(r.file),r)||r.file===o.file)return null;let c=this.graph.getFileContent(r.file),l=this.graph.getFileContent(o.file),u=yt(c),d=yt(l);if(!u||!d)return null;let f=Cb({knownSourceFiles:this.graph.getKnownSourceFiles?.(),routeEntryFiles:this.graph.getRouteEntryFiles?.(),sourceAst:u,sourceFile:r.file,targetFile:o.file,sourceComponent:r.component,targetComponent:o.component});if(!f.ok)return{ok:!1,errorCode:"unsupported-operation",reason:f.reason};let g=dn(u,r),p=dn(d,o);if(!g||!p)return null;let m=_f(f.callSitePath,p);if(!m.ok)return{ok:!1,errorCode:"unsupported-operation",reason:m.reason};let y=Mn(c,g);if(!y)return null;if(Mn(l,p))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child into a different repeat template"};if(a&&(s==="before"||s==="after")&&If(l,d,a))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child relative to a repeat-template anchor outside the target scope"};if(r.tag&&r.tag.toLowerCase()===r.tag){let A=Cc(o,{kind:"native-tag",tag:r.tag});if(A)return{ok:!1,errorCode:"unsupported-operation",reason:A}}let S=Af(this.graph,r);if(!S)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(Sc(g,p))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let b=Ub(c,g,p,S);for(let A of b.conditionPaths){let w=Rf(A,p,y);if(!w.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its condition depends on bindings outside the target scope: ${w.bindingNames.join(", ")}`}}let E=Cf(g,p,y,{preserveConditionalBoundary:b.conditionPaths.length>0});if(!E.ok)return{ok:!1,errorCode:"unsupported-operation",reason:E.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${E.bindingNames.join(", ")}`};let k=BO({sourceFile:r.file,targetFile:o.file,sourceContext:y,targetParentPath:p});if(!k.ok)return{ok:!1,errorCode:"unsupported-operation",reason:k.reason};let I=Bb(y);if(!I.ok)return{ok:!1,errorCode:"unsupported-operation",reason:I.reason};let v=jb(y,I.callbackParams),N=[{order:0,file:r.file,type:"remove-node",locator:Ve(r),removeWhitespace:!0}];for(let A of k.imports)N.push({order:N.length,file:o.file,type:"add-import",moduleSpecifier:A.moduleSpecifier,imports:A.imports});return N.push({order:N.length,file:o.file,type:"insert-jsx-expression-child",parentLocator:Ve(o),expression:Pf(v,b.sourceJsx),placement:s,anchorLocator:a?Ve(a):void 0,selectionContext:uo(o)}),this.buildPlan(t,n,N,i)}async planMoveNode(t,n,r,o){if(!o.canMove)return{ok:!1,errorCode:"capability-denied",reason:"Cannot move this node"};if(Rc(n.params.target))return{ok:!1,errorCode:"unsupported-operation",reason:"Page-block boundaries require the page-block resolver"};if("kind"in n.params.target&&n.params.target.kind==="source-sibling"){let b=n.params.target,E=this.graph.getNode(b.anchorKey);if(!E||r.file!==E.file||r.component!==E.component)return{ok:!1,errorCode:"locator-miss",reason:"Source sibling move requires a sibling in the same component file"};let k=this.graph.getFileVersion(r.file);if(n.documentVersion!==k)return{ok:!1,errorCode:"stale-version",reason:`Document version ${n.documentVersion} is stale or otherwise does not match source sibling file version (current: ${k})`};let I=this.graph.getFileContent(r.file),v=yt(I),N=v?dn(v,r):null,A=v?dn(v,E):null,w=N?.parentPath,F=A?.parentPath;if(!N||!A||!w||!F||w.node!==F.node||!w.isJSXFragment()&&!(w.isJSXElement()&&Ye(w)))return{ok:!1,errorCode:"unsupported-operation",reason:"Source sibling move requires two direct children of the same transparent Fragment"};let B=w.node.loc;return B?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:Ve(r),targetParentLocator:{kind:"jsx-node",strategy:"source-range",sourceRange:{startLine:B.start.line,startColumn:B.start.column,endLine:B.end.line,endColumn:B.end.column}},placement:b.relation,anchorLocator:Ve(E),selectionContext:uo(r)}],o):{ok:!1,errorCode:"locator-miss",reason:"Source Fragment has no stable source range"}}let i=Xb(n.params.target,this.graph);if(i.error)return{ok:!1,errorCode:i.error.errorCode,reason:i.error.reason};let s=i.parentNode;if(!s)return{ok:!1,errorCode:"locator-miss",reason:`Target parent for request '${n.id}' not found in graph`};let a=this.graph.getFileVersion(s.file);if(n.documentVersion!==a)return{ok:!1,errorCode:"stale-version",reason:`Document version ${n.documentVersion} is stale or otherwise does not match target parent version (current: ${a})`};if(ZO(s.key,r.key,this.graph))return{ok:!1,errorCode:"capability-denied",reason:"Cannot move node into its own subtree"};if(r.isRepeatRegion&&s.isBoundary)return{ok:!1,errorCode:"capability-denied",reason:"Cannot move repeat-region node across boundary"};if(!this.graph.getCapability(s.key).canInsertChild)return{ok:!1,errorCode:"capability-denied",reason:"Cannot move node into this parent"};let c=await this.graph.getTextWriteTarget(r.key,0);if(c?.kind==="external-entry"){let b=n.params.target.relation,E=i.anchorNode&&(b==="before"||b==="after")?await this.graph.getTextWriteTarget(i.anchorNode.key,0):null;return this.buildPlan(t,n,[{order:0,file:`external:${c.sourceId}`,type:"invoke-external-adapter",sourceType:c.sourceType,sourceId:c.sourceId,adapterId:c.adapterId,capability:"move-node",value:{operation:"move-node",relation:b,anchorSourceId:E?.kind==="external-entry"?E.sourceId:null,parentKey:"parentKey"in n.params.target?n.params.target.parentKey:null}}],o)}let l=r.file!==s.file,u=n.params.target.relation,d=i.anchorNode,f=this.graph.getTextProvenance?.(r.key,0)??null,g=ds(r,c,f);if(g&&!Tf(g)&&!$b(r,s,c,f))return{ok:!1,errorCode:"unsupported-operation",reason:g};if(r.isRepeatItemRoot&&d?.isRepeatItemRoot&&r.repeatOwnerKey&&r.repeatOwnerKey===d.repeatOwnerKey&&(u==="before"||u==="after")){let b=c,E=await this.graph.getTextWriteTarget(d.key,0);if(b?.kind==="value-binding"&&E?.kind==="value-binding"&&b.locator&&E.locator){let k=fs(b.locator),I=fs(E.locator);if(k&&I&&b.file===E.file&&tF(k.locator,I.locator)){let v=k.index,N=I.index,A=u==="before"?N-(v<N?1:0):N+(v<N?0:1);return this.buildPlan(t,n,[{order:0,file:b.file,type:"move-array-item",locator:k.locator,fromIndex:v,toIndex:A}],o)}}}if(r.isRepeatItemRoot&&zo(this.graph.getFileContent(r.file),r))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed item outside its collection"};let p=this.getRepeatBackedTemplateStructureReason(r),m=Tf(g)?g:p;if(m&&Tf(m)){let b=this.planRepeatTemplateInternalMove(t,n,r,s,o,u,d);if(b)return b;let E=this.planRepeatTemplateHoistMove(t,n,r,s,o,u,d);if(E)return E;let k=this.planCrossFileRepeatTemplateHoistMove(t,n,r,s,o,u,d);return k||{ok:!1,errorCode:"unsupported-operation",reason:m}}if(p)return{ok:!1,errorCode:"unsupported-operation",reason:p};let y=await this.getUpstreamBackedDescendantReason(r);if(y)return{ok:!1,errorCode:"unsupported-operation",reason:y};if(r.tag&&r.tag.toLowerCase()===r.tag){let b=Cc(s,{kind:"native-tag",tag:r.tag});if(b)return{ok:!1,errorCode:"unsupported-operation",reason:b}}if(l)return this.planCrossFileMove(t,n,r,s,o,u,d);let x=kf(this.graph.getFileContent(r.file),r,s);if(!x.ok)return{ok:!1,errorCode:"unsupported-operation",reason:x.reason??`Cannot move node because it depends on bindings outside the target scope: ${x.bindingNames.join(", ")}`};let S=[{order:0,file:r.file,type:"move-node",locator:Ve(r),targetParentLocator:Ve(s),placement:u,anchorLocator:d?Ve(d):void 0,selectionContext:uo(s)}];return this.buildPlan(t,n,S,o)}planCrossFileMove(t,n,r,o,i,s,a){let c=[],l=0,u=this.graph.getFileContent(r.file),d=Af(this.graph,r)??`<${r.component} />`,f=ib(u,r);if(!f.allowed)return{ok:!1,errorCode:"unsupported-operation",reason:f.reason??"Cannot move subtree across files"};if(c.push({order:l++,file:r.file,type:"remove-node",locator:Ve(r),removeWhitespace:!0}),r.importedFrom&&r.exportName){let p=r.tag??r.component,y={moduleSpecifier:Ff(o.file,r.importedFrom),imports:r.exportName==="default"?[{kind:"default",local:p}]:[{kind:"named",imported:r.exportName,local:p===r.exportName?void 0:p}]};c.push({order:l++,file:o.file,type:"add-import",moduleSpecifier:y.moduleSpecifier,imports:y.imports}),c.push({order:l++,file:o.file,type:"insert-child",parentLocator:Ve(o),node:{jsx:d},placement:s,anchorLocator:a?Ve(a):void 0,selectionContext:uo(o)})}else c.push({order:l++,file:o.file,type:"insert-child",parentLocator:Ve(o),node:{jsx:d},placement:s,anchorLocator:a?Ve(a):void 0,selectionContext:uo(o)});let g=this.buildRemoveComponentImportStep(r,u);return g&&c.push({...g,order:l++}),this.buildPlan(t,n,c,i)}buildPlan(t,n,r,o){let s=[...new Set(r.map(a=>a.file))].map(a=>({file:a,content:this.graph.getFileContent(a),version:this.graph.getFileVersion(a),exists:!0,sha256:ke(this.graph.getFileContent(a))}));return{ok:!0,plan:{operationId:t,kind:n.kind,target:n.target,documentVersion:n.documentVersion,steps:r,preSnapshots:s,validatedCapability:o}}}};function Hb(e){return{ok:!1,errorCode:e.errorCode==="readonly-property"?"capability-denied":e.errorCode==="missing-property-state"||e.errorCode==="repeat-target-failed"||e.errorCode==="unsupported-binding"?"unsupported-operation":"invalid-params",reason:e.reason}}import Jf from"@babel/generator";import{parse as xF,parseExpression as bF}from"@babel/parser";import*as C from"@babel/types";import*as Dn from"@babel/types";import Bf from"@babel/generator";import*as Ke from"@babel/types";var iF=typeof Bf=="function"?Bf:Bf.default,sF=/(?:token|secret|key|password|authorization|cookie|signature|credential)/i,aF=/^((?:https?:)?\/\/)[^/@\s]+@/i,cF=/(\/(?:token|secret|api[-_]?key|password|credential|signature)\/)[^/?#]+/gi;function qb(e,t){let n=Wt(e.callee);if(!n)return null;if(n==="fetch")return jf(e.arguments[0],"GET",t,["fetch call"]);if(n.startsWith("axios.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(Zb(r))return jf(e.arguments[0],r,t,["axios client contract"])}if(n.startsWith("ky.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(Zb(r))return jf(e.arguments[0],r,t,["ky client contract"])}return null}function jf(e,t,n,r){if(!e||Ke.isSpreadElement(e)||Ke.isJSXNamespacedName(e))return fF(t,n,r,"missing url argument");let o=ps(e);return{sourceKind:dF(o),...o?{endpointPattern:o}:{},method:t,confidence:o?"exact":"partial",evidence:[{file:n.file,reason:[...r,o?"endpoint pattern resolved":"endpoint pattern unresolved"].join("; ")}]}}function ps(e){if(Ke.isStringLiteral(e))return fo(e.value);if(Ke.isTemplateLiteral(e))return fo(lF(e));if(Ke.isBinaryExpression(e)&&e.operator==="+"){let t=ps(e.left),n=ps(e.right);return!t&&!n?void 0:fo(`${t??$f(e.left)}${n??$f(e.right)}`)}if(Ke.isMemberExpression(e)){let t=Qb(e);if(t)return`env:${t}`}if(!(Ke.isCallExpression(e)&&Wt(e.callee)==="new URL")){if(Ke.isNewExpression(e)&&Ke.isIdentifier(e.callee,{name:"URL"})){let[t,n]=e.arguments,r=t&&!Ke.isSpreadElement(t)?ps(t):void 0,o=n&&!Ke.isSpreadElement(n)?ps(n):void 0;return o&&r?fo(`${o} + ${r}`):r??o}if(Ke.isIdentifier(e))return`:${e.name}`}}function lF(e){let t="";for(let n=0;n<e.quasis.length;n+=1){t+=e.quasis[n]?.value.cooked??e.quasis[n]?.value.raw??"";let r=e.expressions[n];r&&(t+=$f(r))}return t}function $f(e){if(Ke.isIdentifier(e))return`:${e.name}`;if(Ke.isMemberExpression(e)){let t=Qb(e);if(t)return`env:${t}`}return`:${uF(e)}`}function uF(e){return iF(e,{comments:!1}).code.replace(/[^a-zA-Z0-9_$]+/g,"_").replace(/^_+|_+$/g,"")||"param"}function fo(e){let[t]=e.split("#"),[n,r]=t.split("?"),o=n.replace(aF,"$1<redacted>@").replace(cF,"$1<redacted>");if(!r)return o;let i=r.split("&").map(s=>{let[a]=s.split("=");return a?sF.test(a)?`${a}=<redacted>`:`${a}=:${a}`:""}).filter(Boolean).join("&");return i?`${o}?${i}`:o}function dF(e){return e?e.startsWith("/api/")?"site-api-route":/^(?:https?:)?\/\//.test(e)||e.startsWith("env:")?"external-api":e.startsWith("/")?"site-api-route":"unknown-api":"unknown-api"}function fF(e,t,n,r){return{sourceKind:"unknown-api",method:e,confidence:"partial",evidence:[{file:t.file,reason:[...n,r].join("; ")}]}}function Zb(e){return["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(e)}function Qb(e){return!Ke.isMemberExpression(e.object)||!Ke.isIdentifier(e.object.object,{name:"process"})||!pF(e.object.property,"env")?null:Ke.isIdentifier(e.property)?e.property.name:Ke.isStringLiteral(e.property)?e.property.value:null}function pF(e,t){return Ke.isIdentifier(e)&&e.name===t}function Wt(e){if(Ke.isIdentifier(e))return e.name;if(Ke.isMemberExpression(e)){let t=Wt(e.object),n=Ke.isIdentifier(e.property)?e.property.name:Ke.isStringLiteral(e.property)?e.property.value:null;if(t&&n)return`${t}.${n}`}return null}var mF=new Set(["list","listStrict","get","getStrict","getByUrl","getByUrlStrict","schema","categories"]),gF=new Set(["getConfig","submit"]);function Ac(e,t){let n=eE(Wt(e.callee),t);if(!n)return null;let r="cms.collections.";if(n.startsWith(r)){let i=n.slice(r.length);if(!mF.has(i))return null;let s=Vf(e,0),a=i==="getByUrl"||i==="getByUrlStrict",c=a?void 0:s,l=a?s??"/:record-url":c?`/collections/${c}`:"/collections/:collection";return{sourceKind:"vcp-cms-collection",sourceType:"cms-field",operation:i,...c?{collection:c}:{},endpointPattern:l,confidence:s?"exact":"partial",evidence:[{file:t.file,symbol:n,reason:"VCP CMS collection facade"}]}}let o="cms.forms.";if(n.startsWith(o)){let i=n.slice(o.length);if(!gF.has(i))return null;let s=Vf(e,0);return{sourceKind:"vcp-cms-form",sourceType:"cms-field",operation:i,...s?{collection:s}:{},endpointPattern:s?`/forms/${s}`:"/forms/:form",confidence:s?"exact":"partial",evidence:[{file:t.file,symbol:n,reason:"VCP CMS form facade"}]}}if(n==="cmsFetch"||n==="cmsFetchResult"||n==="cmsFetchEnvelope"){let i=Vf(e,0)??hF(e,0,"path")??"/cms/:path",s=yF(i);return{sourceKind:"vcp-cms-collection",sourceType:"cms-field",operation:n,...s?{collection:s}:{},endpointPattern:i,confidence:i==="/cms/:path"?"partial":"safe-derived",evidence:[{file:t.file,symbol:n,reason:"VCP CMS fetch helper"}]}}return null}function eE(e,t){if(!e)return null;let n=e.indexOf("."),r=n<0?e:e.slice(0,n),o=n<0?"":e.slice(n),i=t.imports?.get(r);return i?i.importedName==="cms"&&/^(?:src\/)?lib\/cms(?:\/index)?\.[cm]?[jt]s$/.test(i.source)?`cms${o}`:i.importedName==="collections"&&/^(?:src\/)?lib\/cms\/collections\.[cm]?[jt]s$/.test(i.source)?`cms.collections${o}`:!o&&["cmsFetch","cmsFetchResult","cmsFetchEnvelope"].includes(i.importedName)&&/^(?:src\/)?lib\/cms\/client\.[cm]?[jt]s$/.test(i.source)?i.importedName:null:null}function tE(e,t){let n=Wt(e);return n==="cms.settings"?{sourceKind:"vcp-cms-settings",sourceType:"cms-field",operation:"settings",endpointPattern:"/settings",confidence:"exact",evidence:[{file:t.file,symbol:n,reason:"VCP CMS settings facade"}]}:n==="cms.navigation"?{sourceKind:"vcp-cms-navigation",sourceType:"cms-field",operation:"navigation",endpointPattern:"/navigation",confidence:"exact",evidence:[{file:t.file,symbol:n,reason:"VCP CMS navigation facade"}]}:null}function Tc(e,t){let n=Wt(e.callee),r=t?eE(n,t):n;return typeof r=="string"&&r.startsWith("cms.field.")}function Vf(e,t){let n=e.arguments[t];return Dn.isStringLiteral(n)?n.value:null}function hF(e,t,n){let r=e.arguments[t];if(!Dn.isObjectExpression(r))return null;for(let o of r.properties)if(Dn.isObjectProperty(o)&&!o.computed&&(Dn.isIdentifier(o.key)&&o.key.name===n||Dn.isStringLiteral(o.key)&&o.key.value===n)&&Dn.isStringLiteral(o.value))return o.value.value;return null}function yF(e){let t=/^\/collections\/([^/]+)(?:\/|$)/.exec(e)?.[1];return t&&/^[a-z0-9][a-z0-9_-]*$/i.test(t)?t:null}import*as dt from"@babel/types";var Uf=new WeakMap;function Nr(e,t){let n=Uf.get(e)?.get(t);if(n!==void 0)return n;let r=new Set([t]),o=l=>{let u=l;for(;dt.isMemberExpression(u)||dt.isOptionalMemberExpression(u);)u=u.object;return dt.isIdentifier(u)?u.name:null},i=!0;for(;i;)i=!1,dt.traverseFast(e,l=>{if(!dt.isVariableDeclarator(l)||!l.init)return;let u=o(l.init);if(!(!u||!r.has(u)))for(let d of Object.keys(dt.getBindingIdentifiers(l.id)))r.has(d)||(r.add(d),i=!0)});let s=l=>{let u=o(l);return u?r.has(u):Object.keys(dt.getBindingIdentifiers(l)).some(d=>r.has(d))},a=!1;dt.traverseFast(e,l=>{(dt.isAssignmentExpression(l)&&s(l.left)||dt.isUpdateExpression(l)&&s(l.argument)||dt.isUnaryExpression(l,{operator:"delete"})&&s(l.argument))&&(a=!0)});let c=Uf.get(e)??new Map;return c.set(t,a),Uf.set(e,c),a}function nE(e=4096){if(!Number.isSafeInteger(e)||e<1)throw new RangeError("Re-export relation capacity must be positive.");let t=new Map,n=new Set,r=o=>{let i=t.get(o.fromFile),s=i?.get(o.exportName),a=s?.get(o.targetFile);a?.get(o.maxImportDepth)===o&&(a.delete(o.maxImportDepth),a.size===0&&s.delete(o.targetFile),s.size===0&&i.delete(o.exportName),i.size===0&&t.delete(o.fromFile),n.delete(o))};return{resolve(o,i){let{fromFile:s,exportName:a,targetFile:c,maxImportDepth:l}=o,u=t.get(s)?.get(a)?.get(c)?.get(l);if(u)return u.pending;let d=i();n.size>=e&&r(n.values().next().value);let f={fromFile:s,exportName:a,targetFile:c,maxImportDepth:l,pending:d},g=t.get(s)??new Map,p=g.get(a)??new Map,m=p.get(c)??new Map;return m.set(l,f),p.set(c,m),g.set(a,p),t.set(s,g),n.add(f),d.catch(()=>{r(f)}),d}}}import*as Nt from"@babel/types";import{posix as Kf}from"node:path";function Go(e,t,n=new Set){if(n.has(e))return;let r=new Set(n).add(e);if(Nt.isBooleanLiteral(e))return e.value;if(Nt.isUnaryExpression(e,{operator:"!"})){let l=Go(e.argument,t,r);return l===void 0?void 0:!l}if(Nt.isLogicalExpression(e)){let l=Go(e.left,t,r),u=Go(e.right,t,r);if(e.operator==="&&")return l===!1||u===!1?!1:l===!0?u:void 0;if(e.operator==="||")return l===!0||u===!0?!0:l===!1?u:void 0}if(!Nt.isCallExpression(e)||!Nt.isIdentifier(e.callee))return;let o=t.imports.get(e.callee.name),i=o?.source.startsWith(".")&&t.file?Kf.normalize(Kf.join(Kf.dirname(t.file),o.source)):o?.source;if(o?.importedName==="isProductionBuildPhase"&&/(?:^|\/)lib\/cms\/build-sample(?:\.[jt]s)?$/.test(i??""))return!1;let s=t.functions.get(e.callee.name);if(!s||n.has(s))return;let a=Nt.isExpression(s.body)?s.body:s.body.body.length===1&&Nt.isReturnStatement(s.body.body[0])?s.body.body[0].argument:null;if(!a||!Nt.isExpression(a))return;let c=s.params.flatMap(l=>Nt.isIdentifier(l)?[l.name]:[]);return Go(a,{file:t.file,imports:new Map([...t.imports].filter(([l])=>!c.includes(l))),functions:new Map([...t.functions].filter(([l])=>!c.includes(l)))},r.add(s))}var CH=typeof Jf=="function"?Jf:Jf.default,fE=new WeakMap;function pE(e){let t=new Map;return fE.set(t,new Map([...e].map(n=>[n.file,n]))),t}var EF={maxFunctionDepth:8,maxImportDepth:6},SF=new Set(["src","href","alt","poster","content","title","aria-label"]),rE=new WeakMap;function IF(e,t,n){let r=rE.get(t.fileCache);r||(r=new WeakMap,rE.set(t.fileCache,r));let o=r.get(e);if(!o){o={imported:[],local:new Map};let u=0;for(let d of e.elements.values()){let f={element:d,order:u++};d.importedFrom&&d.exportName&&o.imported.push(f);let g=o.local.get(d.sourceFile);g||(g=new Map,o.local.set(d.sourceFile,g));let p=g.get(d.tag)??[];p.push(f),g.set(d.tag,p)}r.set(e,o)}let i=o.local.get(t.file)?.get(n)??[],s=o.imported,a=[],c=0,l=0;for(;c<s.length||l<i.length;){let u=s[c],d=i[l];u&&(!d||u.order<d.order)?(a.push(u.element),c++):d&&(!u||d.order<u.order)?(a.push(d.element),l++):(a.push(u.element),c++,l++)}return a}async function mE(e){if(!e.element.textSegments.some(s=>s.source||s.value.includes("("))&&!(e.element.attributes??[]).some(s=>(s.source||s.syntaxKind==="expression"&&s.resolution?.status!=="resolved")&&iE(s,e.element))&&!e.graph.regions.some(s=>s.ownerKey===e.element.identity.key&&(s.kind==="repeat-region"||s.kind==="conditional-region")))return{hasDynamicData:!1,bindings:[]};let t=e.fileCache??new Map,n=Yf(e.file,e.source,t),r={file:e.file,analysis:n,readFile:e.readFile,exists:e.exists,fileCache:t,options:{...EF,...e.options},variableCache:new Map,functionDepth:0,importDepth:0,paramSources:new Map,paramArguments:new Map,resolvingVariables:new Set,resolvingComponentProps:new Set,scopeVariables:PE(n,e.element.componentName),scopeFunction:Zf(n,e.element.componentName)};await gE(e.element.componentName,e.graph,r);let o=[];o.push(...await CF(e.element,e.graph,r),...await RF(e.element,e.graph,r));for(let s of e.element.textSegments){let a=await NF(s,e.element,e.graph,r);a&&o.push(jc(a,"text","children"))}for(let s of e.element.attributes??[]){let a=iE(s,e.element);if(!a)continue;let c=await xE(s.source,e.element,e.graph,r);if(!c&&s.syntaxKind==="expression"&&!(s.source&&mo(s.source.base,e.element,e.graph))){let u=n.jsxElementsByRange.get(Vc(e.element.sourceRange))?.openingElement.attributes.find(d=>C.isJSXAttribute(d)&&C.isJSXIdentifier(d.name,{name:s.name}));C.isJSXExpressionContainer(u?.value)&&C.isExpression(u.value.expression)&&!EE(u.value.expression,e.element,e.graph)&&(c=await Ze(u.value.expression,r))}c&&o.push(jc(c,a,s.name))}let i=$F(o).sort(RE);return{hasDynamicData:i.length>0,bindings:i}}async function gE(e,t,n){if(n.importDepth>=n.options.maxImportDepth)return;let r=n.analysis.functions.get(e)??n.analysis.functions.get("default"),o=r?.params[0];if(!r||!o)return;let i=n.analysis.functions.get("default")===r?"default":e,s=[];for(let l of IF(t,n,e)){if(l.sourceFile===n.file&&l.tag===e){s.push(l);continue}!l.importedFrom||!l.exportName||l.importedFrom===n.file&&l.exportName!==i||(l.importedFrom===n.file||await vF(l.importedFrom,l.exportName,n.file,n))&&s.push(l)}if(s.length===0)return;let a=new Map;for(let l of s){let u=`${n.file}#${e}<-${l.identity.key}`;if(!n.resolvingComponentProps.has(u)){n.resolvingComponentProps.add(u);try{let d=await yE(l.sourceFile,n);if(!d)continue;let f=wr(d,n,{importDepth:n.importDepth+1});f.paramSources.clear(),f.scopeVariables=PE(d,l.componentName),f.scopeFunction=Zf(d,l.componentName),f.lexicalContext=void 0,await gE(l.componentName,t,f);let g=await kF(l,t,f);for(let[p,m]of g){if(!m)continue;let y=a.get(p)??[];y.push(m),a.set(p,y)}}finally{n.resolvingComponentProps.delete(u)}}}let c=new Map;for(let[l,u]of a){let d=Gf(u);d.length===1&&c.set(l,d[0])}_F(o,c,n)}var oE=new WeakMap;function vF(e,t,n,r){let o=oE.get(r.fileCache);return o||(o=nE(),oE.set(r.fileCache,o)),o.resolve({fromFile:e,exportName:t,targetFile:n,maxImportDepth:r.options.maxImportDepth},()=>hE(e,t,n,r))}async function hE(e,t,n,r,o=new Set){if(e===n)return!0;if(o.size>=r.options.maxImportDepth||o.has(`${e}#${t}`))return!1;o.add(`${e}#${t}`);let s=(await yE(e,r))?.imports.get(t);if(!s||!nt(s.source))return!1;let a=await Qf(e,s.source,r.exists);return a?a===n?!0:hE(a,s.importedName,n,r,o):!1}async function kF(e,t,n){let r=new Map,o=n.analysis.jsxElementsByRange.get(Vc(e.sourceRange));if(o)for(let s of o.openingElement.attributes)!C.isJSXAttribute(s)||!C.isJSXIdentifier(s.name)||!C.isJSXExpressionContainer(s.value)||!C.isExpression(s.value.expression)||r.set(s.name.name,s.value.expression);let i=new Map;for(let[s,a]of r){let c=e.attributes?.find(d=>d.name===s)?.source??null,u=(c?mo(c.base,e,t):null)?await Uc(c,e,t,n):EE(a,e,t)?null:await Ze(a,n);u&&i.set(s,u)}return i}function Vc(e){return`${e.startLine}:${e.startColumn}:${e.endLine}:${e.endColumn}`}async function yE(e,t){let n=t.fileCache.get(e);if(n)return n;if(!await t.exists(e))return null;let r=await t.readFile(e);return Yf(e,r,t.fileCache)}function _F(e,t,n){if(C.isIdentifier(e)){t.size>0&&n.paramSources.set(e.name,Bc(Object.fromEntries(t),n.file));return}if(C.isObjectPattern(e))for(let r of e.properties){if(!C.isObjectProperty(r)||r.computed||!C.isIdentifier(r.key))continue;let o=t.get(r.key.name);if(!o)continue;let i=C.isAssignmentPattern(r.value)?r.value.left:r.value;C.isIdentifier(i)&&n.paramSources.set(i.name,St(o))}}function iE(e,t){return e.name==="dangerouslySetInnerHTML"?"richtext":SF.has(e.name)?"attribute":t.importedFrom||/^[A-Z]/.test(t.tag)?"component-prop":null}async function CF(e,t,n){let r=[];for(let o of t.regions){if(o.kind!=="repeat-region"||o.ownerKey!==e.identity.key)continue;let i=o.sourceCandidates?.find(a=>a.kind==="repeat-template");if(!i)continue;let s=await Kc(i.collectionSource,n);s&&r.push(jc(Pr(s),"repeat-region",i.collectionExpression))}return r}async function RF(e,t,n){let r=[];for(let o of t.regions){if(o.kind!=="conditional-region"||o.ownerKey!==e.identity.key)continue;let i=o.sourceCandidates?.find(a=>a.kind==="conditional-branch");if(!i)continue;let s=await Kc(i.conditionSource,n);s&&r.push(jc(Pr(s),"conditional-region",i.conditionExpression))}return r}async function NF(e,t,n,r){if(!e.source){let i=r.analysis.jsxElementsByRange.get(Vc(t.sourceRange))?.children.find(s=>C.isJSXExpressionContainer(s)&&s.loc?.start.line===e.sourceRange.startLine&&s.loc.start.column===e.sourceRange.startColumn&&s.loc.end.line===e.sourceRange.endLine&&s.loc.end.column===e.sourceRange.endColumn);return C.isJSXExpressionContainer(i)&&C.isCallExpression(i.expression)&&Tc(i.expression)?bE(i.expression,t,n,r):null}return xE(e.source,t,n,r)}async function xE(e,t,n,r){return e&&mo(e.base,t,n)?Uc(e,t,n,r):Kc(e,r)}async function Uc(e,t,n,r,o){if(!e)return null;let i=mo(e.base,t,n,o);if(!i||i.candidate.itemParamName!==e.base)return null;let s=i.candidate.collectionSource,c=(s?mo(s.base,t,n,i.region):null)?await Uc(s,t,n,r,i.region):s?await Kc(s,r):await PF(i.candidate.collectionExpression,t,n,r,i.region);return c?ms(c,e.path,!0):null}async function PF(e,t,n,r,o){let i;try{i=bF(e,{plugins:["typescript","jsx"]})}catch{return null}return bE(i,t,n,r,o)}async function bE(e,t,n,r,o){let i=wr(r.analysis,r),s=new Set;C.traverseFast(e,a=>{C.isIdentifier(a)&&s.add(a.name)});for(let a of s){let c=mo(a,t,n,o);if(!c)continue;if(c.candidate.itemParamName!==a)return null;let l=await Uc({kind:"identifier",expression:a,base:a,path:[]},t,n,r,o);if(!l)return null;i.paramSources.set(a,l)}return Ze(e,i)}function mo(e,t,n,r){let o=t.identity.key,i=null;for(;o;){for(let s of n.regions){if(s.kind!=="repeat-region"||!s.childKeys.includes(o)||r&&!sE(s.sourceRange,r.sourceRange))continue;let a=s.sourceCandidates?.find(c=>c.kind==="repeat-template"&&(c.itemParamName===e||c.indexParamName===e));a&&(!i||sE(i.region.sourceRange,s.sourceRange))&&(i={candidate:a,region:s})}o=n.elements.get(o)?.parentKey??null}return i}function sE(e,t){let n=e.startLine-t.startLine||e.startColumn-t.startColumn,r=e.endLine-t.endLine||e.endColumn-t.endColumn;return n<=0&&r>=0&&(n<0||r>0)}function EE(e,t,n){let r=!1;return C.traverseFast(e,o=>{!r&&C.isIdentifier(o)&&mo(o.name,t,n)&&(r=!0)}),r}async function Kc(e,t){if(!e)return null;let n=await Hf(e.base,t);return n?ms(n,e.path,!1):null}async function Hf(e,t){let n=t.paramSources.get(e);if(n)return St(n);if(t.variableCache.has(e))return VF(t.variableCache.get(e)??null);let r=Tr(e,t);if(r&&r!==t)return Hf(e,r);if(t.resolvingVariables.has(e))return null;t.resolvingVariables.add(e);let o=await TF(e,t);if(o)return t.variableCache.set(e,St(o)),t.resolvingVariables.delete(e),o;let i=t.scopeVariables?.has(e),s=i?t.scopeVariables.get(e):r?null:t.analysis.variables.get(e);if(s){let c=C.isArrayExpression(s)&&s.elements.length===0?await AF(e,t):await Ze(s,t);return t.variableCache.set(e,c?St(c):null),t.resolvingVariables.delete(e),c}if(i||r)return t.resolvingVariables.delete(e),t.variableCache.set(e,null),null;let a=t.analysis.imports.get(e);if(a&&t.importDepth<t.options.maxImportDepth){let c=await qf(a,t);if(c){let l=wr(c,t,{importDepth:t.importDepth+1}),u=AE(a,c);if(u){let g=(await po(u,[],l)).returnSource;return t.variableCache.set(e,g?St(g):null),t.resolvingVariables.delete(e),g}let d=c.variables.get(a.importedName);if(d){let f=await Ze(d,l);return t.variableCache.set(e,f?St(f):null),t.resolvingVariables.delete(e),f}}}return t.variableCache.set(e,null),t.resolvingVariables.delete(e),null}function Tr(e,t){return t.scopeVariables?.has(e)||t.scopeFunction?.params.some(n=>Ar(n).includes(e))?t:t.lexicalContext?Tr(e,t.lexicalContext):void 0}function wc(e,t,n=new Set){if(C.isIdentifier(e)){let s=Tr(e.name,t);if(s&&s!==t)return wc(e,s,n)}if(n.has(e))return null;if(n.add(e),C.isStringLiteral(e))return e.value;if(!C.isIdentifier(e))return null;let r=Tr(e.name,t),o=t.paramArguments.get(e.name);if(o)return wc(o.expression,o.context,n);let i=t.scopeVariables?.has(e.name)?t.scopeVariables.get(e.name):r?null:t.analysis.variables.get(e.name);return i?wc(i,t,n):null}function Bn(e,t,n=new Set){if(n.has(e))return null;let r=new Set(n).add(e);if(C.isStringLiteral(e))return e.value;if(C.isNumericLiteral(e))return String(e.value);if(C.isIdentifier(e)){if(/token|secret|password|authorization|cookie|credential/i.test(e.name))return":redacted";let o=Tr(e.name,t),i=o??t,s=i.paramArguments.get(e.name),a=i.scopeVariables?.has(e.name)?i.scopeVariables.get(e.name):o?null:i.analysis.variables.get(e.name);return(s?Bn(s.expression,s.context,r):a?Bn(a,i,r):null)??`:${e.name}`}if(C.isBinaryExpression(e,{operator:"+"})){let o=Bn(e.left,t,r),i=Bn(e.right,t,r);return o!==null&&i!==null?o+i:null}if(C.isTemplateLiteral(e)){let o=e.quasis[0]?.value.cooked??"";for(let[i,s]of e.expressions.entries()){if(!C.isExpression(s))return null;o+=(Bn(s,t,r)??":param")+(e.quasis[i+1]?.value.cooked??"")}return o}if(C.isCallExpression(e)&&C.isIdentifier(e.callee)&&["encodeURIComponent","decodeURIComponent"].includes(e.callee.name)&&C.isExpression(e.arguments[0])){let o=Bn(e.arguments[0],t,r);if(o===null||o.startsWith(":"))return o;try{return e.callee.name==="encodeURIComponent"?encodeURIComponent(o):decodeURIComponent(o)}catch{return null}}return C.isTSAsExpression(e)||C.isTSNonNullExpression(e)||C.isParenthesizedExpression(e)?Bn(e.expression,t,r):null}async function AF(e,t){let n=t.scopeFunction;if(!n)return null;let r=[],o=!1,i=0,s=u=>{let d=!1;return C.traverseFast(u,f=>{C.isIdentifier(f,{name:e})&&(d=!0)}),d},a=u=>{let d=u;for(;C.isMemberExpression(d);)d=d.object;return C.isIdentifier(d,{name:e})},c=async(u,d)=>{if(!o){if(C.isFunction(u)){s(u)&&(o=!0);return}if(C.isVariableDeclarator(u)&&(Ar(u.id).includes(e)&&i++,u.init&&s(u.init)&&(o=!0)),(C.isAssignmentExpression(u)||C.isUpdateExpression(u))&&a(C.isAssignmentExpression(u)?u.left:u.argument)){o=!0;return}if(C.isUnaryExpression(u,{operator:"delete"})&&a(u.argument)){o=!0;return}if(C.isCallExpression(u)){if(C.isMemberExpression(u.callee)&&C.isIdentifier(u.callee.object,{name:e})){if(!C.isIdentifier(u.callee.property,{name:"push"})||u.callee.computed||!u.arguments.length){o=!0;return}for(let f of u.arguments){let g=C.isSpreadElement(f)?f.argument:f,p=C.isExpression(g)?await Ze(g,d):null;p?r.push(zf(p)):o=!0}return}if(u.arguments.some(f=>s(f))){o=!0;return}}if(C.isForOfStatement(u)){let f=await Ze(u.right,d),g=wr(d.analysis,d),p=C.isVariableDeclaration(u.left)?u.left.declarations[0]?.id:u.left;f&&p&&Mc(p,zf(f),g),await c(u.body,g);return}for(let f of C.VISITOR_KEYS[u.type]??[]){let g=u[f];for(let p of Array.isArray(g)?g:[g])C.isNode(p)&&await c(p,d)}}};await c(n.body,t);let l=Gf(r);return!o&&i===1&&l.length===1?Pr(l[0]):null}async function TF(e,t){let n=t.analysis.stateSetters.get(e);if(!n)return null;let r=t.analysis.stateSetterCandidates.get(n)??[];for(let o of r){let i=await Ze(o,t);if(i)return i}return null}async function Ze(e,t){if(C.isIdentifier(e))return Hf(e.name,t);if(C.isMemberExpression(e)||C.isOptionalMemberExpression(e)){let n=C.isMemberExpression(e)?tE(e,{file:t.file}):null;if(n)return _E(n);let r=await wF(e,t);if(!r)return null;let o=jF(e);return ms(r,o,!1)}if(C.isAwaitExpression(e))return C.isExpression(e.argument)?Ze(e.argument,t):null;if((C.isCallExpression(e)||C.isOptionalCallExpression(e))&&(C.isMemberExpression(e.callee)||C.isOptionalMemberExpression(e.callee))&&!e.callee.computed&&C.isIdentifier(e.callee.property)&&["trim","trimStart","trimEnd"].includes(e.callee.property.name)&&e.arguments.length===0&&C.isExpression(e.callee.object))return Zo(await Ze(e.callee.object,t));if(C.isCallExpression(e))return IE(e,t);if(C.isObjectExpression(e)){let n=await kE(e,t);return Object.keys(n).length>0?Bc(n,t.file):null}if(C.isArrayExpression(e)){let n={};for(let[r,o]of e.elements.entries()){if(!C.isExpression(o))continue;let i=await Ze(o,t);i&&(n[String(r)]=i)}return Object.keys(n).length?Bc(n,t.file):null}if(C.isConditionalExpression(e)){let n=await Ze(e.consequent,t),r=await Ze(e.alternate,t);return Zo(lE(n,r))}if(C.isLogicalExpression(e)){let n=await Ze(e.left,t),r=await Ze(e.right,t);return Zo(lE(n,r))}return C.isTSAsExpression(e)||C.isTSSatisfiesExpression(e)||C.isTSNonNullExpression(e)||C.isTypeCastExpression(e)||C.isParenthesizedExpression(e)?Ze(e.expression,t):null}async function wF(e,t){let n=e;for(;C.isMemberExpression(n)||C.isOptionalMemberExpression(n);)n=n.object;return C.isExpression(n)?Ze(n,t):null}async function SE(e,t,n=0){if(n>=t.options.maxFunctionDepth)return null;let r=Tr(e,t);if(r){if(r.scopeFunction&&Nr(r.scopeFunction,e))return null;let s=r.paramArguments.get(e);return s&&C.isIdentifier(s.expression)?SE(s.expression.name,s.context,n+1):null}let o=t.analysis.imports.get(e);if(!o||!["cms","collections","cmsFetch","cmsFetchResult","cmsFetchEnvelope"].includes(o.importedName)||Nr(t.analysis.ast,e))return null;let i=await Qf(t.file,o.source,t.exists);return i?{...o,source:i}:null}async function IE(e,t){let n=e.arguments[0],r=C.isExpression(n)?wc(n,t):null,i=Wt(e.callee)?.split(".")[0],s=i?await SE(i,t):null,a=r!==null&&!C.isStringLiteral(n)?{...e,arguments:[C.stringLiteral(r),...e.arguments.slice(1)]}:e;if(s&&["cmsFetch","cmsFetchResult","cmsFetchEnvelope"].includes(s.importedName)&&C.isObjectExpression(n)){let x=vE(n,"path"),S=x&&Bn(x,t);S?.startsWith("/")&&(a={...e,arguments:[{...n,properties:n.properties.map(b=>C.isObjectProperty(b)&&Qo(b)==="path"?{...b,value:C.stringLiteral(fo(S))}:b)},...e.arguments.slice(1)]})}let c=Ac(a,{file:t.file,imports:i&&s?new Map([[i,s]]):new Map});if(c){if(s&&["cmsFetch","cmsFetchResult","cmsFetchEnvelope"].includes(s.importedName)&&c.endpointPattern==="/content/by-url"&&C.isObjectExpression(n)){let x=aE(n,"query"),S=C.isObjectExpression(x)?aE(x,"path"):null,E=(S&&Bn(S,t))?.match(/^\/([a-z0-9][a-z0-9_-]*)\/[^/?#]+(?:[?#].*)?$/i)?.[1];E&&(c.collection=E,c.evidence.push({file:t.file,reason:"CMS collection namespace from the actual content request path"}))}if(C.isMemberExpression(e.callee)){let x=await Qn(e.callee,t);if(x&&!Oc(x.node))return null;if(x&&Oc(x.node)){let S=await Xf(e,t,{node:x.node,context:x.context});return S&&{...S,...S.sourceKind===c.sourceKind?{operation:c.operation}:{}}}}if((c.operation==="getByUrl"||c.operation==="getByUrlStrict")&&C.isExpression(n)){let x=Bn(n,t);x?.startsWith("/")&&(c.endpointPattern=fo(x))}return _E(c)}if(Wt(e.callee)==="Promise.all"&&C.isArrayExpression(n))return Ze(n,t);if(Tc(e)){if(!Tc(e,{file:t.file,imports:i&&s?new Map([[i,s]]):new Map})||!C.isExpression(e.callee))return null;let x=await Qn(e.callee,t);if(x)return Oc(x.node)?Xf(e,t,{node:x.node,context:x.context}):null;let S=e.arguments[0];if(S&&C.isExpression(S))return Zo(await Ze(S,t))}let l=await OF(e,t);if(l)return l;let u=qb(e,{file:t.file});if(u)return{sourceKind:u.sourceKind,sourceType:"api-field",endpointPattern:u.endpointPattern,valuePath:u.valuePath,confidence:u.confidence,readonly:!0,evidence:u.evidence};let d=await LF(e,t);if(d)return d;let f=await MF(e,t);if(f)return f;let g=await DF(e,t);if(g)return g;let p=await Xf(e,t);if(p)return p;let m=[];for(let x of e.arguments)if(C.isExpression(x)){let S=await Ze(x,t);S&&m.push(S)}let y=Gf(m);return y.length===1?Zo(y[0]):null}async function OF(e,t){let n=Wt(e.callee);if(n!=="useQuery"&&n!=="useSuspenseQuery"&&n!=="useInfiniteQuery"&&n!=="useSWR")return null;if(n==="useSWR"){let i=FF(e.arguments[0],t.file,"SWR key"),s=e.arguments[1];if(C.isIdentifier(s)){let a=await qo(s.name,t);if(a)return(await po(a.node,i?[i]:[],a.context)).returnSource??i}return i}let r=e.arguments[0];if(!C.isObjectExpression(r))return Fc(t.file,`${n} without static options`);let o=vE(r,"queryFn");if(!o)return Fc(t.file,`${n} without queryFn`);if(C.isIdentifier(o)){let i=await qo(o.name,t);return i?(await po(i.node,[],i.context)).returnSource:Fc(t.file,`${n} queryFn unresolved`)}return C.isArrowFunctionExpression(o)||C.isFunctionExpression(o)?(await po(o,[],t)).returnSource:C.isCallExpression(o)?IE(o,t):null}function vE(e,t){for(let n of e.properties){if(!C.isObjectProperty(n)||!C.isExpression(n.value))continue;if(Qo(n)===t)return n.value}return null}function aE(e,t){let n=new Set;for(let i of e.properties){if(!C.isObjectProperty(i)||i.computed)return null;let s=Qo(i);if(!s||n.has(s))return null;n.add(s)}let r=e.properties.filter(i=>C.isObjectProperty(i)&&Qo(i)===t);if(r.length!==1)return null;let o=r[0];return C.isObjectProperty(o)&&C.isExpression(o.value)?o.value:null}function FF(e,t,n){return C.isStringLiteral(e)?{sourceKind:e.value.startsWith("/api/")?"site-api-route":"external-api",sourceType:"api-field",endpointPattern:e.value,confidence:"exact",readonly:!0,evidence:[{file:t,reason:n}]}:null}async function LF(e,t){if(!C.isMemberExpression(e.callee)||!C.isIdentifier(e.callee.property))return null;let n=e.callee.property.name;if(!["map","filter","slice","sort","toSorted","reverse","toReversed"].includes(n))return null;let r=C.isExpression(e.callee.object)?await Ze(e.callee.object,t):null;if(!r)return null;if(n!=="map")return Pr(r);let o=e.arguments[0];if(C.isIdentifier(o)){let i=await qo(o.name,t);if(!i)return Pr(r);let s=await po(i.node,[r],i.context);return{...Pr(r),...s.objectReturnMap??s.returnSource?.fieldMap?{fieldMap:s.objectReturnMap??s.returnSource.fieldMap}:{}}}if(C.isArrowFunctionExpression(o)||C.isFunctionExpression(o)){let i=await po(o,[r],t);return{...Pr(r),...i.objectReturnMap??i.returnSource?.fieldMap?{fieldMap:i.objectReturnMap??i.returnSource.fieldMap}:{}}}return Pr(r)}async function MF(e,t){return!C.isMemberExpression(e.callee)||!C.isIdentifier(e.callee.property,{name:"json"})||!C.isExpression(e.callee.object)?null:Ze(e.callee.object,t)}async function DF(e,t){return!C.isMemberExpression(e.callee)||!C.isIdentifier(e.callee.property,{name:"then"})||!C.isExpression(e.callee.object)?null:Zo(await Ze(e.callee.object,t))}async function Xf(e,t,n){let r=n;if(!r&&C.isIdentifier(e.callee))r=await qo(e.callee.name,t)??void 0;else if(!r&&C.isMemberExpression(e.callee)){let s=await Qn(e.callee,t);s&&Oc(s.node)&&(r={node:s.node,context:s.context})}if(!r)return null;let o=[];for(let s of e.arguments){if(!C.isExpression(s)){o.push(Fc(t.file,`unsupported argument for ${Wt(e.callee)??"call"}`));continue}let a=await Ze(s,t);o.push(a)}return(await po(r.node,o,r.context,{arguments:e.arguments,context:t})).returnSource}function Oc(e){return C.isFunctionDeclaration(e)||$c(e)||C.isObjectMethod(e)&&e.kind==="method"}async function Qn(e,t,n=new Set){let r={node:null,context:t};if(n.has(e)||n.size>=32)return r;let o=new Set(n).add(e);if(C.isTSAsExpression(e)||C.isTSSatisfiesExpression(e)||C.isTSNonNullExpression(e))return Qn(e.expression,t,o);if(C.isIdentifier(e)){let i=Tr(e.name,t),s=i??t;if(Nr(i?.scopeFunction??t.analysis.ast,e.name))return r;let a=s.paramArguments.get(e.name);if(a)return Qn(a.expression,a.context,o);let c=i?i.scopeVariables?.get(e.name):s.analysis.variables.get(e.name);if(c)return Qn(c,s,o);if(i)return null;let l=s.analysis.functions.get(e.name);if(l)return{node:l,context:s};let u=s.analysis.imports.get(e.name);if(!u||s.importDepth>=s.options.maxImportDepth)return null;let d=await qf(u,s);return d?Qn(C.identifier(u.importedName),wr(d,s,{importDepth:s.importDepth+1}),o):null}if(C.isMemberExpression(e)&&C.isExpression(e.object)){let i=e.computed?C.isStringLiteral(e.property)?e.property.value:null:C.isIdentifier(e.property)?e.property.name:null;if(!i)return null;let s=await Qn(e.object,t,o);if(!s)return null;if(!C.isObjectExpression(s.node))return{node:null,context:s.context};if(s.node.properties.some(l=>C.isSpreadElement(l)||l.computed))return{node:null,context:s.context};let a=s.node.properties.filter(l=>(C.isObjectMethod(l)||C.isObjectProperty(l))&&(C.isIdentifier(l.key)?l.key.name:C.isStringLiteral(l.key)?l.key.value:null)===i);if(a.length===0)return null;if(a.length!==1)return{node:null,context:s.context};let c=a[0];return C.isObjectMethod(c)?c.kind==="method"?{node:c,context:s.context}:null:C.isObjectProperty(c)&&C.isExpression(c.value)?Qn(c.value,s.context,o):null}return{node:e,context:t}}async function qo(e,t,n=new Set){let r=t.paramArguments.get(e);if(r&&!n.has(r.expression)){if(n.add(r.expression),$c(r.expression))return{node:r.expression,context:r.context};if(C.isIdentifier(r.expression))return qo(r.expression.name,r.context,n)}let o=t.analysis.functions.get(e);if(o)return{node:o,context:t};let i=t.analysis.imports.get(e);if(!i||t.importDepth>=t.options.maxImportDepth)return null;let s=await qf(i,t);if(!s)return null;let a=wr(s,t,{importDepth:t.importDepth+1}),c=AE(i,s);return c?{node:c,context:a}:qo(i.importedName,a)}async function po(e,t,n,r){if(n.functionDepth>=n.options.maxFunctionDepth)return{returnSource:null};let o=wr(n.analysis,n,{functionDepth:n.functionDepth+1}),i=n.analysis.functionParents.get(e),s=n;for(;s&&(s.analysis!==n.analysis||s.scopeFunction!==i);)s=s.lexicalContext;o.lexicalContext=s,o.paramSources=new Map,o.paramArguments=new Map,o.scopeVariables=n.analysis.functionVariables.get(e),o.scopeFunction=e,e.params.forEach((d,f)=>{for(let y of Ar(d))o.paramSources.delete(y),o.paramArguments.delete(y);let g=C.isAssignmentPattern(d)?d.left:d,p=r?.arguments[f];C.isIdentifier(g)&&C.isExpression(p)&&r&&o.paramArguments.set(g.name,{expression:p,context:r.context});let m=t[f];m&&Mc(d,zf(m),o)});let a=BF(e,o),c=null,l,u=!1;for(let d of a){let f=wr(n.analysis,o);if(C.isObjectExpression(d)){l={...l??{},...await kE(d,f)},c=c??Bc(l,n.file);continue}let g=await Ze(d,f);if(g){if(!c){c=g;continue}let p=Wf(c,g);if(!p){u=!0,c=null;continue}c=p}}return{returnSource:u?null:c,...l?{objectReturnMap:l}:{}}}function Mc(e,t,n){if(C.isIdentifier(e)){n.paramSources.set(e.name,St(t));return}if(C.isAssignmentPattern(e)){Mc(e.left,t,n);return}if(C.isObjectPattern(e))for(let r of e.properties){if(!C.isObjectProperty(r)||r.computed||!C.isIdentifier(r.key))continue;let o=ms(t,[{kind:"property",name:r.key.name}],!0),i=C.isAssignmentPattern(r.value)?r.value.left:r.value;o&&Mc(i,o,n)}}function BF(e,t){if(C.isArrowFunctionExpression(e)&&C.isExpression(e.body))return[e.body];let n=[],r=e.body;if(!C.isBlockStatement(r))return n;let o=i=>{if(C.isFunction(i)&&i!==e)return;if(C.isReturnStatement(i)){i.argument&&C.isExpression(i.argument)&&n.push(i.argument);return}if(C.isIfStatement(i)){let a=Go(i.test,{file:t.file,imports:new Map([...t.analysis.imports].filter(([c])=>!Tr(c,t))),functions:t.analysis.functions});if(a!==void 0){a?o(i.consequent):i.alternate&&o(i.alternate);return}}let s=C.VISITOR_KEYS[i.type];for(let a of s??[]){let c=i[a];if(Array.isArray(c))for(let l of c)C.isNode(l)&&o(l);else C.isNode(c)&&o(c)}};return o(r),n}async function kE(e,t){let n={};for(let r of e.properties){if(!C.isObjectProperty(r))continue;let o=Qo(r);if(!o||!C.isExpression(r.value))continue;let i=await Ze(r.value,t);i&&(n[o]=i)}return n}function Qo(e){return C.isIdentifier(e.key)&&!e.computed?e.key.name:C.isStringLiteral(e.key)?e.key.value:null}function jF(e){let t=[],n=e;for(;C.isMemberExpression(n)||C.isOptionalMemberExpression(n);){let r=n.property;n.computed?C.isStringLiteral(r)?t.unshift({kind:"property",name:r.value}):C.isNumericLiteral(r)&&t.unshift({kind:"index",index:r.value}):C.isIdentifier(r)&&t.unshift({kind:"property",name:r.name}),n=n.object}return C.isIdentifier(n),t}function ms(e,t,n){if(t.length===0)return St(e);let r=t[0],o=r?.kind==="property"?r.name:r?String(r.index):null;if(e.fieldMap&&o!==null){let s=e.fieldMap[o];return s?ms(s,t.slice(1),n):null}let i=St(e);if(i.sourceType==="cms-field"){let s=t.filter(c=>c.kind==="property").map(c=>c.name);if(s[0]==="data"&&s[1]==="items")return i.valuePath=Yo(i.valuePath,"data.items[]"),i.cmsFieldRoot=!1,i;let a=s[0]==="fields"?0:s[0]==="data"&&s[1]==="fields"?1:-1;return a>=0?(a===1&&(i.valuePath=Yo(i.valuePath,"data")),i.fieldPath=Yo(i.fieldPath,s.slice(a+1).join(".")),i.cmsFieldRoot=!0,i):i.cmsFieldRoot||n||i.fieldMap?(i.fieldPath=Yo(i.fieldPath,s.join(".")),i):(i.valuePath=Yo(i.valuePath,cE(t)),i)}return i.valuePath=Yo(i.valuePath,cE(t)),i}function cE(e){return e.map(t=>t.kind==="property"?t.name:`[${t.index}]`).join(".").replace(/\.\[/g,"[")}function Yo(e,t){return t?e?t.startsWith("[")?`${e}${t}`:`${e}.${t}`:t:e}function _E(e){return{sourceKind:e.sourceKind,sourceType:e.sourceType,operation:e.operation,collection:e.collection,endpointPattern:e.endpointPattern,valuePath:e.valuePath,confidence:e.confidence,readonly:!0,evidence:e.evidence}}function Pr(e){let t=St(e);return t.sourceType==="cms-field"&&!t.valuePath&&(t.valuePath="items[]"),t}function zf(e){let t=St(e);return t.valuePath=void 0,t.sourceType==="cms-field"&&!t.fieldPath&&(t.cmsFieldRoot=!1),t}function Zo(e){return e?{...St(e),confidence:e.confidence==="unknown"?"unknown":"safe-derived",evidence:[...e.evidence,{file:e.evidence[0]?.file??"unknown",reason:"safe derived expression"}]}:null}function lE(e,t){return e?t?Wf(e,t):St(e):t?St(t):null}function Wf(e,t){if(Dc(e)!==Dc(t))return null;let n=NE(e.confidence,t.confidence)<=0?e.confidence:t.confidence;return{...e,confidence:n,evidence:[...e.evidence,...t.evidence]}}function Gf(e){let t=new Map;for(let n of e){let r=Dc(n),o=t.get(r);t.set(r,o?Wf(o,n):St(n))}return[...t.values()]}function Dc(e){let t=e.fieldMap?Object.fromEntries(Object.entries(e.fieldMap).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>[n,Dc(r)])):void 0;return JSON.stringify({sourceKind:e.sourceKind,sourceType:e.sourceType,endpointPattern:e.endpointPattern,operation:e.operation,collection:e.collection,fieldPath:e.fieldPath,valuePath:e.valuePath,cmsFieldRoot:e.cmsFieldRoot,fieldMap:t})}function Bc(e,t){let n=Object.values(e)[0];return{sourceKind:n?.sourceKind??"unknown-api",sourceType:n?.sourceType??"api-field",endpointPattern:n?.endpointPattern,operation:n?.operation,collection:n?.collection,confidence:n?.confidence??"partial",readonly:!0,evidence:n?.evidence??[{file:t,reason:"object return map"}],fieldMap:e}}function Fc(e,t){return{sourceKind:"unknown-api",sourceType:"api-field",confidence:"unknown",readonly:!0,evidence:[{file:e,reason:t}]}}function jc(e,t,n){return{sourceKind:e.sourceKind,sourceType:e.sourceType,...e.endpointPattern?{endpointPattern:e.endpointPattern}:{},...e.operation?{operation:e.operation}:{},...e.collection?{collection:e.collection}:{},...e.fieldPath?{fieldPath:e.fieldPath}:{},...e.valuePath?{valuePath:e.valuePath}:{},targetKind:t,targetName:n,confidence:e.confidence,readonly:!0,evidence:e.evidence.map(r=>({...r}))}}function CE(e){let t=[...e].sort(RE),n=t[0],r=[...new Set(t.flatMap(o=>o.sourceKind==="vcp-cms-collection"&&o.collection?[o.collection]:[]))];return{hasDynamicData:t.length>0,sourceKinds:[...new Set(t.map(o=>o.sourceKind))],...r.length>0?{collections:r}:{},...n?.endpointPattern?{primaryEndpoint:n.endpointPattern}:{},...n?.collection?{primaryCollection:n.collection}:{},...n?.fieldPath?{primaryFieldPath:n.fieldPath}:{}}}function $F(e){let t=new Set,n=[];for(let r of e){let o=JSON.stringify({sourceKind:r.sourceKind,endpointPattern:r.endpointPattern,collection:r.collection,fieldPath:r.fieldPath,valuePath:r.valuePath,targetKind:r.targetKind,targetName:r.targetName});t.has(o)||(t.add(o),n.push(r))}return n}function RE(e,t){return uE(e.targetKind)-uE(t.targetKind)||NE(e.confidence,t.confidence)||dE(e.sourceKind)-dE(t.sourceKind)||e.targetName.localeCompare(t.targetName)}function uE(e){return{"repeat-region":0,"conditional-region":1,text:2,richtext:3,attribute:4,"component-prop":5}[e]}function dE(e){return e.startsWith("vcp-cms-")?0:e==="site-api-route"?1:e==="external-api"?2:3}function NE(e,t){let n={exact:0,"safe-derived":1,partial:2,unknown:3};return n[e]-n[t]}function Yf(e,t,n){let r=n.get(e);if(r?.source===t)return r;let o=fE.get(n)?.get(e),i=o?.source===t?o.ast:xF(t,{sourceType:"module",plugins:["jsx","typescript"]}),s={file:e,source:t,ast:i,variables:new Map,functions:new Map,imports:new Map,stateSetters:new Map,stateSetterCandidates:new Map,jsxElementsByRange:new Map,functionVariables:new WeakMap,functionParents:new WeakMap},a=[],c=[];C.traverse(i,{enter(d){switch(C.isFunction(d)&&(s.functionParents.set(d,a.at(-1)??null),a.push(d)),d.type){case"CallExpression":c.push(d);break;case"JSXElement":{let f=d.loc;if(!f)return;let g=Vc({startLine:f.start.line,startColumn:f.start.column,endLine:f.end.line,endColumn:f.end.column});s.jsxElementsByRange.has(g)||s.jsxElementsByRange.set(g,d);break}case"ImportDeclaration":{let f=d.source.value;for(let g of d.specifiers)C.isImportSpecifier(g)&&C.isIdentifier(g.local)?s.imports.set(g.local.name,{source:f,importedName:C.isIdentifier(g.imported)?g.imported.name:g.imported.value,localName:g.local.name,isDefault:!1}):C.isImportDefaultSpecifier(g)&&s.imports.set(g.local.name,{source:f,importedName:"default",localName:g.local.name,isDefault:!0});break}case"FunctionDeclaration":{d.id?.name&&s.functions.set(d.id.name,d);break}case"VariableDeclarator":{let f=a.at(-1),g=f&&(C.isFunctionDeclaration(f)||C.isFunctionExpression(f)||C.isArrowFunctionExpression(f)||C.isObjectMethod(f))?f:null,p=g?s.functionVariables.get(g)??new Map:s.variables;g&&!s.functionVariables.has(g)&&s.functionVariables.set(g,p);for(let[m,y]of Lc(d.id,C.isExpression(d.init)?d.init:null))p.set(m,y);if(C.isArrayPattern(d.id)&&C.isCallExpression(d.init)&&Wt(d.init.callee)==="useState"){let[m,y]=d.id.elements;C.isIdentifier(m)&&C.isIdentifier(y)&&s.stateSetters.set(m.name,y.name)}C.isIdentifier(d.id)&&$c(d.init)&&s.functions.set(d.id.name,d.init);break}case"ExportNamedDeclaration":{let f=d.declaration,g=d.source?.value;if(g)for(let p of d.specifiers){if(!C.isExportSpecifier(p))continue;let m=C.isIdentifier(p.exported)?p.exported.name:p.exported.value,y=p.local.name;s.imports.set(m,{source:g,importedName:y,localName:m,isDefault:y==="default"})}if(C.isFunctionDeclaration(f)&&f.id?.name&&s.functions.set(f.id.name,f),C.isVariableDeclaration(f))for(let p of f.declarations)C.isIdentifier(p.id)&&$c(p.init)&&s.functions.set(p.id.name,p.init);break}case"ExportDefaultDeclaration":{let f=d.declaration;if((C.isFunctionDeclaration(f)||C.isFunctionExpression(f)||C.isArrowFunctionExpression(f))&&s.functions.set("default",f),C.isIdentifier(f)){let g=s.functions.get(f.name);g&&s.functions.set("default",g)}break}}},exit(d){C.isFunction(d)&&a.pop()}});let l=new Set(s.stateSetters.values()),u=(d,f)=>{let g=s.stateSetterCandidates.get(d)??[];g.push(f),s.stateSetterCandidates.set(d,g)};if(l.size>0)for(let d of c){let f=C.isIdentifier(d.callee)?d.callee.name:null;f&&l.has(f)&&C.isExpression(d.arguments[0])&&u(f,d.arguments[0]);let g=new Set;for(let p of d.arguments)C.isIdentifier(p)&&p.name!==f&&l.has(p.name)&&g.add(p.name);for(let p of g)u(p,d)}return n.set(e,s),s}function Lc(e,t){return C.isIdentifier(e)?[[e.name,t]]:C.isAssignmentPattern(e)?Lc(e.left,t):C.isArrayPattern(e)?e.elements.flatMap((n,r)=>n&&!C.isRestElement(n)?Lc(n,t?C.memberExpression(t,C.numericLiteral(r),!0):null):[]):C.isObjectPattern(e)?e.properties.flatMap(n=>{if(!C.isObjectProperty(n)||n.computed)return[];let r=Qo(n);return r?Lc(n.value,t?C.memberExpression(t,C.stringLiteral(r),!0):null):[]}):[]}function Ar(e){return!e||C.isVoidPattern(e)?[]:C.isIdentifier(e)?[e.name]:C.isObjectPattern(e)?e.properties.flatMap(t=>C.isObjectProperty(t)?Ar(t.value):Ar(t.argument)):C.isArrayPattern(e)?e.elements.flatMap(t=>t?Ar(C.isRestElement(t)?t.argument:t):[]):C.isAssignmentPattern(e)?Ar(e.left):C.isRestElement(e)?Ar(e.argument):[]}function $c(e){return C.isFunctionExpression(e)||C.isArrowFunctionExpression(e)}function PE(e,t){let n=Zf(e,t);return n?e.functionVariables.get(n):void 0}function Zf(e,t){return e.functions.get(t)??e.functions.get("default")}async function qf(e,t){let n=await Qf(t.file,e.source,t.exists);if(!n)return null;let r=await t.readFile(n);return Yf(n,r,t.fileCache)}function AE(e,t){return e.isDefault?t.functions.get("default")??t.functions.get(e.localName)??null:t.functions.get(e.importedName)??null}async function Qf(e,t,n){return nt(t)?Jr(e,t,n):null}function wr(e,t,n={}){return{file:e.file,analysis:e,readFile:t.readFile,exists:t.exists,fileCache:t.fileCache,options:t.options,variableCache:new Map,functionDepth:n.functionDepth??t.functionDepth,importDepth:n.importDepth??t.importDepth,paramSources:new Map(t.paramSources),paramArguments:e===t.analysis?new Map(t.paramArguments):new Map,resolvingVariables:new Set,resolvingComponentProps:t.resolvingComponentProps,scopeVariables:e===t.analysis?t.scopeVariables:void 0,scopeFunction:e===t.analysis?t.scopeFunction:void 0,lexicalContext:e===t.analysis?t.lexicalContext:void 0}}function VF(e){return e?St(e):null}function St(e){return{...e,evidence:e.evidence.map(t=>({...t})),...e.fieldMap?{fieldMap:Object.fromEntries(Object.entries(e.fieldMap).map(([t,n])=>[t,St(n)]))}:{}}}import*as tp from"@babel/parser";import ep from"@babel/traverse";import*as ce from"@babel/types";import{classifySiteEditPropertyName as UF}from"@vcp-dev/contracts";var np=typeof ep=="function"?ep:ep.default;function rp(e){let t=UF(e.propertyName);if(t.owner!=="generic")return Gt("invalid-property",t.diagnostic?.message??`Property '${e.propertyName}' is not a generic property`);let n=e.selectionRef;if(!n)return Gt("missing-selection-ref","A repeat property target requires a complete selection reference");if(n.key!==e.element.identity.key)return Gt("selection-mismatch","Selection reference does not identify the requested element");if(n.instanceIndex===void 0)return Gt("missing-instance-index","A repeat property target requires an instance index");let r;try{r=tp.parse(e.source,{sourceType:"module",plugins:["typescript","jsx"]})}catch(y){return Gt("repeat-not-found",`Unable to parse repeat source: ${y instanceof Error?y.message:String(y)}`)}let o=KF(r,e.element.sourceRange);if(!o)return Gt("repeat-not-found","The selected element is not inside a supported map repeat");if(!ce.isIdentifier(o.callback.params[0]))return Gt("unsupported-callback","Repeat property materialization requires an identifier callback item");let i=JF(r,o.collection,e.file,e.sources);if(!i)return Gt("collection-not-found","The repeat collection is not a visible local static array");let{array:s,locator:a,sourceFile:c}=i,l=[],u=[];for(let[y,x]of s.elements.entries()){if(!x||!ce.isObjectExpression(x)||!ME(x))return Gt("unsafe-collection","Repeat materialization requires an array of local static objects without spreads");let S=[{kind:"index",index:y}];l.push(S),u.push({kind:"value",root:a.root,path:S})}let d=u.length;if(n.instanceCount!==void 0&&n.instanceCount!==d)return Gt("count-mismatch",`Selection reports ${n.instanceCount} instances but the source collection has ${d}`);let f=n.instanceIndex;if(f>=d)return Gt("index-out-of-range",`Selected repeat instance ${f} is outside the source collection`);let g=s.elements[f];if(!g||!ce.isObjectExpression(g))return Gt("unsafe-collection","Selected repeat item is not an object");let p=YF(e.element,e.propertyName),m=WF(g,e.propertyName);return m?{ok:!0,sourceFile:c,templateFile:e.file,collectionLocator:a,parentObjectLocators:u,selectedParentObjectLocator:u[f],sourceItemIndex:f,sourceItemPath:l[f],collectionIndexMap:Array.from({length:d},(y,x)=>x),callbackItemName:o.callback.params[0].name,targetElementLocator:{kind:"jsx-node",strategy:"structural-path",file:e.element.identity.file,component:e.element.identity.component,structuralPath:e.element.identity.structuralPath,expectedRange:e.element.sourceRange},propertyName:e.propertyName,propertyState:m,selectedResolution:GF(g,e.propertyName),...p?{property:p}:{},selectionRef:n}:Gt("unsafe-property-source",`Property '${e.propertyName}' has a dynamic or unsupported source in the repeat item`)}function KF(e,t){let n=[];return np(e,{CallExpression(r){let o=TE(r.node);o&&OE(o.callback,t)&&n.push({...o,span:wE(r.node)})},OptionalCallExpression(r){let o=TE(r.node);o&&OE(o.callback,t)&&n.push({...o,span:wE(r.node)})}}),n.sort((r,o)=>r.span-o.span),n[0]??null}function TE(e){let t=e.callee;if(!ce.isMemberExpression(t)&&!ce.isOptionalMemberExpression(t)||t.computed||!ce.isIdentifier(t.property)||t.property.name!=="map"||!ce.isExpression(t.object))return null;let n=e.arguments[0];return!n||!ce.isExpression(n)||!ce.isArrowFunctionExpression(n)&&!ce.isFunctionExpression(n)?null:{collection:t.object,callback:n}}function JF(e,t,n,r){let o=gs(t);if(o&&ce.isArrayExpression(o))return{array:o,locator:{kind:"value",root:{kind:"expression",sourceRange:BE(o)}},sourceFile:n};if(!ce.isIdentifier(t))return null;let i=[];if(np(e,{VariableDeclarator(s){ce.isIdentifier(s.node.id)&&s.node.id.name===t.name&&s.node.init&&i.push(s.node)}}),i.length===1){let s=gs(i[0].init);return!s||!ce.isArrayExpression(s)?null:{array:s,locator:{kind:"value",root:{kind:"binding",name:t.name}},sourceFile:n}}return XF(e,t.name,n,r)}function XF(e,t,n,r){if(!r)return null;for(let o of e.program.body){if(!ce.isImportDeclaration(o))continue;let i=o.specifiers.find(f=>f.local.name===t);if(!i||!ce.isStringLiteral(o.source)||!ce.isImportSpecifier(i))continue;let s=HF(n,o.source.value,r);if(!s)return null;let a=ce.isIdentifier(i.imported)?i.imported.name:i.imported.value,c=r.get(s);if(c===void 0)return null;let l;try{l=tp.parse(c,{sourceType:"module",plugins:["typescript","jsx"]})}catch{return null}let u=zF(l,a),d=u?gs(u):null;return!d||!ce.isArrayExpression(d)?null:{array:d,locator:{kind:"value",root:{kind:"binding",name:a}},sourceFile:s}}return null}function zF(e,t){let n=null;return np(e,{VariableDeclarator(r){n||!ce.isIdentifier(r.node.id)||r.node.id.name!==t||!r.node.init||!ce.isExpression(r.node.init)||(n=r.node.init)}}),n}function HF(e,t,n){let r=Cn(e,t);return[r,r+".tsx",r+".ts",r+".jsx",r+".js",r+"/index.tsx",r+"/index.ts",r+"/index.jsx",r+"/index.js"].find(i=>n.has(i))??null}function gs(e){return ce.isParenthesizedExpression(e)?gs(e.expression):ce.isTSAsExpression(e)?LE(e.typeAnnotation)?gs(e.expression):null:ce.isTSSatisfiesExpression(e)?null:e}function LE(e){return ce.isTSTypeReference(e)&&ce.isIdentifier(e.typeName)&&e.typeName.name==="const"}function ME(e){return e.properties.every(t=>!ce.isObjectProperty(t)||t.computed||!ce.isExpression(t.value)?!1:Jc(t.value))}function Jc(e){if(ce.isTSAsExpression(e)&&LE(e.typeAnnotation))return Jc(e.expression);if(ce.isTSSatisfiesExpression(e))return!1;if(ce.isArrayExpression(e))return e.elements.every(n=>!n||ce.isSpreadElement(n)||!ce.isExpression(n)?!1:Jc(n));if(ce.isObjectExpression(e))return ME(e);let t=Tn(e);return t.status==="resolved"||t.status==="undefined"}function WF(e,t){let n=e.properties.filter(o=>ce.isObjectProperty(o)&&DE(o.key)===t);if(n.length>1)return null;let r=n[0];return r?ce.isExpression(r.value)?Jc(r.value)?"static":ce.isIdentifier(r.value)||ce.isMemberExpression(r.value)?"binding":null:null:"missing"}function GF(e,t){let n=e.properties.filter(o=>ce.isObjectProperty(o)&&DE(o.key)===t);if(n.length>1)return{status:"unresolved"};let r=n[0];return!r||!ce.isExpression(r.value)?{status:"undefined"}:Tn(r.value)}function YF(e,t){let n=e.attributes?.filter(r=>r.name===t)??[];return n.length===1?n[0]:void 0}function DE(e){return ce.isIdentifier(e)?e.name:ce.isStringLiteral(e)?e.value:ce.isNumericLiteral(e)?String(e.value):null}function BE(e){return{startLine:e.loc?.start.line??0,startColumn:e.loc?.start.column??0,endLine:e.loc?.end.line??0,endColumn:e.loc?.end.column??0}}function wE(e){return e.start==null||e.end==null?Number.MAX_SAFE_INTEGER:e.end-e.start}function OE(e,t){let n=BE(e);return FE(n.startLine,n.startColumn,t.startLine,t.startColumn)<=0&&FE(n.endLine,n.endColumn,t.endLine,t.endColumn)>=0}function FE(e,t,n,r){return e===n?t-r:e-n}function Gt(e,t){return{ok:!1,errorCode:e,reason:t}}import{classifySiteEditPropertyName as FL}from"@vcp-dev/contracts";import*as de from"@babel/types";import Es from"node:path";import*as Z from"@babel/types";import*as JE from"@babel/parser";import op from"@babel/traverse";import*as ye from"@babel/types";function zc(e,t){let n=[],r=e;for(;ye.isMemberExpression(r);){if(r.computed)if(ye.isNumericLiteral(r.property))n.unshift({kind:"index",index:r.property.value});else if(ye.isStringLiteral(r.property))n.unshift({kind:"property",name:r.property.value});else return null;else{if(!ye.isIdentifier(r.property))return null;n.unshift({kind:"property",name:r.property.name})}r=r.object}return!ye.isIdentifier(r)||r.name!==t?null:n}function jE(e){if(ye.isIdentifier(e))return{base:e.name,path:[]};if(!ye.isMemberExpression(e))return null;let t=[],n=e;for(;ye.isMemberExpression(n);){if(n.computed)if(ye.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(ye.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else{if(!ye.isIdentifier(n.property))return null;t.unshift({kind:"property",name:n.property.name})}n=n.object}return ye.isIdentifier(n)?{base:n.name,path:t}:null}function Pt(e,t){let n=e;for(let r of t){if(r.kind==="property"){if(n===null||Array.isArray(n)||typeof n!="object"||!(r.name in n))return;n=n[r.name];continue}if(!Array.isArray(n)||r.index<0||r.index>=n.length)return;n=n[r.index]}return n}var jn=Symbol("not-closed-literal");function Xc(e){switch(e.type){case"StringLiteral":case"NumericLiteral":case"BooleanLiteral":return e.value;case"NullLiteral":return null;case"TemplateLiteral":return e.expressions.length===0&&e.quasis.length===1?e.quasis[0].value.cooked??e.quasis[0].value.raw:jn;case"TSAsExpression":case"TSSatisfiesExpression":case"TSNonNullExpression":return Xc(e.expression);case"ArrayExpression":{let t=[];for(let n of e.elements){if(!n||ye.isSpreadElement(n))return jn;let r=Xc(n);if(r===jn)return jn;t.push(r)}return t}case"ObjectExpression":{let t={};for(let n of e.properties){if(!ye.isObjectProperty(n)||n.computed||n.shorthand||!ye.isExpression(n.value))return jn;let r=ye.isIdentifier(n.key)?n.key.name:ye.isStringLiteral(n.key)?n.key.value:null;if(!r)return jn;let o=Xc(n.value);if(o===jn)return jn;t[r]=o}return t}default:return jn}}function $E(e){let{resolveBindingTarget:t}=e;async function n(i,s,a,c,l,u,d){let f=Xc(i);if(f!==jn)return f;if(!ye.isTemplateLiteral(i)){if(ye.isTSAsExpression(i)||ye.isTSSatisfiesExpression(i)||ye.isTSNonNullExpression(i))return await n(i.expression,s,a,c,l,u,d);if(ye.isIdentifier(i)){let g=s.getBinding(i.name);if(!g)return;let p=await t({currentFile:a,binding:g,readFile:c,exists:l,fileCache:u,visited:d});return p?.kind==="static"?p.value:void 0}if(ye.isArrayExpression(i)){let g=[];for(let p of i.elements){if(!p||ye.isSpreadElement(p))return;let m=await r(p,s,a,c,l,u,d);if(m===void 0)return;g.push(m)}return g}if(ye.isObjectExpression(i)){let g={};for(let p of i.properties){if(!ye.isObjectProperty(p)||p.computed)return;let m=null;if(ye.isIdentifier(p.key)?m=p.key.name:ye.isStringLiteral(p.key)&&(m=p.key.value),!m)return;if(p.shorthand){if(!ye.isIdentifier(p.value))return;let x=await r(p.value,s,a,c,l,u,d);if(x===void 0)return;g[m]=x;continue}if(!ye.isExpression(p.value))return;let y=await r(p.value,s,a,c,l,u,d);y!==void 0&&(g[m]=y)}return g}if(ye.isMemberExpression(i)){let g=await o(i,s,a,c,l,u,d);if(!g)return;let p=s.getBinding(g.base);if(!p)return;let m=await t({currentFile:a,binding:p,readFile:c,exists:l,fileCache:u,visited:d});return!m||m.kind!=="static"?void 0:Pt(m.value,g.path)}}}async function r(i,s,a,c,l,u,d){if(!ye.isSpreadElement(i))return await n(i,s,a,c,l,u,d)}async function o(i,s,a,c,l,u,d){if(ye.isIdentifier(i))return{base:i.name,path:[]};if(!ye.isMemberExpression(i))return null;let f=[],g=i;for(;ye.isMemberExpression(g);){if(g.computed){let p=g.property;if(ye.isNumericLiteral(p))f.unshift({kind:"index",index:p.value});else if(ye.isStringLiteral(p))f.unshift({kind:"property",name:p.value});else{let m=ye.isExpression(p)?await n(p,s,a,c,l,u,d):void 0;if(typeof m=="string")f.unshift({kind:"property",name:m});else if(Number.isInteger(m))f.unshift({kind:"index",index:m});else return null}}else{if(!ye.isIdentifier(g.property))return null;f.unshift({kind:"property",name:g.property.name})}g=g.object}return ye.isIdentifier(g)?{base:g.name,path:f}:null}return{normalizeExpressionWithScope:o,evaluateStaticExpression:n}}var XE=typeof op=="function"?op:op.default,VE=new WeakMap;function zE(e){try{return JE.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function Hc(e,t,n){let r=e.get(t);if(r?.source===n)return r.ast;let o=zE(n);return e.set(t,{source:n,ast:o}),o}function Wc(e,t){return ip(hs(e).expressionRanges,t,!1)}function HE(e,t){return hs(e).exactExpressions.get(WE(t))??null}function Gc(e,t){return ip(hs(e).jsxRanges,t,!0)}function hs(e){let t=VE.get(e);if(t)return t;let n={expressions:[],expressionRanges:[],jsxRanges:[],exactExpressions:new Map};return XE(e,{Expression(r){let o=r;n.expressions.push(o);let i=UE(o,n.expressions.length-1);if(!i)return;n.expressionRanges.push(i);let s=WE(i.range),a=n.exactExpressions.get(s);(!a||i.span<=(a.node.end??0)-(a.node.start??0))&&n.exactExpressions.set(s,o)},JSXElement(r){let o=UE(r,n.jsxRanges.length);o&&n.jsxRanges.push(o)}}),n.expressionRanges.sort(KE),n.jsxRanges.sort(KE),VE.set(e,n),n}function UE(e,t){let n=ys(e.node);return n?{path:e,range:n,traversalIndex:t,span:(e.node.end??0)-(e.node.start??0)}:null}function WE(e){return`${e.startLine}:${e.startColumn}:${e.endLine}:${e.endColumn}`}function KE(e,t){return e.range.startLine-t.range.startLine||e.range.startColumn-t.range.startColumn||e.traversalIndex-t.traversalIndex}function ip(e,t,n,r){let o=0,i=e.length;for(;o<i;){let c=o+Math.floor((i-o)/2),l=e[c].range;l.startLine<t.startLine||l.startLine===t.startLine&&l.startColumn<t.startColumn?o=c+1:i=c}let s=null,a=n?1/0:-1;for(let c=o;c<e.length;c++){let l=e[c],u=l.range;if(u.startLine>t.endLine||u.startLine===t.endLine&&u.startColumn>t.endColumn)break;if(u.endLine>t.endLine||u.endLine===t.endLine&&u.endColumn>t.endColumn||r&&!r(l.path))continue;((n?l.span<a:l.span>a)||l.span===a&&(!s||l.traversalIndex>s.traversalIndex))&&(s=l,a=l.span)}return s?.path??null}function ys(e){return e.loc?{startLine:e.loc.start.line,startColumn:e.loc.start.column,endLine:e.loc.end.line,endColumn:e.loc.end.column}:null}function ei(e,t){if(t)return sp(e,t);let n=jE(e);return n?n.path.reduce((r,o)=>o.kind==="property"?`${r}.${o.name}`:`${r}[${o.index}]`,n.base):""}function sp(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function xs(e,t,n){let r=null,o=Number.POSITIVE_INFINITY;for(let i of hs(e).expressions){if(sp(i.node,t)!==n)continue;let s=(i.node.end??0)-(i.node.start??0);s<=o&&(r=i,o=s)}return r}function GE(e,t,n,r){return ip(hs(e).expressionRanges,r,!0,o=>sp(o.node,t)===n)}function ti(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}function bs(e){let t=null;if(XE(e,{Program(n){t=n.scope,n.stop()}}),!t)throw new Error("Unable to determine program scope");return t}async function In(e,t,n){let r=n.get(e);if(r)return r;let o=await t(e),i=zE(o),s={source:o,ast:i};return n.set(e,s),s}function ZF(e){return Z.isIdentifier(e.callee)&&(e.callee.name==="useState"||e.callee.name==="useReducer")?e.callee.name:Z.isMemberExpression(e.callee)&&Z.isIdentifier(e.callee.property)&&(e.callee.property.name==="useState"||e.callee.property.name==="useReducer")?e.callee.property.name:null}function qF(e){if(!Z.isNewExpression(e)||!Z.isIdentifier(e.callee,{name:"Proxy"})||e.arguments.length!==2||!Z.isIdentifier(e.arguments[0])||!Z.isObjectExpression(e.arguments[1])||e.arguments[1].properties.length!==1)return null;let[t]=e.arguments[1].properties;if(!Z.isObjectMethod(t)||t.kind!=="method"||t.computed||t.async||t.generator||!Z.isIdentifier(t.key,{name:"get"})||t.params.length!==3||!t.params.every(Z.isIdentifier)||t.body.body.length!==2)return null;let[n,r,o]=t.params,[i,s]=t.body.body;if(Z.isIfStatement(i)&&Z.isBlockStatement(i.consequent)&&i.consequent.body.length!==1)return null;let a=Z.isIfStatement(i)?i.test:null,c=a&&Z.isLogicalExpression(a,{operator:"&&"})?a.right:null,l=Z.isIfStatement(i)?Z.isBlockStatement(i.consequent)?i.consequent.body[0]:i.consequent:null,u=Z.isReturnStatement(s)?s.argument:null;return!a||!Z.isLogicalExpression(a,{operator:"&&"})||!Z.isBinaryExpression(a.left,{operator:"==="})||!Z.isUnaryExpression(a.left.left,{operator:"typeof"})||!Z.isIdentifier(a.left.left.argument,{name:r.name})||!Z.isStringLiteral(a.left.right,{value:"string"})||!Z.isUnaryExpression(c,{operator:"!"})||!Z.isBinaryExpression(c.argument,{operator:"in"})||!Z.isIdentifier(c.argument.left,{name:r.name})||!Z.isIdentifier(c.argument.right,{name:n.name})||!Z.isReturnStatement(l)||!Z.isIfStatement(i)||i.alternate||!Z.isCallExpression(u)||!Z.isMemberExpression(u.callee)||!Z.isIdentifier(u.callee.object,{name:"Reflect"})||!Z.isIdentifier(u.callee.property,{name:"get"})||u.arguments.length!==3||!Z.isIdentifier(u.arguments[0],{name:n.name})||!Z.isIdentifier(u.arguments[1],{name:r.name})||!Z.isIdentifier(u.arguments[2],{name:o.name})?null:e.arguments[0].name}function QF(e){let t=e.getFunctionParent();if(!t)return null;if(t.isFunctionDeclaration()){let s=t.node.id?.name;if(!s)return null;let a=t.parentPath?.isExportDefaultDeclaration()?"default":(t.parentPath?.isExportNamedDeclaration(),s);return{componentName:s,exportName:a}}if(!t.isArrowFunctionExpression()&&!t.isFunctionExpression())return null;let n=t.parentPath;if(!n?.isVariableDeclarator()||!Z.isIdentifier(n.node.id))return null;let r=n.node.id.name,o=n.parentPath,i=o?.parentPath?.isExportDefaultDeclaration()?"default":(o?.parentPath?.isExportNamedDeclaration(),r);return{componentName:r,exportName:i}}function YE(e,t){let n=QF(e.path);if(!n)return null;let r=$o(e,t);return r?{...n,...r}:null}function ZE(e,t,n,r){return e.importedFrom===t?r?e.exportName===r:!0:e.sourceFile===t&&e.tag===n}function ap(e,t){let n=[{kind:"component-prop",file:t.file,displayName:`${t.componentName}.${t.propName}`,canEditHere:!0}];return e.kind==="external"?{...e,chainPrefix:[...n,...e.chainPrefix??[]],editMode:e.editMode==="readonly"?"readonly":"upstream"}:{...e,chainPrefix:[...n,...e.chainPrefix??[]],editMode:"upstream"}}function cp(e,t){for(let n of e.program.body){if(t==="default"&&Z.isExportDefaultDeclaration(n))return Z.isExpression(n.declaration)?{kind:"default-expression",expression:n.declaration}:(Z.isFunctionDeclaration(n.declaration)||Z.isClassDeclaration(n.declaration))&&n.declaration.id?{kind:"default-binding",name:n.declaration.id.name}:null;if(Z.isExportNamedDeclaration(n)){if(n.declaration){if(Z.isVariableDeclaration(n.declaration)){for(let r of n.declaration.declarations)if(Z.isIdentifier(r.id)&&r.id.name===t)return{kind:"local-binding",name:r.id.name}}if((Z.isFunctionDeclaration(n.declaration)||Z.isClassDeclaration(n.declaration))&&n.declaration.id&&n.declaration.id.name===t)return{kind:"local-binding",name:t}}for(let r of n.specifiers)if((Z.isIdentifier(r.exported)?r.exported.name:r.exported.value)===t&&Z.isExportSpecifier(r))return n.source?{kind:"re-export",name:r.local.name,source:n.source.value}:{kind:"local-binding",name:r.local.name}}}return null}function qE(e){let{resolveExternalExpression:t,resolveCollectionCallTarget:n,evaluateStaticExpression:r,resolveSourceInfoProvenance:o,buildExpressionSourceInfo:i}=e;async function s(m){let{currentFile:y,binding:x,readFile:S,exists:b,fileCache:E,visited:k}=m,I=`${y}::${x.kind}::${x.identifier.name}`;if(k.has(I))return null;k.add(I);try{let v=await a({currentFile:y,binding:x,readFile:S,exists:b,fileCache:E,visited:k});if(v)return v;if(x.path.isImportSpecifier()||x.path.isImportDefaultSpecifier())return await g({currentFile:y,binding:x,readFile:S,exists:b,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,fileCache:E,visited:k});if(x.kind==="param")return null;if(x.path.isVariableDeclarator()){let N=x.path.node.init;if(!N||!Z.isExpression(N))return null;let A=qF(N);if(A&&!x.path.scope.getBinding("Proxy")&&!x.path.scope.getBinding("Reflect")){let B=x.path.scope.getBinding(A),X=B?await s({...m,binding:B}):null;if(X?.kind==="static"&&X.value!==null&&!Array.isArray(X.value)&&typeof X.value=="object")return X}let w=x.path.get("init");if(w&&!Array.isArray(w)&&w.isExpression()){let B=await t({currentFile:y,expressionPath:w,readFile:S,exists:b,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:E,visited:k});if(B)return B;if(w.isCallExpression()){let X=await n({currentFile:y,callPath:w,readFile:S,exists:b,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:E,visited:k});if(X)return X}}let F=await r(N,x.path.scope,y,S,b,E,k);return F===void 0?null:{kind:"static",file:y,root:{kind:"binding",name:x.identifier.name},value:F,sourceKind:"binding"}}if(x.path.isIdentifier()&&x.path.parentPath?.isExportDefaultDeclaration()){let N=x.path.parentPath.node.declaration;if(!Z.isExpression(N))return null;let A=await r(N,x.path.scope,y,S,b,E,k);return A===void 0?null:{kind:"static",file:y,root:{kind:"binding",name:x.identifier.name},value:A,sourceKind:"binding"}}return null}finally{k.delete(I)}}async function a(m){let{currentFile:y,binding:x,readFile:S,exists:b,fileCache:E,visited:k}=m;if(!x.path.isVariableDeclarator()||!x.path.get("id").isArrayPattern())return null;let I=x.path,v=I.node.init;if(!v||!Z.isCallExpression(v))return null;let N=ZF(v);if(!N||!Z.isArrayPattern(I.node.id)||I.node.id.elements.findIndex(X=>Z.isIdentifier(X)&&X.name===x.identifier.name)!==0)return null;let w=N==="useReducer"?1:0,F=v.arguments[w];if(!F||!Z.isExpression(F))return null;let B=await r(F,I.scope,y,S,b,E,k);return B===void 0?null:{kind:"static",file:y,root:{kind:"hook-state",name:x.identifier.name,hook:N},value:B,sourceKind:"binding"}}async function c(m){let y=m.expressionPath.scope.getBinding(m.sourceInfo.base);if(!y||!y.constant||y.kind!=="param"||!m.graph)return null;let x=YE(y,m.sourceInfo);if(!x)return null;let S=[...m.graph.elements.values()].filter(E=>ZE(E,m.currentFile,x.componentName,x.exportName));if(!S.length)return null;let b=[];for(let E of S){if(E.sourceFile!==S[0].sourceFile||E.componentName!==S[0].componentName||E.attributeSpreads?.length)return null;let k=await In(E.sourceFile,m.readFile,m.fileCache),I=k.ast?Gc(k.ast,E.sourceRange):null;if(!I)return null;let v=I.parentPath;for(;v&&!v.isFunction();){if(v.isJSXElement()){let $=v.node.openingElement.name;if(!Z.isJSXIdentifier($)||!/^[a-z]/.test($.name))return null}else if(!v.isJSXFragment()&&!v.isReturnStatement()&&!v.isBlockStatement())return null;v=v.parentPath}if(!v)return null;let N=I.get("openingElement").get("attributes").filter($=>$.isJSXAttribute()&&Z.isJSXIdentifier($.node.name,{name:x.propName}));if(N.length!==1)return null;let A=N[0];if(!A?.isJSXAttribute())return null;let w=A.get("value"),F=w.isJSXExpressionContainer()?w.get("expression"):w;if(!F.isExpression())return null;let B=await r(F.node,F.scope,E.sourceFile,m.readFile,m.exists,m.fileCache,m.visited),X=B===void 0?void 0:Pt(B,x.remainingPath);if(X===void 0)return null;b.push(X)}return b}async function l(m){let y=YE(m.binding,m.sourceInfo);if(!y||!m.graph)return null;let x=["component-prop",m.currentFile,m.binding.identifier.start??m.binding.path.node.start??-1,y.componentName,y.propName].join(":");if(m.visited.has(x))return null;m.visited.add(x);try{return await u(m,y,m.graph)}finally{m.visited.delete(x)}}async function u(m,y,x){let S=[...x.elements.values()].filter(A=>ZE(A,m.currentFile,y.componentName,y.exportName));if(S.length!==1)return null;let b=S[0],E=b.attributes?.find(A=>A.name===y.propName);if(E&&!E.source){let A=await d({caller:b,propName:y.propName,remainingPath:y.remainingPath,readFile:m.readFile,fileCache:m.fileCache});if(A)return ap(A,{componentName:y.componentName,propName:y.propName,file:b.sourceFile})}if(!E?.source){let A=await f({caller:b,propName:y.propName,remainingPath:y.remainingPath,readFile:m.readFile,exists:m.exists,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:m.fileCache,visited:m.visited});if(A)return ap(A,{componentName:y.componentName,propName:y.propName,file:b.sourceFile});let w=Yx(m.binding,y.componentName,y.propName);if(!w||w.propName!==y.propName)return null;let F=await r(w.expressionPath.node,w.expressionPath.scope,m.currentFile,m.readFile,m.exists,m.fileCache,m.visited);if(F===void 0)return null;let B=y.remainingPath;return B.length>0&&Pt(F,B)===void 0?null:{kind:"value",file:m.currentFile,root:{kind:"binding",name:y.propName},path:B,sourceKind:"binding",semanticKind:"component-prop",displayExpression:w.displayPath,chainPrefix:[{kind:"component-prop",file:m.currentFile,displayName:w.displayPath,canEditHere:!0}],editMode:"upstream",diagnostics:[]}}let k=await In(b.sourceFile,m.readFile,m.fileCache);if(!k.ast)return null;let I=GE(k.ast,k.source,E.source.expression,E.sourceRange)??xs(k.ast,k.source,E.source.expression);if(!I)return null;let v={...E.source,expression:ti(E.source.expression,y.remainingPath),path:[...E.source.path,...y.remainingPath]},N=await o({currentFile:b.sourceFile,expressionPath:I,sourceInfo:v,readFile:m.readFile,exists:m.exists,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:m.fileCache,visited:m.visited});return N?ap(N.kind==="external"?N:{...N,displayExpression:v.expression},{componentName:y.componentName,propName:y.propName,file:b.sourceFile}):null}async function d(m){let y=await In(m.caller.sourceFile,m.readFile,m.fileCache);if(!y.ast)return null;let x=Gc(y.ast,m.caller.sourceRange);if(!x)return null;let S=x.get("openingElement").get("attributes").find(I=>I.isJSXAttribute()&&I.node.name.type==="JSXIdentifier"&&I.node.name.name===m.propName);if(!S?.isJSXAttribute())return null;let b=S.get("value"),E=b.isStringLiteral()?b:b.isJSXExpressionContainer()?b.get("expression"):null;if(!E?.isExpression())return null;let k=ys(E.node);return k?{kind:"value",file:m.caller.sourceFile,root:{kind:"expression",sourceRange:k},path:m.remainingPath,sourceKind:"binding",semanticKind:"component-prop",displayExpression:m.propName,editMode:"upstream",diagnostics:[]}:null}async function f(m){let y=await In(m.caller.sourceFile,m.readFile,m.fileCache);if(!y.ast)return null;let x=Gc(y.ast,m.caller.sourceRange);if(!x)return null;let S=x.get("openingElement");for(let b of S.get("attributes")){if(!b.isJSXSpreadAttribute())continue;let E=b.get("argument");if(!E.isExpression())continue;let k=await i({expression:E.node,scope:E.scope,source:y.source,currentFile:m.caller.sourceFile,readFile:m.readFile,exists:m.exists,fileCache:m.fileCache,visited:m.visited});if(!k)continue;let I=[{kind:"property",name:m.propName},...m.remainingPath],v={...k,expression:ti(k.expression,I),path:[...k.path,...I]},N=await o({currentFile:m.caller.sourceFile,expressionPath:E,sourceInfo:v,readFile:m.readFile,exists:m.exists,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:m.fileCache,visited:m.visited});if(N)return N.kind==="external"?N:{...N,displayExpression:v.expression}}return null}async function g(m){let{currentFile:y,binding:x,readFile:S,exists:b,fileCache:E,visited:k}=m,I=x.path.parentPath;if(!I||!I.isImportDeclaration())return null;let v=I.node.source.value;if(typeof v!="string")return null;let N=await Jr(y,v,b);if(!N)return null;if(x.path.isImportDefaultSpecifier()){let $=await In(N,S,E),G=$.ast?cp($.ast,"default"):null,D=await p({file:N,exportName:"default",readFile:S,exists:b,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:E,visited:k});return!D||D.kind!=="static"?null:{kind:"static",file:G?.kind==="default-expression"?D.file:N,root:G?.kind==="default-expression"?D.root:{kind:"default-export"},value:D.value,sourceKind:"imported-binding"}}if(!x.path.isImportSpecifier())return null;let A=x.path.node.imported,w=Z.isIdentifier(A)?A.name:A.value,F=await In(N,S,E),B=F.ast?cp(F.ast,w):null,X=await p({file:N,exportName:w,readFile:S,exists:b,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:E,visited:k});return X?X.kind==="external"?X:{kind:"static",file:B?.kind==="re-export"?X.file:N,root:B?.kind==="re-export"||X.root.kind==="binding"&&X.root.name!==B?.name?X.root:{kind:"named-export",name:w},value:X.value,sourceKind:"imported-binding"}:null}async function p(m){let{file:y,exportName:x,readFile:S,exists:b,fileCache:E,visited:k}=m,I=`export::${y}::${x}`;if(!k.has(I)){k.add(I);try{let v=await In(y,S,E);if(!v.ast)return;let N=cp(v.ast,x);if(!N)return;if(N.kind==="default-expression"){let B=N.expression;if(!B||!Z.isIdentifier(B))return;let X=bs(v.ast).getBinding(B.name);return X?await s({currentFile:y,binding:X,readFile:S,exists:b,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:E,visited:k})??void 0:void 0}if(N.kind==="re-export"){if(!N.source||!N.name)return;let B=await Jr(y,N.source,b);return B?p({...m,file:B,exportName:N.name}):void 0}let A=N.name;if(!A)return;let w=bs(v.ast).getBinding(A);return w?await s({currentFile:y,binding:w,readFile:S,exists:b,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:E,visited:k})??void 0:void 0}finally{k.delete(I)}}}return{resolveExportValue:p,resolveComponentPropBinding:l,resolveComponentPropValues:c,resolveBindingTarget:s}}import*as se from"@babel/types";function up(e,t){let n=e.scope.getBinding(t);if(!n)return null;let r=n.path.getFunctionParent();if(!r||!r.isArrowFunctionExpression()&&!r.isFunctionExpression())return null;let o=r.node.params[0],i=En(o,t);if(!i)return null;let s=r.parentPath;return!s||!s.isCallExpression()||!eL(s,r)?null:{callPath:s,basePath:i}}function eL(e,t){let n=e.node.callee;return!se.isMemberExpression(n)||!se.isIdentifier(n.property)||n.property.name!=="map"?!1:e.node.arguments.some(r=>r===t.node)}function nS(e,t){let n=e.get("callee");if(!n.isMemberExpression())return null;let r=n.get("object");return Array.isArray(r)||!r.isExpression()?null:gc(r,t)}function QE(e,t){return e?se.isNumericLiteral(e)&&Number.isInteger(e.value)?e.value:null:t}function eS(e,t,n,r,o){let i=se.isExpression(e.body)?e.body:e.body.body.find(a=>se.isReturnStatement(a))?.argument;if(!i||!se.isExpression(i))return;let s=lp(i,t,n,r,o);return typeof s=="number"?s:void 0}function lp(e,t,n,r,o){if(se.isNumericLiteral(e)||se.isStringLiteral(e)||se.isBooleanLiteral(e))return e.value;if(se.isIdentifier(e))return e.name===t?r:e.name===n?o:void 0;if(se.isMemberExpression(e)){let i=zc(e,t);if(i)return Pt(r,i);let s=zc(e,n);return s?Pt(o,s):void 0}if(se.isBinaryExpression(e)&&e.operator==="-"){let i=se.isExpression(e.left)?lp(e.left,t,n,r,o):void 0,s=se.isExpression(e.right)?lp(e.right,t,n,r,o):void 0;return typeof i=="number"&&typeof s=="number"?i-s:void 0}}function tL(e){if(se.isExpression(e.body))return e.body;for(let t of e.body.body)if(se.isReturnStatement(t)&&t.argument&&se.isExpression(t.argument))return t.argument;return null}function nL(e,t,n){let r=go(e,t,n);return typeof r=="boolean"?r:void 0}function go(e,t,n){if(se.isStringLiteral(e)||se.isNumericLiteral(e)||se.isBooleanLiteral(e))return e.value;if(se.isNullLiteral(e))return null;if(se.isIdentifier(e))return e.name===t?n:void 0;if(se.isMemberExpression(e)){let r=zc(e,t);return r?Pt(n,r):void 0}if(se.isUnaryExpression(e)&&e.operator==="!"){let r=go(e.argument,t,n);return r===void 0?void 0:!r}if(se.isLogicalExpression(e)){let r=go(e.left,t,n);if(r===void 0)return;if(e.operator==="&&")return r&&go(e.right,t,n);if(e.operator==="||")return r||go(e.right,t,n)}if(se.isBinaryExpression(e)){let r=se.isExpression(e.left)?go(e.left,t,n):void 0,o=se.isExpression(e.right)?go(e.right,t,n):void 0;if(r===void 0||o===void 0)return;switch(e.operator){case"===":return r===o;case"!==":return r!==o;case"==":return r==o;case"!=":return r!=o;default:return}}}function rS(e){let t=[],n=e;for(;se.isMemberExpression(n)||se.isOptionalMemberExpression(n);){let r=n.property;if(n.computed)if(se.isNumericLiteral(r))t.unshift({kind:"index",index:r.value});else if(se.isStringLiteral(r))t.unshift({kind:"property",name:r.value});else if(se.isExpression(r))t.unshift({kind:"dynamic",expression:r});else return null;else if(se.isIdentifier(r))t.unshift({kind:"property",name:r.name});else return null;n=n.object}return se.isIdentifier(n)?{base:n.name,segments:t}:null}function oS(e){return e.some(t=>t.kind==="dynamic")}function tS(e){return typeof e=="string"?{kind:"property",name:e}:Number.isInteger(e)?{kind:"index",index:e}:null}function iS(e,t){if(!Array.isArray(e.value))return null;let n=e.collectionPathMap?.length?e.collectionPathMap:e.value.map((r,o)=>[...e.pathPrefix??[],{kind:"index",index:e.collectionIndexMap?.[o]??o}]);return n.length>0?n.map(r=>[...r,...t]):null}function rL(e,t){let n=[],r=[];for(let o of t){let i=Pt(e,o);if(!Array.isArray(i))return null;for(let[s,a]of i.entries())n.push(a),r.push([...o,{kind:"index",index:s}])}return{value:n,collectionPathMap:r}}function sS(e){let{resolveBindingTarget:t,evaluateStaticExpression:n,buildExpressionSourceInfo:r,resolveSourceInfoProvenance:o,resolveComponentPropValues:i}=e;async function s(p){let{currentFile:m,callPath:y,readFile:x,exists:S,fileCache:b,visited:E}=p,k=y.node.callee;if(!se.isMemberExpression(k)||!se.isIdentifier(k.property)||k.property.name!=="map")return null;let I=y.get("callee");if(!I.isMemberExpression())return null;let v=I.get("object");if(Array.isArray(v)||!v.isExpression())return null;let N=await a({currentFile:m,expressionPath:v,readFile:x,exists:S,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:b,visited:E});return!N||!Array.isArray(N.value)||N.value.length===0?null:N}async function a(p){let{currentFile:m,expressionPath:y,readFile:x,exists:S,fileCache:b,visited:E}=p;if(y.isIdentifier()){let k=y.scope.getBinding(y.node.name);if(!k)return null;let I=await t({currentFile:m,binding:k,readFile:x,exists:S,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:b,visited:E});return I?.kind==="static"?I:null}if(y.isCallExpression())return l({currentFile:m,callPath:y,readFile:x,exists:S,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:b,visited:E});if(y.isTSAsExpression()||y.isTSSatisfiesExpression()||y.isTSNonNullExpression()){let k=y.get("expression");if(!Array.isArray(k)&&k.isExpression())return a({...p,expressionPath:k})}if(y.isArrayExpression()){let k=ys(y.node);if(!k)return null;let I=await n(y.node,y.scope,m,x,S,b,E);return Array.isArray(I)?{kind:"static",file:m,root:{kind:"expression",sourceRange:k},value:I,sourceKind:"binding"}:null}if(y.isMemberExpression()){let k=await r({expression:y.node,scope:y.scope,currentFile:m,readFile:x,exists:S,fileCache:b,visited:E});if(!k)return null;let I=await o({currentFile:m,expressionPath:y,sourceInfo:k,readFile:x,exists:S,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:b,visited:E});if(!I||I.kind==="external")return null;let v=await c({currentFile:m,expressionPath:y,provenance:I,readFile:x,exists:S,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:b,visited:E});if(!v||v.kind!=="static")return null;if(I.collectionPathMap?.length){let A=rL(v.value,I.collectionPathMap);if(A)return{kind:"static",file:I.file,root:I.root,value:A.value,sourceKind:I.sourceKind,collectionPathMap:A.collectionPathMap}}let N=Pt(v.value,I.path);return Array.isArray(N)?{kind:"static",file:I.file,root:I.root,value:N,sourceKind:I.sourceKind,pathPrefix:I.path,collectionIndexMap:I.collectionIndexMap,collectionPathMap:I.collectionPathMap}:null}return null}async function c(p){let{provenance:m}=p;if(m.root.kind==="binding"){let b=p.expressionPath.scope.getBinding(m.root.name);if(!b&&m.file!==p.currentFile){let E=await In(m.file,p.readFile,p.fileCache);b=E.ast?bs(E.ast).getBinding(m.root.name):void 0}return b?await t({currentFile:m.file,binding:b,readFile:p.readFile,exists:p.exists,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:p.fileCache,visited:p.visited}):null}if(m.root.kind!=="expression")return null;let y=await In(m.file,p.readFile,p.fileCache);if(!y.ast)return null;let x=HE(y.ast,m.root.sourceRange);if(!x)return null;let S=await n(x.node,x.scope,m.file,p.readFile,p.exists,p.fileCache,p.visited);return S===void 0?null:{kind:"static",file:m.file,root:m.root,value:S,sourceKind:m.sourceKind}}async function l(p){return await u(p)??await d(p)??await f(p)}async function u(p){let{callPath:m}=p,y=m.node.callee;if(!se.isMemberExpression(y)||!se.isIdentifier(y.property)||y.property.name!=="filter")return null;let x=m.get("callee");if(!x.isMemberExpression())return null;let S=x.get("object");if(Array.isArray(S)||!S.isExpression())return null;let b=await a({currentFile:p.currentFile,expressionPath:S,readFile:p.readFile,exists:p.exists,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:p.fileCache,visited:p.visited});if(!b||!Array.isArray(b.value))return null;let[E]=m.node.arguments;if(!se.isArrowFunctionExpression(E)&&!se.isFunctionExpression(E))return null;let k=E.params[0];if(!se.isIdentifier(k))return null;let I=tL(E);if(!I)return null;let v=[],N=[],A=[];for(let[w,F]of b.value.entries()){let B=nL(I,k.name,F);if(typeof B!="boolean")return null;if(B){v.push(F),N.push(b.collectionIndexMap?.[w]??w);let X=b.collectionPathMap?.[w];X&&A.push(X)}}return{...b,value:v,pathPrefix:b.pathPrefix,collectionIndexMap:N,...A.length>0?{collectionPathMap:A}:{}}}async function d(p){let{callPath:m}=p,y=m.node.callee;if(!se.isMemberExpression(y)||!se.isIdentifier(y.property)||y.property.name!=="slice")return null;let x=m.get("callee");if(!x.isMemberExpression())return null;let S=x.get("object");if(Array.isArray(S)||!S.isExpression())return null;let b=await a({currentFile:p.currentFile,expressionPath:S,readFile:p.readFile,exists:p.exists,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:p.fileCache,visited:p.visited});if(!b||!Array.isArray(b.value))return null;let[E,k]=m.node.arguments,I=QE(E,0),v=QE(k,b.value.length);if(I===null||v===null)return null;let N=Math.max(0,I<0?b.value.length+I:I),A=Math.max(0,v<0?b.value.length+v:v),w=b.value.map((B,X)=>b.collectionIndexMap?.[X]??X).slice(N,A),F=b.collectionPathMap?.slice(N,A);return{...b,value:b.value.slice(N,A),pathPrefix:b.pathPrefix,collectionIndexMap:w,...F?{collectionPathMap:F}:{}}}async function f(p){let{callPath:m}=p,y=m.node.callee;if(!se.isMemberExpression(y)||!se.isIdentifier(y.property)||y.property.name!=="sort"&&y.property.name!=="toSorted")return null;let x=m.get("callee");if(!x.isMemberExpression())return null;let S=x.get("object");if(Array.isArray(S)||!S.isExpression())return null;let b=await a({currentFile:p.currentFile,expressionPath:S,readFile:p.readFile,exists:p.exists,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:p.fileCache,visited:p.visited});if(!b||!Array.isArray(b.value))return null;let[E]=m.node.arguments;if(!se.isArrowFunctionExpression(E)&&!se.isFunctionExpression(E))return null;let[k,I]=E.params;if(!se.isIdentifier(k)||!se.isIdentifier(I))return null;let v=b.value.map((A,w)=>({value:A,sourceIndex:b.collectionIndexMap?.[w]??w,originalIndex:w})),N=[...v];for(let A of v)for(let w of v)if(eS(E,k.name,I.name,A.value,w.value)===void 0)return null;return N.sort((A,w)=>{let F=eS(E,k.name,I.name,A.value,w.value)??0;return F===0?A.originalIndex-w.originalIndex:F}),{...b,value:N.map(A=>A.value),pathPrefix:b.pathPrefix,collectionIndexMap:N.map(A=>A.sourceIndex),...b.collectionPathMap?{collectionPathMap:N.map(A=>b.collectionPathMap?.[A.originalIndex]).filter(A=>!!A)}:{}}}async function g(p){let m=null,y=!1,x,S=[];for(let E of p.segments){if(E.kind!=="dynamic")continue;let k=await r({expression:E.expression,scope:p.expressionPath.scope,source:p.fileCache.get(p.currentFile)?.source,currentFile:p.currentFile,readFile:p.readFile,exists:p.exists,fileCache:p.fileCache,visited:p.visited});if(!k)return null;let I=up(p.expressionPath,k.base),v;if(I){y=!0;let N=await s({currentFile:p.currentFile,callPath:I.callPath,readFile:p.readFile,exists:p.exists,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:p.fileCache,visited:p.visited});if(!N||!Array.isArray(N.value))return null;v=N.value.map((A,w)=>{let F=Pt(N.value,[{kind:"index",index:w},...I.basePath,...k.path]);return tS(F)}),x??=N.collectionIndexMap}else{let N=await i({...p,sourceInfo:k});if(!N)return null;v=N.map(tS)}if(v.some(N=>N===null)||m!==null&&m!==v.length)return null;m=v.length,S.push(v)}if(m===null||m===0)return null;let b=[];for(let E=0;E<m;E+=1){let k=[...p.rootPath],I=0;for(let v of p.segments){if(v.kind==="dynamic"){let N=S[I]?.[E];if(!N)return null;k.push(N),I+=1;continue}k.push({...v})}b.push(k)}return{sourceKind:y||m>1?"repeat-template":"binding",...x?{collectionIndexMap:x}:{},collectionPathMap:b}}return{resolveRepeatCollectionTarget:s,resolveCollectionCallTarget:l,resolveDynamicMemberPathMap:g}}var{normalizeExpressionWithScope:oL,evaluateStaticExpression:Yc}=$E({resolveBindingTarget:e=>Zc(e)}),{resolveRepeatCollectionTarget:iL,resolveCollectionCallTarget:sL,resolveDynamicMemberPathMap:aL}=sS({resolveBindingTarget:e=>Zc(e),evaluateStaticExpression:Yc,buildExpressionSourceInfo:$n,resolveSourceInfoProvenance:fn,resolveComponentPropValues:e=>uL(e)}),{resolveExportValue:cL,resolveComponentPropBinding:lL,resolveComponentPropValues:uL,resolveBindingTarget:Zc}=qE({resolveExternalExpression:yp,resolveCollectionCallTarget:sL,evaluateStaticExpression:Yc,resolveSourceInfoProvenance:fn,buildExpressionSourceInfo:$n});function gS(e){return new Map([...e].map(t=>[t.file,{source:t.source,ast:t.ast}]))}var aS=new WeakMap;function dL(e){let t=aS.get(e);return t||(t=new WeakMap,aS.set(e,t)),t}function cS(e,t,n){return{kind:"external",file:e,sourceType:"api-field",sourceId:t,displayPath:n,editMode:"readonly",diagnostics:[{code:"external-source-readonly",message:"Dynamic API data is read-only for content edits"}]}}async function hS(e){let{file:t,source:n,segment:r,readFile:o,exists:i}=e,s=e.fileCache??new Map,a=Hc(s,t,n);if(!a)return null;let c=Wc(a,r.sourceRange);if(!c)return null;let l=await $n({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:o,exists:i,fileCache:s,visited:new Set});if(!l){let f=await Sp({currentFile:t,expressionPath:c,readFile:o,exists:i,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:s,visited:new Set});return f?pp(f,ei(c.node,n)):null}let u=new Set,d=await OL({currentFile:t,expressionPath:c,segment:{...r,source:l},readFile:o,exists:i,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:s,visited:u});return d?pp(d,l.expression):null}async function ni(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=Hc(i,t,n);if(!s)return null;let a=e.sourceRange?Wc(s,e.sourceRange):e.expression!==void 0?xs(s,n,e.expression):null;if(!a)return null;let c=qc(a);if(!c.isIdentifier()&&!c.isMemberExpression())return null;let l=new Set,u=await $n({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:r,exists:o,fileCache:i,visited:l}),d=u?await fn({currentFile:t,expressionPath:c,sourceInfo:u,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:l}):await kS({currentFile:t,expressionPath:c,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:l});return pp(d,e.expression??ei(c.node,n))}async function hp(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=Hc(i,t,n);if(!s)return Yt("unsupported-expression","Unable to parse source for provenance resolution");let a=new Set;return e.target.kind==="text-segment"?fL({file:t,source:n,ast:s,segment:e.target.segment,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:a}):pL({file:t,source:n,ast:s,candidate:e.target.candidate,readFile:r,exists:o,graph:e.graph,fileCache:i,visited:a})}async function $n(e){if(de.isIdentifier(e.expression))return{kind:"identifier",expression:e.expression.name,base:e.expression.name,path:[]};if(!de.isMemberExpression(e.expression))return null;let t=await oL(e.expression,e.scope,e.currentFile,e.readFile,e.exists,e.fileCache,e.visited);return t?{kind:t.path.some(n=>n.kind==="index")?"index-expression":"member-expression",expression:ei(e.expression,e.source),base:t.base,path:t.path}:null}function pp(e,t){if(!e||e.kind==="value"&&e.editMode==="readonly")return null;if(e.kind==="external")return{kind:"external-entry",file:e.file,sourceType:e.sourceType,sourceId:e.sourceId,adapterId:e.adapterId,displayExpression:e.displayPath};let n={kind:"value",root:e.root,path:e.path.length>0?e.path:[]};return{kind:"value-binding",file:e.file,locator:n,root:e.root,path:e.path,displayExpression:e.displayExpression??t,sourceKind:e.sourceKind,...e.collectionIndexMap?{collectionIndexMap:e.collectionIndexMap}:{},...e.collectionPathMap?{collectionPathMap:e.collectionPathMap}:{}}}async function fL(e){let{file:t,source:n,ast:r,segment:o,readFile:i,exists:s,fileCache:a,visited:c}=e,l=Wc(r,o.sourceRange),u=l?await $n({expression:l.node,scope:l.scope,source:n,currentFile:t,readFile:i,exists:s,fileCache:a,visited:c}):null;if(!u){if(!l||l.isStringLiteral()||l.isTemplateLiteral()&&l.node.expressions.length===0)return lS(t,o.value);let f=await Sp({currentFile:t,expressionPath:l,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:c});return f?f.kind==="external"?mS(t,f):gp(t,ei(l.node,n),f):mL({expression:l.node,scope:l.scope,currentFile:t,source:n,readFile:i,exists:s,fileCache:a,visited:c,functionCallContracts:e.functionCallContracts})}if(!l)return Yt("unsupported-expression","Unable to locate text expression for provenance resolution");let d=await fn({currentFile:t,expressionPath:l,sourceInfo:u,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:c});if(!d){let f=mp(l.node);if(f)return Yt(f.code,f.message);let g=l.scope.getBinding(u.base);if(g?.path.isVariableDeclarator()){let p=mp(g.path.node.init);if(p)return Yt(p.code,p.message)}return g?.path.isVariableDeclarator()&&de.isCallExpression(g.path.node.init)?gL("unsupported-expression",SS(g.path.node.init,e.functionCallContracts)):Yt("unsupported-expression",`Unable to resolve provenance for expression "${u.expression}"`)}return d.kind==="external"?mS(t,d):gp(t,u.expression,d)}async function pL(e){let{file:t,source:n,ast:r,candidate:o,readFile:i,exists:s,fileCache:a,visited:c}=e;if(!o.conditionSource)return Yt("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let l=xs(r,n,o.conditionExpression);if(!l)return Yt("conditional-branch-unresolved",`Unable to locate conditional expression "${o.conditionExpression}"`);let u=await fn({currentFile:t,expressionPath:l,sourceInfo:o.conditionSource,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:c});if(!u)return Yt("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);if(u.kind==="external")return Yt("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let d=gp(t,o.conditionExpression,u);return d.finalSource?{...d,finalSource:{...d.finalSource,kind:"conditional-branch",displayPath:o.conditionExpression},chain:[...d.chain,{kind:"conditional-branch",file:u.file,displayName:o.conditionExpression,canEditHere:!0}]}:d}function lS(e,t){return{finalSource:{kind:"jsx-literal",file:e,locator:null,displayPath:t},chain:[{kind:"jsx-literal",file:e,displayName:t,canEditHere:!0}],confidence:"exact",editMode:"direct",diagnostics:[]}}async function mL(e){let t=await xS(e);if(t.length===0)return Yt("unsupported-expression",`Unsupported expression type: ${e.expression.type}`);if(hL(e.expression))return yS(t);if(ES(e.expression))return Yt("unsupported-expression","i18n helpers require a static message id string");if(de.isMemberExpression(e.expression)&&e.expression.computed&&!de.isNumericLiteral(e.expression.property)&&!de.isStringLiteral(e.expression.property))return Yt("dynamic-key","Computed member expressions are not supported for provenance resolution");let[n]=t;return Yt(n.code,n.message)}function Yt(e,t){return{finalSource:null,chain:[],confidence:"unknown",editMode:"unsupported",diagnostics:[{code:e,message:t}]}}function gL(e,t){return yS([{code:e,message:t}])}function yS(e){return{finalSource:null,chain:[],confidence:"partial",editMode:"readonly",diagnostics:e}}function hL(e){return de.isCallExpression(e)||de.isConditionalExpression(e)||de.isLogicalExpression(e)||de.isBinaryExpression(e)}function Ss(e){let t=new Set;return e.filter(n=>{let r=`${n.code}:${n.message}`;return t.has(r)?!1:(t.add(r),!0)})}async function xS(e){let{expression:t,scope:n,currentFile:r,readFile:o,exists:i,fileCache:s,visited:a,functionCallContracts:c}=e,l=mp(t);if(l)return[l];if(de.isCallExpression(t))return[{code:"unsupported-expression",message:SS(t,c)}];if(de.isMemberExpression(t)&&t.computed){let u=t.property;if(!de.isNumericLiteral(u)&&!de.isStringLiteral(u)){if(!de.isExpression(u))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}];let f=await Yc(u,n,r,o,i,s,a);if(typeof f!="string"&&!Number.isInteger(f))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}]}}return de.isBinaryExpression(t)?Ss([...await dp(t.left,t.right,e),{code:"unsupported-expression",message:"Mixed expressions are recognized but remain readonly until a safer composition editing strategy is available"}]):de.isLogicalExpression(t)?Ss([...await dp(t.left,t.right,e),{code:"unsupported-expression",message:t.operator==="??"||t.operator==="||"?"Fallback expressions are recognized but remain readonly until a safer composition editing strategy is available":"Complex conditional expressions are recognized but remain readonly until a safer editing strategy is available"}]):de.isConditionalExpression(t)?Ss([...await dp(t.test,t.consequent,t.alternate,e),{code:"unsupported-expression",message:"Complex conditional expressions are recognized but remain readonly until a safer editing strategy is available"}]):[]}function mp(e){return ES(e)?uS("i18n helpers require a static message id string"):SL(e)?uS("CMS helpers require static entry id and field path string arguments"):null}async function dp(...e){let t=e[e.length-1],n=e.slice(0,-1),r=[];for(let o of n)r.push(...await xS({...t,expression:o}));return r}function yL(e,t){let n=(t??[]).filter(r=>r.sourceType===e.sourceType&&(r.capabilities===void 0||r.capabilities.includes("write-text")));if(e.adapterId){let r=n.find(o=>o.adapterId===e.adapterId);if(r)return{adapterId:r.adapterId,editMode:"proxy",diagnostics:[]}}else if(n.length>0)return{adapterId:n[0]?.adapterId,editMode:"proxy",diagnostics:[]};return{adapterId:void 0,editMode:"readonly",diagnostics:[xL(e.sourceType)]}}async function yp(e){for(let n of _L){if(!dS(e.expressionPath,n.helperNames))continue;let r=await n.resolve(e);if(r)return pS(fS(r),e.externalAdapters)}let t={currentFile:e.currentFile,expressionPath:e.expressionPath,readFile:e.readFile,exists:e.exists,graph:e.graph};for(let n of e.externalSourceResolvers??[]){if(!dS(e.expressionPath,n.helperNames))continue;let r=await n.resolve(t);if(r)return pS(fS(r),e.externalAdapters)}return null}function xL(e){return{code:"missing-adapter",message:`No external adapter is registered for ${e}`}}function bL(e){return{code:"external-source-readonly",message:e}}function uS(e){return{code:"unsupported-expression",message:e}}function xp(e){return!e||!de.isCallExpression(e)?null:de.isIdentifier(e.callee)?e.callee.name:de.isMemberExpression(e.callee)&&!e.callee.computed&&de.isIdentifier(e.callee.object)&&de.isIdentifier(e.callee.property)?`${e.callee.object.name}.${e.callee.property.name}`:null}function dS(e,t){if(!t||t.length===0)return!0;let n=xp(e.node);return n?t.includes(n):!1}function fS(e){return"match"in e?{match:e.match,editMode:e.editMode,diagnostics:Ss(e.diagnostics??[])}:{match:e,diagnostics:[]}}function pS(e,t){let n=yL(e.match,t);return{kind:"external",file:e.match.file,sourceType:e.match.sourceType,sourceId:e.match.sourceId,adapterId:e.match.adapterId??n.adapterId,displayPath:e.match.displayPath,editMode:e.editMode==="readonly"?"readonly":n.editMode,diagnostics:Ss([...e.diagnostics,...e.editMode==="readonly"||n.editMode==="readonly"?n.diagnostics:[]])}}function EL(e){if(!e.isCallExpression())return null;let t=e.node.callee;if(!de.isIdentifier(t)||t.name!=="getCmsField")return null;let[n,r]=e.node.arguments;if(!n||!r||!de.isStringLiteral(n)||!de.isStringLiteral(r))return null;let o=n.value,i=r.value;return{sourceType:"cms-field",sourceId:`${o}:${i}`,file:`cms://${o}/${i.replace(/\./g,"/")}`,displayPath:`${o}.${i}`}}function SL(e){return!!e&&de.isCallExpression(e)&&de.isIdentifier(e.callee)&&e.callee.name==="getCmsField"&&(e.arguments.length<2||!de.isStringLiteral(e.arguments[0])||!de.isStringLiteral(e.arguments[1]))}function bS(e){if(!(!e||!de.isCallExpression(e))){if(de.isIdentifier(e.callee)&&e.callee.name==="t"){let[t]=e.arguments;return t&&de.isStringLiteral(t)?t.value:null}if(de.isMemberExpression(e.callee)&&!e.callee.computed&&de.isIdentifier(e.callee.object)&&e.callee.object.name==="intl"&&de.isIdentifier(e.callee.property)&&e.callee.property.name==="formatMessage"){let[t]=e.arguments;if(!t||!de.isObjectExpression(t))return null;for(let n of t.properties)if(de.isObjectProperty(n)&&!n.computed&&(de.isIdentifier(n.key)&&n.key.name==="id"||de.isStringLiteral(n.key)&&n.key.value==="id")&&de.isStringLiteral(n.value))return n.value.value;return null}}}function ES(e){return bS(e)===null}async function IL(e,t,n){let r=new Set,o=Es.posix.dirname(e);for(;r.add(o),!(o==="."||o==="/");){let i=Es.posix.dirname(o);if(i===o){r.add(".");break}o=i}r.add("src"),r.add(".");for(let i of r){let s=i==="."?["locales","messages"]:[Es.posix.join(i,"locales"),Es.posix.join(i,"messages")];for(let a of s){let c=Es.posix.join(a,`${t}.json`);if(await n(c))return c}}return null}async function vL(e){let t=bS(e.expressionPath.node);if(typeof t!="string"||t.length===0)return null;let n="en",r=await IL(e.currentFile,n,e.exists);return r?{sourceType:"i18n-message",sourceId:`${n}:${t}`,file:r,displayPath:t}:null}async function kL(e){if(!e.expressionPath.isCallExpression())return null;let t=e.expressionPath.node.callee;if(!de.isIdentifier(t)||t.name!=="apiField")return null;let[n,r]=e.expressionPath.node.arguments;if(!n||!de.isExpression(n))return null;let o=await Yc(n,e.expressionPath.scope,e.currentFile,e.readFile,e.exists,e.fileCache,e.visited);if(typeof o!="string"||o.length===0)return null;let i={sourceType:"api-field",sourceId:o,file:`api://${o}`,displayPath:o};return r?{match:i,editMode:"readonly",diagnostics:[bL("API mapping transforms must stay readonly until a reversible mapping strategy is registered")]}:i}var _L=[{helperNames:["getCmsField"],resolve:({expressionPath:e})=>EL(e)},{helperNames:["apiField"],resolve:e=>kL(e)},{helperNames:["t","intl.formatMessage"],resolve:({currentFile:e,expressionPath:t,exists:n})=>vL({currentFile:e,expressionPath:t,exists:n})}];function bp(e){return{...e,editMode:"readonly",diagnostics:[{code:"unsupported-expression",message:"Derived display values are readonly because no identity-preserving write target exists"}]}}function mS(e,t){return{finalSource:{kind:t.sourceType,file:t.file,locator:null,displayPath:t.displayPath,externalSource:{sourceType:t.sourceType,sourceId:t.sourceId,adapterId:t.adapterId}},chain:[...t.chainPrefix??[],{kind:t.sourceType,file:t.file,displayName:t.displayPath,canEditHere:t.editMode!=="readonly"}],confidence:"exact",editMode:t.editMode==="direct"?t.file===e?"direct":"proxy":t.editMode,diagnostics:t.diagnostics}}function gp(e,t,n){let r={kind:"value",root:n.root,path:n.path.length>0?n.path:[]},o=n.path.some(l=>l.kind==="index"),i=wL(n),s;n.semanticKind?s=n.semanticKind:i?s="config-entry":n.sourceKind==="repeat-template"?s="repeat-template":n.path.length===0?s=n.sourceKind==="imported-binding"?"imported-binding":"binding":s=o?"array-item":"object-field";let a=n.displayExpression??t,c=[...n.chainPrefix??[]];return n.sourceKind==="binding"?c.push({kind:"binding",file:n.file,displayName:n.root.kind==="binding"?n.root.name:a,canEditHere:n.editMode!=="readonly"}):n.sourceKind==="imported-binding"?c.push({kind:"imported-binding",file:n.file,displayName:n.root.kind==="named-export"?n.root.name:"default",canEditHere:n.editMode!=="readonly"}):n.sourceKind==="repeat-template"&&c.push({kind:"repeat-template",file:n.file,displayName:t,canEditHere:n.editMode!=="readonly"}),n.path.length>0&&n.sourceKind!=="repeat-template"&&c.push({kind:o?"array-item":"object-field",file:n.file,displayName:a,canEditHere:n.editMode!=="readonly"}),i&&c.push({kind:"config-entry",file:n.file,displayName:i.displayPath,canEditHere:n.editMode!=="readonly"}),{finalSource:{kind:s,file:n.file,locator:r,root:n.root,path:n.path,displayPath:a,externalSource:i?{sourceType:"config-entry",sourceId:i.sourceId}:void 0},chain:n.editMode==="readonly"?c.map(l=>({...l,canEditHere:!1})):c,confidence:n.sourceKind==="repeat-template"?"safe-derived":"exact",editMode:n.editMode??(n.file===e?"direct":"proxy"),diagnostics:n.diagnostics??[]}}var CL=[{helperName:"formatPrice",purity:"pure",sourceArgIndex:0},{helperName:"formatDate",purity:"pure",sourceArgIndex:0},{helperName:"pickLabel",purity:"pure",sourceArgIndex:0}];function Ep(e,t){let n=[...CL,...t??[]];for(let r=n.length-1;r>=0;r-=1){let o=n[r];if(o?.helperName===e)return o}return null}function SS(e,t){let n=e.callee;return de.isIdentifier(n)&&Ep(n.name,t)?.purity==="side-effect"?`Helper "${n.name}" is registered as side-effectful and remains readonly`:"Function calls remain readonly because purity does not establish an identity-preserving write target"}async function Sp(e){let t=await yp(e);if(t)return t;let n=await IS({...e,expressionPath:e.expressionPath});if(n)return n;if(e.expressionPath.isTemplateLiteral()){let r=e.expressionPath.node.expressions[0],o=e.expressionPath.get("expressions.0");if(e.expressionPath.node.expressions.length===1&&r&&o&&!Array.isArray(o)&&o.isExpression()){let i=await $n({expression:o.node,scope:o.scope,source:e.fileCache.get(e.currentFile)?.source,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(i){let s=await fn({...e,expressionPath:o,sourceInfo:i});if(s&&s.kind==="value")return{...s,displayExpression:i.expression,editMode:"readonly",diagnostics:[{code:"unsupported-expression",message:"Mixed expressions are recognized but remain readonly until a safer composition editing strategy is available"}]}}}}return await AL(e)}async function IS(e){let t=await vn({...e,allowComposed:!1});if(t?.kind!=="source")return null;let n=qc(e.expressionPath);return n.isIdentifier()||n.isMemberExpression()?t.provenance:bp(t.provenance)}async function vn(e){let t=qc(e.expressionPath),n=PL(e.currentFile,t.node);if(n&&e.visited.has(n))return null;n&&e.visited.add(n);try{if(t.isStringLiteral()||t.isNumericLiteral()||t.isBooleanLiteral()||t.isNullLiteral())return{kind:"none"};if(t.isIdentifier()){let r=await $n({expression:t.node,scope:t.scope,source:e.fileCache.get(e.currentFile)?.source,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(!r)return null;let o=await fn({currentFile:e.currentFile,expressionPath:t,sourceInfo:r,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});return!o||o.kind==="external"?null:{kind:"source",provenance:o}}if(t.isMemberExpression()){let r=await $n({expression:t.node,scope:t.scope,source:e.fileCache.get(e.currentFile)?.source,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(!r)return null;let o=await fn({currentFile:e.currentFile,expressionPath:t,sourceInfo:r,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});return!o||o.kind==="external"?null:{kind:"source",provenance:o}}if(t.isConditionalExpression()){let r=t.get("test"),o=t.get("consequent"),i=t.get("alternate");if(Array.isArray(r)||Array.isArray(o)||Array.isArray(i)||!r.isExpression()||!o.isExpression()||!i.isExpression())return null;let s=await vn({...e,expressionPath:r,allowComposed:!0}),a=await vn({...e,expressionPath:o,allowComposed:!1}),c=await vn({...e,expressionPath:i,allowComposed:!1});return fp(s,a,c)}if(t.isCallExpression())return RL({...e,expressionPath:t});if(!e.allowComposed)return null;if(t.isBinaryExpression()){let r=t.get("left"),o=t.get("right");if(Array.isArray(r)||Array.isArray(o)||!r.isExpression()||!o.isExpression())return null;let i=await vn({...e,expressionPath:r,allowComposed:!0}),s=await vn({...e,expressionPath:o,allowComposed:!0});return fp(i,s)}if(t.isLogicalExpression()){let r=t.get("left"),o=t.get("right");if(Array.isArray(r)||Array.isArray(o)||!r.isExpression()||!o.isExpression())return null;let i=await vn({...e,expressionPath:r,allowComposed:!0}),s=await vn({...e,expressionPath:o,allowComposed:!0});return fp(i,s)}if(t.isUnaryExpression()){let r=t.get("argument");return Array.isArray(r)||!r.isExpression()?null:vn({...e,expressionPath:r,allowComposed:!0})}return null}finally{n&&e.visited.delete(n)}}function qc(e){let t=e;for(;t.isParenthesizedExpression()||t.isTSAsExpression()||t.isTSSatisfiesExpression()||t.isTSNonNullExpression()||t.isTSTypeAssertion();){let n=t.get("expression");if(Array.isArray(n)||!n.isExpression())return t;t=n}return t}async function RL(e){let t=xp(e.expressionPath.node);if(t==="Math.round"||t==="Math.floor"||t==="Math.ceil"||t==="Math.trunc"||t==="useCountUp"){let r=e.expressionPath.get("arguments.0");return!r||Array.isArray(r)||!r.isExpression()?null:vn({...e,expressionPath:r,allowComposed:!1})}let n=e.expressionPath.get("callee");if(n.isMemberExpression()&&!n.node.computed){let r=n.node.property;if(de.isIdentifier(r)&&(r.name==="toFixed"||r.name==="toString")){let o=n.get("object");return Array.isArray(o)||!o.isExpression()?null:vn({...e,expressionPath:o,allowComposed:!1})}}return null}function fp(...e){let t=null;for(let n of e){if(!n)return null;if(n.kind!=="none"){if(!t){t=n.provenance;continue}if(!NL(t,n.provenance))return null}}return t?{kind:"source",provenance:t}:{kind:"none"}}function NL(e,t){return e.file===t.file&&e.sourceKind===t.sourceKind&&JSON.stringify(e.root)===JSON.stringify(t.root)&&JSON.stringify(e.path)===JSON.stringify(t.path)&&JSON.stringify(e.collectionIndexMap??null)===JSON.stringify(t.collectionIndexMap??null)&&JSON.stringify(e.collectionPathMap??null)===JSON.stringify(t.collectionPathMap??null)}function PL(e,t){return t.start==null||t.end==null?null:`safe-derived:${e}:${t.start}:${t.end}`}async function AL(e){if(!e.expressionPath.isCallExpression())return null;let t=xp(e.expressionPath.node);if(!t)return null;let n=Ep(t,e.functionCallContracts);if(!n||n.purity!=="pure")return null;let r=n.sourceArgIndex??0,o=e.expressionPath.get(`arguments.${r}`);if(!o||Array.isArray(o)||!o.isExpression())return null;let i=await vS({currentFile:e.currentFile,argumentPath:o,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});return i?bp(i):null}async function vS(e){let t=await yp({currentFile:e.currentFile,expressionPath:e.argumentPath,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(t)return t;let n=await $n({expression:e.argumentPath.node,scope:e.argumentPath.scope,source:e.fileCache.get(e.currentFile)?.source,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(n){let r=await fn({currentFile:e.currentFile,expressionPath:e.argumentPath,sourceInfo:n,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});return!r||r.kind==="external"?r:{...r,displayExpression:n.expression}}return await Sp({currentFile:e.currentFile,expressionPath:e.argumentPath,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited})}async function TL(e){if(!e.binding.path.isVariableDeclarator())return null;let t=e.binding.path.node.init;if(!t||!de.isCallExpression(t))return null;let n=t.callee;if(!de.isIdentifier(n))return null;let r=Ep(n.name,e.functionCallContracts);if(!r||r.purity!=="pure")return null;let o=r.sourceArgIndex??0,i=e.binding.path.get("init");if(!i||Array.isArray(i)||!i.isCallExpression())return null;let s=i.get(`arguments.${o}`);if(!s||Array.isArray(s)||!s.isExpression())return null;let a=await vS({currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited,argumentPath:s});return a?bp(a):null}function wL(e){if(e.sourceKind!=="imported-binding")return null;let t=e.root.kind==="binding"||e.root.kind==="named-export"?e.root.name:e.root.kind==="default-export"?"default":null;if(!t)return null;let n=/(^|[\/.-])(config|settings)([\/.-]|$)/i.test(e.file),r=/config|settings/i.test(t);if(!n&&!r)return null;let o=ti(t,e.path);return{sourceId:o,displayPath:o}}async function OL(e){let t=e.segment.source;return t?fn({currentFile:e.currentFile,expressionPath:e.expressionPath,sourceInfo:t,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited}):null}async function fn(e){let t=e.sourceInfo,n=up(e.expressionPath,t.base);if(n){let l=await iL({currentFile:e.currentFile,callPath:n.callPath,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,fileCache:e.fileCache,visited:e.visited});if(!l){let m=nS(n.callPath,[...n.basePath,...t.path]);return os(m)?cS(e.currentFile,m.sourceId,m.displayPath):null}let u=iS(l,[...n.basePath,...t.path]),d=l.collectionIndexMap?.[0]??0,f=[...l.pathPrefix??[],{kind:"index",index:d},...n.basePath,...t.path],g=[{kind:"index",index:0},...n.basePath,...t.path];return Pt(l.value,g)===void 0?null:{kind:"value",file:l.file,root:l.root,path:u?.[0]??f,sourceKind:"repeat-template",collectionIndexMap:l.collectionIndexMap,...u?{collectionPathMap:u}:{}}}let r=e.expressionPath.scope.getBinding(t.base);if(!r)return null;if(r.path.isImportNamespaceSpecifier()){let l=t.path[0],u=r.path.parentPath;if(!l||l.kind!=="property"||!u?.isImportDeclaration())return null;let d=await Jr(e.currentFile,u.node.source.value,e.exists);if(!d)return null;let f=await cL({file:d,exportName:l.name,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(!f||f.kind==="external")return null;let g=t.path.slice(1);return Pt(f.value,g)===void 0?null:{kind:"value",file:f.file,root:f.root,path:g,sourceKind:"imported-binding",collectionIndexMap:f.collectionIndexMap}}let o=Wx(r);if(o){let l=o.expressionPath,u=await $n({expression:l.node,scope:l.scope,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(u){let d=await fn({...e,expressionPath:l,sourceInfo:{...u,expression:ti(u.expression,t.path),path:[...u.path,...t.path]}});if(d)return d}else if(r.constant){let d=`dynamic-alias:${e.currentFile}:${l.node.start}`;if(e.visited.has(d))return null;e.visited.add(d);try{let f=await kS({...e,expressionPath:qc(l),memberSuffix:t.path});if(f?.kind==="value")return f}finally{e.visited.delete(d)}}if(t.path.length===0){let d=await IS({currentFile:e.currentFile,expressionPath:l,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(d)return d}}if(r.kind==="param")return lL({currentFile:e.currentFile,binding:r,sourceInfo:t,graph:e.graph,readFile:e.readFile,exists:e.exists,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});let i=await TL({currentFile:e.currentFile,binding:r,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(i)return i;let s=pc(r,t.path,dL(e.fileCache));if(os(s))return cS(e.currentFile,s.sourceId,s.displayPath);let a=await Zc({currentFile:e.currentFile,binding:r,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});return a?a.kind==="external"?t.path.length===0?a:null:Pt(a.value,t.path)===void 0?null:{kind:"value",file:a.file,root:a.root,path:t.path,sourceKind:a.sourceKind,collectionIndexMap:a.collectionIndexMap}:null}async function kS(e){let t=rS(e.expressionPath.node);if(!t||!oS(t.segments))return null;let n=await fn({currentFile:e.currentFile,expressionPath:e.expressionPath,sourceInfo:{kind:"identifier",expression:t.base,base:t.base,path:[]},readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(!n||n.kind==="external")return n;let r=await aL({...e,rootPath:n.path,segments:t.segments});if(!r)return null;let o=r.collectionPathMap.map(i=>[...i,...e.memberSuffix??[]]);if(e.memberSuffix){let i=e.expressionPath.scope.getBinding(t.base),s=i?await Zc({...e,binding:i}):null;if(s?.kind!=="static"||o.some(a=>Pt(s.value,a.slice(n.path.length))===void 0))return null}return{...n,path:o[0]??n.path,sourceKind:r.sourceKind,displayExpression:ei(e.expressionPath.node,e.fileCache.get(e.currentFile)?.source),...r.collectionIndexMap?{collectionIndexMap:r.collectionIndexMap}:{},collectionPathMap:o}}async function _S(e){let t=FL(e.propertyName);if(t.owner==="blocked")return Or(t.owner,t.diagnostic);if(t.owner==="class-name-source"||t.owner==="style")return Or(t.owner,{code:"owner-delegated",message:`Property '${e.propertyName}' is owned by ${t.owner}`});let n=e.element.attributes?.filter(l=>l.name===e.propertyName)??[];if(n.length>1)return Or("generic",{code:"duplicate-property-source",message:`Property '${e.propertyName}' has multiple explicit sources`});let r=n[0],o=[];r&&o.push({kind:"attribute",order:r.order??e.element.attributes.indexOf(r),attribute:r});let i=e.element.attributeSpreads??[];for(let l of i)o.push({kind:"spread",order:l.order,spread:l,target:await ML(e,l)});o.sort((l,u)=>l.order-u.order);let s=o.at(-1);if(!s)return{status:"missing",owner:"generic"};if(o.filter(l=>l.kind==="spread"&&l.order>s.order).some(l=>!l.target))return Or("generic",{code:"ambiguous-property-source",message:`A spread may provide or override property '${e.propertyName}'`});if(s.kind==="spread")return s.target?{status:"binding",owner:"generic",target:s.target}:Or("generic",{code:"ambiguous-property-source",message:`The final spread source for '${e.propertyName}' is not provably writable`});let c=o.filter(l=>l.kind==="spread"&&l.order<s.order);return e.operation==="remove"&&c.length>0?Or("generic",{code:"remove-exposes-spread",message:`Removing '${e.propertyName}' would expose an earlier spread source`}):LL(e,s.attribute)}async function LL(e,t){if(t.resolution&&t.resolution.status!=="resolved"&&!t.source){let r=await ni({file:e.file,source:e.source,sourceRange:t.sourceRange,expression:t.value,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache});return r&&r.kind!=="external-entry"?{status:"binding",owner:"generic",attribute:t,target:{kind:"value-binding",target:r}}:Or("generic",{code:"unsupported-property-source",message:`Property '${e.propertyName}' has an unresolved value source`})}if(!t.source?.expression)return{status:"direct",owner:"generic",attribute:t,target:{kind:"jsx-attribute",file:e.file,sourceRange:t.sourceRange}};let n=await ni({file:e.file,source:e.source,sourceRange:t.sourceRange,expression:t.source.expression,sourceInfo:t.source,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache});return!n||n.kind==="external-entry"?Or("generic",{code:"unsupported-property-source",message:`Property '${e.propertyName}' does not have a local writable source`}):{status:"binding",owner:"generic",attribute:t,target:{kind:"value-binding",target:n}}}async function ML(e,t){let n=t.source?.expression;if(!n)return;let r=await ni({file:e.file,source:e.source,sourceRange:t.sourceRange,expression:n,sourceInfo:t.source,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache});if(!(!r||r.kind==="external-entry"))return{kind:"value-binding",target:DL(r,e.propertyName)}}function DL(e,t){let n=[...e.path??[],{kind:"property",name:t}];return{...e,path:n,locator:e.locator?{...e.locator,path:n}:{kind:"value",root:e.root??{kind:"binding",name:t},path:n}}}function Or(e,t){return{status:"blocked",owner:e,...t?{diagnostic:t}:{}}}function CS(e){let t=new Map;for(let r of e.elements.values()){if(r.importedFrom===void 0)continue;let o=t.get(r.importedFrom);o||(o={candidates:[],keys:new Map},t.set(r.importedFrom,o)),o.candidates.push(r)}let n=r=>{if(ho(r.tag))return r.identity.key;let o=t.get(r.sourceFile);if(!o)return null;if(o.keys.has(r.componentName))return o.keys.get(r.componentName);let i=o.candidates.filter(a=>VL(a,r.componentName)),s=i.length===1?i[0].identity.key:null;return o.keys.set(r.componentName,s),s};return r=>BL({...r,graph:e},n)}function BL(e,t){let{key:n,element:r,graph:o,provenances:i}=e,s=$L(n,r,o,t),a=s?.tag??(ho(r.tag)?r.tag:r.componentName),c=s?.identity.key??t(r,o)??n,l=KL(s),u=JL(n,r,o,i,s),d=jL(n,r,o,i,c);return{componentName:a,instanceKey:c,templateOwner:UL(s??r,a),...l.length>0?{variantKeys:l}:{},...u.length>0?{slotKeys:u}:{},editableStrategy:d,impactScope:XL(d),alternativeStrategies:zL(d)}}function jL(e,t,n,r,o){for(let i of r.values())if(i?.editMode==="upstream")return"upstream";return Ip(e,n)?"instance":!ho(t.tag)&&t.sourceFile!==n.routeId&&o!==e?"template":"instance"}function $L(e,t,n,r){if(ho(t.tag))return t;let o=Ip(e,n);if(o)return o;let i=r(t,n);return i?n.elements.get(i)??null:null}function VL(e,t){return e.exportName===t||e.tag===t||e.exportName==="default"}function UL(e,t){return ho(e.tag)&&e.importedFrom?`${e.importedFrom}#${t}`:`${e.sourceFile}#${t}`}function KL(e){if(!e?.attributes)return[];let t=new Set(["variant","size","tone"]);return e.attributes.filter(n=>t.has(n.name)).map(n=>n.name)}function JL(e,t,n,r,o){let i=new Set,s=Ip(e,n);s&&o?.identity.key===s.identity.key&&i.add("children");for(let a of r.values()){let c=a?.chain.find(u=>u.kind==="component-prop");if(!c)continue;let l=c.displayName.split(".").pop();l&&i.add(l)}return i.size===0&&ho(t.tag)&&t.childKeys.length>0&&i.add("children"),[...i]}function Ip(e,t){let n=t.elements.get(e)?.parentKey??null;for(;n;){let r=t.elements.get(n);if(!r)break;if(ho(r.tag))return r;n=r.parentKey}return null}function ho(e){return/^[A-Z]/.test(e)}function XL(e){switch(e){case"template":return"component-template";case"upstream":return"upstream-source";default:return"current-instance"}}function zL(e){switch(e){case"template":return["instance"];case"upstream":return["template"];default:return["template"]}}function PS(e){let t=e.isRepeat??(e.graph?tM(e.element,e.graph):!1),n=e.propertyProvenance??new Map,r=e.repeatTargets??new Map,o=eM(e.element.attributes??[]),i=[...r.values()].some(u=>u.ok),s=o.map(u=>HL({attribute:u,element:e.element,isRepeat:t,selectionRef:e.selectionRef,provenance:n.get(u.name),repeatTarget:r.get(u.name)})),a=(e.element.attributeSpreads?.length??0)>0,c=(e.element.attributeSpreads??[]).slice().sort((u,d)=>u.order-d.order).map(u=>({raw:u.raw,sourceRange:nM(u.sourceRange,e.source),order:u.order,diagnostics:u.source?[]:[{code:"unsupported-spread-source",message:"The spread source cannot be resolved safely, so property ownership is conservative."}]})),l=t&&e.selectionRef?.instanceIndex!==void 0&&i;return{documentVersion:e.documentVersion,...e.selectionRef?{selectionRef:e.selectionRef}:{},items:s,spreads:c,creation:t?{selection:l?"materialize":"unsupported",template:"unsupported"}:{selection:a?"unsupported":"direct",template:a?"unsupported":"direct"}}}function HL(e){let{attribute:t,provenance:n,repeatTarget:r}=e,o=e.selectionRef?.instanceIndex!==void 0&&r?.ok===!0?r:null,i=WL(t,n,e.isRepeat),s=["selection","template"].map(y=>({scope:y,result:Ic({state:n,scope:y,operation:"set",selectionRef:e.selectionRef,isRepeat:e.isRepeat,repeatTarget:r})})),a=s.find(({result:y})=>y.ok)?.result,c=a?.ok?a.target:void 0,l=c?.kind==="value-binding"&&o&&(JSON.stringify(c.locator.root)!==JSON.stringify(o.selectedParentObjectLocator.root)||JSON.stringify(c.locator.path??[])!==JSON.stringify([...o.selectedParentObjectLocator.path??[],{kind:"property",name:t.name}]))?null:o,u=GL(t,n,l,e.isRepeat),d=c?qL(c,e.element,t.name):void 0,f=s.filter(({result:y})=>y.ok).map(({scope:y})=>y),g=f.length>0?ZL(n,o,e.element):"unsupported",p=o?"repeat-item":e.isRepeat?"repeat-template":"node",m=QL(t,n,r);if(f.length===0&&m.length===0){let y=s.find(({result:x})=>!x.ok)?.result;y&&!y.ok&&m.push({code:y.code,message:y.reason})}return{name:t.name,source:i,resolution:u,editMode:g,sourceScope:p,allowedWriteScopes:f,...d?{effectiveWriteTarget:d}:{},diagnostics:m}}function WL(e,t,n){let r;if(n&&t?.status==="binding"){let o=t.target;r=o?.kind==="value-binding"&&o.target.sourceKind==="repeat-template"?"repeat-template":"binding"}else e.syntaxKind==="boolean-shorthand"?r="boolean-shorthand":e.syntaxKind==="literal"||!e.source?r="literal":r="expression";return{kind:r,...e.raw!==void 0?{raw:e.raw}:{}}}function GL(e,t,n,r){return n?RS(n.selectedResolution):t?.status==="blocked"?{status:"unresolved"}:r&&t?.status==="binding"?{status:"unresolved"}:RS(YL(e))}function YL(e){return e.resolution?e.resolution:e.syntaxKind==="boolean-shorthand"?{status:"resolved",value:!0}:e.resolvedValue!==void 0?{status:"resolved",value:e.resolvedValue}:e.source?{status:"unresolved"}:{status:"resolved",value:e.value}}function RS(e){return!e||e.status==="unresolved"?{status:"unresolved"}:e.status==="undefined"?{status:"undefined"}:{status:"resolved",value:e.value}}function ZL(e,t,n){if(t)return"direct";if(!e||e.status==="blocked")return"unsupported";if(e.status==="missing"||e.status==="direct")return"direct";let r=e.target;return r?.kind!=="value-binding"?"unsupported":r.target.file===n.sourceFile?"direct":"proxy"}function qL(e,t,n){return e.kind==="repeat-property"?{kind:"value-path",file:e.target.sourceFile,isProxy:e.target.sourceFile!==t.sourceFile,displayPath:NS({...e.target.selectedParentObjectLocator,path:[...e.target.selectedParentObjectLocator.path??[],{kind:"property",name:n}]})}:e.kind==="value-binding"?{kind:"value-path",file:e.file,isProxy:e.file!==t.sourceFile,displayPath:NS(e.locator)}:{kind:"jsx-node",file:t.sourceFile,isProxy:!1,displayPath:t.componentName+" > "+n}}function QL(e,t,n){let r=[];return t?.diagnostic&&r.push({code:t.diagnostic.code,message:t.diagnostic.message}),n&&!n.ok&&t?.status!=="missing"&&r.push({code:`repeat-${n.errorCode}`,message:n.reason}),e.resolution?.status==="unresolved"&&r.length===0&&r.push({code:"unsupported-property-source",message:`Property '${e.name}' has an unresolved value source`}),r}function eM(e){let t=new Set;return e.filter(n=>t.has(n.name)?!1:(t.add(n.name),!0))}function tM(e,t){let n=t.regions.filter(r=>r.kind==="repeat-region");for(let r of n){let o=e;for(;o;){if(r.childKeys.includes(o.identity.key))return!0;o=o.parentKey?t.elements.get(o.parentKey):void 0}}return!1}function NS(e){return`${e.root.kind==="binding"?e.root.name:e.root.kind==="expression"?e.root.sourceRange?"expression":"value":e.root.kind}${(e.path??[]).map(n=>n.kind==="index"?`[${n.index}]`:`.${n.name}`).join("")}`}function nM(e,t){if(!t)return{start:e.startColumn,end:e.endColumn};let n=t.split(`
7
+ `),r=(o,i)=>n.slice(0,Math.max(0,o-1)).reduce((s,a)=>s+a.length+1,0)+i;return{start:r(e.startLine,e.startColumn),end:r(e.endLine,e.endColumn)}}function rM(e){return e==="api-field"||e==="cms-field"||e==="i18n-message"||e==="config-entry"}var oM=160;function AS(e,t,n,r={}){let o=Ro(e),i=[];for(let[s,a]of e.elements){let c=n.get(s),l={canUpdateText:r.canUpdateTextByKey?.get(s)??c?.canUpdateText??!1,canInsertChild:c?.canInsertChild??!1,canMove:c?.canMove??!1,canRemove:c?.canRemove??!1};i.push({key:s,tag:a.tag,label:a.tag===a.componentName?a.tag:`${a.tag} (${a.componentName})`,parentKey:a.parentKey,childKeys:[...a.childKeys],operationSummary:l,...r.dynamicDataSummaryByKey?.get(s)?{dynamicDataSummary:r.dynamicDataSummaryByKey.get(s)}:{}})}return{composition:o,routeId:e.routeId,version:e.version,rootKeys:[...e.rootKeys],entries:i}}function TS(e,t,n,r,o,i,s,a,c,l,u){let d=Ro(t),f=t.elements.get(e),g=n.nodes.get(e),p=r.get(e);if(!f||!g||!p)throw new Error(`Node not found: ${e}`);let m=MS(f.textSegments,s),y=DS(e,t,f,p,m),x=m?cM(m):void 0,S=lM(i,m),b=f.textSegments.map(v=>({index:v.index,value:v.value,editable:BS(v,p,s?.get(v.index)??null),source:o.get(v.index)??null})),E=FS(f,t),k=f.childKeys.map(v=>{let N=t.elements.get(v);return N?{key:v,tag:N.tag,label:N.tag}:null}).filter(v=>v!==null),I=[];if(f.parentKey){let v=t.elements.get(f.parentKey);if(v)for(let N of v.childKeys){if(N===e)continue;let A=t.elements.get(N);A&&I.push({key:N,tag:A.tag,label:A.tag})}}return{composition:d,key:e,tag:f.tag,componentName:f.componentName,sourceFile:f.sourceFile,sourceLocator:OS(f),label:f.tag,capabilities:y,writeTarget:i,effectiveWriteTarget:S,provenanceChain:x,componentSemantic:c,styleSource:l,conditional:a,...u?{dynamicData:u}:{},textSegments:b,boundaryKind:f.boundaryKind,isOpaque:f.isOpaque,ancestors:E,children:k,siblings:I}}function wS(e,t,n,r,o,i,s,a){let c=Ro(t),l=t.elements.get(e),u=n.nodes.get(e),d=r.get(e);if(!l||!u||!d)throw new Error(`Node not found: ${e}`);let f=MS(l.textSegments,i),g=iM(l);return{composition:c,key:e,tag:l.tag,...g?{linkSourceKind:g}:{},componentName:l.componentName,sourceFile:l.sourceFile,sourceLocator:OS(l),label:l.tag,capabilities:DS(e,t,l,d,f),provenanceChain:f?{editMode:f.editMode,diagnostics:f.diagnostics.map(p=>({code:p.code,message:p.message}))}:void 0,...s?{dynamicData:s}:{},...a?{properties:a}:{},textSegments:l.textSegments.map(p=>{let m=o.get(p.index);return{index:p.index,editable:BS(p,d,i?.get(p.index)??null),source:m?{kind:m.kind}:null}}),boundaryKind:l.boundaryKind,isOpaque:l.isOpaque,ancestors:FS(l,t)}}function iM(e){if(e.tag==="a")return"native-anchor";if(e.importedFrom==="next/link"&&e.exportName==="default")return"next-link";if(e.tag==="Link")return"unsupported"}function OS(e){return{sourceFile:e.sourceFile,componentName:e.componentName,openingElementRange:sM(e.sourceRange),structuralPath:e.identity.structuralPath,...aM(e.textSegments)}}function FS(e,t){let n=[],r=e.parentKey;for(;r;){let o=t.elements.get(r);if(!o)break;n.push({key:r,tag:o.tag,label:o.tag}),r=o.parentKey}return n.reverse(),n}function sM(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function aM(e){let t=e.map(n=>n.value.trim()).filter(Boolean).join(" ").replace(/\s+/g," ").trim();return t?{textPreview:t.slice(0,oM)}:{}}function LS(e,t){let n=t.find(r=>r.editable&&r.source&&r.source.kind!=="literal");return n?.source?{kind:"value-binding",file:n.source.file,componentName:e.componentName,isProxy:n.source.file!==e.file}:{kind:"jsx-node",file:e.file,componentName:e.componentName,isProxy:e.isProxy}}function MS(e,t){if(!t)return null;for(let n of e){let r=t.get(n.index);if(r)return r}return null}function DS(e,t,n,r,o){let i=n.identity.structuralPath.includes("#repeat:"),s=t.regions.some(u=>u.kind==="repeat-region"&&u.childKeys.includes(e)),a=o?.diagnostics.find(u=>u.code==="missing-adapter"||u.code==="external-source-readonly")?.code,c=r.canUpdateText?{mode:o?.editMode??"direct",reasonCode:a??(o?.editMode==="upstream"?"component-prop":o?.finalSource?.kind==="repeat-template"?"repeat-item-data":void 0)}:{mode:"unsupported",reasonCode:"capability-denied"},l=r.canUpdateText&&jS(c.mode);return{...r,canUpdateText:l,editModes:{updateText:c,insertChild:r.canInsertChild?{mode:"direct",reasonCode:i||s?"repeat-template":void 0}:{mode:"unsupported",reasonCode:"capability-denied"},move:r.canMove?{mode:s?"proxy":"direct",reasonCode:s?"repeat-collection":void 0}:{mode:"unsupported",reasonCode:"capability-denied"},remove:r.canRemove?{mode:s?"proxy":"direct",reasonCode:s?"repeat-collection":void 0}:{mode:"unsupported",reasonCode:"capability-denied"}}}}function BS(e,t,n){return!e.editable||!t.canUpdateText?!1:n?jS(n.editMode):!0}function jS(e){return e==="direct"||e==="proxy"||e==="upstream"}function cM(e){return{finalSource:e.finalSource?{kind:e.finalSource.kind,file:e.finalSource.file,displayPath:e.finalSource.displayPath,externalSource:e.finalSource.externalSource}:null,chain:e.chain.map(t=>({kind:t.kind,file:t.file,displayName:t.displayName,canEditHere:t.canEditHere})),confidence:e.confidence,editMode:e.editMode,diagnostics:e.diagnostics.map(t=>({code:t.code,message:t.message}))}}function lM(e,t){return t?.finalSource?t.finalSource.kind==="jsx-literal"?{kind:"jsx-node",file:e.file,isProxy:e.isProxy}:t.finalSource.kind==="config-entry"&&t.finalSource.locator?{kind:"value-path",file:t.finalSource.file,isProxy:t.finalSource.file!==e.file,displayPath:t.finalSource.displayPath}:rM(t.finalSource.kind)?{kind:"external-entry",file:t.finalSource.file,isProxy:!1,displayPath:t.finalSource.displayPath,sourceType:t.finalSource.externalSource?.sourceType,sourceId:t.finalSource.externalSource?.sourceId}:{kind:"value-path",file:t.finalSource.file,isProxy:t.finalSource.file!==e.file,displayPath:t.finalSource.displayPath}:{kind:e.kind==="route-export"?"route-export":"jsx-node",file:e.file,isProxy:e.isProxy}}var vp=["set-class-name-source","apply-style-draft"];function $S(e){let t=e.attributes?.find(n=>n.name==="className");if(!t)return{kind:"class-name-source",className:"",sourceKind:"missing",editable:!0,operationBoundary:vp,diagnostics:[{code:"missing-class-name",message:"No className attribute is present on this element"}]};if(t.resolution&&t.resolution.status!=="resolved")return{kind:"class-name-source",className:"",sourceKind:"dynamic-expression",editable:!1,operationBoundary:[],sourcePath:t.source?.expression,diagnostics:[{code:"dynamic-binding",message:"Style binding is unresolved and cannot be edited"}]};if(t.source?.expression){let n=t.source.expression,r=typeof t.resolvedValue=="string"?t.resolvedValue:t.value!==n?t.value:void 0;return typeof r!="string"?{kind:"class-name-source",className:"",sourceKind:"dynamic-expression",editable:!1,operationBoundary:[],sourcePath:n,diagnostics:[{code:t.resolvedValue===void 0?"dynamic-binding":"non-string-binding",message:t.resolvedValue===void 0?"Style binding is dynamic and cannot be edited":"Style binding must resolve to a static string before it can be edited"}]}:{kind:"class-name-source",className:r,sourceKind:"static-expression",editable:!0,operationBoundary:vp,sourcePath:n}}return{kind:"class-name-source",className:t.value,sourceKind:t.resolvedValue===void 0?"static-attribute":"static-expression",editable:!0,operationBoundary:vp}}import VS from"node:path";function _p(){let e=Promise.resolve();return{async runExclusive(t){let n,r=new Promise(i=>{n=i}),o=e;e=o.then(()=>r,()=>r),await o;try{return await t()}finally{n()}}}}async function KS(e,t,n){let r=[],o=new Set;for(let i of e.intents){let s=pM(i.path);if(!s.ok)return s;let a=s.path;if(o.has(a))return{ok:!1,code:"duplicate-target",path:a,reason:`Duplicate file target: ${a}`};if(o.add(a),i.kind==="create-only"){let c=t.has(a),l=n?await n(a):!1;if(c||l)return{ok:!1,code:"create-only-exists",path:a,reason:`Create-only file already exists: ${a}`}}r.push({...i,path:a})}return{ok:!0,plan:{operationId:e.operationId,intents:r}}}async function Qc(e){let t=()=>uM(e);return e.mutex?e.mutex.runExclusive(t):t()}async function uM(e){let t=await KS(e.plan,e.overlay,e.exists);if(!t.ok)return{ok:!1,stage:"precheck",reason:t.reason,error:t,recoveryRequired:!1};let n=dM(e.overlay,t.plan),r;try{r=await e.buildCandidate({overlay:n,plan:t.plan})}catch(l){return{ok:!1,stage:"build",reason:"Candidate build failed.",error:l,recoveryRequired:!1}}let o,i;try{o=await e.prepareHistory?.({candidate:r,plan:t.plan}),await e.reverify?.({candidate:r,plan:t.plan,history:o}),i=await e.writeCandidate({candidate:r,plan:t.plan}),await e.markCandidateWritten?.({candidate:r,plan:t.plan,history:o,receipt:i})}catch(l){return kp({candidate:r,plan:t.plan,failedStage:"commit",error:l,history:o,receipt:i,rollbackCandidate:e.rollbackCandidate})}let s=r;try{let l=await e.validateCandidate({candidate:r,plan:t.plan,receipt:i});l!==void 0&&(s=l)}catch(l){return kp({candidate:r,plan:t.plan,failedStage:"validate",error:l,history:o,receipt:i,rollbackCandidate:e.rollbackCandidate})}let a;try{a=await e.publishCandidate({candidate:s,plan:t.plan,history:o,receipt:i})}catch(l){return kp({candidate:s,plan:t.plan,failedStage:"publish",error:l,history:o,receipt:i,rollbackCandidate:e.rollbackCandidate})}let c={candidate:s,plan:t.plan,history:o,receipt:i,published:a};try{await e.swapCandidate?.(c)}catch(l){return US("swap",l,"Live state swap failed after durable publish.")}try{await e.finalizeCandidate?.(c)}catch(l){return US("finalize",l,"Transaction finalization failed after live state swap.")}try{e.emitCommitted?.({candidate:s,plan:t.plan,published:a})}catch{}return{ok:!0,stage:"publish",published:a,plan:t.plan}}function dM(e,t){let n=new Map(e);for(let r of t.intents)r.kind==="delete"?n.delete(r.path):n.set(r.path,r.content);return n}function kp(e){return e.rollbackCandidate({candidate:e.candidate,plan:e.plan,failedStage:e.failedStage,error:e.error,...e.history===void 0?{}:{history:e.history},...e.receipt===void 0?{}:{receipt:e.receipt}}).then(()=>({ok:!1,stage:e.failedStage,reason:fM(e.failedStage),error:e.error,recoveryRequired:!1})).catch(t=>({ok:!1,stage:"rollback",reason:"Rollback failed after candidate commit/validation/publish failure.",error:t,recoveryRequired:!0,cause:e.error}))}function US(e,t,n){return{ok:!1,stage:e,reason:n,error:t,recoveryRequired:!0}}function fM(e){switch(e){case"commit":return"Candidate write or commit verification failed.";case"validate":return"Candidate validation failed.";case"publish":return"Candidate publish failed."}}function pM(e){if(e.length===0)return{ok:!1,code:"unsafe-path",path:e,reason:"File path must not be empty."};if(e.includes("\0")||e.includes("\\"))return{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`};if(/^[a-zA-Z]:/.test(e)||VS.isAbsolute(e))return{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`};let t=VS.posix.normalize(e);return t==="."||t===".."||t.startsWith("../")||t.includes("/../")?{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`}:t.startsWith("./")||t.includes("/./")?{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`}:{ok:!0,path:t}}var mM=50,gM=8*1024*1024;function HS(e,t={}){let n=[],r=[],o=t.externalAdapters??[],i=Math.max(0,t.maxUndoEntries??mM),s=Math.max(0,t.maxUndoBytes??gM);return{prepareRewritePlan:a,execute:c,executeFilePlan:l,undo:u,redo:d};async function a(v){let N=[...v.steps].sort(($,G)=>$.order-G.order),A=N.filter($=>$.type!=="invoke-external-adapter");if(A.length!==N.length)return{ok:!1,errorCode:"unsupported-operation",reason:"External adapter writes require a transactional prepare/commit/rollback contract."};let w=new Set(A.map($=>$.file)),F=await S(w),B=new Map(F.map($=>[$.file,$.exists===!1?"":$.content])),X;for(let $ of A){let G=zS($,B.get($.file)??"");if(!G.ok)return{ok:!1,errorCode:G.errorCode,reason:G.reason};B.set($.file,G.source),X=G.selectionRef??X}return{ok:!0,filePlan:{operationId:v.operationId,kind:"source-edit",target:v.target,documentVersion:v.documentVersion,conflictPolicy:"compare-and-swap",edits:[...B].map(([$,G])=>({operation:"upsert",file:$,content:G,baseContentHash:F.find(D=>D.file===$)?.sha256??null}))},...X?{selectionRef:X}:{}}}async function c(v){let N=[...v.steps].sort((D,fe)=>D.order-fe.order),A=N.filter(D=>D.type!=="invoke-external-adapter"),w=N.filter(D=>D.type==="invoke-external-adapter"),F=new Set(A.map(D=>D.file));if(A.length>0&&w.length>0)return{ok:!1,operationId:v.operationId,errorCode:"unsupported-operation",reason:"Mixed local file rewrites and external adapter writes require an explicit compensation contract.",rolledBack:!1};if(A.length===0)return y(v,w);let B=await S(F),X=new Map;for(let D of B)X.set(D.file,D.exists===!1?"":D.content);let $;for(let D of A){let fe=X.get(D.file)??"",Fe=zS(D,fe);if(!Fe.ok)return{ok:!1,operationId:v.operationId,errorCode:Fe.errorCode,reason:Fe.reason,rolledBack:!1};X.set(D.file,Fe.source),Fe.selectionRef&&($=Fe.selectionRef)}let G=await E([...X].map(([D,fe])=>({file:D,content:fe,exists:!0,version:0,sha256:ke(fe)})),B);return G.ok===!1?{ok:!1,operationId:v.operationId,errorCode:G.rolledBack?"writeback-failed":"rollback-failed",reason:G.reason,rolledBack:G.rolledBack}:(n.push({operationId:v.operationId,preSnapshots:B,postSnapshots:G.snapshots,plan:v}),f(),r.length=0,{ok:!0,operationId:v.operationId,kind:v.kind,target:v.target,resultVersion:Math.max(...G.snapshots.map(D=>D.version)),affectedFiles:[...F],...$?{selectionRef:$}:{}})}async function l(v){let N=new Set(v.edits.map(G=>G.file)),A=await S(N),w=x(v,A);if(w)return{ok:!1,operationId:v.operationId,errorCode:"stale-version",reason:w.reason,affectedFiles:[w.file],rolledBack:!1};let F=new Map(A.map(G=>[G.file,G])),B=v.edits.find(G=>G.operation==="create-only"&&F.get(G.file)?.exists!==!1);if(B)return{ok:!1,operationId:v.operationId,errorCode:"stale-version",reason:`MATERIALIZATION_INSTANCE_CONFLICT: create-only target already exists: ${B.file}`,affectedFiles:[B.file],rolledBack:!1};let X=v.edits.map(G=>G.operation==="delete"?{file:G.file,content:"",exists:!1,version:0}:{file:G.file,content:G.content,exists:!0,version:0,sha256:ke(G.content)}),$=await E(X,A,new Set(v.edits.filter(G=>G.operation==="create-only").map(G=>G.file)));return $.ok===!1?{ok:!1,operationId:v.operationId,errorCode:$.rolledBack?"writeback-failed":"rollback-failed",reason:$.reason,rolledBack:$.rolledBack}:(n.push({operationId:v.operationId,preSnapshots:A,postSnapshots:$.snapshots,plan:{operationId:v.operationId,kind:v.kind,target:v.target,documentVersion:v.documentVersion,steps:[],preSnapshots:A}}),f(),r.length=0,{ok:!0,operationId:v.operationId,kind:v.kind,target:v.target,resultVersion:Math.max(...$.snapshots.map(G=>G.version)),affectedFiles:[...N]})}async function u(){let v=n.at(-1);if(!v)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to undo"};let N=await E(v.preSnapshots,v.postSnapshots);return N.ok===!1?{ok:!1,operationId:v.operationId,errorCode:N.rolledBack?"writeback-failed":"rollback-failed",reason:N.reason,rolledBack:N.rolledBack}:(n.pop(),r.push(v),{ok:!0,operationId:v.operationId,kind:v.plan.kind,target:v.plan.target,resultVersion:Math.max(...N.snapshots.map(A=>A.version)),affectedFiles:v.preSnapshots.map(A=>A.file)})}async function d(){let v=r.at(-1);if(!v)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to redo"};let N=await E(v.postSnapshots,v.preSnapshots);return N.ok===!1?{ok:!1,operationId:v.operationId,errorCode:N.rolledBack?"writeback-failed":"rollback-failed",reason:N.reason,rolledBack:N.rolledBack}:(r.pop(),n.push(v),f(),{ok:!0,operationId:v.operationId,kind:v.plan.kind,target:v.plan.target,resultVersion:Math.max(...N.snapshots.map(A=>A.version)),affectedFiles:v.postSnapshots.map(A=>A.file)})}function f(){for(;n.length>i;)n.shift();for(;n.length>0&&g()>s;)n.shift()}function g(){return n.reduce((v,N)=>v+p(N),0)}function p(v){return m(v.preSnapshots)+m(v.postSnapshots)}function m(v){return v.reduce((N,A)=>N+A.file.length+A.content.length,0)}async function y(v,N){let A=[];for(let w of N){let F=w.capability??"write-text",B=o.find($=>$.sourceType===w.sourceType&&(w.adapterId===void 0||$.adapterId===w.adapterId)&&($.capabilities===void 0||$.capabilities.includes(F)));if(!B)return{ok:!1,operationId:v.operationId,errorCode:"unsupported-operation",reason:`No external adapter registered for ${w.sourceType}`,rolledBack:!1};let X=await B.execute(w);if(!X.ok)return{ok:!1,operationId:v.operationId,errorCode:"writeback-failed",reason:X.reason??`External adapter failed for ${w.sourceType}`,rolledBack:!1};A.push(w.file)}return{ok:!0,operationId:v.operationId,kind:v.kind,target:v.target,resultVersion:0,affectedFiles:A}}function x(v,N){if(v.conflictPolicy!=="compare-and-swap")return null;let A=new Map(N.map(w=>[w.file,w]));for(let w of v.edits){if(w.operation==="create-only")continue;if(w.baseContentHash===void 0)return{file:w.file,reason:`Source file ${w.file} is missing baseContentHash. Reopen the file before saving.`};let F=A.get(w.file),B=w.baseContentHash;if(B===null){if(F?.exists!==!1)return{file:w.file,reason:`Source file ${w.file} was created or changed before save.`};continue}if(!B)return{file:w.file,reason:`Source file ${w.file} is missing baseContentHash. Reopen the file before saving.`};if(F?.exists===!1||F?.sha256!==B)return{file:w.file,reason:`Source file ${w.file} changed before save. Reload or explicitly overwrite the newer version.`}}return null}async function S(v){let N=[];for(let A of v)N.push(await b(A));return N}async function b(v){if(!await e.exists(v))return{file:v,content:"",version:0,exists:!1};let A=Math.max(1,e.getVersion(v)),w=await e.readFile(v);return{file:v,content:w,version:A,exists:!0,sha256:ke(w)}}async function E(v,N,A=new Set){let w=[];try{for(let F of v){if(A.has(F.file)){if(!e.createExclusive)throw new Error("Create-only write requires atomic exclusive-create support.");await e.createExclusive(F.file,F.content)}else await k(F);let B=e.bumpVersion(F.file);w.push(F.file),F.version=B}}catch(F){let B=await I(N.filter($=>w.includes($.file)));if(B.ok===!1)return{ok:!1,reason:`Writeback failed, then rollback failed for ${B.failedFiles.join(", ")}: ${XS(F)}`,rolledBack:!1,instanceConflict:JS(F)};let X=JS(F);return{ok:!1,reason:`${X?"MATERIALIZATION_INSTANCE_CONFLICT: ":""}Writeback failed and committed files were restored: ${XS(F)}`,rolledBack:!0,instanceConflict:X}}return{ok:!0,snapshots:v.map(hM)}}async function k(v){if(v.exists===!1){await e.deleteFile(v.file);return}await e.writeFile(v.file,v.content)}async function I(v){let N=[];for(let A of v)try{await k(A),e.bumpVersion(A.file)}catch{N.push(A.file)}return N.length===0?{ok:!0}:{ok:!1,failedFiles:N}}}function JS(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="EEXIST"}function hM(e){let t=e.exists!==!1;return{file:e.file,content:t?e.content:"",version:e.version,exists:t,...t?{sha256:ke(e.content)}:{}}}function XS(e){return e instanceof Error?e.message:String(e)}function zS(e,t){switch(e.type){case"invoke-external-adapter":return{ok:!1,reason:"External adapter steps must be executed asynchronously",errorCode:"unsupported-operation"};case"add-import":return It(sn({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-import":return It(Co({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-node":return It(qr({source:t,locator:e.locator,removeWhitespace:e.removeWhitespace}));case"insert-child":return It(on({source:t,locator:e.parentLocator,node:e.node,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"update-text":return It(ra({source:t,locator:e.locator,segmentIndex:e.segmentIndex,newText:e.newText}));case"update-value":return It(ki({source:t,locator:e.locator,next:e.value}));case"update-array-item":return It(ki({source:t,locator:e.locator,next:e.value}));case"insert-bound-array-item":return It(la({source:t,locator:e.locator,index:e.index,value:e.value}));case"insert-jsx-expression-child":return It(oa({source:t,locator:e.parentLocator,expression:e.expression,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"remove-bound-array-item":return It(ua({source:t,locator:e.locator,index:e.index}));case"move-array-item":return It(da({source:t,locator:e.locator,fromIndex:e.fromIndex,toIndex:e.toIndex}));case"move-node":return It(eo({source:t,locator:e.locator,targetParentLocator:e.targetParentLocator,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"move-repeat-template-child":return It(ia({source:t,locator:e.locator,targetParentLocator:e.targetParentLocator,placement:e.placement,anchorLocator:e.anchorLocator,repeatExpression:e.repeatExpression,selectionContext:e.selectionContext}));case"set-class-name-source":return yM(e,t);case"set-property-changes":return It(sa({source:t,locator:e.locator,changes:e.changes}));case"set-link-target":return It(aa({source:t,locator:e.locator,link:e.link,changes:e.changes}));case"set-property-binding":return It(ca({source:t,locator:e.locator,name:e.name,object:e.object,property:e.property}));case"upsert-object-property":return It(pa({source:t,objectLocator:e.locator,name:e.name,value:e.value}));default:return{ok:!1,reason:`Unknown step type: ${e.type}`,errorCode:"unknown"}}}function yM(e,t){let{request:n}=e;if(n.newAttrRaw!==null&&!ih(n.newAttrRaw))return{ok:!1,reason:"newAttrRaw must be a valid JSX className attribute.",errorCode:"invalid-params"};let r=n.oldAttrRange!==null&&n.oldAttrRaw!==null,o=n.openingElementRange.start,i=n.openingElementRange.end,s=t.slice(o,i);if(!(Number.isInteger(o)&&Number.isInteger(i)&&o>=0&&i>o&&i<=t.length&&s.startsWith("<")&&s.endsWith(">")&&!s.startsWith("</")&&(n.oldAttrRange===null||n.oldAttrRange.start>=o&&n.oldAttrRange.end<=i)))return{ok:!1,reason:"The opening element range changed before className save.",errorCode:"stale-version"};if(!r&&n.expectedVersion.contentHash!==ke(t))return{ok:!1,reason:"The source file changed before className save.",errorCode:"stale-version"};if(n.oldAttrRange){if(t.slice(n.oldAttrRange.start,n.oldAttrRange.end)!==n.oldAttrRaw)return{ok:!1,reason:"The className attribute changed before save.",errorCode:"stale-version"}}else if(n.oldAttrRaw!==null)return{ok:!1,reason:"The className attribute range no longer matches.",errorCode:"stale-version"};return{ok:!0,source:oh({source:t,oldAttrRange:n.oldAttrRange,openingElementRange:n.openingElementRange,newAttrRaw:n.newAttrRaw})}}function It(e){if(e.ok)return{ok:!0,source:e.source,...e.selectionRef?{selectionRef:e.selectionRef}:{}};switch(e.diagnostic.code){case"locator-miss":return{ok:!1,reason:e.diagnostic.message,errorCode:"locator-miss"};case"unsupported-syntax":case"binding-not-found":case"export-not-found":case"property-not-found":case"array-index-out-of-range":case"directive-conflict":case"metadata-shape-unsupported":return{ok:!1,reason:e.diagnostic.message,errorCode:"unsupported-operation"};case"invalid-parent-child-relation":case"self-closing-element":return{ok:!1,reason:e.diagnostic.message,errorCode:"invalid-target"};case"parse-failed":case"printer-failed":return{ok:!1,reason:e.diagnostic.message,errorCode:"ast-error"};default:return{ok:!1,reason:e.diagnostic.message,errorCode:"writeback-failed"}}}import{computeSiteEditCompositionKey as el,SiteEditCompositionContextSchema as xM,SiteEditCompositionSelectorSchema as bM}from"@vcp-dev/contracts";var At=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="SiteEditCompositionError"}};function WS(e,t){throw new At("INVALID_COMPOSITION",e,{value:t})}function tl(e){let t=xM.safeParse(e);return t.success?t.data:WS("Invalid SiteEditCompositionContext.",e)}function GS(e){let t=[],n=new Map,r=new Map;for(let l of e.compositions){let u=tl(l?.context);if(typeof l.entryFile!="string"||!l.entryFile)throw new At("INVALID_COMPOSITION","A registered composition must have a non-empty entryFile.");let d=el(u);if(n.has(d))throw new At("DUPLICATE_COMPOSITION",`Composition key ${d} is registered more than once.`,{key:d,context:u});let f=r.get(l.entryFile);if(f)throw new At("DUPLICATE_COMPOSITION",`Entry file ${l.entryFile} is registered more than once.`,{entryFile:l.entryFile,context:f});let g={context:u,entryFile:l.entryFile,key:d};t.push(g),n.set(d,g),r.set(l.entryFile,d)}if(t.length===0)throw new At("INVALID_COMPOSITION","At least one composition must be registered.");let o=new Map;for(let l of e.initialDocumentVersions??[]){let u=tl(l?.composition);if(!Number.isInteger(l?.version)||(l?.version??-1)<0)throw new At("INVALID_INITIAL_DOCUMENT_VERSION","Initial document version must be a non-negative integer.",{context:u,version:l?.version});let d=el(u);if(!n.has(d))throw new At("UNKNOWN_COMPOSITION","Initial document version references an unregistered composition.",{context:u,key:d});if(o.has(d))throw new At("DUPLICATE_COMPOSITION","Initial document versions must contain each composition at most once.",{context:u,key:d});o.set(d,l.version)}function i(l){let u=bM.safeParse(l);if(!u.success)return WS("Invalid SiteEditCompositionSelector.",l);let d=t.filter(({context:f})=>f.routeId===u.data.routeId&&(u.data.templateId===void 0?f.effectiveTemplateId===void 0:f.effectiveTemplateId===u.data.templateId));if(d.length===1)return d[0];throw d.length>1?new At("AMBIGUOUS_COMPOSITION","The composition selector matches multiple registered contexts.",{selector:u.data}):new At("UNKNOWN_COMPOSITION","The composition selector is not registered.",{selector:u.data})}function s(l){let u=tl(l),d=el(u),f=n.get(d);if(!f)throw new At("UNKNOWN_COMPOSITION","The composition context is not registered.",{context:u,key:d});return f}function a(l){let u=tl(l?.context);if(typeof l.entryFile!="string"||!l.entryFile)throw new At("INVALID_COMPOSITION","A registered composition must have a non-empty entryFile.");let d=el(u),f=n.get(d);if(f){if(f.entryFile===l.entryFile)return f;throw new At("DUPLICATE_COMPOSITION",`Composition key ${d} is registered more than once.`,{key:d,context:u})}let g=[...n.values()].find(m=>m.entryFile===l.entryFile);if(g)throw new At("DUPLICATE_COMPOSITION",`Entry file ${l.entryFile} is registered more than once.`,{entryFile:l.entryFile,context:g.context});let p={context:u,entryFile:l.entryFile,key:d};return t.push(p),n.set(d,p),p}function c(l){let u=n.get(l);if(!u)return;n.delete(l);let d=t.findIndex(f=>f.key===l);return d>=0&&t.splice(d,1),o.delete(l),u}return{entries:t,byKey:n,initialVersions:o,register:a,unregister:c,resolveSelector:i,resolveContext:s,getByKey:l=>n.get(l),routeIds:()=>[...new Set(t.map(({context:l})=>l.routeId))]}}function Cp(e){let t=new Map,n=new Map;return{readFile(r){let o=t.get(r);return o||(o=e.readFile(r),t.set(r,o)),o},exists(r){let o=n.get(r);return o||(o=e.exists(r),n.set(r,o)),o}}}async function YS(e,t){if(e.length===0)return[];if(e.length===1)return[await t(e[0])];let n=new Array(e.length),r=[],o=0,i=Array.from({length:Math.min(4,e.length)},async()=>{for(;o<e.length&&r.length===0;){let c=o++;try{n[c]=await t(e[c])}catch(l){r.push({index:c,error:l})}}}),s=await Promise.allSettled(i),a=r.sort((c,l)=>c.index-l.index)[0];if(a)throw a.error;for(let c of s)if(c.status==="rejected")throw c.reason;return n}import{composeSiteEditRepeatInstanceKey as EM,stripSiteEditRepeatInstanceKeys as ZS}from"@vcp-dev/contracts";function qS(e){let t=new Map,n=new Map,r=new Map;for(let o of e.entries){t.set(o.key,o);let i=ZS(o.key)??o.key;if(i===o.key)continue;let s=n.get(i)??0;r.set(o.key,s),n.set(i,s+1)}return{entriesByKey:t,repeatOccurrenceIndexByKey:r}}function SM(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 nl(e){return e?.map(t=>({...t}))}function Rp(e,t){if(t===null||e?.kind!=="value-binding"||e.sourceKind!=="repeat-template")return e;let n=e.collectionIndexMap?.[t]??t,r=nl(e.collectionPathMap?.[t])??nl(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:nl(e.path),locator:e.locator?{...e.locator,path:r}:e.locator,collectionIndexMap:e.collectionIndexMap?[...e.collectionIndexMap]:void 0,collectionPathMap:e.collectionPathMap?.map(o=>nl(o)??[])}}function QS(e,t,n){let r=new Set;for(let g of t.regions)if(g.kind==="repeat-region")for(let p of g.childKeys)r.add(p);if(r.size===0)return e;let o=new Map(e.entries.map(g=>[g.key,g])),i=[],s=new Map,a=(g,p)=>EM(g,p),c=(g,p,m)=>{let y=o.get(g);if(!y)return a(g,m);let x=a(g,m),S={...y,key:x,parentKey:p,childKeys:[]};return i.push(S),S.childKeys=y.childKeys.flatMap(b=>l(b,m,x)),x},l=(g,p,m)=>{if(!r.has(g))return[c(g,m,p)];let y=d(g,p),x=[];for(let S=0;S<y;S+=1)x.push(c(g,m,[...p,S]));return x},u=Array.from(new Set([...e.rootKeys,...e.entries.filter(g=>g.parentKey===null).map(g=>g.key)]));for(let g of u){if(!r.has(g)){c(g,null,[]);continue}let p=d(g,[]);for(let m=0;m<p;m+=1)c(g,null,[m])}return{...e,rootKeys:[...e.rootKeys],entries:i};function d(g,p){let m=new Set;for(let y of f(g)){let x=n.get(y);if(x){for(let S of[...x.textTargets.values(),...x.elementPropertyTargets.values()])if(!(S?.kind!=="value-binding"||S.sourceKind!=="repeat-template"))for(let b of IM(S))b.length<=p.length||vM(b,p)&&m.add(b[p.length])}}return m.size>0?m.size:SM(n.get(g))}function f(g){let p=s.get(g);if(p)return p;let m=[g],y=o.get(g);for(let x of y?.childKeys??[])m.push(...f(x));return s.set(g,m),m}}function eI(e){let t=e.parts.at(-1);return typeof t?.repeatIndex=="number"?t.repeatIndex:null}function tI(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((ZS(s.key)??s.key)===n){if(s.key===t)return i;i+=1}return null}function IM(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 vM(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 nI(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 rI(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}}function oI(e){return{path:e.path,code:e.code,message:e.message,...e.details?{details:JSON.parse(JSON.stringify(e.details))}:{}}}function kM(e){return e.map(t=>`${t.code} (${t.path}): ${t.message}`).join("; ")}var Is=class extends Error{constructor(t){let n=t.map(oI);super(kM(n)),this.name="RouteBuildDiagnosticsError",this.diagnostics=n}};function iI(e,t){let n=t instanceof Error&&t.message?t.message:String(t);return t instanceof Is?{routeId:e,message:n,diagnostics:t.diagnostics.map(oI)}:{routeId:e,message:n}}function Np(e){return e.map(({routeId:t,message:n})=>`${t}: ${n}`).join("; ")}function Pp(e,t){let n=new Map(e);for(let r of t)n.delete(r);return n}function vs(e,t){e.clear();for(let[n,r]of t)e.set(n,r)}function sI(e,t){for(let n of t){if(n.exists===!1){e.delete(n.file);continue}e.set(n.file,n.content)}}function rl(e,t,n,r){if(!e.has(t)&&e.size>=r){let o=e.keys().next().value;o&&e.delete(o)}e.set(t,n)}function aI(e){let{journal:t,index:n,observedFileDigests:r}=e;if(r.length!==t.files.length)return"ambiguous";let o=t.files.every((l,u)=>l.preDigest===r[u]),i=t.files.every((l,u)=>l.postDigest===r[u]),s=t.historyTransition,a=n.digest===s.expectedIndexDigest,c=n.digest===s.publishedIndexDigest&&n.cursor===s.publishedCursor&&n.currentId===s.publishedCurrentId;return o&&a?"safely-uncommitted":i&&c?"durably-committed":"ambiguous"}var wM=/^(?:src\/)?app\/.*\/?page\.[cm]?[jt]sx?$/,OM=["layout.tsx","layout.ts","layout.jsx","layout.js","layout.mjs","layout.cjs"],cI=32,il=256;function FM(e){return{expectedIndexDigest:e.digest,publishedIndexDigest:e.digest,publishedCursor:e.cursor,publishedCurrentId:e.currentId}}var lI={maxEntries:50,maxBytes:8*1024*1024};function LM(){let e=new Map;return{async readFile(t){return(await import("node:fs/promises")).readFile(t,"utf-8")},async readFileBytes(t){return(await import("node:fs/promises")).readFile(t)},async getFileInfo(t){let n=await import("node:fs/promises");try{let r=await n.lstat(t);return!r.isFile()||r.isSymbolicLink()?null:{path:t,sizeBytes:r.size}}catch{return null}},async writeFile(t,n){await ha(t,n)},async deleteFile(t){await(await import("node:fs/promises")).rm(t,{force:!0})},async exists(t){let n=await import("node:fs/promises");try{return await n.access(t),!0}catch{return!1}},getVersion(t){return e.get(t)??1},bumpVersion(t){let n=(e.get(t)??1)+1;return e.set(t,n),n}}}async function uI(e,t){if(t.length===0)return[];let n;try{n=JSON.parse(await e.readFile("package.json"))}catch{return[]}if(!n||typeof n!="object")return[];let r=n.dependencies;return!r||typeof r!="object"||Array.isArray(r)?[]:t.filter(o=>{if(!Object.prototype.hasOwnProperty.call(r,o))return!1;let i=r[o];return typeof i=="string"&&i.trim().length>0})}function MM(){let e=[],t=[];return{prepareAppend(r){return{kind:"append",entry:r}},prepareUndo(){let r=e.at(-1);return r?{kind:"undo",entry:r}:null},prepareRedo(){let r=t.at(-1);return r?{kind:"redo",entry:r}:null},publishPrepared(r){if(r.kind==="append"){e.push(r.entry),n(),t.length=0;return}if(r.kind==="undo"){if(e.at(-1)!==r.entry)throw new Error("undo history changed before publish");e.pop(),t.push(r.entry);return}if(t.at(-1)!==r.entry)throw new Error("redo history changed before publish");t.pop(),e.push(r.entry),n()},peekUndo(){return e.at(-1)??null},pushUndo(r){e.push(r),n(),t.length=0},popUndo(){return e.pop()??null},peekRedo(){return t.at(-1)??null},pushRedo(r){t.push(r)},popRedo(){return t.pop()??null},clearRedo(){t.length=0},getStatus(){return{canUndo:e.length>0,canRedo:t.length>0,undoDepth:e.length,redoDepth:t.length,recoveryRequired:!1}}};function n(){for(;e.length>lI.maxEntries||DM(e)>lI.maxBytes;)e.shift()}}function DM(e){return e.reduce((t,n)=>t+BM(n),0)}function BM(e){return dI(e.preSnapshots)+dI(e.postSnapshots)+jM(e.provenance)}function jM(e){return e?new TextEncoder().encode(JSON.stringify(e)).byteLength:0}function dI(e){return e.reduce((t,n)=>t+n.file.length+n.content.length,0)}function fI(e,t){return{key:CM(e),composition:e,routeId:e.routeId,entryFile:t,graph:null,topology:null,capabilities:null,document:null,pageBlockIndex:null,pageComposition:null,pageCompositionProjection:null,documentIndex:null,pagePlacementByKey:null,pagePlacementUnitByKey:null,pageUnitByKey:null,pagePlacementsByUnitKey:null,dependencyFiles:new Set([t]),detailProjections:null,fileVersions:new Map,styleContext:null}}var sl=class extends Error{constructor(t){super(t.reason),this.result=t}},yo=class extends Error{constructor(t){super(Np(t)),this.failedRoutes=t}};function pI(e,t){if(!e)return;let n=[...t];if(n.some(o=>o?.entries.some(i=>i.key===e.key)))return e;let r=$t(e.key)??e.key;for(let o of n){let i=o?.entries.find(s=>($t(s.key)??s.key)===r);if(i)return{...e,key:i.key}}return e}function $M(e,t,n){if(!n)return;let r=$t(n.key)??n.key;if(n.key!==e&&n.key!==t&&r!==t)throw new Error(`Selection reference '${n.key}' does not match selected key '${e}'`);if(n.instanceIndex!==void 0&&(!Number.isInteger(n.instanceIndex)||n.instanceIndex<0))throw new Error("Selection reference instanceIndex must be non-negative");if(n.instanceCount!==void 0&&(!Number.isInteger(n.instanceCount)||n.instanceCount<=0))throw new Error("Selection reference instanceCount must be positive");if(n.instanceIndex!==void 0&&n.instanceCount!==void 0&&n.instanceIndex>=n.instanceCount)throw new Error("Selection reference instanceIndex must be smaller than instanceCount");return{...n,key:t}}var VM=/\.(?:[cm]?[jt]sx?)$/i,UM=/\.json$/i,KM=/\.(?:css|scss|sass)$/i,JM=/\.mdx$/i,XM=/\.ya?ml$/i;function zM(e){if(!e||e.kind!=="value-binding")return null;let t="path"in e?e.path:void 0,n=e.root,r=n&&(n.kind==="binding"||n.kind==="named-export")?n.name:void 0;return{kind:e.sourceKind,file:e.file,expression:e.displayExpression,bindingName:r,path:t?.map(o=>o.kind==="property"?o.name:o.index)}}function HM(e){return{kind:e.isProxy?"component-proxy":"jsx-node",file:e.file,componentName:e.componentName,isProxy:e.isProxy}}function WM(e,t){let n=new Map;for(let i of t)n.set(i.path,i.operation==="delete"?{exists:!1}:{exists:!0,content:i.content});let r=new Map,o=new Map;return{async readFile(i){let s=n.get(i);if(s){if(!s.exists)throw new Error(`Source file not found: ${i}`);return s.content}let a=r.get(i);return a||(a=e.readFile(i),r.set(i,a)),a},async writeFile(){throw new Error("Source edit preflight overlay is read-only.")},async deleteFile(){throw new Error("Source edit preflight overlay is read-only.")},async exists(i){let s=n.get(i);if(s)return s.exists;let a=o.get(i);return a||(a=e.exists(i),o.set(i,a)),a},async getFileInfo(i){let s=n.get(i);return s?s.exists?{path:i,sizeBytes:Buffer.byteLength(s.content,"utf8")}:null:e.getFileInfo?.(i)??null},async listFiles(i={}){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let s=bI(await e.listFiles(i)),a=new Map(s.files.map(l=>[l.path,l]));for(let[l,u]of n)if(GM(l,i.roots??[])){if(!u.exists){a.delete(l);continue}a.set(l,{path:l,sizeBytes:Buffer.byteLength(u.content,"utf8")})}let c=[...a.values()].sort((l,u)=>l.path.localeCompare(u.path));return s.truncated?{files:c,truncated:s.truncated}:c},getVersion(i){return e.getVersion(i)},bumpVersion(i){return e.getVersion(i)}}}function GM(e,t){return t.length===0?!0:t.some(n=>e===n||e.startsWith(`${n}/`))}function bI(e){return Array.isArray(e)?{files:e}:e}function YM(e){if(!NM(e.path))return{ok:!1,errorCode:"invalid-params",message:`Source file is read-only: ${e.path}`,details:{path:e.path}};if(e.operation==="upsert"&&e.content.includes("\0"))return{ok:!1,errorCode:"invalid-params",message:`Source file content must be valid text: ${e.path}`,details:{path:e.path}};if(e.operation==="delete"){if(e.capability!==AM||e.confirmDelete!==!0||e.confirmPath!==e.path)return{ok:!1,errorCode:"capability-denied",message:`Source file delete requires explicit confirmation: ${e.path}`,details:{path:e.path}};let t=RM(e.path);return t?{ok:!1,errorCode:"capability-denied",message:`Protected source file cannot be deleted: ${e.path}`,details:{path:e.path,protectionReason:t}}:{ok:!0}}if(VM.test(e.path)){let t=Rn({source:e.content,profile:zr({filePath:e.path,source:e.content})});if(!t.ok)return{ok:!1,errorCode:"ast-error",message:t.diagnostic.message,details:{path:e.path}}}if(UM.test(e.path))try{JSON.parse(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`JSON parse failed: ${Ot(t)}`,details:{path:e.path}}}if(KM.test(e.path)){let t=mI({content:e.content,path:e.path,profile:"css"});if(!t.ok)return t}if(JM.test(e.path)){let t=mI({content:e.content,path:e.path,profile:"mdx"});if(!t.ok)return t}if(XM.test(e.path))try{TM(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`YAML parse failed: ${Ot(t)}`,details:{path:e.path}}}return{ok:!0}}function mI({content:e,path:t,profile:n}){let r=[],o=null,i=!1,s=!1,a=!1,c=!1,l=!0;for(let d=0;d<e.length;d+=1){let f=e[d]??"",g=e[d+1]??"";if(n==="mdx"&&l&&e.startsWith("```",d)){c=!c;let p=e.indexOf(`
8
8
  `,d);if(p===-1){l=!0;break}d=p,l=!0;continue}if(c){l=f===`
9
9
  `||f==="\r";continue}if(s){f==="*"&&g==="/"&&(s=!1,d+=1),l=f===`
10
10
  `||f==="\r";continue}if(a){f===`
11
11
  `||f==="\r"?(a=!1,l=!0):l=!1;continue}if(o){if(i)i=!1;else if(f==="\\")i=!0;else if(f===o)o=null;else if(n==="css"&&(f===`
12
12
  `||f==="\r"))return ri(t,`Unterminated string literal in ${t}.`);l=f===`
13
13
  `||f==="\r";continue}if(f==="/"&&g==="*"){s=!0,d+=1,l=!1;continue}if(n==="mdx"&&f==="/"&&g==="/"){a=!0,d+=1,l=!1;continue}if(f==="'"||f==='"'||n==="mdx"&&f==="`"){o=f,l=!1;continue}if(f==="{"||f==="("||f==="["){r.push({char:f,offset:d}),l=!1;continue}if(f==="}"||f===")"||f==="]"){let p=f==="}"?"{":f===")"?"(":"[",m=r.pop();if(!m||m.char!==p)return ri(t,`Unexpected closing token "${f}" in ${t}.`);l=!1;continue}l=f===`
14
- `||f==="\r"}if(s)return ri(t,`Unterminated block comment in ${t}.`);if(o)return ri(t,`Unterminated string literal in ${t}.`);if(c)return ri(t,`Unterminated MDX code fence in ${t}.`);let u=r.at(-1);return u?ri(t,`Unclosed token "${u.char}" in ${t}.`):{ok:!0}}function ri(e,t){return{ok:!1,errorCode:"ast-error",message:t,details:{path:e}}}function al(e){let t="idle",n=e.fileSystem??LD(),r=oh(),o=HS({compositions:e.compositions,initialDocumentVersions:e.initialDocumentVersions}),i=new Map,s=new Map,a=new Set,c=null,l=e.history??(e.historyStore?Hh(e.historyStore):DD()),u=XS(n,{externalAdapters:e.externalAdapters}),d=new Map,f=mh(il),g=new Set,p=0,m=e.historyStore?.recoveryRequired??!1,y=_p(),x=k();function S(h){return(ol.isAbsolute(h)?ol.relative(e.projectRoot,h):h).replace(/\\/g,"/").replace(/^\.\//,"")}function b(h,R){let _=ol.posix.dirname(h),T=R.replace(/\.(?:tsx?|jsx?)$/i,""),L=ol.posix.relative(_,T);return L.startsWith(".")?L:`./${L}`}function E(h,R){return h.startLine===R.startLine&&h.startColumn===R.startColumn&&h.endLine===R.endLine&&h.endColumn===R.endColumn}async function k(){let h=e.historyStore;if(h)try{let R=await h.readTransactionJournal();if(!R)return;let _=await h.readIndex(),T=await Promise.all(R.files.map(async D=>await n.exists(D.path)?ke(await n.readFile(D.path)):null));if(iI({journal:R,index:_,observedFileDigests:T})!=="ambiguous"){await h.clearTransactionJournal(R.transactionId);let D=await h.readStatus();D.recoveryRequired||(await h.cleanupTmp(),D=await h.readStatus()),m=D.recoveryRequired;return}await h.markRecoveryRequired(`Ambiguous transaction journal ${R.transactionId} at phase ${R.phase}`),m=!0}catch(R){m=!0,await h.markRecoveryRequired(`Transaction journal recovery failed: ${Ot(R)}`).catch(()=>{})}}function I(){return t==="disposed"}e.onEvent&&r.subscribe(e.onEvent);for(let h of o.entries){let R=uI(h.context,h.entryFile);i.set(h.key,R),v(R,R.dependencyFiles)}function v(h,R){let _=new Set(R);N(h),h.dependencyFiles=_;for(let T of h.dependencyFiles){let L=s.get(T);L||(L=new Set,s.set(T,L)),L.add(h.key)}}function N(h){for(let R of h.dependencyFiles){let _=s.get(R);_&&(_.delete(h.key),_.size===0&&s.delete(R))}h.dependencyFiles.clear()}function A(h){let R=new Set;for(let _ of h)for(let T of s.get(_)??[])R.add(T);return R}function w(h){for(let R of h)if(!s.has(R))return!1;return!0}async function F(h,R,_,T,L,D){let J=new Map,z=kS(h),Q=pS(L.values()),W=dE(L.values()),H=typeof D.exists=="function"?ne=>D.exists(ne):async()=>!1;for(let[ne,le]of h.elements){let ve=R.nodes.get(ne);if(!ve)continue;let ie=_.get(le.sourceFile)??T.get(le.sourceFile),Ae=new Map,Se=new Map,j=new Map,q=[];for(let Ge of le.textSegments){if(!ie){Ae.set(Ge.index,null);continue}let fi=await mS({file:le.sourceFile,source:ie,segment:Ge,readFile:Vt=>D.readFile(Vt),exists:H,graph:h,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Vt,adapterId:Kr,capabilities:Ul})=>({sourceType:Vt,adapterId:Kr,capabilities:Ul})),functionCallContracts:e.functionCallContracts,fileCache:Q}),wt=await hp({file:le.sourceFile,source:ie,target:{kind:"text-segment",segment:Ge},readFile:Vt=>D.readFile(Vt),exists:H,graph:h,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Vt,adapterId:Kr,capabilities:Ul})=>({sourceType:Vt,adapterId:Kr,capabilities:Ul})),functionCallContracts:e.functionCallContracts,fileCache:Q}),tn=zD(fi);Ae.set(Ge.index,tn),Se.set(Ge.index,fi),j.set(Ge.index,wt),q.push({editable:Ge.editable,source:tn})}let ge=new Map,Ce=new Map;if(ie)for(let Ge of le.attributes??[]){let fi=await ni({file:le.sourceFile,source:ie,sourceRange:Ge.sourceRange,expression:Ge.source?.expression??Ge.value,sourceInfo:Ge.source,readFile:tn=>D.readFile(tn),exists:H,graph:h,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:tn,adapterId:Vt,capabilities:Kr})=>({sourceType:tn,adapterId:Vt,capabilities:Kr})),functionCallContracts:e.functionCallContracts,fileCache:Q}),wt=await vS({element:le,file:le.sourceFile,source:ie,propertyName:Ge.name,readFile:tn=>D.readFile(tn),exists:H,graph:h,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:tn,adapterId:Vt,capabilities:Kr})=>({sourceType:tn,adapterId:Vt,capabilities:Kr})),functionCallContracts:e.functionCallContracts,fileCache:Q});Ce.set(Ge.name,wt),ge.set(Ge.name,fi)}let Te=OS(HD(ve.writeTarget),q),Qe=z({key:ne,element:le,provenances:j}),or=BS(le),_n=ie?await fE({element:le,graph:h,file:le.sourceFile,source:ie,readFile:Ge=>D.readFile(Ge),exists:H,fileCache:W}):void 0,Ur=h.regions.find(Ge=>Ge.kind==="conditional-region"&&Ge.childKeys.includes(ne)),bt,en=Ur?.sourceCandidates?.[0];if(ie&&Ur&&en?.kind==="conditional-branch"){let Ge=await hp({file:le.sourceFile,source:ie,target:{kind:"conditional-branch",candidate:en},readFile:wt=>D.readFile(wt),exists:H,graph:h,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:wt,adapterId:tn,capabilities:Vt})=>({sourceType:wt,adapterId:tn,capabilities:Vt})),functionCallContracts:e.functionCallContracts,fileCache:Q});bt={currentBranch:Ur.childKeys.indexOf(ne)<=0?"then":"else",availableBranches:Ur.childKeys.length>1?["then","else"]:["then"],conditionExpression:en.conditionExpression,provenance:{finalSource:Ge.finalSource?{kind:Ge.finalSource.kind,file:Ge.finalSource.file,displayPath:Ge.finalSource.displayPath}:null,chain:Ge.chain.map(wt=>({kind:wt.kind,file:wt.file,displayName:wt.displayName,canEditHere:wt.canEditHere})),confidence:Ge.confidence,editMode:Ge.editMode,diagnostics:Ge.diagnostics.map(wt=>({code:wt.code,message:wt.message}))}}}J.set(ne,{textSources:Ae,textTargets:Se,elementPropertyTargets:ge,propertyProvenances:Ce,isRepeat:fM(ne,h),provenances:j,writeTarget:Te,componentSemantic:Qe,styleSource:or,conditional:bt,dynamicData:_n})}return J}function B(h){return typeof n.getVersion=="function"?n.getVersion(h):0}function X(h,R){let _=o.initialVersions.get(h.key)??0;for(let T of R.values())_=Math.max(_,T);return Math.max(_,h.graph?.version??0)}function $(h){return i.get(h)?.graph?.version??o.initialVersions.get(h)??0}function G(h){try{return $(o.resolveSelector(h.composition).key)}catch{return 0}}async function M(h,R,_=n,T={}){let L=await Ca(h,R,D=>_.readFile(D),D=>_.exists(D),{additionalEntries:await Fe(h,_),...T});if(L.diagnostics.length>0)throw new Is(L.diagnostics);return T.validationOnly||f.remember(L.parsedModules.values()),L}async function fe(h,R,_={}){let T=i.get(h);if(!T)return null;let L=_.sourceCache??Pp(d,[]),D=_.fileSystem??Cp(n),{graph:J,allSources:z,parsedModules:Q,entryModule:W}=await M(T.entryFile,R,D,{version:T.graph?.version??1}),H=new Map;for(let bt of z.keys())H.set(bt,B(bt));let ne=Math.max(X(T,H),_.minimumVersion??0);_.changed&&ne<=(T.graph?.version??0)&&(ne=(T.graph?.version??0)+1),J.version=ne;for(let[bt,en]of z)rl(L,bt,en,il);let le=await ot(T.composition,T.entryFile,z,L,D);J.routeId=T.routeId,J.composition=T.composition;let ve=tc(J),ie=ma(ve,J),Ae=await F(J,ve,z,L,Q,D);lt(ie,Ae);let Se=Ee(J,ie,Ae),j=Vr(Ae),q=ZS(NS(J,ve,ie,{canUpdateTextByKey:Se,dynamicDataSummaryByKey:j}),J,Ae),ge=yn({route:T.routeId,composition:T.composition,entryFile:T.entryFile,version:ne,source:R,ast:W?.ast}),Ce=Gy(ge),Te=null,Qe=[];if(ge.ok){qD(q,J,ge.projection,Q);let bt=ec({composition:T.composition,entryFile:T.entryFile,graph:J,parsedModules:Q,projection:ge.projection});if(bt.diagnostics.length===0){let en=Hi({composition:T.composition,entryFile:T.entryFile,graph:J,parsedModules:Q,projection:ge.projection,documentVersion:ne,roots:bt.roots});en.diagnostics.length===0&&(Te=en,Qe=en.descriptors)}}let or={...q,composition:T.composition,pageBlocks:Qe,...le?{styleContext:le}:{},pageComposition:Ce},_n=new Set([T.entryFile,...z.keys()]);if(le){_n.add(le.entryCss.path);for(let bt of le.stylesheets)_n.add(bt.path)}let Ur={...T,dependencyFiles:_n,graph:J,topology:ve,capabilities:ie,document:or,pageBlockIndex:Te,pageComposition:Ce,pageCompositionProjection:ge.projection,pagePlacementByKey:ge.ok?ge.projection.placementByKey:null,pagePlacementUnitByKey:ge.ok?ge.projection.placementUnitByKey:null,pageUnitByKey:ge.ok?ge.projection.unitByKey:null,pagePlacementsByUnitKey:ge.ok?ge.projection.placementsByUnitKey:null,documentIndex:YS(or),detailProjections:Ae,fileVersions:H,styleContext:le};if(_.publish===!1)return Ur;for(let bt of _n){let en=z.get(bt)??L.get(bt);en!==void 0&&(rl(d,bt,en,il),g.delete(bt))}return v(T,_n),Object.assign(T,Ur),T}async function Fe(h,R=n){let _=[];for(let T of sM(h))typeof R.exists=="function"&&await R.exists(T)&&_.push({file:T,source:await R.readFile(T)});return _}async function ot(h,R,_,T,L){let D=[];for(let[H,ne]of _){if(Ap(H)){D.push(H);continue}for(let le of cM(ne)){let ve=hI(H,le);ve&&D.push(ve)}}if(!D.length){for(let H of aM(R))if(await L.exists(H)){D.push(H);break}}let J=new Map,z=dM(D).slice(0,sI);for(;z.length>0&&J.size<sI;){let H=z.shift();if(J.has(H)||!Ap(H))continue;let ne=await Tt(H,T,L);if(ne!==null){J.set(H,{path:H,content:ne});for(let le of lM(ne)){let ve=hI(H,le);ve&&!J.has(ve)&&!z.includes(ve)&&z.push(ve)}}}let Q=[...J.values()].map(H=>({...H,hash:ke(H.content)})),W=Q[0];return W?{composition:h,revision:ke(JSON.stringify(Q.map(({path:H,hash:ne})=>({path:H,hash:ne})))),entryCss:W,stylesheets:Q.slice(1)}:null}async function Tt(h,R,_){let T=R.get(h);if(T!==void 0)return T;if(!await _.exists(h))return null;let L=await _.readFile(h);return rl(R,h,L,il),L}function Vr(h){let R=new Map;for(let[_,T]of h)T.dynamicData?.bindings.length&&R.set(_,kE(T.dynamicData.bindings));return R}function Ee(h,R,_){let T=new Map;for(let[L,D]of h.elements){if(!R.get(L)?.canUpdateText){T.set(L,!1);continue}let z=_.get(L),Q=D.textSegments.some(W=>{if(!W.editable)return!1;let H=z?.provenances.get(W.index)??null;return!H||Le(H)});T.set(L,Q)}return T}function lt(h,R){for(let[_,T]of R){let L=h.get(_);L?.canUpdateText&&T.dynamicData?.bindings.some(D=>D.readonly&&(D.targetKind==="text"||D.targetKind==="richtext"))&&h.set(_,{...L,canUpdateText:!1})}}function Le(h){return h.editMode==="direct"||h.editMode==="proxy"||h.editMode==="upstream"}async function pe(h,R={}){let _=[...new Set(h)],T=R.affectedCompositionKeys!==void 0,L=T?new Set(R.affectedCompositionKeys):A(_);if(!T&&(L.size===0||!w(_)))for(let W of i.values())Am(W,_)&&L.add(W.key);let D=!T&&L.size===0&&_.some(gI),J=R.publish===!1?Pp(d,_):void 0,z={rebuiltRoutes:[],failedRoutes:[],...R.publish===!1?{candidateRouteStates:[],candidateSourceCache:J}:{}},Q=Cp(n);for(let W of i.values())if(!(R.excludedCompositionKeys?.has(W.key)||!(L.has(W.key)||D)))try{let ne=!!W.graph,le=await Q.readFile(W.entryFile),ve=await fe(W.key,le,{...R,fileSystem:Q,...J?{sourceCache:J}:{}});ve?.graph&&(z.rebuiltRoutes.push({documentChanged:ne,composition:W.composition,routeId:W.routeId,version:ve.graph.version}),z.candidateRouteStates?.push({composition:W.composition,key:W.key,routeId:W.routeId,state:ve}))}catch(ne){z.failedRoutes.push({...rI(W.routeId,ne),composition:W.composition})}return z}function $e(h){let R=[...new Set(h)],_=A(R);if(_.size>0&&w(R))return[..._];for(let T of i.values())Am(T,R)&&_.add(T.key);return[..._]}function kt(h){let R=new Set($e(h));return o.entries.filter(_=>R.has(_.key)).map(_=>_.context)}function pn(h){return[...new Set($e(h))].sort((_,T)=>_<T?-1:_>T?1:0).map(_=>o.getByKey(_)?.context).filter(_=>_!==void 0)}function _t(h,R){let _=new Set($e(R)),T=h.provenance?.affectedCompositions??[];if(T.length===0)return _;if([...new Set(T.map(D=>o.resolveContext(D).key))].some(D=>!_.has(D)))throw new Error("History provenance does not match the affected composition index.");return _}function Fs(h,R){let _=h.composition??h.provenance?.initiatingComposition;if(_){let D=o.resolveContext(_);return{context:D.context,key:D.key}}let T=[...new Set($e(R))];if(T.length!==1)throw new Error(`Legacy history entry cannot be attributed to a unique composition (affected composition count: ${T.length}).`);let L=o.getByKey(T[0]);if(!L)throw new Error("Legacy history entry references an unknown affected composition.");return{context:L.context,key:L.key}}function Ll(h,R){r.emit({type:"operation-completed",composition:h.composition,result:h});for(let{composition:_,version:T}of R.rebuiltRoutes)r.emit({type:"document-changed",composition:_,version:T});for(let{composition:_,message:T}of R.failedRoutes)r.emit({type:"graph-error",composition:_,message:T})}function Am(h,R){return R.some(_=>h.dependencyFiles.has(_)||h.entryFile===_||h.graph?.fileIndex.has(_))}function Tm(h){for(let R of h)a.add(R);c||I()||(c=(async()=>{t="building";let R=!1;try{for(;a.size>0;){if(I())return;await Gv(),await y.runExclusive(async()=>{if(p>0||I())return;let _=[...a];a.clear();let T=await wm(_);if(T.length===0)return;let L=$e(T);for(let z of L){let Q=i.get(z)?.composition;Q&&r.emit({type:"graph-invalidated",composition:Q})}let{rebuiltRoutes:D,failedRoutes:J}=await pe(T,{changed:!0});for(let{documentChanged:z,composition:Q,version:W}of D)r.emit({type:"graph-ready",composition:Q,version:W}),z&&r.emit({type:"document-changed",composition:Q,version:W});for(let{composition:z,message:Q}of J)R=!0,r.emit({type:"graph-error",composition:z,message:Q})})}}finally{c=null,t!=="disposed"&&(t=!R&&[...i.values()].some(_=>_.graph)?"ready":"idle"),a.size>0&&Tm([])}})())}async function Gv(){for(;p>0;)await new Promise(h=>setTimeout(h,0))}async function wm(h){let R=[];for(let _ of new Set(h)){let T=d.get(_);if(T===void 0){if(g.has(_)&&!await n.exists(_))continue;g.delete(_),R.push(_);continue}try{await n.readFile(_)!==T&&(g.delete(_),R.push(_))}catch(L){if(!ZD(L))try{if(await n.exists(_))continue}catch{continue}g.add(_),R.push(_)}}return R}function Om(h){oI(d,h);for(let R of h)R.exists===!1?g.add(R.file):g.delete(R.file)}function Fm(h){g.clear();for(let R of h)g.add(R)}async function Lm(h){let R=await wm(h);if(R.length===0)return;let _=$e(R);for(let D of _){let J=i.get(D)?.composition;J&&r.emit({type:"graph-invalidated",composition:J})}let{rebuiltRoutes:T,failedRoutes:L}=await pe(R,{changed:!0});for(let{documentChanged:D,composition:J,version:z}of T)r.emit({type:"graph-ready",composition:J,version:z}),D&&r.emit({type:"document-changed",composition:J,version:z});for(let{composition:D,message:J}of L)r.emit({type:"graph-error",composition:D,message:J})}async function Yv(h,R){let _=Io(h,R);if(!_?.graph)return;let T=$t(h)??h,L=_.graph.elements.get(T);L&&await Lm([L.sourceFile])}async function Dm(h){let R=new Set;if(h.target.kind==="node"){let _=Io(h.target.key,h.composition),T=$t(h.target.key)??h.target.key,L=_?.graph?.elements.get(T);L&&R.add(L.sourceFile)}else if(h.target.kind==="route"){let _=i.get(o.resolveSelector(h.target.composition).key);_&&R.add(_.entryFile)}else if(h.target.kind==="page-unit"){let _=i.get(o.resolveSelector(h.target.composition).key);_&&R.add(_.entryFile)}else if(h.target.kind==="page-block"){let _=i.get(o.resolveSelector(h.target.composition).key),T=_?.pageBlockIndex?.bindings.get(h.target.blockKey);if(T&&(R.add(T.ownerFile),R.add(T.descriptor.source.file)),_?.pageBlockIndex&&h.params.kind==="move-node"&&"kind"in h.params.target&&h.params.target.kind==="block-boundary"){let L=_.pageBlockIndex.bindings.get(h.params.target.anchorBlockKey);L&&(R.add(L.ownerFile),R.add(L.descriptor.source.file))}}else if(h.target.kind==="source-file")R.add(h.target.path);else if(h.target.kind==="source-batch")for(let _ of h.target.paths)R.add(_);if(h.params.kind==="move-node"&&!("kind"in h.params.target)){let _=[h.params.target.parentKey,...h.params.target.relation==="before"||h.params.target.relation==="after"?[h.params.target.anchorKey]:[]];for(let T of _){let L=Io(T,h.composition),D=$t(T)??T,J=L?.graph?.elements.get(D);J&&R.add(J.sourceFile)}}await Lm(R)}async function Zv(h){if(h.params.kind!=="source-edit")return Bl(h,"invalid-params","source-edit requires source-edit params");for(let R of h.params.edits){let _=YD(R);if(!_.ok)return Bl(h,_.errorCode,_.message,_.details)}p+=1;try{let R=await sk(h.params.edits);if(!R.ok)return Bl(h,R.errorCode,R.message,R.details);await Dm(h);let _={operationId:h.id,kind:"source-edit",target:h.target,documentVersion:h.documentVersion,conflictPolicy:h.params.conflictPolicy,edits:h.params.edits.map(T=>T.operation==="delete"?{operation:"delete",file:T.path,baseContentHash:T.baseContentHash??null}:{operation:"upsert",file:T.path,baseContentHash:T.baseContentHash??null,content:T.content})};return await rr({request:h,filePlan:_})}catch(R){return{composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!1,resultVersion:G(h),error:{code:U.INTERNAL_ERROR,message:Ot(R)}}}finally{p-=1}}async function qv(h){if(h.target.kind!=="project"||h.params.kind!=="insert-page-resource")return Y(h,U.INVALID_PARAMS,"insert-page-resource requires project target and matching params.");p+=1;try{let R=await mi({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:[...h.params.artifact.components.flatMap(T=>T.materialization.files.map(L=>({path:L.pathTemplate,content:L.content}))),...h.params.artifact.pages.flatMap(T=>T.materialization.files.map(L=>({path:L.pathTemplate,content:L.content})))],exists:T=>n.exists(T),readFile:T=>n.readFile(T)});if(!R.ok)return Y(h,U.MATERIALIZATION_REJECTED,R.message);let _=await rd({artifact:h.params.artifact,exists:T=>n.exists(T)});return _.ok?await rr({request:h,filePlan:{operationId:h.id,kind:"source-edit",target:h.target,documentVersion:h.documentVersion,conflictPolicy:"overwrite",edits:_.files},output:{kind:"insert-page-resource",package_instance_id:_.packageInstanceId,pages:_.pages},historyPolicy:"none"}):Y(h,_.code==="MATERIALIZATION_CONFLICT"?U.MATERIALIZATION_CONFLICT:U.MATERIALIZATION_REJECTED,_.message,_.path?{path:_.path}:void 0)}catch(R){return Y(h,U.INTERNAL_ERROR,Ot(R))}finally{p-=1}}async function Qv(h){if(h.target.kind!=="project"||h.params.kind!=="delete-page-source")return Y(h,U.INVALID_PARAMS,"delete-page-source requires project target and matching params.");if(!n.listFiles)return Y(h,U.PLAN_FAILED,"Complete project file listing is required for page deletion.");p+=1;try{let R=yI(await n.listFiles({maxFiles:5e4,maxDepth:64}));if(R.truncated)return Y(h,U.PLAN_FAILED,"Project file listing is incomplete; page deletion was refused.",{truncationReasons:R.truncated.reasons});let _=R.files.filter(({path:J})=>/\.(?:tsx?|jsx?)$/.test(J)),T=Object.fromEntries(await Promise.all(_.map(async({path:J})=>[J,await n.readFile(J)]))),L=Xx({expectedUrlPath:h.params.expectedUrlPath,files:T});if(!L.ok)return Y(h,L.code==="HOME_PAGE_LOCKED"?U.HOME_PAGE_LOCKED:L.code==="ROUTE_NOT_FOUND"?U.ROUTE_NOT_FOUND:U.PLAN_FAILED,L.message);let D=await Promise.all(L.edits.map(async J=>({...J,baseContentHash:ke(await n.readFile(J.file))})));return rr({request:h,filePlan:{operationId:h.id,kind:"source-edit",target:h.target,documentVersion:h.documentVersion,conflictPolicy:"compare-and-swap",edits:D},output:{kind:"delete-page-source",deleted_files:L.deletedFiles,updated_files:L.updatedFiles,preserved_shared_files:L.preservedSharedFiles,warnings:L.warnings},historyPolicy:"none"})}catch(R){return Y(h,U.INTERNAL_ERROR,Ot(R))}finally{p-=1}}async function ek(h,R){if(h.kind!=="insert-child"&&h.kind!=="replace-node")return Y(h,U.UNSUPPORTED_OPERATION,"Only page-unit insert-child and replace-node materialization are supported by this transaction.");if(h.params.kind!=="insert-child"&&h.params.kind!=="replace-node"||h.kind!==h.params.kind)return Y(h,U.INVALID_PARAMS,"Page-unit materialization operation kind must match its params.");if(h.params.kind==="insert-child"){if(!("kind"in h.params.position)||h.params.position.kind!=="page-composition")return Y(h,U.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.");if(h.params.position.documentVersion!==h.documentVersion)return Y(h,U.VERSION_STALE,"Page-unit insert-child placement belongs to a different document version.")}let _=R.document,T=R.pageCompositionProjection;if(!_||_.pageComposition?.status!=="supported"||!T||T.status!=="supported")return Y(h,U.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(h.documentVersion!==_.version||T.documentVersion!==_.version)return Y(h,U.VERSION_STALE,`Document version ${h.documentVersion} is stale (current: ${_.version}).`);let L=h.params.node.kind==="component-call"?h.params.node.materialization:void 0;if(!L)return Y(h,U.UNSUPPORTED_OPERATION,"Page-unit insertion currently requires a static materialization manifest.");let D=h.params.kind==="insert-child"?h.params.position:null,J=await mi({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:L.files.map(W=>({path:W.pathTemplate,content:W.content})),exists:W=>n.exists(W),readFile:W=>n.readFile(W)});if(!J.ok)return Y(h,U.MATERIALIZATION_REJECTED,J.message);let z=await cI(n,Object.keys(L.projectDependencies??{})),Q=await ud({manifest:L,generatedRoot:"components/site/generated",controlledFiles:L.files.map(W=>({pathTemplate:W.pathTemplate})),exists:W=>n.exists(W),availableHostDependencies:z,hostCapabilities:qu(),commit:async W=>{let H=await n.readFile(R.entryFile),ne=R.document,le=R.pageCompositionProjection;if(!ne||ne.pageComposition?.status!=="supported"||ne.version!==h.documentVersion||!le||le.status!=="supported"||le.documentVersion!==ne.version)return{ok:!0,data:Y(h,U.VERSION_STALE,"The route changed before the page-unit insertion could commit.")};let ve=W.entry.path,ie=pk(W.instanceName),Ae,Se=[];if(h.params.kind==="insert-child"){if(!D||!("kind"in D)||D.kind!=="page-composition")return{ok:!0,data:Y(h,U.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.")};let Ce=$i({routeId:R.routeId,entryFile:R.entryFile,currentDocumentVersion:ne.version,expectedDocumentVersion:h.documentVersion,source:H,projection:le,placementKey:D.placementKey,component:{source:ve,exportName:W.entry.export.kind==="default"?"default":W.entry.export.name,localName:ie}});if(!Ce.ok)return{ok:!0,data:Y(h,Vl(Ce.error.code),Ce.error.message,{diagnostics:Ce.error.diagnostics})};let Te=Ce.plan.rewriteStep,Qe;switch(Te.kind){case"insert-root-expression":Qe=Vi({source:H,locator:Te.locator,expectedSourceHash:Te.sourceHash,action:{kind:"insert",jsx:Te.node.jsx,placement:Te.placement,replaceOriginal:Te.replaceOriginal}});break;case"insert-child":Qe=on({source:H,locator:Te.parentLocator,node:Te.node,placement:Te.placement,...Te.anchorLocator?{anchorLocator:Te.anchorLocator}:{}});break;default:Qe={ok:!1,source:H,diagnostic:{code:"unsupported-syntax",message:`Unsupported route composition rewrite: ${String(Te)}`}}}if(!Qe.ok)return{ok:!0,data:Y(h,U.AST_PARSE_ERROR,Qe.diagnostic.message)};Ae=Qe.source}else{let Ce=Pd({routeId:R.routeId,composition:R.composition,entryFile:R.entryFile,currentDocumentVersion:ne.version,expectedDocumentVersion:h.documentVersion,source:H,projection:le,placementUnitKey:h.target.placementUnitKey,operation:"replace-node"});if(!Ce.ok)return{ok:!0,data:Y(h,Vl(Ce.error.code),Ce.error.message,{diagnostics:Ce.error.diagnostics})};let Te=Ce.plan.rewriteStep,Qe;switch(Te.kind){case"replace-root-expression":Qe=Vi({source:H,locator:Te.locator,expectedSourceHash:Te.sourceHash,action:{kind:"replace",jsx:`<${ie} />`}});break;case"replace-node":Qe=ko({source:H,locator:Te.locator,node:{jsx:`<${ie} />`}});break;default:Qe={ok:!1,source:H,diagnostic:{message:`Unsupported page-unit replacement rewrite: ${Te.kind}`}}}if(!Qe.ok)return{ok:!0,data:Y(h,U.AST_PARSE_ERROR,Qe.diagnostic.message)};let or=await Ml({routeState:R,placementUnitKey:h.target.placementUnitKey,source:H,mutatedSource:Qe.source});Ae=or.source,Se=await Promise.all(or.files.map(async _n=>({operation:"delete",file:_n,baseContentHash:ke(await n.readFile(_n))})))}let j=sn({source:Ae,moduleSpecifier:b(R.entryFile,ve),imports:W.entry.export.kind==="default"?[{kind:"default",local:ie}]:[{kind:"named",imported:W.entry.export.name,local:ie}]});if(!j.ok)return{ok:!0,data:Y(h,U.AST_PARSE_ERROR,j.diagnostic.message)};let q=W.files.map(Ce=>({operation:"create-only",file:Ce.path,content:Ce.content})),ge=[{operation:"upsert",file:R.entryFile,content:j.source,baseContentHash:ke(H)},...q,...Se];p+=1;try{let Ce=await rr({request:h,filePlan:{operationId:h.id,kind:"source-edit",target:{kind:"source-file",path:R.entryFile},documentVersion:h.documentVersion,conflictPolicy:"compare-and-swap",edits:ge}});return!Ce.ok&&Ce.error?.message.includes("MATERIALIZATION_INSTANCE_CONFLICT")?{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:Ce.error?.message??"Static prefab instance conflicted during commit."}}:{ok:!0,data:Ce}}finally{p-=1}}});return Q.ok?Q.data:Y(h,Q.error.code==="MATERIALIZATION_INSTANCE_CONFLICT"?U.MATERIALIZATION_CONFLICT:U.MATERIALIZATION_REJECTED,Q.error.message,{materializationCode:Q.error.code})}async function tk(h,R){if(h.kind!=="insert-child"&&h.kind!=="replace-node")return Y(h,U.UNSUPPORTED_OPERATION,"Only page-block insert-child and replace-node use this materialization transaction.");if(h.params.kind!==h.kind||h.kind==="replace-node"&&h.params.kind!=="replace-node"||h.kind==="insert-child"&&h.params.kind!=="insert-child")return Y(h,U.INVALID_PARAMS,"Page-block materialization operation kind must match its params.");let _=R.document,T=R.pageBlockIndex;if(!_||!T||T.diagnostics.length>0)return Y(h,U.UNSUPPORTED_OPERATION,"The current route has no complete verified page-block index.");if(h.documentVersion!==_.version||T.documentVersion!==_.version)return Y(h,U.VERSION_STALE,`Document version ${h.documentVersion} is stale (current: ${_.version}).`);let L=jo(T,h.target,h.documentVersion,h.selectionRef);if(!L.ok)return Y(h,Ls(L.code),L.message);let D=L.binding;if(!(h.kind==="insert-child"?D.descriptor.capabilities.insert:D.descriptor.capabilities.replace)){let ie=D.descriptor.unavailableReasons?.[h.kind==="insert-child"?"insert":"replace"]?.reason??"The selected page block does not permit this operation.";return Y(h,U.UNSUPPORTED_OPERATION,ie)}let z=(h.kind==="insert-child",h.params);if(z.kind!==h.kind)return Y(h,U.INVALID_PARAMS,"Page-block materialization operation kind must match its params.");let Q=z.node;if(Q.kind!=="component-call"||!Q.materialization)return Y(h,U.UNSUPPORTED_OPERATION,"Page-block materialization requires a static component manifest.");let W;if(z.kind==="insert-child"){let ie=z.position;if(!("kind"in ie&&ie.kind==="block-boundary"))return Y(h,U.INVALID_PARAMS,"Page-block insert-child requires a block-boundary position.");if(ie.documentVersion!==h.documentVersion)return Y(h,U.VERSION_STALE,"The block insertion boundary belongs to a different document version.");let Ae=nc(T,ie);if(!Ae.ok)return Y(h,Ls(Ae.code),Ae.message);W=Ae.boundary}let H=Q.materialization,ne=await mi({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:H.files.map(ie=>({path:ie.pathTemplate,content:ie.content})),exists:ie=>n.exists(ie),readFile:ie=>n.readFile(ie)});if(!ne.ok)return Y(h,U.MATERIALIZATION_REJECTED,ne.message);let le=await cI(n,Object.keys(H.projectDependencies??{})),ve=await ud({manifest:H,generatedRoot:"components/site/generated",controlledFiles:H.files.map(ie=>({pathTemplate:ie.pathTemplate})),exists:ie=>n.exists(ie),availableHostDependencies:le,hostCapabilities:qu(),commit:async ie=>{let Ae=R.document,Se=R.pageBlockIndex;if(!Ae||!Se||Ae.version!==h.documentVersion||Se.documentVersion!==Ae.version||!Se.bindings.has(D.blockKey))return{ok:!0,data:Y(h,U.VERSION_STALE,"The route or selected block changed before materialization could commit.")};let j=Se.bindings.get(D.blockKey);if(!j||j.ownerFile!==D.ownerFile||j.ownerSourceHash!==D.ownerSourceHash||j.sourceHash!==D.sourceHash)return{ok:!0,data:Y(h,U.VERSION_STALE,"The selected block owner or source changed before materialization could commit.")};let q=new Set([D.ownerFile,D.descriptor.source.file,...W?[W.ownerFile,W.anchorLocator.file,...W.parentLocator?[W.parentLocator.file]:[]]:[]]),ge=new Map;try{for(let Te of q)ge.set(Te,await n.readFile(Te))}catch{return{ok:!0,data:Y(h,U.VERSION_STALE,"A selected owner, root, or boundary file is no longer readable.")}}let Ce=_x({operationId:h.id,documentVersion:h.documentVersion,target:h.target,binding:D,...W?{boundary:W}:{},operation:z.kind,materialization:ie,files:ge});if(!Ce.ok){let Te=ik(Ce.code);return{ok:!0,data:Y(h,Te,Ce.message,{materializationCode:Ce.code})}}p+=1;try{let Te=await rr({request:h,filePlan:Ce.plan});return!Te.ok&&Te.error?.message.includes("MATERIALIZATION_INSTANCE_CONFLICT")?{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:Te.error.message||"Static prefab instance conflicted during commit."}}:{ok:!0,data:Te}}finally{p-=1}}});return ve.ok?ve.data:Y(h,ve.error.code==="MATERIALIZATION_INSTANCE_CONFLICT"?U.MATERIALIZATION_CONFLICT:U.MATERIALIZATION_REJECTED,ve.error.message,{materializationCode:ve.error.code})}async function nk(h,R){if(h.kind!=="move-node"&&h.kind!=="remove-node")return Y(h,U.UNSUPPORTED_OPERATION,"Only page-unit move-node and remove-node are currently supported by the page composition transaction.");let _=R.document,T=R.pageCompositionProjection;if(!_||_.pageComposition?.status!=="supported"||!T||T.status!=="supported")return Y(h,U.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(h.documentVersion!==_.version||T.documentVersion!==_.version)return Y(h,U.VERSION_STALE,`Document version ${h.documentVersion} is stale (current: ${_.version}).`);let L=await n.readFile(R.entryFile),D=Pd({routeId:R.routeId,composition:R.composition,entryFile:R.entryFile,currentDocumentVersion:_.version,expectedDocumentVersion:h.documentVersion,source:L,projection:T,placementUnitKey:h.target.placementUnitKey,operation:h.kind,targetPlacement:h.kind==="move-node"&&h.params.kind==="move-node"&&"kind"in h.params.target&&h.params.target.kind==="page-composition"?h.params.target:void 0});if(!D.ok)return Y(h,Vl(D.error.code),D.error.message,{diagnostics:D.error.diagnostics});let J=D.plan.rewriteStep,z;switch(J.kind){case"move-node":z=eo({source:L,locator:J.locator,targetParentLocator:J.targetParentLocator,placement:J.placement,...J.anchorLocator?{anchorLocator:J.anchorLocator}:{}});break;case"remove-node":z=qr({source:L,locator:J.locator});break;case"remove-root-expression":z=Vi({source:L,locator:J.locator,expectedSourceHash:J.sourceHash,action:{kind:"remove"}});break;default:z={ok:!1,source:L,diagnostic:{message:`Unsupported page-unit mutation rewrite: ${J.kind}`}}}if(!z.ok)return Y(h,U.AST_PARSE_ERROR,z.diagnostic.message);let Q=z.source,W=[];if(h.kind==="remove-node"){let ne=await Ml({routeState:R,placementUnitKey:h.target.placementUnitKey,source:L,mutatedSource:Q});Q=ne.source,W=await Promise.all(ne.files.map(async le=>({operation:"delete",file:le,baseContentHash:ke(await n.readFile(le))})))}let H=[{operation:"upsert",file:R.entryFile,content:Q,baseContentHash:ke(L)},...W];p+=1;try{return await rr({request:h,filePlan:{operationId:h.id,kind:"source-edit",target:{kind:"source-file",path:R.entryFile},documentVersion:h.documentVersion,conflictPolicy:"compare-and-swap",edits:H}})}finally{p-=1}}async function rk(h,R){if(h.kind!=="move-node"&&h.kind!=="remove-node")return Y(h,U.UNSUPPORTED_OPERATION,"Only page-block move-node and remove-node use this source transaction.");let _=R.document,T=R.pageBlockIndex;if(!_||!T||T.diagnostics.length>0)return Y(h,U.UNSUPPORTED_OPERATION,"The current route has no complete verified page-block index.");if(h.documentVersion!==_.version||T.documentVersion!==_.version)return Y(h,U.VERSION_STALE,`Document version ${h.documentVersion} is stale (current: ${_.version}).`);let L=jo(T,h.target,h.documentVersion,h.selectionRef);if(!L.ok)return Y(h,Ls(L.code),L.message);let D=L.binding;if(D.documentVersion!==_.version)return Y(h,U.VERSION_STALE,"The resolved page-block binding is stale.");if(!(h.kind==="move-node"?D.descriptor.capabilities.move:D.descriptor.capabilities.remove)){let Se=D.descriptor.unavailableReasons?.[h.kind==="move-node"?"move":"remove"]?.reason??"The selected block does not permit this operation.";return Y(h,U.UNSUPPORTED_OPERATION,Se)}if(h.kind==="remove-node"){let Se=[...i.values()].filter(j=>j.dependencyFiles.has(D.ownerFile));if(Se.includes(R)||Se.push(R),Se.some(j=>!j.pageBlockIndex||j.pageBlockIndex.descriptors.length<=1))return Y(h,U.UNSUPPORTED_OPERATION,"The selected source is the last editable page block in an affected composition.")}let z=null;if(h.kind==="move-node"){if(h.params.kind!=="move-node"||!("kind"in h.params.target)||h.params.target.kind!=="block-boundary")return Y(h,U.INVALID_PARAMS,"Page-block move requires a block-boundary target.");if(h.params.target.anchorBlockKey===D.blockKey)return Y(h,U.INVALID_TARGET,"A page block cannot be moved relative to itself.");let Se=nc(T,h.params.target);if(!Se.ok)return Y(h,Ls(Se.code),Se.message);let j=T.bindings.get(h.params.target.anchorBlockKey);if(!j||!D.descriptor.siblingBlockKeys.includes(j.blockKey)||!j.descriptor.siblingBlockKeys.includes(D.blockKey)||j.ownerFile!==D.ownerFile||j.root.ownerNode.kind!==D.root.ownerNode.kind||j.root.ownerNode.key!==D.root.ownerNode.key||j.root.parentStructuralPath!==D.root.parentStructuralPath)return Y(h,U.INVALID_TARGET,"The selected block and boundary anchor are not verified same-owner source siblings.");if(z=Se.boundary,z.ownerFile!==D.ownerFile||z.sourceHash!==D.ownerSourceHash||!z.parentLocator)return Y(h,U.INVALID_TARGET,"The move boundary does not belong to the selected block's source owner.")}let Q=D.ownerFile,W=await n.readFile(Q);if(ke(W)!==D.ownerSourceHash)return Y(h,U.VERSION_STALE,"The page-block owner source changed after resolution.");let H=D.descriptor.source.file===Q?W:await n.readFile(D.descriptor.source.file);if(ke(H)!==D.descriptor.source.contentHash)return Y(h,U.VERSION_STALE,"The selected page-block source changed after resolution.");let ne=ok(D),le=h.kind==="remove-node"?qr({source:W,locator:ne}):eo({source:W,locator:ne,targetParentLocator:Dl(z.parentLocator),anchorLocator:Dl(z.anchorLocator),placement:z.placement});if(!le.ok)return Y(h,U.AST_PARSE_ERROR,le.diagnostic.message);let ve=le.source,ie=[];if(h.kind==="remove-node"&&D.root.ownerNode.kind==="route-member"&&D.root.callChain.length>0&&D.descriptor.placementUnitKey){let Se=await Ml({routeState:R,placementUnitKey:D.descriptor.placementUnitKey,source:W,mutatedSource:ve});ve=Se.source,ie=Se.files}let Ae=[{operation:"upsert",file:Q,content:ve,baseContentHash:D.ownerSourceHash},...await Promise.all(ie.map(async Se=>({operation:"delete",file:Se,baseContentHash:ke(await n.readFile(Se))})))];p+=1;try{return await rr({request:h,filePlan:{operationId:h.id,kind:"source-edit",target:h.target,documentVersion:h.documentVersion,conflictPolicy:"compare-and-swap",edits:Ae}})}finally{p-=1}}function ok(h){return Dl(h.ownerLocator)}function Dl(h){return{kind:"jsx-node",strategy:"source-range",sourceRange:h.sourceRange,...h.structuralPath&&h.componentName?{expectedIdentity:{file:h.file,component:h.componentName,structuralPath:h.structuralPath}}:{}}}function Ls(h){return h==="VERSION_STALE"?U.VERSION_STALE:h==="INVALID_PARAMS"?U.INVALID_PARAMS:U.INVALID_TARGET}function ik(h){return h==="VERSION_STALE"?U.VERSION_STALE:h==="INVALID_PARAMS"?U.INVALID_PARAMS:h==="INVALID_TARGET"?U.INVALID_TARGET:h.startsWith("MATERIALIZATION_")?U.MATERIALIZATION_REJECTED:U.UNSUPPORTED_OPERATION}async function Ml(h){let R={source:h.mutatedSource,files:[]},_=h.routeState.graph,T=h.routeState.pageCompositionProjection;if(!_||!T||T.status!=="supported"||!n.listFiles)return R;let D=T.placementUnitByKey.get(h.placementUnitKey)?.sourceRange;if(!D)return R;let J=[..._.elements.values()].find(j=>j.sourceFile===h.routeState.entryFile&&j.importedFrom&&E(j.sourceRange,D));if(!J?.importedFrom||!J.exportName)return R;let z=S(J.importedFrom),Q="components/site/generated/";if(!z.startsWith(Q))return R;let W=z.slice(Q.length).split("/")[0];if(!W||!/-[0-9a-f]{8}$/i.test(W))return R;let H=`${Q}${W}`;if([..._.elements.values()].filter(j=>j.sourceFile===h.routeState.entryFile&&S(j.importedFrom??"")===z).length!==1)return R;let le=await n.listFiles({maxFiles:5e3,maxDepth:32}),ve=Array.isArray(le)?le:le.files;if(!Array.isArray(le)&&le.truncated)return R;let ie=ve.map(({path:j})=>j).filter(j=>j===H||j.startsWith(`${H}/`));if(ie.length===0||!ie.includes(z))return R;for(let{path:j}of ve)if(!(j===h.routeState.entryFile||j===H||j.startsWith(`${H}/`)))try{if((await n.readFile(j)).includes(W))return R}catch{return R}let Ae=b(h.routeState.entryFile,z),Se=Co({source:h.mutatedSource,moduleSpecifier:Ae,imports:J.exportName==="default"?[{kind:"default"}]:[{kind:"named",imported:J.exportName}]});return Se.ok?Se.source.includes(W)?{source:Se.source,files:[]}:{source:Se.source,files:ie.sort((j,q)=>j.localeCompare(q))}:R}async function sk(h){if(n.getFileInfo){for(let J of h)if(await n.exists(J.path)&&await n.getFileInfo(J.path)===null)return{ok:!1,errorCode:"invalid-params",message:`Source edit path must resolve to a regular non-symbolic-link file: ${J.path}`,details:{path:J.path}}}for(let J of h){if(J.operation!=="upsert"||!/^(?:src\/)?app\/globals\.css$/i.test(J.path))continue;let z=await n.exists(J.path)?await ru(n,J.path):null;if(z?.ok){let Q=_D(z.content,J.content);if(!Q.ok)return{ok:!1,errorCode:"invalid-params",message:Q.message,details:{path:J.path,code:Q.code}}}}let R=ak(h);if(R.length===0)return{ok:!0};let _=WD(n,h),T=new Map,L=(J,z)=>{let Q=T.get(J);if(Q?.source===z)return Q.result;let W=je(J,z);return T.set(J,{source:z,result:W}),W},D;try{D=await WS(R,async J=>{let z=i.get(J);return z?[...(await M(z.entryFile,await _.readFile(z.entryFile),_,{validationOnly:!0,parseModule:L,validatedImports:f.getImports})).parsedModules.values()]:[]})}catch(J){return{ok:!1,errorCode:"ast-error",message:`Source edit preflight failed: ${Ot(J)}`,details:{compositionKeys:R}}}for(let J of D)f.remember(J);return{ok:!0}}function ak(h){return h.map(_=>_.path).some(gI)?[...i.keys()]:[]}function Bl(h,R,_,T){let L=ks(R);return{composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!1,resultVersion:G(h),error:{code:L,message:_,...T?{details:T}:{}}}}async function jl(h){let R=[];for(let _ of new Set(h))R.push(await ck(_));return R}async function ck(h){if(!(typeof n.exists=="function"?await n.exists(h):!0))return{file:h,content:"",version:Math.max(0,B(h)),exists:!1};let _=await n.readFile(h);return{file:h,content:_,version:Math.max(1,B(h)),exists:!0,sha256:ke(_)}}async function Mm(h,R,_,T){if(!e.historyStore)return null;let L=new Map(R.map(z=>[z.file,z])),D=new Map(_.map(z=>[z.file,z])),J=[...new Set([...L.keys(),...D.keys()])].sort().map(z=>{let Q=L.get(z),W=D.get(z);return{path:z,preDigest:Q?.exists===!1||!Q?null:ke(Q.content),postDigest:W?.exists===!1||!W?null:ke(W.content)}});return{schemaVersion:2,transactionId:`${h}:${T.expectedIndexDigest}`,operationId:h,phase:"prepared",historyTransition:T,files:J}}async function Bm(h){return!h||!e.historyStore||await e.historyStore.writeTransactionJournal(h),h}async function So(h){h&&e.historyStore&&await e.historyStore.clearTransactionJournal(h.transactionId)}async function $l(h,R){let _=[];try{for(let T of h)await jm(T),typeof n.bumpVersion=="function"&&n.bumpVersion(T.file),_.push(T.file)}catch(T){let L=await lk(R.filter(D=>_.includes(D.file)));return L.ok?{ok:!1,reason:`Writeback failed and committed files were restored: ${Ot(T)}`,rolledBack:!0}:{ok:!1,reason:`Writeback failed, then rollback failed for ${L.failedFiles.join(", ")}: ${Ot(T)}`,rolledBack:!1}}return{ok:!0,snapshots:h.map(uk)}}async function jm(h){if(h.exists===!1){await n.deleteFile(h.file);return}await n.writeFile(h.file,h.content)}async function lk(h){let R=[];for(let _ of h)try{await jm(_),typeof n.bumpVersion=="function"&&n.bumpVersion(_.file)}catch{R.push(_.file)}return R.length===0?{ok:!0}:{ok:!1,failedFiles:R}}function uk(h){let R=h.exists!==!1;return{file:h.file,content:R?h.content:"",version:h.version,exists:R,...R?{sha256:ke(h.content)}:{}}}async function rr(h){return y.runExclusive(()=>dk(h))}async function dk(h){let R=h.filePlan.edits.map(j=>j.file),_=o.resolveSelector(h.request.composition),T=_.context,L=h.historyPolicy==="none"?void 0:{initiatingComposition:T,affectedCompositions:pn(R)},D=await jl(R),J=new Map(D.filter(j=>j.exists!==!1).map(j=>[j.file,j.content])),z=Vm(),Q=new Map(d),W=new Set(g),H=new Set([...i.values()].filter(j=>h.filePlan.edits.some(q=>q.operation==="delete"&&q.file===j.entryFile)).map(j=>j.key)),ne=h.filePlan.edits.map(j=>j.operation==="delete"?{file:j.file,content:"",version:0,exists:!1}:{file:j.file,content:j.content,version:0,exists:!0,sha256:ke(j.content)}),le={operationId:h.filePlan.operationId,intents:h.filePlan.edits.map(j=>j.operation==="delete"?{kind:"delete",path:j.file}:{kind:j.operation==="create-only"?"create-only":"upsert",path:j.file,content:j.content})},ve=null,ie=!1,Ae=await Qc({overlay:J,exists:j=>n.exists(j),plan:le,buildCandidate:async({plan:j})=>({plan:j}),prepareHistory:async()=>{let j=h.historyPolicy==="none"?null:await l.prepareAppend({composition:o.resolveSelector(h.request.composition).context,operationId:h.request.id,kind:h.request.kind,target:h.request.target,preSnapshots:D,postSnapshots:ne,...h.selectionRef?{selectionRef:h.selectionRef}:{},...h.output?{output:h.output}:{},...L?{provenance:L}:{}}),q=j?.historyTransition?j.historyTransition:e.historyStore?FD(await e.historyStore.readIndex()):null;if(e.historyStore&&!q)throw new Error("Durable history did not provide an exact index transition.");return ve=await Mm(h.request.id,D,ne,q),ve=await Bm(ve),{history:j,historyTransition:q}},reverify:async()=>{},writeCandidate:async()=>{let j=await u.executeFilePlan(h.filePlan);if(!j.ok)throw new sl(j);return{postSnapshots:await jl(j.affectedFiles),affectedFiles:j.affectedFiles,internalResultVersion:j.resultVersion}},validateCandidate:async({candidate:j,receipt:q})=>{let ge=await pe(q.affectedFiles,{changed:!0,minimumVersion:q.internalResultVersion,publish:!1,excludedCompositionKeys:H});if(ge.failedRoutes.length>0)throw new yo(ge.failedRoutes);let Ce=Km(z,ge.candidateRouteStates??[]),Te=Um(Ce,_.key);return{...j,rebuild:ge,routeSnapshots:Ce,resultVersion:Te,...dI(h.selectionRef,Ce.map(Qe=>Qe.state.document))?{selectionRef:dI(h.selectionRef,Ce.map(Qe=>Qe.state.document))}:{}}},publishCandidate:async({candidate:j,history:q,receipt:ge})=>{q?.history&&(await l.publishPrepared(q.history),ie=!0);let Ce=j.resultVersion??ge.internalResultVersion;return{composition:T,requestId:h.request.id,kind:h.request.kind,target:h.request.target,ok:!0,resultVersion:Ce,affectedFiles:ge.affectedFiles,fileChanges:ge.postSnapshots.map(Te=>({path:Te.file,operation:Te.exists===!1?"delete":"upsert"})),...h.output?{output:h.output}:{},...j.selectionRef?{selectionRef:j.selectionRef}:{}}},swapCandidate:({candidate:j,receipt:q})=>{j.routeSnapshots&&Ds(j.routeSnapshots),j.rebuild?.candidateSourceCache&&vs(d,j.rebuild.candidateSourceCache),Om(q.postSnapshots)},finalizeCandidate:async()=>{await So(ve);for(let j of H)i.delete(j)},emitCommitted:({candidate:j,published:q})=>{Ll(q,j.rebuild??{rebuiltRoutes:[],failedRoutes:[]})},rollbackCandidate:async({history:j,receipt:q})=>{if(ie)throw new Error("history was published before transaction finalization failed");if(q){let ge=await $l(D,q.postSnapshots);if(!ge.ok)throw new Error(ge.reason)}Ds(z),vs(d,Q),Fm(W),j?.history&&await l.discardPrepared?.(j.history),await So(ve)}});if(Ae.ok)return Ae.published;if(Ae.stage==="precheck"||Ae.stage==="build")try{await So(ve)}catch(j){let q=await Bs(Ot(j));return Y(h.request,q,"Unable to clear an uncommitted transaction journal.")}if(Ae.recoveryRequired){let j=await Bs(Ae.reason);return Y(h.request,j===U.RECOVERY_PERSIST_FAILED?j:U.ROLLBACK_FAILED,Ae.reason)}let Se=Ae.error;return Se instanceof sl?{...Y(h.request,ks(Se.result.errorCode),Se.result.reason),...Se.result.affectedFiles?{affectedFiles:Se.result.affectedFiles}:{}}:Se instanceof yo?Y(h.request,U.ROUTE_REBUILD_FAILED,`Route rebuild failed and source was rolled back: ${Np(Se.failedRoutes)}`,{failedRoutes:Se.failedRoutes}):Y(h.request,Xm(Ae.stage),Ot(Se))}async function $m(h){return y.runExclusive(async()=>{let R=h==="undo"?await l.prepareUndo():await l.prepareRedo();return R?fk(h,R):{composition:o.entries[0].context,requestId:h,kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:o.initialVersions.get(o.entries[0].key)??0,error:{code:U.INTERNAL_ERROR,message:h==="undo"?"Nothing to undo":"Nothing to redo"}}})}async function fk(h,R){let _=R.entry,T=h==="undo"?_.preSnapshots:_.postSnapshots,L=h==="undo"?_.postSnapshots:_.preSnapshots,D=T.map(q=>q.file),{context:J,key:z}=Fs(_,D),Q=await jl(D),W=new Map(Q.filter(q=>q.exists!==!1).map(q=>[q.file,q.content])),H=$(z),ne=Vm(),le=new Map(d),ve=new Set(g),ie=null,Ae=!1,Se,j=await Qc({overlay:W,plan:{operationId:`${h}:${_.operationId}`,intents:T.map(q=>q.exists===!1?{kind:"delete",path:q.file}:{kind:"upsert",path:q.file,content:q.content})},buildCandidate:async()=>({}),prepareHistory:async()=>(ie=await Mm(`${h}:${_.operationId}`,Q,T,R.historyTransition),ie=await Bm(ie),R),reverify:async()=>{},writeCandidate:async()=>{let q=await $l(T,L);if(!q.ok)throw new Error(q.reason);return{snapshots:q.snapshots}},validateCandidate:async({candidate:q})=>{Se=_t(_,D);let ge=await pe(D,{changed:!0,minimumVersion:H+1,publish:!1,affectedCompositionKeys:Se});if(ge.failedRoutes.length>0)throw new yo(ge.failedRoutes);let Ce=Km(ne,ge.candidateRouteStates??[]),Te=Um(Ce,z);return{...q,rebuild:ge,routeSnapshots:Ce,resultVersion:Te}},publishCandidate:async({candidate:q,history:ge,receipt:Ce})=>{if(!ge)throw new Error("history cursor intent is missing");await l.publishPrepared(ge),Ae=!0;let Te=q.resultVersion??H+1;return{composition:J,requestId:h,kind:_.kind,target:_.target,ok:!0,resultVersion:Te,affectedFiles:D,fileChanges:Ce.snapshots.map(Qe=>({path:Qe.file,operation:Qe.exists===!1?"delete":"upsert"})),..._.output?{output:_.output}:{}}},swapCandidate:({candidate:q,receipt:ge})=>{q.routeSnapshots&&Ds(q.routeSnapshots),q.rebuild?.candidateSourceCache&&vs(d,q.rebuild.candidateSourceCache),Om(ge.snapshots)},finalizeCandidate:async()=>{await So(ie)},emitCommitted:({candidate:q,published:ge})=>Ll(ge,q.rebuild??{rebuiltRoutes:[],failedRoutes:[]}),rollbackCandidate:async({history:q,receipt:ge})=>{if(Ae)throw new Error("history cursor was published before transaction finalization failed");if(ge){let Ce=await $l(L,ge.snapshots);if(!Ce.ok)throw new Error(Ce.reason)}Ds(ne),vs(d,le),Fm(ve),q&&await l.discardPrepared?.(q),await So(ie)}});if(j.ok)return j.published;if(j.stage==="precheck"||j.stage==="build")try{await So(ie)}catch(q){let ge=await Bs(Ot(q));return{composition:J,requestId:h,kind:_.kind,target:_.target,ok:!1,resultVersion:H,error:{code:ge,message:"Unable to clear an uncommitted transaction journal."}}}if(j.recoveryRequired){let q=await Bs(j.reason);return{composition:J,requestId:h,kind:_.kind,target:_.target,ok:!1,resultVersion:H,affectedFiles:D,error:{code:q===U.RECOVERY_PERSIST_FAILED?q:U.ROLLBACK_FAILED,message:j.reason}}}return{composition:J,requestId:h,kind:_.kind,target:_.target,ok:!1,resultVersion:H,affectedFiles:D,error:{code:j.error instanceof yo?U.ROUTE_REBUILD_FAILED:Xm(j.stage),message:Ot(j.error),...j.error instanceof yo?{details:{failedRoutes:j.error.failedRoutes}}:{}}}}function Vm(){return[...i.values()].map(h=>({composition:h.composition,key:h.key,routeId:h.routeId,state:{...h,dependencyFiles:new Set(h.dependencyFiles),fileVersions:new Map(h.fileVersions)}}))}function Um(h,R){return h.find(T=>T.key===R)?.state.graph?.version??o.initialVersions.get(R)??0}function Km(h,R){let _=new Map(h.map(T=>[T.key,T]));for(let T of R)_.set(T.key,T);return[..._.values()]}function Ds(h){for(let R of i.values())N(R);for(let R of h){let _={...R.state,dependencyFiles:new Set(R.state.dependencyFiles),fileVersions:new Map(R.state.fileVersions)};i.set(R.key,_),v(_,_.dependencyFiles)}}async function Ms(h){let R=i.get(h);if(!R)throw new Error(`Composition not found: ${h}`);if(R.graph)return;let _=await n.readFile(R.entryFile);await fe(h,_)}function Io(h,R){let _=i.get(o.resolveSelector(R).key)??null;return!_||!Jm(_,h)?null:_}function Jm(h,R){if(h.documentIndex?.entriesByKey.has(R)||h.graph?.elements.has(R))return!0;let _=$t(R);return _&&_!==R?h.graph?.elements.has(_)===!0:!1}function Y(h,R,_,T){return{composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!1,resultVersion:G(h),error:{code:R,message:_,...T?{details:T}:{}}}}function Xm(h){return h==="validate"?U.ROUTE_REBUILD_FAILED:h==="publish"?U.HISTORY_COMMIT_FAILED:U.WRITE_IO_ERROR}async function Bs(h){if(m=!0,!l.markRecoveryRequired)return U.RECOVERY_REQUIRED;try{return await l.markRecoveryRequired(h),U.RECOVERY_REQUIRED}catch{return U.RECOVERY_PERSIST_FAILED}}function pk(h){let _=h.split(/[^a-zA-Z0-9]+/).filter(Boolean).map(T=>T.charAt(0).toUpperCase()+T.slice(1)).join("").replace(/^[^a-zA-Z_$]+/,"");return _?`Prefab${_}`:"GeneratedPrefab"}function Vl(h){return h==="VERSION_STALE"?U.VERSION_STALE:h==="CROSS_PAGE_MOVE_UNSUPPORTED"?U.CROSS_PAGE_MOVE_UNSUPPORTED:U.UNSUPPORTED_OPERATION}async function zm(h){if(h.target.kind==="route"){let _=i.get(o.resolveSelector(h.target.composition).key)??null;return _?(_.graph||await Ms(_.key),_):Y(h,U.ROUTE_NOT_FOUND,"Composition not found for route target.")}if(h.target.kind==="page-unit"){let _=i.get(o.resolveSelector(h.target.composition).key)??null;return _?(_.graph||await Ms(_.key),_):Y(h,U.ROUTE_NOT_FOUND,"Composition not found for page-unit target.")}if(h.target.kind==="page-block"){let _=i.get(o.resolveSelector(h.target.composition).key)??null;return _?(_.graph||await Ms(_.key),_):Y(h,U.ROUTE_NOT_FOUND,"Composition not found for page-block target.")}if(h.target.kind!=="node")return Y(h,U.UNSUPPORTED_OPERATION,`${h.kind} source target execution is not implemented yet.`);let R=i.get(o.resolveSelector(h.composition).key)??null;return R?(R.graph||await Ms(R.key),Jm(R,h.target.key)?R:Y(h,U.NODE_NOT_FOUND,`Target key not found: ${h.target.key}`)):Y(h,U.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(),f.clear(),g.clear()},registerComposition(h,R){let _=o.register({context:h,entryFile:R}),T=i.get(_.key);if(T?.entryFile===R)return;T&&N(T);let L=uI(_.context,R);i.set(_.key,L),v(L,L.dependencyFiles),r.emit({type:"graph-invalidated",composition:_.context})},unregisterComposition(h){let R=o.resolveSelector(h),_=i.get(R.key);_&&(N(_),i.delete(R.key),o.unregister(R.key),i.size===0&&(t="idle"),r.emit({type:"graph-invalidated",composition:R.context}))},getCompositionEntryFiles(){return[...i.values()].map(h=>h.entryFile)},getCompositionContext(h){return o.resolveSelector(h).context},async initializeComposition(h){let R=o.resolveSelector(h),_=i.get(R.key);if(!_)throw new Error(`Composition not registered: ${R.key}`);if(_.graph)t="ready";else{t="building";try{let T=await n.readFile(_.entryFile);await fe(R.key,T),t="ready",r.emit({type:"graph-ready",composition:R.context,version:i.get(R.key)?.graph?.version??0})}catch(T){throw t="idle",r.emit({type:"graph-error",composition:R.context,message:Ot(T)}),T}}},getDocument(h){let R=o.resolveSelector(h),_=i.get(R.key);if(!_)throw new Error(`Composition not registered: ${R.key}`);if(!_.document)throw new Error(`Composition not built: ${R.key}`);return _.document},async getHistoryStatus(){await x;let h=await l.getStatus?.();return h?{...h,recoveryRequired:m}:{canUndo:!1,canRedo:!1,undoDepth:0,redoDepth:0,recoveryRequired:m}},getObjectEditContext(h,R,_){let T=Io(h,R),L=$t(h)??h;if(T?.graph&&T.topology&&T.capabilities&&T.detailProjections){let D=T.detailProjections.get(L);if(D){let J=T.graph.elements.get(L);if(!J)throw new Error(`Key not found: ${h}`);let z=$D(h,L,_),Q=new Map;if(D.isRepeat&&z?.instanceIndex!==void 0)for(let ne of J.attributes??[])Q.set(ne.name,rp({file:J.sourceFile,source:d.get(J.sourceFile)??"",element:J,propertyName:ne.name,selectionRef:z,graph:T.graph,sources:d}));let W=RS({element:J,graph:T.graph,source:d.get(J.sourceFile),documentVersion:T.graph.version,selectionRef:_,isRepeat:D.isRepeat,propertyProvenance:D.propertyProvenances,repeatTargets:Q}),H=AS(L,T.graph,T.topology,T.capabilities,D.textSources,D.provenances,D.dynamicData,W);return h===L?H:tI(H,h,T.document??null,T.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${h}`)},getRenderDetail(h,R){let _=Io(h,R),T=$t(h)??h;if(_?.graph&&_.topology&&_.capabilities&&_.detailProjections){let L=_.detailProjections.get(T);if(L){let D=PS(T,_.graph,_.topology,_.capabilities,L.textSources,L.writeTarget,L.provenances,L.conditional,L.componentSemantic,L.styleSource,L.dynamicData);return h===T?D:eI(D,h,_.document??null,_.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${h}`)},getClassNameSource(h,R){let _=Io(h,R),T=$t(h)??h;if(!_?.graph)throw new Error(`Key not found: ${h}`);let L=_.graph.elements.get(T);if(!L)throw new Error(`Key not found: ${h}`);let D=d.get(L.sourceFile);if(D===void 0)throw new Error(`Source not loaded: ${L.sourceFile}`);return Iu({key:T,route:{composition:_.composition,routeId:_.routeId,graph:_.graph,source:D}})},refreshSourceForKey:Yv,async execute(h){if(await x,m)return Y(h,U.RECOVERY_REQUIRED,"The edit engine requires explicit recovery before accepting mutations.");if(h.kind==="source-edit")return Zv(h);if(h.kind==="insert-page-resource")return qv(h);if(h.kind==="delete-page-source")return Qv(h);let R=await zm(h);if("ok"in R)return R;await Dm(h);let _=await zm(h);if("ok"in _)return _;let T=_;if(h.target.kind==="page-unit"){let H=h;return h.kind==="insert-child"||h.kind==="replace-node"?ek(H,T):h.kind==="move-node"||h.kind==="remove-node"?nk(H,T):Y(h,U.UNSUPPORTED_OPERATION,"Only page-unit insert-child, replace-node, move-node, and remove-node are currently supported by the page composition transaction.")}if(h.target.kind==="page-block"){let H=h;return h.kind==="insert-child"||h.kind==="replace-node"?tk(H,T):h.kind==="move-node"||h.kind==="remove-node"?rk(H,T):Y(h,U.UNSUPPORTED_OPERATION,"Page-block operation is not supported by the current structural transaction.")}let D=h.params,J=h.target.kind==="node"?h.target.key:null;if(D.kind==="move-node"&&"kind"in D.target&&D.target.kind==="source-sibling"){let H=D.target,ne=J?T.document?.entries.find(q=>q.key===J):null,le=T.document?.entries.find(q=>q.key===H.anchorKey),ve=ne?.pageCompositionActionScope,ie=ve?.kind==="source-siblings"?ve.siblingKeys:null,Ae=ie?.indexOf(ne?.key??"")??-1,Se=ie?.indexOf(H.anchorKey)??-1,j=H.relation==="before"?Ae-1:Ae+1;if(!ne||!le||!ie||Ae<0||Se!==j||le.pageCompositionActionScope?.kind!=="source-siblings"||le.pageCompositionActionScope.siblingKeys.length!==ie.length||le.pageCompositionActionScope.siblingKeys.some((q,ge)=>q!==ie[ge])||!ne.operationSummary.canMove)return Y(h,U.INVALID_TARGET,"Source sibling move is unavailable because the current source sibling scope or adjacent anchor no longer matches.")}if(!T.graph||!T.topology||!T.capabilities)return{composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!1,resultVersion:G(h),error:{code:h.target.kind==="route"?U.ROUTE_NOT_FOUND:U.NODE_NOT_FOUND,message:h.target.kind==="route"?"Composition not ready for route target.":h.target.kind==="node"?`Target key not found: ${h.target.key}`:`${h.kind} source target execution is not implemented yet.`}};let z=oM(T,T.graph,T.capabilities,d,i),Q=await new Nc(z).plan(h);if(!Q.ok)return{composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!1,resultVersion:G(h),error:{code:ks(Q.errorCode),message:Q.reason}};let W=Q.plan;if(W.steps.length===0)return h.kind==="set-props"?{composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!0,resultVersion:G(h),affectedFiles:[]}:{composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!1,resultVersion:G(h),error:{code:U.PLAN_FAILED,message:"Planner could not generate a valid execution plan"}};p+=1;try{if(W.steps.some(ne=>ne.type==="invoke-external-adapter")){let ne=await u.execute(W);if(!ne.ok)return Y(h,ks(ne.errorCode),ne.reason);let le={composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!0,resultVersion:Math.max(G(h),ne.resultVersion),affectedFiles:ne.affectedFiles,...ne.selectionRef?{selectionRef:ne.selectionRef}:{}};return Ll(le,{rebuiltRoutes:[],failedRoutes:[]}),le}let H=await u.prepareRewritePlan(W);return H.ok?await rr({request:h,filePlan:H.filePlan,...H.selectionRef?{selectionRef:H.selectionRef}:{}}):Y(h,ks(H.errorCode),H.reason)}catch(H){return{composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!1,resultVersion:G(h),error:{code:U.INTERNAL_ERROR,message:Ot(H)}}}finally{p-=1}},async undo(h){if(await x,m)return{composition:o.entries[0].context,requestId:"undo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:$(o.entries[0].key),error:{code:U.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting undo."}};p+=1;try{return await $m("undo")}finally{p-=1}},async redo(h){if(await x,m)return{composition:o.entries[0].context,requestId:"redo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:$(o.entries[0].key),error:{code:U.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting redo."}};p+=1;try{return await $m("redo")}finally{p-=1}},notifyFileChanged(h){Tm([h])},getAffectedCompositions(h){return kt(h)},subscribe(h){return r.subscribe(h)}}}function ZD(e){return e instanceof Error&&"code"in e&&(e.code==="ENOENT"||e.code==="ENOTDIR")}function qD(e,t,n,r){let o=new Map,i=new Map,s=(d,f,g)=>{let p=d.get(f)??new Set,m=p.size;return p.add(g),d.set(f,p),p.size!==m},a=(d,f)=>{if(!d.importedFrom)return!1;if(d.exportName==="default")return s(i,d.importedFrom,f);let g=s(o,`${d.importedFrom}#${d.tag}`,f);return d.exportName&&d.exportName!==d.tag&&(g=s(o,`${d.importedFrom}#${d.exportName}`,f)||g),g},c=d=>o.get(`${d.sourceFile}#${d.componentName}`)??i.get(d.sourceFile);for(let d of t.elements.values()){if(d.sourceFile!==n.entryFile||!d.importedFrom||!/^[A-Z]/.test(d.tag))continue;let f=n.placements.find(p=>p.members.some(m=>m.sourceRange!==null&&_s(d.sourceRange,m.sourceRange)));if(!f)continue;let g=f.placementUnitKey;a(d,g)}let l=!0;for(;l;){l=!1;for(let d of t.elements.values()){if(d.sourceFile===n.entryFile||!d.importedFrom||!/^[A-Z]/.test(d.tag))continue;let f=c(d);if(f)for(let g of f)l=a(d,g)||l}}let u=n.placements.find(d=>d.placementKey===n.container.placementKey&&d.relation==="append");for(let d of e.entries){let f=$t(d.key)??d.key,g=t.elements.get(d.key)??t.elements.get(f);if(!g)continue;if(g.sourceFile===n.entryFile){if(n.container.sourceRange&&_s(g.sourceRange,n.container.sourceRange)&&u){d.pageCompositionUnitKey=u.placementUnitKey;continue}let y=n.placements.find(x=>x.members.some(S=>S.sourceRange!==null&&(_s(g.sourceRange,S.sourceRange)||rM(S.sourceRange,g.sourceRange))));if(y){d.pageCompositionUnitKey=y.placementUnitKey;continue}}let p=o.get(`${g.sourceFile}#${g.componentName}`);if(p){p.size===1&&(d.pageCompositionUnitKey=p.values().next().value);continue}let m=i.get(g.sourceFile);m?.size===1&&(d.pageCompositionUnitKey=m.values().next().value)}QD(e,t,n,r)}function QD(e,t,n,r){let o=new Map(e.entries.map(f=>[f.key,f])),i=e.entries.filter(f=>{let g=f.pageCompositionUnitKey;return g?f.parentKey?o.get(f.parentKey)?.pageCompositionUnitKey!==g:!0:!1}),s=new Map,a=(f,g)=>{s.set(f,Math.min(2,(s.get(f)??0)+g))},c=f=>n.placements.some(g=>g.members.some(p=>p.sourceRange!==null&&_s(f.sourceRange,p.sourceRange)));for(let f of t.elements.values())f.sourceFile!==n.entryFile||!f.importedFrom||!/^[A-Z]/.test(f.tag)||!c(f)||a(`${f.importedFrom}#${f.exportName??f.tag}`,1);let l=[...t.elements.values()].flatMap(f=>f.sourceFile!==n.entryFile&&f.importedFrom&&/^[A-Z]/.test(f.tag)?[{owner:`${f.sourceFile}#${f.componentName}`,ownerDefault:`${f.sourceFile}#default`,target:`${f.importedFrom}#${f.exportName??f.tag}`}]:[]);for(let f=0;f<=l.length;f+=1){let g=!1;for(let p of l){let m=s.get(p.owner)??s.get(p.ownerDefault)??0;if(!m)continue;let y=s.get(p.target)??0,x=Math.min(2,y+m);x!==y&&(s.set(p.target,x),g=!0)}if(!g)break}let u=f=>s.get(`${f.sourceFile}#${f.componentName}`)??s.get(`${f.sourceFile}#default`)??0;for(let f of i){f.pageCompositionActionScope={kind:"unavailable"};let g=t.elements.get(f.key);f.pageCompositionUnitKey&&g?.sourceFile===n.entryFile&&(f.pageCompositionActionScope={kind:"route-unit"})}let d=new Map;for(let f of i){let g=t.elements.get(f.key);if(!g||g.sourceFile===n.entryFile||f.key!==($t(f.key)??f.key))continue;let p=r.get(g.sourceFile);if(!p)continue;let m=Ie(p.ast,{kind:"jsx-node",strategy:"source-range",sourceRange:g.sourceRange});if(!m.ok||!m.match.path.isJSXElement())continue;let y=m.match.path,x=y.parentPath;if(!x||!x.isJSXFragment()&&!(x.isJSXElement()&&Ye(x))){u(g)===1&&pI(y)&&(f.pageCompositionActionScope={kind:"route-unit"});continue}if(!pI(x))continue;let S=d.get(x.node)??[];S.push({entry:f,element:g,parentPath:x}),d.set(x.node,S)}for(let f of d.values()){let g=f[0];if(!g)continue;let p=g.entry.pageCompositionUnitKey,m=[],y=!!(p&&u(g.element)===1);for(let S of g.parentPath.node.children){if(eM(S))continue;if(!tM(S)){y=!1;break}let b=[...t.elements.values()].find(k=>k.sourceFile===g.element.sourceFile&&k.componentName===g.element.componentName&&_s(k.sourceRange,nM(S))),E=b?o.get(b.identity.key):null;if(!b||!E||E.parentKey||E.pageCompositionUnitKey!==p||u(b)!==1){y=!1;break}m.push(E)}if(!y||m.length!==f.length||f.some(({entry:S})=>!m.some(b=>b.key===S.key)))continue;if(m.length===1){m[0].pageCompositionActionScope={kind:"route-unit"};continue}if(m.length<2)continue;let x=m.map(S=>S.key);for(let S of m)S.pageCompositionActionScope={kind:"source-siblings",siblingKeys:x}}}function pI(e){let t=e.parentPath;return!!(t?.isReturnStatement?.()||t?.isArrowFunctionExpression?.()&&t.node.body===e.node)}function eM(e){return!!(e&&typeof e=="object"&&e.type==="JSXText"&&!(e.value??"").trim())}function tM(e){return!!(e&&typeof e=="object"&&e.type==="JSXElement")}function nM(e){return{startLine:e.loc?.start.line??-1,startColumn:e.loc?.start.column??-1,endLine:e.loc?.end.line??-1,endColumn:e.loc?.end.column??-1}}function _s(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function rM(e,t){return mI(e.startLine,e.startColumn,t.startLine,t.startColumn)<=0&&mI(e.endLine,e.endColumn,t.endLine,t.endColumn)>=0}function mI(e,t,n,r){return e!==n?e-n:t-r}function oM(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 f=t.elements.get(u);for(let g of f?.childKeys??[])a(g,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),f=t.elements.get(d.baseKey);return f?l(u,f):null},getChildNodes(u){let d=c(u),g=e.documentIndex?.entriesByKey.get(u)?.childKeys;if(g)return g.map(m=>{let y=$t(m)??m,x=t.elements.get(y);return x?l(m,x):null}).filter(m=>m!==null);let p=t.elements.get(d.baseKey);return p?p.childKeys.map(m=>{let y=t.elements.get(m);return y?l(m,y):null}).filter(m=>m!==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),f=n.get(d.baseKey);return f?{...f,key:u,constraints:f.constraints.map(g=>({...g})),...f.editModes?{editModes:{...f.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},getClassNameSource(u){let d=c(u),f=t.elements.get(d.baseKey),g=f?r.get(f.sourceFile):void 0;return!f||g===void 0?null:Iu({key:d.baseKey,route:{composition:e.composition,routeId:e.routeId,graph:t,source:g}})},getEditableTextSegmentIndex(u){let d=c(u),g=e.detailProjections?.get(d.baseKey)?.textTargets.keys()?.next();return g&&!g.done?g.value:null},async getTextWriteTarget(u,d){let f=c(u);return Rp(e.detailProjections?.get(f.baseKey)?.textTargets.get(d)??null,f.repeatIndex)},async getElementPropertyWriteTarget(u,d){let f=c(u);return Rp(e.detailProjections?.get(f.baseKey)?.elementPropertyTargets.get(d)??null,f.repeatIndex)},getPropertyState(u,d,f){let g=c(u),p=t.elements.get(g.baseKey);if(!p)return null;let y=e.detailProjections?.get(g.baseKey)?.propertyProvenances.get(d);if(y)return y;let x=p.attributes?.find(S=>S.name===d);return x?x.source?{status:"blocked",owner:"generic",diagnostic:{code:"unsupported-property-source",message:`Property '${d}' has an unresolved value source`}}:{status:"direct",owner:"generic",attribute:x,target:{kind:"jsx-attribute",file:p.sourceFile,sourceRange:x.sourceRange}}:(p.attributeSpreads?.length??0)>0?{status:"blocked",owner:"generic",diagnostic:{code:"ambiguous-property-source",message:`A spread may provide or override property '${d}'`}}:{status:"missing",owner:"generic"}},getRepeatPropertyTarget(u,d,f){let g=c(u),p=t.elements.get(g.baseKey);if(!p)return{ok:!1,errorCode:"repeat-not-found",reason:`Node not found: ${u}`};let m=f?{...f,key:g.baseKey}:g.repeatIndex!==null?{key:g.baseKey,instanceIndex:g.repeatIndex}:void 0;return rp({file:p.sourceFile,source:r.get(p.sourceFile)??"",element:p,propertyName:d,selectionRef:m,graph:t,sources:r})},getTextProvenance(u,d){let f=c(u);return e.detailProjections?.get(f.baseKey)?.provenances.get(d)??null}};function c(u){let d=PD(u);return d?{baseKey:d.baseKey,repeatIndex:QS(e.document??null,u,d.baseKey,e.documentIndex)??qS(d)}:{baseKey:u,repeatIndex:null}}function l(u,d){let f=$t(u)??u,g=e.documentIndex?.entriesByKey.get(u);return{key:u,file:d.sourceFile,component:d.componentName,tag:d.tag,structuralPath:d.identity.structuralPath,sourceRange:d.sourceRange,parentKey:g?.parentKey??d.parentKey??void 0,isRepeatRegion:d.boundaryKind==="repeat-region"||s.has(f),isBoundary:!1,importedFrom:d.importedFrom,exportName:d.exportName,isRepeatItemRoot:i.has(f),repeatOwnerKey:i.get(f)??s.get(f),attributes:d.attributes?.map(p=>({name:p.name,value:p.value,source:p.source?{expression:p.source.expression,base:p.source.base,path:p.source.path.map(m=>({...m}))}:null,resolvedValue:p.resolvedValue}))}}}var iM={"stale-version":U.VERSION_STALE,"capability-denied":U.CAPABILITY_REJECTED,"invalid-params":U.INVALID_PARAMS,"locator-miss":U.LOCATOR_FAILED,"route-not-found":U.ROUTE_NOT_FOUND,"unsupported-operation":U.UNSUPPORTED_OPERATION,"invalid-target":U.INVALID_TARGET,"ast-error":U.AST_PARSE_ERROR,"writeback-failed":U.WRITE_IO_ERROR,"rollback-failed":U.RECOVERY_REQUIRED,unknown:U.INTERNAL_ERROR};function ks(e){return iM[e]}function Ot(e){return e instanceof Error&&e.message?e.message:String(e)}function gI(e){return/\.(?:[cm]?[jt]sx?|css|scss|sass|mdx|json)$/i.test(e)}function sM(e){let t=xo(e);if(!wD.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=>OD.map(a=>`${s}/${a}`))}function aM(e){let n=xo(e).startsWith("src/app/")?"src/app":"app";return[`${n}/globals.css`,`${n}/global.css`]}function cM(e){return xI(e,/\bimport\s+(?:[^'";]+?\s+from\s+)?["']([^"']+\.css(?:\?[^"']*)?)["']/g)}function lM(e){return xI(e,/@import\s+(?:url\(\s*)?["']([^"']+)["']/g)}function xI(e,t){let n=[];for(let r of e.matchAll(t)){let o=bI(r[1]??"");o&&n.push(o)}return n}function hI(e,t){let n=bI(t);return!n||n.startsWith("tailwindcss")||n.startsWith("http:")||n.startsWith("https:")?null:n.startsWith("@/")?xo(`src/${n.slice(2)}`):n.startsWith("./")||n.startsWith("../")?xo(`${uM(e)}/${n}`):n.startsWith("/")?xo(n.slice(1)):Ap(n)?xo(n):null}function bI(e){return e.split(/[?#]/,1)[0]?.trim()??""}function Ap(e){return/\.css$/i.test(e)}function uM(e){let t=xo(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function dM(e){return Array.from(new Set(e))}function xo(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 fM(e,t){let n=t.elements.get(e);if(!n)return!1;for(let r of t.regions){if(r.kind!=="repeat-region")continue;let o=n;for(;o;){if(r.childKeys.includes(o.identity.key))return!0;o=o.parentKey?t.elements.get(o.parentKey):void 0}}return!1}var cl=class{constructor(t){this.options=t,this.fileSystem=new gi(t.files),this.engine=this.createEngine(this.fileSystem)}get status(){return this.engine.status}initializeComposition(t){return this.engine.initializeComposition(t)}getDocument(t){return Xs(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,r){return zs(r?this.engine.getObjectEditContext(t,n,r):this.engine.getObjectEditContext(t,n))}getClassNameSource(t,n){return this.engine.getClassNameSource(t,n)}getSourceTree(t){return Gs(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}getSourceFile(t){return Ys(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}resolveSourceLocation(t){return Zs(t,this.engine.getRenderDetail(t.key,t.composition))}async planOperation(t){let n=mM.safeParse(t);if(!n.success)return{result:Js(t,n.error.issues.map(i=>i.message))};let r=new gi(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:Gr(i)},a=r.getChangedFiles();if(a.length===0)return{result:s};let c=gM.parse({siteId:t.siteId,baseSnapshotId:t.baseSnapshotId,operationId:t.id,reason:`site-edit:${t.kind}`,patches:a.map(l=>hM(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 al({projectRoot:"/snapshot",fileSystem:t,compositions:this.options.compositions,onEvent:r&&this.options.onEvent?o=>{let i=Hs(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}:{},resourceTranslationLocale:this.options.resourceTranslationLocale})}};function hM(e,t){return e.after===void 0?{path:e.path,operation:"delete",...t||e.before===void 0?{}:{expectedHash:ke(e.before)}}:{path:e.path,operation:e.before===void 0?"create":"update",...t||e.before===void 0?{}:{expectedHash:ke(e.before)},fullContent:e.after}}function yM(e){return new cl(e)}import{SiteEditOperationRequestSchema as EM}from"@vcp-dev/contracts";import kn from"node:fs/promises";import Ft from"node:path";import{SITE_EDIT_SOURCE_ALLOWED_DIRS as xM,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as bM}from"@vcp-dev/contracts";var ll=class{constructor(t){this.options=t,this.fileSystem=this.createFileSystem(),this.engine=al({...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,r){return r?this.engine.getObjectEditContext(t,n,r):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 Gs(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.engine.getCompositionEntryFiles()})}getSourceFile(t){return Ys(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.engine.getCompositionEntryFiles()})}resolveSourceLocation(t){return Zs(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 kn.readFile(Ft.join(n,r),"utf8")},async readFileBytes(r){return kn.readFile(Ft.join(n,r))},async getFileInfo(r){let o=Ft.join(n,...r.split("/"));try{let i=await kn.lstat(o);return!i.isFile()||i.isSymbolicLink()?null:{path:r,sizeBytes:i.size}}catch{return null}},async writeFile(r,o){await ha(Ft.join(n,r),o)},async createExclusive(r,o){let i=Ft.join(n,r);await kn.mkdir(Ft.dirname(i),{recursive:!0});let s=await kn.open(i,"wx");try{await s.writeFile(o,"utf8")}catch(a){throw await s.close(),await kn.rm(i,{force:!0}),a}await s.close()},async deleteFile(r){await kn.rm(Ft.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=Ft.join(n,i),a=Ft.dirname(Ft.join(n,o));for(;a!==s&&a.startsWith(`${s}${Ft.sep}`);){try{await kn.rmdir(a)}catch(c){if(c instanceof Error&&"code"in c&&c.code==="ENOENT"){a=Ft.dirname(a);continue}break}a=Ft.dirname(a)}},async exists(r){try{return await kn.access(Ft.join(n,r)),!0}catch{return!1}},async listFiles(r={}){let o=r.roots??[...bM,...xM],i=[],s=new Set,a=new Set,c=0;for(let d of o)await u(d,i,1);let l=i.sort((d,f)=>d.path.localeCompare(f.path));return a.size>0?{files:l,truncated:{reasons:[...a]}}:{files:l};async function u(d,f,g){if(r.maxDepth!==void 0&&g>r.maxDepth){a.add("max-depth");return}let p=Ft.join(n,...d.split("/")),m;try{m=await kn.lstat(p)}catch{return}if(m.isSymbolicLink())return;if(m.isFile()){let x=m.ino>0?`${String(m.dev)}:${String(m.ino)}`:null;if(x&&s.has(x))return;if(r.maxFiles!==void 0&&f.length>=r.maxFiles){a.add("max-files");return}if(r.maxTotalBytes!==void 0&&c+m.size>r.maxTotalBytes){a.add("max-total-bytes");return}x&&s.add(x),f.push({path:d,sizeBytes:m.size}),c+=m.size;return}if(!m.isDirectory())return;if(r.maxFiles!==void 0&&f.length>=r.maxFiles){a.add("max-files");return}let y=await kn.readdir(p,{withFileTypes:!0});for(let x of y)x.isSymbolicLink()||await u(`${d}/${x.name}`,f,g+1)}},getVersion(r){return t.get(r)??1},bumpVersion(r){let o=(t.get(r)??1)+1;return t.set(r,o),o}}}};function Tp(e){return new ll(e)}var ul=class{constructor(t){this.options=t,this.listeners=new Set,this.engine=Tp({projectRoot:t.projectRoot,fileSystem:t.fileSystem,compositions:t.compositions,onEvent:n=>{let r=Hs(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:Xs(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,r){return{ok:!0,composition:this.engine.getCompositionContext(n),data:zs(r?this.engine.getObjectEditContext(t,n,r):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=EM.safeParse(r);if(!o.success)return Js(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,...s.details?{details:s.details}:{}},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:Gr(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:Gr(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:Gr(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 SM(e){return new ul(e)}import{GeneratedSiteCapabilitiesSchema as RM}from"@vcp-dev/contracts";import{GeneratedSiteCapabilitiesSchema as IM}from"@vcp-dev/contracts";function dl(e){let t=kM(e.host_capabilities),n=e.platform_managed_paths??[],r=new Set(e.platform_managed_packages??[]);return e.node.kind==="external"?r.has(e.node.path)?er(e.node,"platform-managed","controlled platform package"):t?_M(e.node.path,t)?er(e.node,"host-public","declared Starter runtime dependency"):er(e.node,"unsupported-external-private","external package is not declared by the trusted Starter contract"):er(e.node,"unknown","trusted host capability contract is invalid"):EI(e.node.path,n)?er(e.node,"platform-managed","controlled platform path"):t?II(e.node.path,t.generated_sections_path)?er(e.node,"private","site-generated section path"):EI(e.node.path,t.public_paths)?er(e.node,"host-public","declared Starter public path"):er(e.node,"private","site-local file outside host public paths"):er(e.node,"unknown","trusted host capability contract is invalid")}function vM(e){return e.nodes.map(t=>dl({...e,node:t})).sort((t,n)=>t.path===n.path?t.ownership.localeCompare(n.ownership):t.path.localeCompare(n.path))}function er(e,t,n){return{path:e.path,kind:e.kind,ownership:t,reason:n}}function kM(e){let t=IM.safeParse(e);return t.success?t.data:null}function _M(e,t){return t.runtime_dependencies.some(({name:n})=>e===n||e.startsWith(`${n}/`))}function EI(e,t){return t.some(n=>II(e,n))}function II(e,t){let n=CM(t),r=vI(e);return n.endsWith("/*")?r.startsWith(n.slice(0,-1)):SI(r)===SI(n)}function CM(e){return vI(e.split("#",1)[0]??e)}function vI(e){return e.replace(/^@\//u,"").replace(/\\/g,"/").replace(/^\.\//u,"")}function SI(e){return e.replace(/\.(?:jsx?|tsx?|json)$/iu,"")}function fl(e){let t=RM.safeParse(e.host_capabilities).success,n=[];t||n.push({code:"HOST_CAPABILITIES_INVALID",path:"<host-capabilities>",message:"Portable dependency audit requires the schema-validated Starter host contract."}),e.closure.complete||n.push({code:"INCOMPLETE_SOURCE_NODE",path:"<closure>",message:"Portable source closure is not complete."});for(let i of e.closure.errors)n.push({...i});let r=e.closure.nodes.map(i=>{let s=dl({node:i,host_capabilities:e.host_capabilities,platform_managed_paths:e.platform_managed_paths,platform_managed_packages:e.platform_managed_packages});return s.ownership==="unknown"?n.push({code:"UNKNOWN_DEPENDENCY_OWNERSHIP",path:i.path,message:`Portable dependency ownership is not proven for ${i.path}.`}):s.ownership==="unsupported-external-private"&&n.push({code:"UNSUPPORTED_EXTERNAL_DEPENDENCY",path:i.path,message:`Portable source closure depends on unsupported external package ${i.path}.`}),i.status!=="complete"&&n.push({code:"INCOMPLETE_SOURCE_NODE",path:i.path,message:`Portable source node ${i.path} is ${i.status}.`}),{...i,ownership:s.ownership,ownership_reason:s.reason}}),o=NM(n).sort(PM);return{complete:o.length===0,nodes:r.sort(AM),edges:[...e.closure.edges].sort(TM),errors:o}}function NM(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function PM(e,t){return Zt(e.path,t.path)||Zt(e.code,t.code)||Zt(e.specifier??"",t.specifier??"")||Zt(e.message,t.message)}function AM(e,t){return Zt(e.path,t.path)||Zt(e.kind,t.kind)||Zt(e.ownership,t.ownership)||Zt(e.status,t.status)}function TM(e,t){return Zt(e.from,t.from)||Zt(e.target??"",t.target??"")||Zt(e.specifier??"",t.specifier??"")||Zt(e.kind,t.kind)||Zt(e.resolution,t.resolution)}function Zt(e,t){return e<t?-1:e>t?1:0}import{createHash as Sm}from"node:crypto";import{BlockRenderRefSchema as $j,GeneratedSiteCapabilitiesSchema as Vj,PORTABLE_BLOCK_LOCAL_ASSET_CHUNK_BYTES as Nv,PORTABLE_BLOCK_LOCAL_ASSET_MAX_BYTES as Uj,SiteEditPageBlockTargetSchema as Kj}from"@vcp-dev/contracts";import{SiteEditPageBlockTargetSchema as wM,SiteIdSchema as OM,SnapshotIdSchema as FM}from"@vcp-dev/contracts";async function Op(e){if(!OM.safeParse(e.site_id).success||!FM.safeParse(e.base_snapshot_id).success||!wM.safeParse(e.target).success)return Vn("INVALID_PARAMS","Invalid site, snapshot, or page block identity.");if(!DM(e.composition,e.target.composition))return Vn("INVALID_TARGET","The target selector does not match the requested composition.");let t=new Map,n=new Map;for(let[u,d]of e.files){if(!wp(u))return Vn("INVALID_PARAMS","Snapshot contains an unsafe source path.");let f=typeof d=="string"?d:LM(u,d);f!==null&&(n.set(u,f),/\.(?:[cm]?[jt]sx?)$/i.test(u)&&t.set(u,f))}let r;try{r=ac({files:n})}catch{return Vn("INVALID_TARGET","Snapshot composition inventory is invalid.")}let o=r.find(u=>u.context.routeId===e.composition.routeId&&u.context.effectiveTemplateId===e.composition.templateId);if(!o)return Vn("INVALID_TARGET","The requested route/template is absent from this snapshot.");let i=t.get(o.entryFile);if(i===void 0)return Vn("INVALID_TARGET","The selected composition entry is unavailable.");let s=await Ca(o.entryFile,i,async u=>{if(!wp(u)||!/\.(?:[cm]?[jt]sx?)$/i.test(u))throw new Error("Unsafe imported source path");let d=t.get(u);if(d===void 0)throw new Error("Source file unavailable");return d},async u=>wp(u)&&t.has(u),{version:e.document_version});if(s.diagnostics.length>0||!s.entryModule)return Vn("INVALID_TARGET","The selected snapshot source graph is incomplete.");s.graph.routeId=e.composition.routeId,s.graph.composition={routeId:e.composition.routeId,...e.composition.templateId!==void 0?{effectiveTemplateId:e.composition.templateId}:{}};let a=yn({route:e.composition.routeId,composition:s.graph.composition,entryFile:o.entryFile,version:e.document_version,source:i,ast:s.entryModule.ast});if(!a.ok)return Vn("INVALID_TARGET","The selected snapshot page composition is unsupported.");let c=ec({composition:s.graph.composition,entryFile:o.entryFile,graph:s.graph,parsedModules:s.parsedModules,projection:a.projection});if(c.diagnostics.length>0)return Vn("INVALID_TARGET","The selected snapshot has unproven page block roots.");let l=Hi({composition:s.graph.composition,entryFile:o.entryFile,graph:s.graph,parsedModules:s.parsedModules,projection:a.projection,documentVersion:e.document_version,roots:c.roots});return l.diagnostics.length>0?{...Vn("INVALID_TARGET","The selected snapshot block index is incomplete."),index:l}:{...jo(l,e.target,e.document_version,e.selection_ref),index:l}}function LM(e,t){if(!/\.(?:[cm]?[jt]sx?)$/i.test(e))return null;try{return new TextDecoder("utf-8",{fatal:!0}).decode(t)}catch{return null}}function wp(e){return e.length>0&&!e.startsWith("/")&&!e.includes("\\")&&!e.includes("\0")&&e.split("/").every(t=>t.length>0&&t!=="."&&t!=="..")}function DM(e,t){return e.routeId===t.routeId&&e.templateId===t.templateId}function Vn(e,t){return{ok:!1,code:e,message:t}}import{createHash as YM}from"node:crypto";import Cs from"node:path";import Mp from"@babel/generator";import{parse as ZM}from"@babel/parser";import qM from"@babel/traverse";import*as O from"@babel/types";import{SiteEditSourcePathSchema as QM}from"@vcp-dev/contracts";import*as Lt from"@babel/types";var kI=[".tsx",".ts",".jsx",".js"],MM=new Set(["json","css","scss","sass","less","svg","png","jpg","jpeg","gif","webp","avif","ico","bmp","woff","woff2","ttf","otf","eot","mp4","webm","mp3","wav","ogg","pdf","txt","md","csv","xml","yaml","yml"]);function Lr(e){let t=$M(e.files),n=CI(e.max_depth??32,"max_depth"),r=CI(e.max_nodes??512,"max_nodes"),o=[...new Set(e.entry_files.map(PI).filter(Boolean))],i=new Map,s=[],a=[],c=new Set,l=new Set,u=new Set,d=[];o.length===0&&a.push({code:"SOURCE_ENTRY_UNRESOLVED",path:"<entry>",message:"Portable source closure requires at least one entry file."});for(let m of o)if(!(!m||l.has(m))){if(!oi(m,c,r)){a.push({code:"SOURCE_NODE_BUDGET_EXHAUSTED",path:m,message:"Portable source closure node budget was exhausted."});continue}l.add(m),d.push({path:m,depth:0})}for(;d.length>0;){let m=d.shift();if(u.has(m.path))continue;u.add(m.path);let y=t.get(m.path);if(y===void 0){let I=o.includes(m.path)?"SOURCE_ENTRY_UNRESOLVED":ii(m.path)?"SOURCE_ASSET_UNRESOLVED":"SOURCE_FILE_UNRESOLVED";Fr(i,{path:m.path,kind:ii(m.path)?"asset":"source",depth:m.depth,status:"unresolved"}),a.push({code:I,path:m.path,message:`Portable source closure could not read ${m.path}.`});continue}let x=ii(m.path)?"asset":"source";if(x==="asset"){let I=VM(m.path,y);Fr(i,{path:m.path,kind:x,depth:m.depth,status:I?"parse-failed":"complete"}),I&&a.push(I);continue}let S=Lp(y),b=je(m.path,S);if(!b.ok){Fr(i,{path:m.path,kind:x,depth:m.depth,status:"parse-failed"}),a.push({code:"SOURCE_PARSE_FAILED",path:m.path,message:b.diagnostic.message});continue}let E=jM(b.module.ast),k=!1;for(let I of E){let v=BM({from:m.path,depth:m.depth,reference:I,files:t,nodes:i,errors:a,maxDepth:n,maxNodes:r,visited:u,queued:l,discovered:c});s.push(v.edge),v.next&&(v.next.depth>n?k=!0:!u.has(v.next.path)&&!l.has(v.next.path)&&(l.add(v.next.path),d.push(v.next))),v.depthExhausted&&(k=!0)}Fr(i,{path:m.path,kind:x,depth:m.depth,status:k?"depth-exhausted":"complete"}),k&&a.push({code:"SOURCE_DEPTH_EXHAUSTED",path:m.path,message:`Portable source closure reached max_depth=${n} before closing all dependencies.`})}let f=[...i.values()].sort(HM),g=XM(s).sort(WM),p=zM(a).sort(GM);return{entry_files:o.sort(Un),nodes:f,edges:g,errors:p,complete:p.length===0,budget:{max_depth:n,max_nodes:r}}}function BM(e){let{reference:t}=e;if(t.specifier===null)return e.errors.push({code:"SOURCE_DYNAMIC_IMPORT_UNRESOLVED",path:e.from,message:"Portable source closure cannot resolve a non-literal dynamic import."}),{edge:{from:e.from,specifier:null,kind:t.kind,target:null,resolution:"non-literal"},depthExhausted:!1};if(!nt(t.specifier)){let o=KM(t.specifier);return oi(o,e.discovered,e.maxNodes)?(Fr(e.nodes,{path:o,kind:"external",depth:null,status:"complete"}),{edge:{from:e.from,specifier:t.specifier,kind:t.kind,target:o,resolution:"external"},depthExhausted:!1}):(e.errors.push({code:"SOURCE_NODE_BUDGET_EXHAUSTED",path:o,specifier:t.specifier,message:"Portable source closure node budget was exhausted."}),{edge:{from:e.from,specifier:t.specifier,kind:t.kind,target:o,resolution:"budget-exhausted"},depthExhausted:!1})}let n=Dp(e.from,t.specifier);if(AI(e.from,t.specifier,n))return e.errors.push({code:"SOURCE_UNSAFE_IMPORT",path:n,specifier:t.specifier,message:`Portable source closure rejected unsafe local import ${t.specifier} from ${e.from}.`}),oi(n,e.discovered,e.maxNodes)?Fr(e.nodes,{path:n,kind:ii(n)?"asset":"source",depth:e.depth+1,status:"unresolved"}):e.errors.push({code:"SOURCE_NODE_BUDGET_EXHAUSTED",path:n,specifier:t.specifier,message:"Portable source closure node budget was exhausted."}),{edge:{from:e.from,specifier:t.specifier,kind:t.kind,target:n,resolution:"unresolved"},depthExhausted:!1};let r=NI(e.from,t.specifier,e.files);if(!r){let o=ii(n);return e.errors.push({code:o?"SOURCE_ASSET_UNRESOLVED":"SOURCE_FILE_UNRESOLVED",path:n,specifier:t.specifier,message:`Portable source closure could not resolve ${t.specifier} from ${e.from}.`}),oi(n,e.discovered,e.maxNodes)?Fr(e.nodes,{path:n,kind:o?"asset":"source",depth:e.depth+1,status:"unresolved"}):e.errors.push({code:"SOURCE_NODE_BUDGET_EXHAUSTED",path:n,specifier:t.specifier,message:"Portable source closure node budget was exhausted."}),{edge:{from:e.from,specifier:t.specifier,kind:t.kind,target:n,resolution:"unresolved"},depthExhausted:!1}}if(e.depth>=e.maxDepth&&!e.visited.has(r)&&!e.queued.has(r)){let o=ii(r)?"asset":"source";return oi(r,e.discovered,e.maxNodes)?Fr(e.nodes,{path:r,kind:o,depth:e.depth+1,status:"depth-exhausted"}):e.errors.push({code:"SOURCE_NODE_BUDGET_EXHAUSTED",path:r,specifier:t.specifier,message:"Portable source closure node budget was exhausted."}),{edge:{from:e.from,specifier:t.specifier,kind:t.kind,target:r,resolution:"budget-exhausted"},depthExhausted:!0}}return oi(r,e.discovered,e.maxNodes)?{edge:{from:e.from,specifier:t.specifier,kind:t.kind,target:r,resolution:"resolved"},next:{path:r,depth:e.depth+1},depthExhausted:!1}:(e.errors.push({code:"SOURCE_NODE_BUDGET_EXHAUSTED",path:r,specifier:t.specifier,message:"Portable source closure node budget was exhausted."}),{edge:{from:e.from,specifier:t.specifier,kind:t.kind,target:r,resolution:"budget-exhausted"},depthExhausted:!1})}function jM(e){let t=[];for(let n of e.program.body)Lt.isImportDeclaration(n)?t.push({specifier:n.source.value,kind:n.importKind==="type"?"type":"import"}):Lt.isExportNamedDeclaration(n)&&n.source?t.push({specifier:n.source.value,kind:"export"}):Lt.isExportAllDeclaration(n)&&t.push({specifier:n.source.value,kind:"export"});return Fp(e.program,n=>{if(Lt.isCallExpression(n)&&Lt.isImport(n.callee)){let r=n.arguments[0];Lt.isStringLiteral(r)?t.push({specifier:r.value,kind:"dynamic"}):t.push({specifier:null,kind:"dynamic"})}Lt.isTSImportType(n)&&t.push({specifier:Lt.isStringLiteral(n.argument)?n.argument.value:null,kind:"type"})}),JM(t)}function Fp(e,t){t(e);for(let n of Object.values(e))if(Array.isArray(n))for(let r of n)RI(r)&&Fp(r,t);else RI(n)&&Fp(n,t)}function Dr(e,t,n){let r=Dp(e,t);return!nt(t)||AI(e,t,r)?null:NI(e,t,n)}function NI(e,t,n){let r=Dp(e,t);if(!r||r.startsWith("../")||r==="..")return null;if(n.has(r))return r;let o=r.replace(/[?#].*$/u,"");if(o!==r&&n.has(o))return o;if(UM(o))return null;for(let i of kI){let s=`${o}${i}`;if(n.has(s))return s}for(let i of kI){let s=`${o}/index${i}`;if(n.has(s))return s}return null}function Dp(e,t){let n=Cn(e,t);return PI(n)}function PI(e){let t=e.replace(/\\/g,"/"),n=[];for(let r of t.split("/"))if(!(!r||r===".")){if(r===".."){n.length>0&&n.at(-1)!==".."?n.pop():n.push("..");continue}n.push(r)}return n.join("/")}function $M(e){return e instanceof Map?e:new Map(Object.entries(e))}function Lp(e){return typeof e=="string"?e:Buffer.from(e).toString("utf8")}function VM(e,t){if(e.toLowerCase().endsWith(".css")&&/[@\\]|url\s*\(/iu.test(Lp(t)))return{code:"SOURCE_ASSET_INVALID",path:e,message:"Stylesheet dependencies or escaped/dynamic CSS are not statically closed."};if(e.replace(/[?#].*$/u,"").toLowerCase().endsWith(".json"))try{JSON.parse(Lp(t))}catch{return{code:"SOURCE_ASSET_INVALID",path:e,message:`Portable source closure found invalid JSON asset: ${e}.`}}return null}function Fr(e,t){let n=e.get(t.path);(!n||_I(t.status)>_I(n.status))&&e.set(t.path,t)}function oi(e,t,n){return t.has(e)?!0:t.size>=n?!1:(t.add(e),!0)}function _I(e){return e==="complete"?1:0}function ii(e){let n=e.replace(/[?#].*$/u,"").split(".").pop()?.toLowerCase();return n!==void 0&&MM.has(n)}function UM(e){return/\.[a-z0-9]+$/iu.test(e)}function KM(e){return e.startsWith("@")?e.split("/").slice(0,2).join("/"):e.split("/")[0]??e}function JM(e){let t=new Set;return e.filter(n=>{let r=`${n.kind}\0${n.specifier??"<dynamic>"}`;return t.has(r)?!1:(t.add(r),!0)})}function XM(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function zM(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function HM(e,t){return Un(e.path,t.path)||Un(e.kind,t.kind)}function WM(e,t){return Un(e.from,t.from)||Un(e.target??"",t.target??"")||Un(e.specifier??"",t.specifier??"")||Un(e.kind,t.kind)}function GM(e,t){return Un(e.path,t.path)||Un(e.code,t.code)||Un(e.specifier??"",t.specifier??"")}function Un(e,t){return e<t?-1:e>t?1:0}function CI(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`Portable source closure ${t} must be a positive safe integer.`);return e}function RI(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}function AI(e,t,n){if(t.includes("\0")||t.includes("\\")||n.startsWith("../")||n===".."||n.startsWith("/"))return!0;if(t.startsWith("@/")){let r=t.slice(2);return r.length===0||r.split("/").some(o=>o==="..")}return e.startsWith("/")}var Bp=qM,Kp=typeof Bp=="function"?Bp:Bp.default,eB=typeof Mp=="function"?Mp:Mp.default,TI=new Set(["Array","Boolean","Infinity","JSON","Math","NaN","Number","Object","String","undefined"]),DI=new Map([["JSON",new Set(["stringify"])],["Object",new Set(["keys","values","entries","getOwnPropertyNames"])],["Array",new Set(["isArray"])]]),MI=new Set(["Boolean","Number","String"]),tB=new Set(["assign","values","entries"]);function Jp(e){let{selection:t,files:n}=e,r=t.strategy==="extract-jsx"||t.strategy==="collection-container"?t.entry_file:t.source_file;if(!Up(r))return vt("SOURCE_INPUT_INVALID",r,"The selected Portable entry path is not safe.");if(!QM.safeParse(t.source_file).success)return vt("SOURCE_ENTRY_NOT_FOUND",t.source_file,"The selected root source is outside the allowed Snapshot source paths.");if(t.call_chain.length>1)return vt("SOURCE_NOT_PORTABLE",t.source_file,"Nested component invocation bindings are not yet a proven independent entry.");if(t.invocation&&!t.invocation.complete)return vt("SOURCE_NOT_PORTABLE",t.source_file,"The selected root has an incomplete invocation binding set.");if(t.strategy==="reuse-entry"){if(t.entry_file!==t.source_file)return vt("SOURCE_INPUT_INVALID",t.entry_file,"A reusable entry must point at the proven selected component source.");let i=hl(n,t.source_file);return i===null||!LI(t,i)?vt("SOURCE_ENTRY_NOT_FOUND",t.source_file,"The reusable selected source is missing or does not match its pinned hash."):pl({entryFile:r,entryContent:i,files:n,selection:t})}let o=hl(n,t.source_file);if(o===null||!LI(t,o))return vt("SOURCE_ENTRY_NOT_FOUND",t.source_file,"The selected source is missing or does not match its pinned hash.");if(t.strategy==="managed-thin-entry"){let i={generated_path:r,source_file:t.source_file,structural_path:t.structural_path};return pl({entryFile:r,entryContent:o,files:n,selection:t,sourceMapping:i})}if(t.strategy==="collection-container"){let i=t.collection_container_file;if(!i||!Up(i)||!n.has(i)||n.has(r)||!t.invocation?.complete)return vt("SOURCE_INPUT_INVALID",r,"The proven collection container or isolated entry is unavailable.");let s=yr({component:"PortableCollection",bindings:t.invocation.bindings,targetBlockId:"portable-captured-collection"});if(!s.ok)return vt("SOURCE_NOT_PORTABLE",r,"The collection invocation has unsupported bindings.");let a=s.plan.requiresRouteSearchParams?"{searchParams}: {searchParams?: Promise<Record<string, string | string[] | undefined>>}":"",c=`import PortableCollection from ${JSON.stringify(`@/${i.replace(/\.[cm]?[jt]sx?$/u,"")}`)};
14
+ `||f==="\r"}if(s)return ri(t,`Unterminated block comment in ${t}.`);if(o)return ri(t,`Unterminated string literal in ${t}.`);if(c)return ri(t,`Unterminated MDX code fence in ${t}.`);let u=r.at(-1);return u?ri(t,`Unclosed token "${u.char}" in ${t}.`):{ok:!0}}function ri(e,t){return{ok:!1,errorCode:"ast-error",message:t,details:{path:e}}}function al(e){let t="idle",n=e.fileSystem??LM(),r=sh(),o=GS({compositions:e.compositions,initialDocumentVersions:e.initialDocumentVersions}),i=new Map,s=new Map,a=new Set,c=null,l=e.history??(e.historyStore?Gh(e.historyStore):MM()),u=HS(n,{externalAdapters:e.externalAdapters}),d=new Map,f=hh(il),g=new Set,p=0,m=e.historyStore?.recoveryRequired??!1,y=_p(),x=k();function S(h){return(ol.isAbsolute(h)?ol.relative(e.projectRoot,h):h).replace(/\\/g,"/").replace(/^\.\//,"")}function b(h,R){let _=ol.posix.dirname(h),T=R.replace(/\.(?:tsx?|jsx?)$/i,""),L=ol.posix.relative(_,T);return L.startsWith(".")?L:`./${L}`}function E(h,R){return h.startLine===R.startLine&&h.startColumn===R.startColumn&&h.endLine===R.endLine&&h.endColumn===R.endColumn}async function k(){let h=e.historyStore;if(h)try{let R=await h.readTransactionJournal();if(!R)return;let _=await h.readIndex(),T=await Promise.all(R.files.map(async M=>await n.exists(M.path)?ke(await n.readFile(M.path)):null));if(aI({journal:R,index:_,observedFileDigests:T})!=="ambiguous"){await h.clearTransactionJournal(R.transactionId);let M=await h.readStatus();M.recoveryRequired||(await h.cleanupTmp(),M=await h.readStatus()),m=M.recoveryRequired;return}await h.markRecoveryRequired(`Ambiguous transaction journal ${R.transactionId} at phase ${R.phase}`),m=!0}catch(R){m=!0,await h.markRecoveryRequired(`Transaction journal recovery failed: ${Ot(R)}`).catch(()=>{})}}function I(){return t==="disposed"}e.onEvent&&r.subscribe(e.onEvent);for(let h of o.entries){let R=fI(h.context,h.entryFile);i.set(h.key,R),v(R,R.dependencyFiles)}function v(h,R){let _=new Set(R);N(h),h.dependencyFiles=_;for(let T of h.dependencyFiles){let L=s.get(T);L||(L=new Set,s.set(T,L)),L.add(h.key)}}function N(h){for(let R of h.dependencyFiles){let _=s.get(R);_&&(_.delete(h.key),_.size===0&&s.delete(R))}h.dependencyFiles.clear()}function A(h){let R=new Set;for(let _ of h)for(let T of s.get(_)??[])R.add(T);return R}function w(h){for(let R of h)if(!s.has(R))return!1;return!0}async function F(h,R,_,T,L,M){let J=new Map,z=CS(h),Q=gS(L.values()),W=pE(L.values()),H=typeof M.exists=="function"?ne=>M.exists(ne):async()=>!1;for(let[ne,le]of h.elements){let ve=R.nodes.get(ne);if(!ve)continue;let ie=_.get(le.sourceFile)??T.get(le.sourceFile),Ae=new Map,Se=new Map,j=new Map,q=[];for(let Ge of le.textSegments){if(!ie){Ae.set(Ge.index,null);continue}let fi=await hS({file:le.sourceFile,source:ie,segment:Ge,readFile:Vt=>M.readFile(Vt),exists:H,graph:h,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Vt,adapterId:Kr,capabilities:Ul})=>({sourceType:Vt,adapterId:Kr,capabilities:Ul})),functionCallContracts:e.functionCallContracts,fileCache:Q}),wt=await hp({file:le.sourceFile,source:ie,target:{kind:"text-segment",segment:Ge},readFile:Vt=>M.readFile(Vt),exists:H,graph:h,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Vt,adapterId:Kr,capabilities:Ul})=>({sourceType:Vt,adapterId:Kr,capabilities:Ul})),functionCallContracts:e.functionCallContracts,fileCache:Q}),tn=zM(fi);Ae.set(Ge.index,tn),Se.set(Ge.index,fi),j.set(Ge.index,wt),q.push({editable:Ge.editable,source:tn})}let ge=new Map,Ce=new Map;if(ie)for(let Ge of le.attributes??[]){let fi=await ni({file:le.sourceFile,source:ie,sourceRange:Ge.sourceRange,expression:Ge.source?.expression??Ge.value,sourceInfo:Ge.source,readFile:tn=>M.readFile(tn),exists:H,graph:h,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:tn,adapterId:Vt,capabilities:Kr})=>({sourceType:tn,adapterId:Vt,capabilities:Kr})),functionCallContracts:e.functionCallContracts,fileCache:Q}),wt=await _S({element:le,file:le.sourceFile,source:ie,propertyName:Ge.name,readFile:tn=>M.readFile(tn),exists:H,graph:h,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:tn,adapterId:Vt,capabilities:Kr})=>({sourceType:tn,adapterId:Vt,capabilities:Kr})),functionCallContracts:e.functionCallContracts,fileCache:Q});Ce.set(Ge.name,wt),ge.set(Ge.name,fi)}let Te=LS(HM(ve.writeTarget),q),Qe=z({key:ne,element:le,provenances:j}),or=$S(le),_n=ie?await mE({element:le,graph:h,file:le.sourceFile,source:ie,readFile:Ge=>M.readFile(Ge),exists:H,fileCache:W}):void 0,Ur=h.regions.find(Ge=>Ge.kind==="conditional-region"&&Ge.childKeys.includes(ne)),bt,en=Ur?.sourceCandidates?.[0];if(ie&&Ur&&en?.kind==="conditional-branch"){let Ge=await hp({file:le.sourceFile,source:ie,target:{kind:"conditional-branch",candidate:en},readFile:wt=>M.readFile(wt),exists:H,graph:h,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:wt,adapterId:tn,capabilities:Vt})=>({sourceType:wt,adapterId:tn,capabilities:Vt})),functionCallContracts:e.functionCallContracts,fileCache:Q});bt={currentBranch:Ur.childKeys.indexOf(ne)<=0?"then":"else",availableBranches:Ur.childKeys.length>1?["then","else"]:["then"],conditionExpression:en.conditionExpression,provenance:{finalSource:Ge.finalSource?{kind:Ge.finalSource.kind,file:Ge.finalSource.file,displayPath:Ge.finalSource.displayPath}:null,chain:Ge.chain.map(wt=>({kind:wt.kind,file:wt.file,displayName:wt.displayName,canEditHere:wt.canEditHere})),confidence:Ge.confidence,editMode:Ge.editMode,diagnostics:Ge.diagnostics.map(wt=>({code:wt.code,message:wt.message}))}}}J.set(ne,{textSources:Ae,textTargets:Se,elementPropertyTargets:ge,propertyProvenances:Ce,isRepeat:fD(ne,h),provenances:j,writeTarget:Te,componentSemantic:Qe,styleSource:or,conditional:bt,dynamicData:_n})}return J}function B(h){return typeof n.getVersion=="function"?n.getVersion(h):0}function X(h,R){let _=o.initialVersions.get(h.key)??0;for(let T of R.values())_=Math.max(_,T);return Math.max(_,h.graph?.version??0)}function $(h){return i.get(h)?.graph?.version??o.initialVersions.get(h)??0}function G(h){try{return $(o.resolveSelector(h.composition).key)}catch{return 0}}async function D(h,R,_=n,T={}){let L=await Ca(h,R,M=>_.readFile(M),M=>_.exists(M),{additionalEntries:await Fe(h,_),...T});if(L.diagnostics.length>0)throw new Is(L.diagnostics);return T.validationOnly||f.remember(L.parsedModules.values()),L}async function fe(h,R,_={}){let T=i.get(h);if(!T)return null;let L=_.sourceCache??Pp(d,[]),M=_.fileSystem??Cp(n),{graph:J,allSources:z,parsedModules:Q,entryModule:W}=await D(T.entryFile,R,M,{version:T.graph?.version??1}),H=new Map;for(let bt of z.keys())H.set(bt,B(bt));let ne=Math.max(X(T,H),_.minimumVersion??0);_.changed&&ne<=(T.graph?.version??0)&&(ne=(T.graph?.version??0)+1),J.version=ne;for(let[bt,en]of z)rl(L,bt,en,il);let le=await ot(T.composition,T.entryFile,z,L,M);J.routeId=T.routeId,J.composition=T.composition;let ve=tc(J),ie=ma(ve,J),Ae=await F(J,ve,z,L,Q,M);lt(ie,Ae);let Se=Ee(J,ie,Ae),j=Vr(Ae),q=QS(AS(J,ve,ie,{canUpdateTextByKey:Se,dynamicDataSummaryByKey:j}),J,Ae),ge=yn({route:T.routeId,composition:T.composition,entryFile:T.entryFile,version:ne,source:R,ast:W?.ast}),Ce=Zy(ge),Te=null,Qe=[];if(ge.ok){qM(q,J,ge.projection,Q);let bt=ec({composition:T.composition,entryFile:T.entryFile,graph:J,parsedModules:Q,projection:ge.projection});if(bt.diagnostics.length===0){let en=Hi({composition:T.composition,entryFile:T.entryFile,graph:J,parsedModules:Q,projection:ge.projection,documentVersion:ne,roots:bt.roots});en.diagnostics.length===0&&(Te=en,Qe=en.descriptors)}}let or={...q,composition:T.composition,pageBlocks:Qe,...le?{styleContext:le}:{},pageComposition:Ce},_n=new Set([T.entryFile,...z.keys()]);if(le){_n.add(le.entryCss.path);for(let bt of le.stylesheets)_n.add(bt.path)}let Ur={...T,dependencyFiles:_n,graph:J,topology:ve,capabilities:ie,document:or,pageBlockIndex:Te,pageComposition:Ce,pageCompositionProjection:ge.projection,pagePlacementByKey:ge.ok?ge.projection.placementByKey:null,pagePlacementUnitByKey:ge.ok?ge.projection.placementUnitByKey:null,pageUnitByKey:ge.ok?ge.projection.unitByKey:null,pagePlacementsByUnitKey:ge.ok?ge.projection.placementsByUnitKey:null,documentIndex:qS(or),detailProjections:Ae,fileVersions:H,styleContext:le};if(_.publish===!1)return Ur;for(let bt of _n){let en=z.get(bt)??L.get(bt);en!==void 0&&(rl(d,bt,en,il),g.delete(bt))}return v(T,_n),Object.assign(T,Ur),T}async function Fe(h,R=n){let _=[];for(let T of sD(h))typeof R.exists=="function"&&await R.exists(T)&&_.push({file:T,source:await R.readFile(T)});return _}async function ot(h,R,_,T,L){let M=[];for(let[H,ne]of _){if(Ap(H)){M.push(H);continue}for(let le of cD(ne)){let ve=xI(H,le);ve&&M.push(ve)}}if(!M.length){for(let H of aD(R))if(await L.exists(H)){M.push(H);break}}let J=new Map,z=dD(M).slice(0,cI);for(;z.length>0&&J.size<cI;){let H=z.shift();if(J.has(H)||!Ap(H))continue;let ne=await Tt(H,T,L);if(ne!==null){J.set(H,{path:H,content:ne});for(let le of lD(ne)){let ve=xI(H,le);ve&&!J.has(ve)&&!z.includes(ve)&&z.push(ve)}}}let Q=[...J.values()].map(H=>({...H,hash:ke(H.content)})),W=Q[0];return W?{composition:h,revision:ke(JSON.stringify(Q.map(({path:H,hash:ne})=>({path:H,hash:ne})))),entryCss:W,stylesheets:Q.slice(1)}:null}async function Tt(h,R,_){let T=R.get(h);if(T!==void 0)return T;if(!await _.exists(h))return null;let L=await _.readFile(h);return rl(R,h,L,il),L}function Vr(h){let R=new Map;for(let[_,T]of h)T.dynamicData?.bindings.length&&R.set(_,CE(T.dynamicData.bindings));return R}function Ee(h,R,_){let T=new Map;for(let[L,M]of h.elements){if(!R.get(L)?.canUpdateText){T.set(L,!1);continue}let z=_.get(L),Q=M.textSegments.some(W=>{if(!W.editable)return!1;let H=z?.provenances.get(W.index)??null;return!H||Le(H)});T.set(L,Q)}return T}function lt(h,R){for(let[_,T]of R){let L=h.get(_);L?.canUpdateText&&T.dynamicData?.bindings.some(M=>M.readonly&&(M.targetKind==="text"||M.targetKind==="richtext"))&&h.set(_,{...L,canUpdateText:!1})}}function Le(h){return h.editMode==="direct"||h.editMode==="proxy"||h.editMode==="upstream"}async function pe(h,R={}){let _=[...new Set(h)],T=R.affectedCompositionKeys!==void 0,L=T?new Set(R.affectedCompositionKeys):A(_);if(!T&&(L.size===0||!w(_)))for(let W of i.values())wm(W,_)&&L.add(W.key);let M=!T&&L.size===0&&_.some(yI),J=R.publish===!1?Pp(d,_):void 0,z={rebuiltRoutes:[],failedRoutes:[],...R.publish===!1?{candidateRouteStates:[],candidateSourceCache:J}:{}},Q=Cp(n);for(let W of i.values())if(!(R.excludedCompositionKeys?.has(W.key)||!(L.has(W.key)||M)))try{let ne=!!W.graph,le=await Q.readFile(W.entryFile),ve=await fe(W.key,le,{...R,fileSystem:Q,...J?{sourceCache:J}:{}});ve?.graph&&(z.rebuiltRoutes.push({documentChanged:ne,composition:W.composition,routeId:W.routeId,version:ve.graph.version}),z.candidateRouteStates?.push({composition:W.composition,key:W.key,routeId:W.routeId,state:ve}))}catch(ne){z.failedRoutes.push({...iI(W.routeId,ne),composition:W.composition})}return z}function $e(h){let R=[...new Set(h)],_=A(R);if(_.size>0&&w(R))return[..._];for(let T of i.values())wm(T,R)&&_.add(T.key);return[..._]}function kt(h){let R=new Set($e(h));return o.entries.filter(_=>R.has(_.key)).map(_=>_.context)}function pn(h){return[...new Set($e(h))].sort((_,T)=>_<T?-1:_>T?1:0).map(_=>o.getByKey(_)?.context).filter(_=>_!==void 0)}function _t(h,R){let _=new Set($e(R)),T=h.provenance?.affectedCompositions??[];if(T.length===0)return _;if([...new Set(T.map(M=>o.resolveContext(M).key))].some(M=>!_.has(M)))throw new Error("History provenance does not match the affected composition index.");return _}function Fs(h,R){let _=h.composition??h.provenance?.initiatingComposition;if(_){let M=o.resolveContext(_);return{context:M.context,key:M.key}}let T=[...new Set($e(R))];if(T.length!==1)throw new Error(`Legacy history entry cannot be attributed to a unique composition (affected composition count: ${T.length}).`);let L=o.getByKey(T[0]);if(!L)throw new Error("Legacy history entry references an unknown affected composition.");return{context:L.context,key:L.key}}function Ll(h,R){r.emit({type:"operation-completed",composition:h.composition,result:h});for(let{composition:_,version:T}of R.rebuiltRoutes)r.emit({type:"document-changed",composition:_,version:T});for(let{composition:_,message:T}of R.failedRoutes)r.emit({type:"graph-error",composition:_,message:T})}function wm(h,R){return R.some(_=>h.dependencyFiles.has(_)||h.entryFile===_||h.graph?.fileIndex.has(_))}function Om(h){for(let R of h)a.add(R);c||I()||(c=(async()=>{t="building";let R=!1;try{for(;a.size>0;){if(I())return;await Gv(),await y.runExclusive(async()=>{if(p>0||I())return;let _=[...a];a.clear();let T=await Fm(_);if(T.length===0)return;let L=$e(T);for(let z of L){let Q=i.get(z)?.composition;Q&&r.emit({type:"graph-invalidated",composition:Q})}let{rebuiltRoutes:M,failedRoutes:J}=await pe(T,{changed:!0});for(let{documentChanged:z,composition:Q,version:W}of M)r.emit({type:"graph-ready",composition:Q,version:W}),z&&r.emit({type:"document-changed",composition:Q,version:W});for(let{composition:z,message:Q}of J)R=!0,r.emit({type:"graph-error",composition:z,message:Q})})}}finally{c=null,t!=="disposed"&&(t=!R&&[...i.values()].some(_=>_.graph)?"ready":"idle"),a.size>0&&Om([])}})())}async function Gv(){for(;p>0;)await new Promise(h=>setTimeout(h,0))}async function Fm(h){let R=[];for(let _ of new Set(h)){let T=d.get(_);if(T===void 0){if(g.has(_)&&!await n.exists(_))continue;g.delete(_),R.push(_);continue}try{await n.readFile(_)!==T&&(g.delete(_),R.push(_))}catch(L){if(!ZM(L))try{if(await n.exists(_))continue}catch{continue}g.add(_),R.push(_)}}return R}function Lm(h){sI(d,h);for(let R of h)R.exists===!1?g.add(R.file):g.delete(R.file)}function Mm(h){g.clear();for(let R of h)g.add(R)}async function Dm(h){let R=await Fm(h);if(R.length===0)return;let _=$e(R);for(let M of _){let J=i.get(M)?.composition;J&&r.emit({type:"graph-invalidated",composition:J})}let{rebuiltRoutes:T,failedRoutes:L}=await pe(R,{changed:!0});for(let{documentChanged:M,composition:J,version:z}of T)r.emit({type:"graph-ready",composition:J,version:z}),M&&r.emit({type:"document-changed",composition:J,version:z});for(let{composition:M,message:J}of L)r.emit({type:"graph-error",composition:M,message:J})}async function Yv(h,R){let _=Io(h,R);if(!_?.graph)return;let T=$t(h)??h,L=_.graph.elements.get(T);L&&await Dm([L.sourceFile])}async function Bm(h){let R=new Set;if(h.target.kind==="node"){let _=Io(h.target.key,h.composition),T=$t(h.target.key)??h.target.key,L=_?.graph?.elements.get(T);L&&R.add(L.sourceFile)}else if(h.target.kind==="route"){let _=i.get(o.resolveSelector(h.target.composition).key);_&&R.add(_.entryFile)}else if(h.target.kind==="page-unit"){let _=i.get(o.resolveSelector(h.target.composition).key);_&&R.add(_.entryFile)}else if(h.target.kind==="page-block"){let _=i.get(o.resolveSelector(h.target.composition).key),T=_?.pageBlockIndex?.bindings.get(h.target.blockKey);if(T&&(R.add(T.ownerFile),R.add(T.descriptor.source.file)),_?.pageBlockIndex&&h.params.kind==="move-node"&&"kind"in h.params.target&&h.params.target.kind==="block-boundary"){let L=_.pageBlockIndex.bindings.get(h.params.target.anchorBlockKey);L&&(R.add(L.ownerFile),R.add(L.descriptor.source.file))}}else if(h.target.kind==="source-file")R.add(h.target.path);else if(h.target.kind==="source-batch")for(let _ of h.target.paths)R.add(_);if(h.params.kind==="move-node"&&!("kind"in h.params.target)){let _=[h.params.target.parentKey,...h.params.target.relation==="before"||h.params.target.relation==="after"?[h.params.target.anchorKey]:[]];for(let T of _){let L=Io(T,h.composition),M=$t(T)??T,J=L?.graph?.elements.get(M);J&&R.add(J.sourceFile)}}await Dm(R)}async function Zv(h){if(h.params.kind!=="source-edit")return Bl(h,"invalid-params","source-edit requires source-edit params");for(let R of h.params.edits){let _=YM(R);if(!_.ok)return Bl(h,_.errorCode,_.message,_.details)}p+=1;try{let R=await sk(h.params.edits);if(!R.ok)return Bl(h,R.errorCode,R.message,R.details);await Bm(h);let _={operationId:h.id,kind:"source-edit",target:h.target,documentVersion:h.documentVersion,conflictPolicy:h.params.conflictPolicy,edits:h.params.edits.map(T=>T.operation==="delete"?{operation:"delete",file:T.path,baseContentHash:T.baseContentHash??null}:{operation:"upsert",file:T.path,baseContentHash:T.baseContentHash??null,content:T.content})};return await rr({request:h,filePlan:_})}catch(R){return{composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!1,resultVersion:G(h),error:{code:U.INTERNAL_ERROR,message:Ot(R)}}}finally{p-=1}}async function qv(h){if(h.target.kind!=="project"||h.params.kind!=="insert-page-resource")return Y(h,U.INVALID_PARAMS,"insert-page-resource requires project target and matching params.");p+=1;try{let R=await mi({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:[...h.params.artifact.components.flatMap(T=>T.materialization.files.map(L=>({path:L.pathTemplate,content:L.content}))),...h.params.artifact.pages.flatMap(T=>T.materialization.files.map(L=>({path:L.pathTemplate,content:L.content})))],exists:T=>n.exists(T),readFile:T=>n.readFile(T)});if(!R.ok)return Y(h,U.MATERIALIZATION_REJECTED,R.message);let _=await rd({artifact:h.params.artifact,exists:T=>n.exists(T)});return _.ok?await rr({request:h,filePlan:{operationId:h.id,kind:"source-edit",target:h.target,documentVersion:h.documentVersion,conflictPolicy:"overwrite",edits:_.files},output:{kind:"insert-page-resource",package_instance_id:_.packageInstanceId,pages:_.pages},historyPolicy:"none"}):Y(h,_.code==="MATERIALIZATION_CONFLICT"?U.MATERIALIZATION_CONFLICT:U.MATERIALIZATION_REJECTED,_.message,_.path?{path:_.path}:void 0)}catch(R){return Y(h,U.INTERNAL_ERROR,Ot(R))}finally{p-=1}}async function Qv(h){if(h.target.kind!=="project"||h.params.kind!=="delete-page-source")return Y(h,U.INVALID_PARAMS,"delete-page-source requires project target and matching params.");if(!n.listFiles)return Y(h,U.PLAN_FAILED,"Complete project file listing is required for page deletion.");p+=1;try{let R=bI(await n.listFiles({maxFiles:5e4,maxDepth:64}));if(R.truncated)return Y(h,U.PLAN_FAILED,"Project file listing is incomplete; page deletion was refused.",{truncationReasons:R.truncated.reasons});let _=R.files.filter(({path:J})=>/\.(?:tsx?|jsx?)$/.test(J)),T=Object.fromEntries(await Promise.all(_.map(async({path:J})=>[J,await n.readFile(J)]))),L=Hx({expectedUrlPath:h.params.expectedUrlPath,files:T});if(!L.ok)return Y(h,L.code==="HOME_PAGE_LOCKED"?U.HOME_PAGE_LOCKED:L.code==="ROUTE_NOT_FOUND"?U.ROUTE_NOT_FOUND:U.PLAN_FAILED,L.message);let M=await Promise.all(L.edits.map(async J=>({...J,baseContentHash:ke(await n.readFile(J.file))})));return rr({request:h,filePlan:{operationId:h.id,kind:"source-edit",target:h.target,documentVersion:h.documentVersion,conflictPolicy:"compare-and-swap",edits:M},output:{kind:"delete-page-source",deleted_files:L.deletedFiles,updated_files:L.updatedFiles,preserved_shared_files:L.preservedSharedFiles,warnings:L.warnings},historyPolicy:"none"})}catch(R){return Y(h,U.INTERNAL_ERROR,Ot(R))}finally{p-=1}}async function ek(h,R){if(h.kind!=="insert-child"&&h.kind!=="replace-node")return Y(h,U.UNSUPPORTED_OPERATION,"Only page-unit insert-child and replace-node materialization are supported by this transaction.");if(h.params.kind!=="insert-child"&&h.params.kind!=="replace-node"||h.kind!==h.params.kind)return Y(h,U.INVALID_PARAMS,"Page-unit materialization operation kind must match its params.");if(h.params.kind==="insert-child"){if(!("kind"in h.params.position)||h.params.position.kind!=="page-composition")return Y(h,U.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.");if(h.params.position.documentVersion!==h.documentVersion)return Y(h,U.VERSION_STALE,"Page-unit insert-child placement belongs to a different document version.")}let _=R.document,T=R.pageCompositionProjection;if(!_||_.pageComposition?.status!=="supported"||!T||T.status!=="supported")return Y(h,U.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(h.documentVersion!==_.version||T.documentVersion!==_.version)return Y(h,U.VERSION_STALE,`Document version ${h.documentVersion} is stale (current: ${_.version}).`);let L=h.params.node.kind==="component-call"?h.params.node.materialization:void 0;if(!L)return Y(h,U.UNSUPPORTED_OPERATION,"Page-unit insertion currently requires a static materialization manifest.");let M=h.params.kind==="insert-child"?h.params.position:null,J=await mi({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:L.files.map(W=>({path:W.pathTemplate,content:W.content})),exists:W=>n.exists(W),readFile:W=>n.readFile(W)});if(!J.ok)return Y(h,U.MATERIALIZATION_REJECTED,J.message);let z=await uI(n,Object.keys(L.projectDependencies??{})),Q=await ud({manifest:L,generatedRoot:"components/site/generated",controlledFiles:L.files.map(W=>({pathTemplate:W.pathTemplate})),exists:W=>n.exists(W),availableHostDependencies:z,hostCapabilities:qu(),commit:async W=>{let H=await n.readFile(R.entryFile),ne=R.document,le=R.pageCompositionProjection;if(!ne||ne.pageComposition?.status!=="supported"||ne.version!==h.documentVersion||!le||le.status!=="supported"||le.documentVersion!==ne.version)return{ok:!0,data:Y(h,U.VERSION_STALE,"The route changed before the page-unit insertion could commit.")};let ve=W.entry.path,ie=pk(W.instanceName),Ae,Se=[];if(h.params.kind==="insert-child"){if(!M||!("kind"in M)||M.kind!=="page-composition")return{ok:!0,data:Y(h,U.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.")};let Ce=$i({routeId:R.routeId,entryFile:R.entryFile,currentDocumentVersion:ne.version,expectedDocumentVersion:h.documentVersion,source:H,projection:le,placementKey:M.placementKey,component:{source:ve,exportName:W.entry.export.kind==="default"?"default":W.entry.export.name,localName:ie}});if(!Ce.ok)return{ok:!0,data:Y(h,Vl(Ce.error.code),Ce.error.message,{diagnostics:Ce.error.diagnostics})};let Te=Ce.plan.rewriteStep,Qe;switch(Te.kind){case"insert-root-expression":Qe=Vi({source:H,locator:Te.locator,expectedSourceHash:Te.sourceHash,action:{kind:"insert",jsx:Te.node.jsx,placement:Te.placement,replaceOriginal:Te.replaceOriginal}});break;case"insert-child":Qe=on({source:H,locator:Te.parentLocator,node:Te.node,placement:Te.placement,...Te.anchorLocator?{anchorLocator:Te.anchorLocator}:{}});break;default:Qe={ok:!1,source:H,diagnostic:{code:"unsupported-syntax",message:`Unsupported route composition rewrite: ${String(Te)}`}}}if(!Qe.ok)return{ok:!0,data:Y(h,U.AST_PARSE_ERROR,Qe.diagnostic.message)};Ae=Qe.source}else{let Ce=Pd({routeId:R.routeId,composition:R.composition,entryFile:R.entryFile,currentDocumentVersion:ne.version,expectedDocumentVersion:h.documentVersion,source:H,projection:le,placementUnitKey:h.target.placementUnitKey,operation:"replace-node"});if(!Ce.ok)return{ok:!0,data:Y(h,Vl(Ce.error.code),Ce.error.message,{diagnostics:Ce.error.diagnostics})};let Te=Ce.plan.rewriteStep,Qe;switch(Te.kind){case"replace-root-expression":Qe=Vi({source:H,locator:Te.locator,expectedSourceHash:Te.sourceHash,action:{kind:"replace",jsx:`<${ie} />`}});break;case"replace-node":Qe=ko({source:H,locator:Te.locator,node:{jsx:`<${ie} />`}});break;default:Qe={ok:!1,source:H,diagnostic:{message:`Unsupported page-unit replacement rewrite: ${Te.kind}`}}}if(!Qe.ok)return{ok:!0,data:Y(h,U.AST_PARSE_ERROR,Qe.diagnostic.message)};let or=await Dl({routeState:R,placementUnitKey:h.target.placementUnitKey,source:H,mutatedSource:Qe.source});Ae=or.source,Se=await Promise.all(or.files.map(async _n=>({operation:"delete",file:_n,baseContentHash:ke(await n.readFile(_n))})))}let j=sn({source:Ae,moduleSpecifier:b(R.entryFile,ve),imports:W.entry.export.kind==="default"?[{kind:"default",local:ie}]:[{kind:"named",imported:W.entry.export.name,local:ie}]});if(!j.ok)return{ok:!0,data:Y(h,U.AST_PARSE_ERROR,j.diagnostic.message)};let q=W.files.map(Ce=>({operation:"create-only",file:Ce.path,content:Ce.content})),ge=[{operation:"upsert",file:R.entryFile,content:j.source,baseContentHash:ke(H)},...q,...Se];p+=1;try{let Ce=await rr({request:h,filePlan:{operationId:h.id,kind:"source-edit",target:{kind:"source-file",path:R.entryFile},documentVersion:h.documentVersion,conflictPolicy:"compare-and-swap",edits:ge}});return!Ce.ok&&Ce.error?.message.includes("MATERIALIZATION_INSTANCE_CONFLICT")?{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:Ce.error?.message??"Static prefab instance conflicted during commit."}}:{ok:!0,data:Ce}}finally{p-=1}}});return Q.ok?Q.data:Y(h,Q.error.code==="MATERIALIZATION_INSTANCE_CONFLICT"?U.MATERIALIZATION_CONFLICT:U.MATERIALIZATION_REJECTED,Q.error.message,{materializationCode:Q.error.code})}async function tk(h,R){if(h.kind!=="insert-child"&&h.kind!=="replace-node")return Y(h,U.UNSUPPORTED_OPERATION,"Only page-block insert-child and replace-node use this materialization transaction.");if(h.params.kind!==h.kind||h.kind==="replace-node"&&h.params.kind!=="replace-node"||h.kind==="insert-child"&&h.params.kind!=="insert-child")return Y(h,U.INVALID_PARAMS,"Page-block materialization operation kind must match its params.");let _=R.document,T=R.pageBlockIndex;if(!_||!T||T.diagnostics.length>0)return Y(h,U.UNSUPPORTED_OPERATION,"The current route has no complete verified page-block index.");if(h.documentVersion!==_.version||T.documentVersion!==_.version)return Y(h,U.VERSION_STALE,`Document version ${h.documentVersion} is stale (current: ${_.version}).`);let L=jo(T,h.target,h.documentVersion,h.selectionRef);if(!L.ok)return Y(h,Ls(L.code),L.message);let M=L.binding;if(!(h.kind==="insert-child"?M.descriptor.capabilities.insert:M.descriptor.capabilities.replace)){let ie=M.descriptor.unavailableReasons?.[h.kind==="insert-child"?"insert":"replace"]?.reason??"The selected page block does not permit this operation.";return Y(h,U.UNSUPPORTED_OPERATION,ie)}let z=(h.kind==="insert-child",h.params);if(z.kind!==h.kind)return Y(h,U.INVALID_PARAMS,"Page-block materialization operation kind must match its params.");let Q=z.node;if(Q.kind!=="component-call"||!Q.materialization)return Y(h,U.UNSUPPORTED_OPERATION,"Page-block materialization requires a static component manifest.");let W;if(z.kind==="insert-child"){let ie=z.position;if(!("kind"in ie&&ie.kind==="block-boundary"))return Y(h,U.INVALID_PARAMS,"Page-block insert-child requires a block-boundary position.");if(ie.documentVersion!==h.documentVersion)return Y(h,U.VERSION_STALE,"The block insertion boundary belongs to a different document version.");let Ae=nc(T,ie);if(!Ae.ok)return Y(h,Ls(Ae.code),Ae.message);W=Ae.boundary}let H=Q.materialization,ne=await mi({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:H.files.map(ie=>({path:ie.pathTemplate,content:ie.content})),exists:ie=>n.exists(ie),readFile:ie=>n.readFile(ie)});if(!ne.ok)return Y(h,U.MATERIALIZATION_REJECTED,ne.message);let le=await uI(n,Object.keys(H.projectDependencies??{})),ve=await ud({manifest:H,generatedRoot:"components/site/generated",controlledFiles:H.files.map(ie=>({pathTemplate:ie.pathTemplate})),exists:ie=>n.exists(ie),availableHostDependencies:le,hostCapabilities:qu(),commit:async ie=>{let Ae=R.document,Se=R.pageBlockIndex;if(!Ae||!Se||Ae.version!==h.documentVersion||Se.documentVersion!==Ae.version||!Se.bindings.has(M.blockKey))return{ok:!0,data:Y(h,U.VERSION_STALE,"The route or selected block changed before materialization could commit.")};let j=Se.bindings.get(M.blockKey);if(!j||j.ownerFile!==M.ownerFile||j.ownerSourceHash!==M.ownerSourceHash||j.sourceHash!==M.sourceHash)return{ok:!0,data:Y(h,U.VERSION_STALE,"The selected block owner or source changed before materialization could commit.")};let q=new Set([M.ownerFile,M.descriptor.source.file,...W?[W.ownerFile,W.anchorLocator.file,...W.parentLocator?[W.parentLocator.file]:[]]:[]]),ge=new Map;try{for(let Te of q)ge.set(Te,await n.readFile(Te))}catch{return{ok:!0,data:Y(h,U.VERSION_STALE,"A selected owner, root, or boundary file is no longer readable.")}}let Ce=Rx({operationId:h.id,documentVersion:h.documentVersion,target:h.target,binding:M,...W?{boundary:W}:{},operation:z.kind,materialization:ie,files:ge});if(!Ce.ok){let Te=ik(Ce.code);return{ok:!0,data:Y(h,Te,Ce.message,{materializationCode:Ce.code})}}p+=1;try{let Te=await rr({request:h,filePlan:Ce.plan});return!Te.ok&&Te.error?.message.includes("MATERIALIZATION_INSTANCE_CONFLICT")?{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:Te.error.message||"Static prefab instance conflicted during commit."}}:{ok:!0,data:Te}}finally{p-=1}}});return ve.ok?ve.data:Y(h,ve.error.code==="MATERIALIZATION_INSTANCE_CONFLICT"?U.MATERIALIZATION_CONFLICT:U.MATERIALIZATION_REJECTED,ve.error.message,{materializationCode:ve.error.code})}async function nk(h,R){if(h.kind!=="move-node"&&h.kind!=="remove-node")return Y(h,U.UNSUPPORTED_OPERATION,"Only page-unit move-node and remove-node are currently supported by the page composition transaction.");let _=R.document,T=R.pageCompositionProjection;if(!_||_.pageComposition?.status!=="supported"||!T||T.status!=="supported")return Y(h,U.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(h.documentVersion!==_.version||T.documentVersion!==_.version)return Y(h,U.VERSION_STALE,`Document version ${h.documentVersion} is stale (current: ${_.version}).`);let L=await n.readFile(R.entryFile),M=Pd({routeId:R.routeId,composition:R.composition,entryFile:R.entryFile,currentDocumentVersion:_.version,expectedDocumentVersion:h.documentVersion,source:L,projection:T,placementUnitKey:h.target.placementUnitKey,operation:h.kind,targetPlacement:h.kind==="move-node"&&h.params.kind==="move-node"&&"kind"in h.params.target&&h.params.target.kind==="page-composition"?h.params.target:void 0});if(!M.ok)return Y(h,Vl(M.error.code),M.error.message,{diagnostics:M.error.diagnostics});let J=M.plan.rewriteStep,z;switch(J.kind){case"move-node":z=eo({source:L,locator:J.locator,targetParentLocator:J.targetParentLocator,placement:J.placement,...J.anchorLocator?{anchorLocator:J.anchorLocator}:{}});break;case"remove-node":z=qr({source:L,locator:J.locator});break;case"remove-root-expression":z=Vi({source:L,locator:J.locator,expectedSourceHash:J.sourceHash,action:{kind:"remove"}});break;default:z={ok:!1,source:L,diagnostic:{message:`Unsupported page-unit mutation rewrite: ${J.kind}`}}}if(!z.ok)return Y(h,U.AST_PARSE_ERROR,z.diagnostic.message);let Q=z.source,W=[];if(h.kind==="remove-node"){let ne=await Dl({routeState:R,placementUnitKey:h.target.placementUnitKey,source:L,mutatedSource:Q});Q=ne.source,W=await Promise.all(ne.files.map(async le=>({operation:"delete",file:le,baseContentHash:ke(await n.readFile(le))})))}let H=[{operation:"upsert",file:R.entryFile,content:Q,baseContentHash:ke(L)},...W];p+=1;try{return await rr({request:h,filePlan:{operationId:h.id,kind:"source-edit",target:{kind:"source-file",path:R.entryFile},documentVersion:h.documentVersion,conflictPolicy:"compare-and-swap",edits:H}})}finally{p-=1}}async function rk(h,R){if(h.kind!=="move-node"&&h.kind!=="remove-node")return Y(h,U.UNSUPPORTED_OPERATION,"Only page-block move-node and remove-node use this source transaction.");let _=R.document,T=R.pageBlockIndex;if(!_||!T||T.diagnostics.length>0)return Y(h,U.UNSUPPORTED_OPERATION,"The current route has no complete verified page-block index.");if(h.documentVersion!==_.version||T.documentVersion!==_.version)return Y(h,U.VERSION_STALE,`Document version ${h.documentVersion} is stale (current: ${_.version}).`);let L=jo(T,h.target,h.documentVersion,h.selectionRef);if(!L.ok)return Y(h,Ls(L.code),L.message);let M=L.binding;if(M.documentVersion!==_.version)return Y(h,U.VERSION_STALE,"The resolved page-block binding is stale.");if(!(h.kind==="move-node"?M.descriptor.capabilities.move:M.descriptor.capabilities.remove)){let Se=M.descriptor.unavailableReasons?.[h.kind==="move-node"?"move":"remove"]?.reason??"The selected block does not permit this operation.";return Y(h,U.UNSUPPORTED_OPERATION,Se)}if(h.kind==="remove-node"){let Se=[...i.values()].filter(j=>j.dependencyFiles.has(M.ownerFile));if(Se.includes(R)||Se.push(R),Se.some(j=>!j.pageBlockIndex||j.pageBlockIndex.descriptors.length<=1))return Y(h,U.UNSUPPORTED_OPERATION,"The selected source is the last editable page block in an affected composition.")}let z=null;if(h.kind==="move-node"){if(h.params.kind!=="move-node"||!("kind"in h.params.target)||h.params.target.kind!=="block-boundary")return Y(h,U.INVALID_PARAMS,"Page-block move requires a block-boundary target.");if(h.params.target.anchorBlockKey===M.blockKey)return Y(h,U.INVALID_TARGET,"A page block cannot be moved relative to itself.");let Se=nc(T,h.params.target);if(!Se.ok)return Y(h,Ls(Se.code),Se.message);let j=T.bindings.get(h.params.target.anchorBlockKey);if(!j||!M.descriptor.siblingBlockKeys.includes(j.blockKey)||!j.descriptor.siblingBlockKeys.includes(M.blockKey)||j.ownerFile!==M.ownerFile||j.root.ownerNode.kind!==M.root.ownerNode.kind||j.root.ownerNode.key!==M.root.ownerNode.key||j.root.parentStructuralPath!==M.root.parentStructuralPath)return Y(h,U.INVALID_TARGET,"The selected block and boundary anchor are not verified same-owner source siblings.");if(z=Se.boundary,z.ownerFile!==M.ownerFile||z.sourceHash!==M.ownerSourceHash||!z.parentLocator)return Y(h,U.INVALID_TARGET,"The move boundary does not belong to the selected block's source owner.")}let Q=M.ownerFile,W=await n.readFile(Q);if(ke(W)!==M.ownerSourceHash)return Y(h,U.VERSION_STALE,"The page-block owner source changed after resolution.");let H=M.descriptor.source.file===Q?W:await n.readFile(M.descriptor.source.file);if(ke(H)!==M.descriptor.source.contentHash)return Y(h,U.VERSION_STALE,"The selected page-block source changed after resolution.");let ne=ok(M),le=h.kind==="remove-node"?qr({source:W,locator:ne}):eo({source:W,locator:ne,targetParentLocator:Ml(z.parentLocator),anchorLocator:Ml(z.anchorLocator),placement:z.placement});if(!le.ok)return Y(h,U.AST_PARSE_ERROR,le.diagnostic.message);let ve=le.source,ie=[];if(h.kind==="remove-node"&&M.root.ownerNode.kind==="route-member"&&M.root.callChain.length>0&&M.descriptor.placementUnitKey){let Se=await Dl({routeState:R,placementUnitKey:M.descriptor.placementUnitKey,source:W,mutatedSource:ve});ve=Se.source,ie=Se.files}let Ae=[{operation:"upsert",file:Q,content:ve,baseContentHash:M.ownerSourceHash},...await Promise.all(ie.map(async Se=>({operation:"delete",file:Se,baseContentHash:ke(await n.readFile(Se))})))];p+=1;try{return await rr({request:h,filePlan:{operationId:h.id,kind:"source-edit",target:h.target,documentVersion:h.documentVersion,conflictPolicy:"compare-and-swap",edits:Ae}})}finally{p-=1}}function ok(h){return Ml(h.ownerLocator)}function Ml(h){return{kind:"jsx-node",strategy:"source-range",sourceRange:h.sourceRange,...h.structuralPath&&h.componentName?{expectedIdentity:{file:h.file,component:h.componentName,structuralPath:h.structuralPath}}:{}}}function Ls(h){return h==="VERSION_STALE"?U.VERSION_STALE:h==="INVALID_PARAMS"?U.INVALID_PARAMS:U.INVALID_TARGET}function ik(h){return h==="VERSION_STALE"?U.VERSION_STALE:h==="INVALID_PARAMS"?U.INVALID_PARAMS:h==="INVALID_TARGET"?U.INVALID_TARGET:h.startsWith("MATERIALIZATION_")?U.MATERIALIZATION_REJECTED:U.UNSUPPORTED_OPERATION}async function Dl(h){let R={source:h.mutatedSource,files:[]},_=h.routeState.graph,T=h.routeState.pageCompositionProjection;if(!_||!T||T.status!=="supported"||!n.listFiles)return R;let M=T.placementUnitByKey.get(h.placementUnitKey)?.sourceRange;if(!M)return R;let J=[..._.elements.values()].find(j=>j.sourceFile===h.routeState.entryFile&&j.importedFrom&&E(j.sourceRange,M));if(!J?.importedFrom||!J.exportName)return R;let z=S(J.importedFrom),Q="components/site/generated/";if(!z.startsWith(Q))return R;let W=z.slice(Q.length).split("/")[0];if(!W||!/-[0-9a-f]{8}$/i.test(W))return R;let H=`${Q}${W}`;if([..._.elements.values()].filter(j=>j.sourceFile===h.routeState.entryFile&&S(j.importedFrom??"")===z).length!==1)return R;let le=await n.listFiles({maxFiles:5e3,maxDepth:32}),ve=Array.isArray(le)?le:le.files;if(!Array.isArray(le)&&le.truncated)return R;let ie=ve.map(({path:j})=>j).filter(j=>j===H||j.startsWith(`${H}/`));if(ie.length===0||!ie.includes(z))return R;for(let{path:j}of ve)if(!(j===h.routeState.entryFile||j===H||j.startsWith(`${H}/`)))try{if((await n.readFile(j)).includes(W))return R}catch{return R}let Ae=b(h.routeState.entryFile,z),Se=Co({source:h.mutatedSource,moduleSpecifier:Ae,imports:J.exportName==="default"?[{kind:"default"}]:[{kind:"named",imported:J.exportName}]});return Se.ok?Se.source.includes(W)?{source:Se.source,files:[]}:{source:Se.source,files:ie.sort((j,q)=>j.localeCompare(q))}:R}async function sk(h){if(n.getFileInfo){for(let J of h)if(await n.exists(J.path)&&await n.getFileInfo(J.path)===null)return{ok:!1,errorCode:"invalid-params",message:`Source edit path must resolve to a regular non-symbolic-link file: ${J.path}`,details:{path:J.path}}}for(let J of h){if(J.operation!=="upsert"||!/^(?:src\/)?app\/globals\.css$/i.test(J.path))continue;let z=await n.exists(J.path)?await ru(n,J.path):null;if(z?.ok){let Q=_M(z.content,J.content);if(!Q.ok)return{ok:!1,errorCode:"invalid-params",message:Q.message,details:{path:J.path,code:Q.code}}}}let R=ak(h);if(R.length===0)return{ok:!0};let _=WM(n,h),T=new Map,L=(J,z)=>{let Q=T.get(J);if(Q?.source===z)return Q.result;let W=je(J,z);return T.set(J,{source:z,result:W}),W},M;try{M=await YS(R,async J=>{let z=i.get(J);return z?[...(await D(z.entryFile,await _.readFile(z.entryFile),_,{validationOnly:!0,parseModule:L,validatedImports:f.getImports})).parsedModules.values()]:[]})}catch(J){return{ok:!1,errorCode:"ast-error",message:`Source edit preflight failed: ${Ot(J)}`,details:{compositionKeys:R}}}for(let J of M)f.remember(J);return{ok:!0}}function ak(h){return h.map(_=>_.path).some(yI)?[...i.keys()]:[]}function Bl(h,R,_,T){let L=ks(R);return{composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!1,resultVersion:G(h),error:{code:L,message:_,...T?{details:T}:{}}}}async function jl(h){let R=[];for(let _ of new Set(h))R.push(await ck(_));return R}async function ck(h){if(!(typeof n.exists=="function"?await n.exists(h):!0))return{file:h,content:"",version:Math.max(0,B(h)),exists:!1};let _=await n.readFile(h);return{file:h,content:_,version:Math.max(1,B(h)),exists:!0,sha256:ke(_)}}async function jm(h,R,_,T){if(!e.historyStore)return null;let L=new Map(R.map(z=>[z.file,z])),M=new Map(_.map(z=>[z.file,z])),J=[...new Set([...L.keys(),...M.keys()])].sort().map(z=>{let Q=L.get(z),W=M.get(z);return{path:z,preDigest:Q?.exists===!1||!Q?null:ke(Q.content),postDigest:W?.exists===!1||!W?null:ke(W.content)}});return{schemaVersion:2,transactionId:`${h}:${T.expectedIndexDigest}`,operationId:h,phase:"prepared",historyTransition:T,files:J}}async function $m(h){return!h||!e.historyStore||await e.historyStore.writeTransactionJournal(h),h}async function So(h){h&&e.historyStore&&await e.historyStore.clearTransactionJournal(h.transactionId)}async function $l(h,R){let _=[];try{for(let T of h)await Vm(T),typeof n.bumpVersion=="function"&&n.bumpVersion(T.file),_.push(T.file)}catch(T){let L=await lk(R.filter(M=>_.includes(M.file)));return L.ok?{ok:!1,reason:`Writeback failed and committed files were restored: ${Ot(T)}`,rolledBack:!0}:{ok:!1,reason:`Writeback failed, then rollback failed for ${L.failedFiles.join(", ")}: ${Ot(T)}`,rolledBack:!1}}return{ok:!0,snapshots:h.map(uk)}}async function Vm(h){if(h.exists===!1){await n.deleteFile(h.file);return}await n.writeFile(h.file,h.content)}async function lk(h){let R=[];for(let _ of h)try{await Vm(_),typeof n.bumpVersion=="function"&&n.bumpVersion(_.file)}catch{R.push(_.file)}return R.length===0?{ok:!0}:{ok:!1,failedFiles:R}}function uk(h){let R=h.exists!==!1;return{file:h.file,content:R?h.content:"",version:h.version,exists:R,...R?{sha256:ke(h.content)}:{}}}async function rr(h){return y.runExclusive(()=>dk(h))}async function dk(h){let R=h.filePlan.edits.map(j=>j.file),_=o.resolveSelector(h.request.composition),T=_.context,L=h.historyPolicy==="none"?void 0:{initiatingComposition:T,affectedCompositions:pn(R)},M=await jl(R),J=new Map(M.filter(j=>j.exists!==!1).map(j=>[j.file,j.content])),z=Km(),Q=new Map(d),W=new Set(g),H=new Set([...i.values()].filter(j=>h.filePlan.edits.some(q=>q.operation==="delete"&&q.file===j.entryFile)).map(j=>j.key)),ne=h.filePlan.edits.map(j=>j.operation==="delete"?{file:j.file,content:"",version:0,exists:!1}:{file:j.file,content:j.content,version:0,exists:!0,sha256:ke(j.content)}),le={operationId:h.filePlan.operationId,intents:h.filePlan.edits.map(j=>j.operation==="delete"?{kind:"delete",path:j.file}:{kind:j.operation==="create-only"?"create-only":"upsert",path:j.file,content:j.content})},ve=null,ie=!1,Ae=await Qc({overlay:J,exists:j=>n.exists(j),plan:le,buildCandidate:async({plan:j})=>({plan:j}),prepareHistory:async()=>{let j=h.historyPolicy==="none"?null:await l.prepareAppend({composition:o.resolveSelector(h.request.composition).context,operationId:h.request.id,kind:h.request.kind,target:h.request.target,preSnapshots:M,postSnapshots:ne,...h.selectionRef?{selectionRef:h.selectionRef}:{},...h.output?{output:h.output}:{},...L?{provenance:L}:{}}),q=j?.historyTransition?j.historyTransition:e.historyStore?FM(await e.historyStore.readIndex()):null;if(e.historyStore&&!q)throw new Error("Durable history did not provide an exact index transition.");return ve=await jm(h.request.id,M,ne,q),ve=await $m(ve),{history:j,historyTransition:q}},reverify:async()=>{},writeCandidate:async()=>{let j=await u.executeFilePlan(h.filePlan);if(!j.ok)throw new sl(j);return{postSnapshots:await jl(j.affectedFiles),affectedFiles:j.affectedFiles,internalResultVersion:j.resultVersion}},validateCandidate:async({candidate:j,receipt:q})=>{let ge=await pe(q.affectedFiles,{changed:!0,minimumVersion:q.internalResultVersion,publish:!1,excludedCompositionKeys:H});if(ge.failedRoutes.length>0)throw new yo(ge.failedRoutes);let Ce=Xm(z,ge.candidateRouteStates??[]),Te=Jm(Ce,_.key);return{...j,rebuild:ge,routeSnapshots:Ce,resultVersion:Te,...pI(h.selectionRef,Ce.map(Qe=>Qe.state.document))?{selectionRef:pI(h.selectionRef,Ce.map(Qe=>Qe.state.document))}:{}}},publishCandidate:async({candidate:j,history:q,receipt:ge})=>{q?.history&&(await l.publishPrepared(q.history),ie=!0);let Ce=j.resultVersion??ge.internalResultVersion;return{composition:T,requestId:h.request.id,kind:h.request.kind,target:h.request.target,ok:!0,resultVersion:Ce,affectedFiles:ge.affectedFiles,fileChanges:ge.postSnapshots.map(Te=>({path:Te.file,operation:Te.exists===!1?"delete":"upsert"})),...h.output?{output:h.output}:{},...j.selectionRef?{selectionRef:j.selectionRef}:{}}},swapCandidate:({candidate:j,receipt:q})=>{j.routeSnapshots&&Ms(j.routeSnapshots),j.rebuild?.candidateSourceCache&&vs(d,j.rebuild.candidateSourceCache),Lm(q.postSnapshots)},finalizeCandidate:async()=>{await So(ve);for(let j of H)i.delete(j)},emitCommitted:({candidate:j,published:q})=>{Ll(q,j.rebuild??{rebuiltRoutes:[],failedRoutes:[]})},rollbackCandidate:async({history:j,receipt:q})=>{if(ie)throw new Error("history was published before transaction finalization failed");if(q){let ge=await $l(M,q.postSnapshots);if(!ge.ok)throw new Error(ge.reason)}Ms(z),vs(d,Q),Mm(W),j?.history&&await l.discardPrepared?.(j.history),await So(ve)}});if(Ae.ok)return Ae.published;if(Ae.stage==="precheck"||Ae.stage==="build")try{await So(ve)}catch(j){let q=await Bs(Ot(j));return Y(h.request,q,"Unable to clear an uncommitted transaction journal.")}if(Ae.recoveryRequired){let j=await Bs(Ae.reason);return Y(h.request,j===U.RECOVERY_PERSIST_FAILED?j:U.ROLLBACK_FAILED,Ae.reason)}let Se=Ae.error;return Se instanceof sl?{...Y(h.request,ks(Se.result.errorCode),Se.result.reason),...Se.result.affectedFiles?{affectedFiles:Se.result.affectedFiles}:{}}:Se instanceof yo?Y(h.request,U.ROUTE_REBUILD_FAILED,`Route rebuild failed and source was rolled back: ${Np(Se.failedRoutes)}`,{failedRoutes:Se.failedRoutes}):Y(h.request,Hm(Ae.stage),Ot(Se))}async function Um(h){return y.runExclusive(async()=>{let R=h==="undo"?await l.prepareUndo():await l.prepareRedo();return R?fk(h,R):{composition:o.entries[0].context,requestId:h,kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:o.initialVersions.get(o.entries[0].key)??0,error:{code:U.INTERNAL_ERROR,message:h==="undo"?"Nothing to undo":"Nothing to redo"}}})}async function fk(h,R){let _=R.entry,T=h==="undo"?_.preSnapshots:_.postSnapshots,L=h==="undo"?_.postSnapshots:_.preSnapshots,M=T.map(q=>q.file),{context:J,key:z}=Fs(_,M),Q=await jl(M),W=new Map(Q.filter(q=>q.exists!==!1).map(q=>[q.file,q.content])),H=$(z),ne=Km(),le=new Map(d),ve=new Set(g),ie=null,Ae=!1,Se,j=await Qc({overlay:W,plan:{operationId:`${h}:${_.operationId}`,intents:T.map(q=>q.exists===!1?{kind:"delete",path:q.file}:{kind:"upsert",path:q.file,content:q.content})},buildCandidate:async()=>({}),prepareHistory:async()=>(ie=await jm(`${h}:${_.operationId}`,Q,T,R.historyTransition),ie=await $m(ie),R),reverify:async()=>{},writeCandidate:async()=>{let q=await $l(T,L);if(!q.ok)throw new Error(q.reason);return{snapshots:q.snapshots}},validateCandidate:async({candidate:q})=>{Se=_t(_,M);let ge=await pe(M,{changed:!0,minimumVersion:H+1,publish:!1,affectedCompositionKeys:Se});if(ge.failedRoutes.length>0)throw new yo(ge.failedRoutes);let Ce=Xm(ne,ge.candidateRouteStates??[]),Te=Jm(Ce,z);return{...q,rebuild:ge,routeSnapshots:Ce,resultVersion:Te}},publishCandidate:async({candidate:q,history:ge,receipt:Ce})=>{if(!ge)throw new Error("history cursor intent is missing");await l.publishPrepared(ge),Ae=!0;let Te=q.resultVersion??H+1;return{composition:J,requestId:h,kind:_.kind,target:_.target,ok:!0,resultVersion:Te,affectedFiles:M,fileChanges:Ce.snapshots.map(Qe=>({path:Qe.file,operation:Qe.exists===!1?"delete":"upsert"})),..._.output?{output:_.output}:{}}},swapCandidate:({candidate:q,receipt:ge})=>{q.routeSnapshots&&Ms(q.routeSnapshots),q.rebuild?.candidateSourceCache&&vs(d,q.rebuild.candidateSourceCache),Lm(ge.snapshots)},finalizeCandidate:async()=>{await So(ie)},emitCommitted:({candidate:q,published:ge})=>Ll(ge,q.rebuild??{rebuiltRoutes:[],failedRoutes:[]}),rollbackCandidate:async({history:q,receipt:ge})=>{if(Ae)throw new Error("history cursor was published before transaction finalization failed");if(ge){let Ce=await $l(L,ge.snapshots);if(!Ce.ok)throw new Error(Ce.reason)}Ms(ne),vs(d,le),Mm(ve),q&&await l.discardPrepared?.(q),await So(ie)}});if(j.ok)return j.published;if(j.stage==="precheck"||j.stage==="build")try{await So(ie)}catch(q){let ge=await Bs(Ot(q));return{composition:J,requestId:h,kind:_.kind,target:_.target,ok:!1,resultVersion:H,error:{code:ge,message:"Unable to clear an uncommitted transaction journal."}}}if(j.recoveryRequired){let q=await Bs(j.reason);return{composition:J,requestId:h,kind:_.kind,target:_.target,ok:!1,resultVersion:H,affectedFiles:M,error:{code:q===U.RECOVERY_PERSIST_FAILED?q:U.ROLLBACK_FAILED,message:j.reason}}}return{composition:J,requestId:h,kind:_.kind,target:_.target,ok:!1,resultVersion:H,affectedFiles:M,error:{code:j.error instanceof yo?U.ROUTE_REBUILD_FAILED:Hm(j.stage),message:Ot(j.error),...j.error instanceof yo?{details:{failedRoutes:j.error.failedRoutes}}:{}}}}function Km(){return[...i.values()].map(h=>({composition:h.composition,key:h.key,routeId:h.routeId,state:{...h,dependencyFiles:new Set(h.dependencyFiles),fileVersions:new Map(h.fileVersions)}}))}function Jm(h,R){return h.find(T=>T.key===R)?.state.graph?.version??o.initialVersions.get(R)??0}function Xm(h,R){let _=new Map(h.map(T=>[T.key,T]));for(let T of R)_.set(T.key,T);return[..._.values()]}function Ms(h){for(let R of i.values())N(R);for(let R of h){let _={...R.state,dependencyFiles:new Set(R.state.dependencyFiles),fileVersions:new Map(R.state.fileVersions)};i.set(R.key,_),v(_,_.dependencyFiles)}}async function Ds(h){let R=i.get(h);if(!R)throw new Error(`Composition not found: ${h}`);if(R.graph)return;let _=await n.readFile(R.entryFile);await fe(h,_)}function Io(h,R){let _=i.get(o.resolveSelector(R).key)??null;return!_||!zm(_,h)?null:_}function zm(h,R){if(h.documentIndex?.entriesByKey.has(R)||h.graph?.elements.has(R))return!0;let _=$t(R);return _&&_!==R?h.graph?.elements.has(_)===!0:!1}function Y(h,R,_,T){return{composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!1,resultVersion:G(h),error:{code:R,message:_,...T?{details:T}:{}}}}function Hm(h){return h==="validate"?U.ROUTE_REBUILD_FAILED:h==="publish"?U.HISTORY_COMMIT_FAILED:U.WRITE_IO_ERROR}async function Bs(h){if(m=!0,!l.markRecoveryRequired)return U.RECOVERY_REQUIRED;try{return await l.markRecoveryRequired(h),U.RECOVERY_REQUIRED}catch{return U.RECOVERY_PERSIST_FAILED}}function pk(h){let _=h.split(/[^a-zA-Z0-9]+/).filter(Boolean).map(T=>T.charAt(0).toUpperCase()+T.slice(1)).join("").replace(/^[^a-zA-Z_$]+/,"");return _?`Prefab${_}`:"GeneratedPrefab"}function Vl(h){return h==="VERSION_STALE"?U.VERSION_STALE:h==="CROSS_PAGE_MOVE_UNSUPPORTED"?U.CROSS_PAGE_MOVE_UNSUPPORTED:U.UNSUPPORTED_OPERATION}async function Wm(h){if(h.target.kind==="route"){let _=i.get(o.resolveSelector(h.target.composition).key)??null;return _?(_.graph||await Ds(_.key),_):Y(h,U.ROUTE_NOT_FOUND,"Composition not found for route target.")}if(h.target.kind==="page-unit"){let _=i.get(o.resolveSelector(h.target.composition).key)??null;return _?(_.graph||await Ds(_.key),_):Y(h,U.ROUTE_NOT_FOUND,"Composition not found for page-unit target.")}if(h.target.kind==="page-block"){let _=i.get(o.resolveSelector(h.target.composition).key)??null;return _?(_.graph||await Ds(_.key),_):Y(h,U.ROUTE_NOT_FOUND,"Composition not found for page-block target.")}if(h.target.kind!=="node")return Y(h,U.UNSUPPORTED_OPERATION,`${h.kind} source target execution is not implemented yet.`);let R=i.get(o.resolveSelector(h.composition).key)??null;return R?(R.graph||await Ds(R.key),zm(R,h.target.key)?R:Y(h,U.NODE_NOT_FOUND,`Target key not found: ${h.target.key}`)):Y(h,U.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(),f.clear(),g.clear()},registerComposition(h,R){let _=o.register({context:h,entryFile:R}),T=i.get(_.key);if(T?.entryFile===R)return;T&&N(T);let L=fI(_.context,R);i.set(_.key,L),v(L,L.dependencyFiles),r.emit({type:"graph-invalidated",composition:_.context})},unregisterComposition(h){let R=o.resolveSelector(h),_=i.get(R.key);_&&(N(_),i.delete(R.key),o.unregister(R.key),i.size===0&&(t="idle"),r.emit({type:"graph-invalidated",composition:R.context}))},getCompositionEntryFiles(){return[...i.values()].map(h=>h.entryFile)},getCompositionContext(h){return o.resolveSelector(h).context},async initializeComposition(h){let R=o.resolveSelector(h),_=i.get(R.key);if(!_)throw new Error(`Composition not registered: ${R.key}`);if(_.graph)t="ready";else{t="building";try{let T=await n.readFile(_.entryFile);await fe(R.key,T),t="ready",r.emit({type:"graph-ready",composition:R.context,version:i.get(R.key)?.graph?.version??0})}catch(T){throw t="idle",r.emit({type:"graph-error",composition:R.context,message:Ot(T)}),T}}},getDocument(h){let R=o.resolveSelector(h),_=i.get(R.key);if(!_)throw new Error(`Composition not registered: ${R.key}`);if(!_.document)throw new Error(`Composition not built: ${R.key}`);return _.document},async getHistoryStatus(){await x;let h=await l.getStatus?.();return h?{...h,recoveryRequired:m}:{canUndo:!1,canRedo:!1,undoDepth:0,redoDepth:0,recoveryRequired:m}},getObjectEditContext(h,R,_){let T=Io(h,R),L=$t(h)??h;if(T?.graph&&T.topology&&T.capabilities&&T.detailProjections){let M=T.detailProjections.get(L);if(M){let J=T.graph.elements.get(L);if(!J)throw new Error(`Key not found: ${h}`);let z=$M(h,L,_),Q=new Map;if(M.isRepeat&&z?.instanceIndex!==void 0)for(let ne of J.attributes??[])Q.set(ne.name,rp({file:J.sourceFile,source:d.get(J.sourceFile)??"",element:J,propertyName:ne.name,selectionRef:z,graph:T.graph,sources:d}));let W=PS({element:J,graph:T.graph,source:d.get(J.sourceFile),documentVersion:T.graph.version,selectionRef:_,isRepeat:M.isRepeat,propertyProvenance:M.propertyProvenances,repeatTargets:Q}),H=wS(L,T.graph,T.topology,T.capabilities,M.textSources,M.provenances,M.dynamicData,W);return h===L?H:rI(H,h,T.document??null,T.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${h}`)},getRenderDetail(h,R){let _=Io(h,R),T=$t(h)??h;if(_?.graph&&_.topology&&_.capabilities&&_.detailProjections){let L=_.detailProjections.get(T);if(L){let M=TS(T,_.graph,_.topology,_.capabilities,L.textSources,L.writeTarget,L.provenances,L.conditional,L.componentSemantic,L.styleSource,L.dynamicData);return h===T?M:nI(M,h,_.document??null,_.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${h}`)},getClassNameSource(h,R){let _=Io(h,R),T=$t(h)??h;if(!_?.graph)throw new Error(`Key not found: ${h}`);let L=_.graph.elements.get(T);if(!L)throw new Error(`Key not found: ${h}`);let M=d.get(L.sourceFile);if(M===void 0)throw new Error(`Source not loaded: ${L.sourceFile}`);return Iu({key:T,route:{composition:_.composition,routeId:_.routeId,graph:_.graph,source:M}})},refreshSourceForKey:Yv,async execute(h){if(await x,m)return Y(h,U.RECOVERY_REQUIRED,"The edit engine requires explicit recovery before accepting mutations.");if(h.kind==="source-edit")return Zv(h);if(h.kind==="insert-page-resource")return qv(h);if(h.kind==="delete-page-source")return Qv(h);let R=await Wm(h);if("ok"in R)return R;await Bm(h);let _=await Wm(h);if("ok"in _)return _;let T=_;if(h.target.kind==="page-unit"){let H=h;return h.kind==="insert-child"||h.kind==="replace-node"?ek(H,T):h.kind==="move-node"||h.kind==="remove-node"?nk(H,T):Y(h,U.UNSUPPORTED_OPERATION,"Only page-unit insert-child, replace-node, move-node, and remove-node are currently supported by the page composition transaction.")}if(h.target.kind==="page-block"){let H=h;return h.kind==="insert-child"||h.kind==="replace-node"?tk(H,T):h.kind==="move-node"||h.kind==="remove-node"?rk(H,T):Y(h,U.UNSUPPORTED_OPERATION,"Page-block operation is not supported by the current structural transaction.")}let M=h.params,J=h.target.kind==="node"?h.target.key:null;if(M.kind==="move-node"&&"kind"in M.target&&M.target.kind==="source-sibling"){let H=M.target,ne=J?T.document?.entries.find(q=>q.key===J):null,le=T.document?.entries.find(q=>q.key===H.anchorKey),ve=ne?.pageCompositionActionScope,ie=ve?.kind==="source-siblings"?ve.siblingKeys:null,Ae=ie?.indexOf(ne?.key??"")??-1,Se=ie?.indexOf(H.anchorKey)??-1,j=H.relation==="before"?Ae-1:Ae+1;if(!ne||!le||!ie||Ae<0||Se!==j||le.pageCompositionActionScope?.kind!=="source-siblings"||le.pageCompositionActionScope.siblingKeys.length!==ie.length||le.pageCompositionActionScope.siblingKeys.some((q,ge)=>q!==ie[ge])||!ne.operationSummary.canMove)return Y(h,U.INVALID_TARGET,"Source sibling move is unavailable because the current source sibling scope or adjacent anchor no longer matches.")}if(!T.graph||!T.topology||!T.capabilities)return{composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!1,resultVersion:G(h),error:{code:h.target.kind==="route"?U.ROUTE_NOT_FOUND:U.NODE_NOT_FOUND,message:h.target.kind==="route"?"Composition not ready for route target.":h.target.kind==="node"?`Target key not found: ${h.target.key}`:`${h.kind} source target execution is not implemented yet.`}};let z=oD(T,T.graph,T.capabilities,d,i),Q=await new Nc(z).plan(h);if(!Q.ok)return{composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!1,resultVersion:G(h),error:{code:ks(Q.errorCode),message:Q.reason}};let W=Q.plan;if(W.steps.length===0)return h.kind==="set-props"?{composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!0,resultVersion:G(h),affectedFiles:[]}:{composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!1,resultVersion:G(h),error:{code:U.PLAN_FAILED,message:"Planner could not generate a valid execution plan"}};p+=1;try{if(W.steps.some(ne=>ne.type==="invoke-external-adapter")){let ne=await u.execute(W);if(!ne.ok)return Y(h,ks(ne.errorCode),ne.reason);let le={composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!0,resultVersion:Math.max(G(h),ne.resultVersion),affectedFiles:ne.affectedFiles,...ne.selectionRef?{selectionRef:ne.selectionRef}:{}};return Ll(le,{rebuiltRoutes:[],failedRoutes:[]}),le}let H=await u.prepareRewritePlan(W);return H.ok?await rr({request:h,filePlan:H.filePlan,...H.selectionRef?{selectionRef:H.selectionRef}:{}}):Y(h,ks(H.errorCode),H.reason)}catch(H){return{composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!1,resultVersion:G(h),error:{code:U.INTERNAL_ERROR,message:Ot(H)}}}finally{p-=1}},async undo(h){if(await x,m)return{composition:o.entries[0].context,requestId:"undo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:$(o.entries[0].key),error:{code:U.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting undo."}};p+=1;try{return await Um("undo")}finally{p-=1}},async redo(h){if(await x,m)return{composition:o.entries[0].context,requestId:"redo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:$(o.entries[0].key),error:{code:U.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting redo."}};p+=1;try{return await Um("redo")}finally{p-=1}},notifyFileChanged(h){Om([h])},getAffectedCompositions(h){return kt(h)},subscribe(h){return r.subscribe(h)}}}function ZM(e){return e instanceof Error&&"code"in e&&(e.code==="ENOENT"||e.code==="ENOTDIR")}function qM(e,t,n,r){let o=new Map,i=new Map,s=(d,f,g)=>{let p=d.get(f)??new Set,m=p.size;return p.add(g),d.set(f,p),p.size!==m},a=(d,f)=>{if(!d.importedFrom)return!1;if(d.exportName==="default")return s(i,d.importedFrom,f);let g=s(o,`${d.importedFrom}#${d.tag}`,f);return d.exportName&&d.exportName!==d.tag&&(g=s(o,`${d.importedFrom}#${d.exportName}`,f)||g),g},c=d=>o.get(`${d.sourceFile}#${d.componentName}`)??i.get(d.sourceFile);for(let d of t.elements.values()){if(d.sourceFile!==n.entryFile||!d.importedFrom||!/^[A-Z]/.test(d.tag))continue;let f=n.placements.find(p=>p.members.some(m=>m.sourceRange!==null&&_s(d.sourceRange,m.sourceRange)));if(!f)continue;let g=f.placementUnitKey;a(d,g)}let l=!0;for(;l;){l=!1;for(let d of t.elements.values()){if(d.sourceFile===n.entryFile||!d.importedFrom||!/^[A-Z]/.test(d.tag))continue;let f=c(d);if(f)for(let g of f)l=a(d,g)||l}}let u=n.placements.find(d=>d.placementKey===n.container.placementKey&&d.relation==="append");for(let d of e.entries){let f=$t(d.key)??d.key,g=t.elements.get(d.key)??t.elements.get(f);if(!g)continue;if(g.sourceFile===n.entryFile){if(n.container.sourceRange&&_s(g.sourceRange,n.container.sourceRange)&&u){d.pageCompositionUnitKey=u.placementUnitKey;continue}let y=n.placements.find(x=>x.members.some(S=>S.sourceRange!==null&&(_s(g.sourceRange,S.sourceRange)||rD(S.sourceRange,g.sourceRange))));if(y){d.pageCompositionUnitKey=y.placementUnitKey;continue}}let p=o.get(`${g.sourceFile}#${g.componentName}`);if(p){p.size===1&&(d.pageCompositionUnitKey=p.values().next().value);continue}let m=i.get(g.sourceFile);m?.size===1&&(d.pageCompositionUnitKey=m.values().next().value)}QM(e,t,n,r)}function QM(e,t,n,r){let o=new Map(e.entries.map(f=>[f.key,f])),i=e.entries.filter(f=>{let g=f.pageCompositionUnitKey;return g?f.parentKey?o.get(f.parentKey)?.pageCompositionUnitKey!==g:!0:!1}),s=new Map,a=(f,g)=>{s.set(f,Math.min(2,(s.get(f)??0)+g))},c=f=>n.placements.some(g=>g.members.some(p=>p.sourceRange!==null&&_s(f.sourceRange,p.sourceRange)));for(let f of t.elements.values())f.sourceFile!==n.entryFile||!f.importedFrom||!/^[A-Z]/.test(f.tag)||!c(f)||a(`${f.importedFrom}#${f.exportName??f.tag}`,1);let l=[...t.elements.values()].flatMap(f=>f.sourceFile!==n.entryFile&&f.importedFrom&&/^[A-Z]/.test(f.tag)?[{owner:`${f.sourceFile}#${f.componentName}`,ownerDefault:`${f.sourceFile}#default`,target:`${f.importedFrom}#${f.exportName??f.tag}`}]:[]);for(let f=0;f<=l.length;f+=1){let g=!1;for(let p of l){let m=s.get(p.owner)??s.get(p.ownerDefault)??0;if(!m)continue;let y=s.get(p.target)??0,x=Math.min(2,y+m);x!==y&&(s.set(p.target,x),g=!0)}if(!g)break}let u=f=>s.get(`${f.sourceFile}#${f.componentName}`)??s.get(`${f.sourceFile}#default`)??0;for(let f of i){f.pageCompositionActionScope={kind:"unavailable"};let g=t.elements.get(f.key);f.pageCompositionUnitKey&&g?.sourceFile===n.entryFile&&(f.pageCompositionActionScope={kind:"route-unit"})}let d=new Map;for(let f of i){let g=t.elements.get(f.key);if(!g||g.sourceFile===n.entryFile||f.key!==($t(f.key)??f.key))continue;let p=r.get(g.sourceFile);if(!p)continue;let m=Ie(p.ast,{kind:"jsx-node",strategy:"source-range",sourceRange:g.sourceRange});if(!m.ok||!m.match.path.isJSXElement())continue;let y=m.match.path,x=y.parentPath;if(!x||!x.isJSXFragment()&&!(x.isJSXElement()&&Ye(x))){u(g)===1&&gI(y)&&(f.pageCompositionActionScope={kind:"route-unit"});continue}if(!gI(x))continue;let S=d.get(x.node)??[];S.push({entry:f,element:g,parentPath:x}),d.set(x.node,S)}for(let f of d.values()){let g=f[0];if(!g)continue;let p=g.entry.pageCompositionUnitKey,m=[],y=!!(p&&u(g.element)===1);for(let S of g.parentPath.node.children){if(eD(S))continue;if(!tD(S)){y=!1;break}let b=[...t.elements.values()].find(k=>k.sourceFile===g.element.sourceFile&&k.componentName===g.element.componentName&&_s(k.sourceRange,nD(S))),E=b?o.get(b.identity.key):null;if(!b||!E||E.parentKey||E.pageCompositionUnitKey!==p||u(b)!==1){y=!1;break}m.push(E)}if(!y||m.length!==f.length||f.some(({entry:S})=>!m.some(b=>b.key===S.key)))continue;if(m.length===1){m[0].pageCompositionActionScope={kind:"route-unit"};continue}if(m.length<2)continue;let x=m.map(S=>S.key);for(let S of m)S.pageCompositionActionScope={kind:"source-siblings",siblingKeys:x}}}function gI(e){let t=e.parentPath;return!!(t?.isReturnStatement?.()||t?.isArrowFunctionExpression?.()&&t.node.body===e.node)}function eD(e){return!!(e&&typeof e=="object"&&e.type==="JSXText"&&!(e.value??"").trim())}function tD(e){return!!(e&&typeof e=="object"&&e.type==="JSXElement")}function nD(e){return{startLine:e.loc?.start.line??-1,startColumn:e.loc?.start.column??-1,endLine:e.loc?.end.line??-1,endColumn:e.loc?.end.column??-1}}function _s(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function rD(e,t){return hI(e.startLine,e.startColumn,t.startLine,t.startColumn)<=0&&hI(e.endLine,e.endColumn,t.endLine,t.endColumn)>=0}function hI(e,t,n,r){return e!==n?e-n:t-r}function oD(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 f=t.elements.get(u);for(let g of f?.childKeys??[])a(g,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),f=t.elements.get(d.baseKey);return f?l(u,f):null},getChildNodes(u){let d=c(u),g=e.documentIndex?.entriesByKey.get(u)?.childKeys;if(g)return g.map(m=>{let y=$t(m)??m,x=t.elements.get(y);return x?l(m,x):null}).filter(m=>m!==null);let p=t.elements.get(d.baseKey);return p?p.childKeys.map(m=>{let y=t.elements.get(m);return y?l(m,y):null}).filter(m=>m!==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),f=n.get(d.baseKey);return f?{...f,key:u,constraints:f.constraints.map(g=>({...g})),...f.editModes?{editModes:{...f.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},getClassNameSource(u){let d=c(u),f=t.elements.get(d.baseKey),g=f?r.get(f.sourceFile):void 0;return!f||g===void 0?null:Iu({key:d.baseKey,route:{composition:e.composition,routeId:e.routeId,graph:t,source:g}})},getEditableTextSegmentIndex(u){let d=c(u),g=e.detailProjections?.get(d.baseKey)?.textTargets.keys()?.next();return g&&!g.done?g.value:null},async getTextWriteTarget(u,d){let f=c(u);return Rp(e.detailProjections?.get(f.baseKey)?.textTargets.get(d)??null,f.repeatIndex)},async getElementPropertyWriteTarget(u,d){let f=c(u);return Rp(e.detailProjections?.get(f.baseKey)?.elementPropertyTargets.get(d)??null,f.repeatIndex)},getPropertyState(u,d,f){let g=c(u),p=t.elements.get(g.baseKey);if(!p)return null;let y=e.detailProjections?.get(g.baseKey)?.propertyProvenances.get(d);if(y)return y;let x=p.attributes?.find(S=>S.name===d);return x?x.source?{status:"blocked",owner:"generic",diagnostic:{code:"unsupported-property-source",message:`Property '${d}' has an unresolved value source`}}:{status:"direct",owner:"generic",attribute:x,target:{kind:"jsx-attribute",file:p.sourceFile,sourceRange:x.sourceRange}}:(p.attributeSpreads?.length??0)>0?{status:"blocked",owner:"generic",diagnostic:{code:"ambiguous-property-source",message:`A spread may provide or override property '${d}'`}}:{status:"missing",owner:"generic"}},getRepeatPropertyTarget(u,d,f){let g=c(u),p=t.elements.get(g.baseKey);if(!p)return{ok:!1,errorCode:"repeat-not-found",reason:`Node not found: ${u}`};let m=f?{...f,key:g.baseKey}:g.repeatIndex!==null?{key:g.baseKey,instanceIndex:g.repeatIndex}:void 0;return rp({file:p.sourceFile,source:r.get(p.sourceFile)??"",element:p,propertyName:d,selectionRef:m,graph:t,sources:r})},getTextProvenance(u,d){let f=c(u);return e.detailProjections?.get(f.baseKey)?.provenances.get(d)??null}};function c(u){let d=PM(u);return d?{baseKey:d.baseKey,repeatIndex:tI(e.document??null,u,d.baseKey,e.documentIndex)??eI(d)}:{baseKey:u,repeatIndex:null}}function l(u,d){let f=$t(u)??u,g=e.documentIndex?.entriesByKey.get(u);return{key:u,file:d.sourceFile,component:d.componentName,tag:d.tag,structuralPath:d.identity.structuralPath,sourceRange:d.sourceRange,parentKey:g?.parentKey??d.parentKey??void 0,isRepeatRegion:d.boundaryKind==="repeat-region"||s.has(f),isBoundary:!1,importedFrom:d.importedFrom,exportName:d.exportName,isRepeatItemRoot:i.has(f),repeatOwnerKey:i.get(f)??s.get(f),attributes:d.attributes?.map(p=>({name:p.name,value:p.value,source:p.source?{expression:p.source.expression,base:p.source.base,path:p.source.path.map(m=>({...m}))}:null,resolvedValue:p.resolvedValue}))}}}var iD={"stale-version":U.VERSION_STALE,"capability-denied":U.CAPABILITY_REJECTED,"invalid-params":U.INVALID_PARAMS,"locator-miss":U.LOCATOR_FAILED,"route-not-found":U.ROUTE_NOT_FOUND,"unsupported-operation":U.UNSUPPORTED_OPERATION,"invalid-target":U.INVALID_TARGET,"ast-error":U.AST_PARSE_ERROR,"writeback-failed":U.WRITE_IO_ERROR,"rollback-failed":U.RECOVERY_REQUIRED,unknown:U.INTERNAL_ERROR};function ks(e){return iD[e]}function Ot(e){return e instanceof Error&&e.message?e.message:String(e)}function yI(e){return/\.(?:[cm]?[jt]sx?|css|scss|sass|mdx|json)$/i.test(e)}function sD(e){let t=xo(e);if(!wM.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=>OM.map(a=>`${s}/${a}`))}function aD(e){let n=xo(e).startsWith("src/app/")?"src/app":"app";return[`${n}/globals.css`,`${n}/global.css`]}function cD(e){return EI(e,/\bimport\s+(?:[^'";]+?\s+from\s+)?["']([^"']+\.css(?:\?[^"']*)?)["']/g)}function lD(e){return EI(e,/@import\s+(?:url\(\s*)?["']([^"']+)["']/g)}function EI(e,t){let n=[];for(let r of e.matchAll(t)){let o=SI(r[1]??"");o&&n.push(o)}return n}function xI(e,t){let n=SI(t);return!n||n.startsWith("tailwindcss")||n.startsWith("http:")||n.startsWith("https:")?null:n.startsWith("@/")?xo(`src/${n.slice(2)}`):n.startsWith("./")||n.startsWith("../")?xo(`${uD(e)}/${n}`):n.startsWith("/")?xo(n.slice(1)):Ap(n)?xo(n):null}function SI(e){return e.split(/[?#]/,1)[0]?.trim()??""}function Ap(e){return/\.css$/i.test(e)}function uD(e){let t=xo(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function dD(e){return Array.from(new Set(e))}function xo(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 fD(e,t){let n=t.elements.get(e);if(!n)return!1;for(let r of t.regions){if(r.kind!=="repeat-region")continue;let o=n;for(;o;){if(r.childKeys.includes(o.identity.key))return!0;o=o.parentKey?t.elements.get(o.parentKey):void 0}}return!1}var cl=class{constructor(t){this.options=t,this.fileSystem=new gi(t.files),this.engine=this.createEngine(this.fileSystem)}get status(){return this.engine.status}initializeComposition(t){return this.engine.initializeComposition(t)}getDocument(t){return Xs(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,r){return zs(r?this.engine.getObjectEditContext(t,n,r):this.engine.getObjectEditContext(t,n))}getClassNameSource(t,n){return this.engine.getClassNameSource(t,n)}getSourceTree(t){return Gs(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}getSourceFile(t){return Ys(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}resolveSourceLocation(t){return Zs(t,this.engine.getRenderDetail(t.key,t.composition))}async planOperation(t){let n=mD.safeParse(t);if(!n.success)return{result:Js(t,n.error.issues.map(i=>i.message))};let r=new gi(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:Gr(i)},a=r.getChangedFiles();if(a.length===0)return{result:s};let c=gD.parse({siteId:t.siteId,baseSnapshotId:t.baseSnapshotId,operationId:t.id,reason:`site-edit:${t.kind}`,patches:a.map(l=>hD(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 al({projectRoot:"/snapshot",fileSystem:t,compositions:this.options.compositions,onEvent:r&&this.options.onEvent?o=>{let i=Hs(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}:{},resourceTranslationLocale:this.options.resourceTranslationLocale})}};function hD(e,t){return e.after===void 0?{path:e.path,operation:"delete",...t||e.before===void 0?{}:{expectedHash:ke(e.before)}}:{path:e.path,operation:e.before===void 0?"create":"update",...t||e.before===void 0?{}:{expectedHash:ke(e.before)},fullContent:e.after}}function yD(e){return new cl(e)}import{SiteEditOperationRequestSchema as ED}from"@vcp-dev/contracts";import kn from"node:fs/promises";import Ft from"node:path";import{SITE_EDIT_SOURCE_ALLOWED_DIRS as xD,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as bD}from"@vcp-dev/contracts";var ll=class{constructor(t){this.options=t,this.fileSystem=this.createFileSystem(),this.engine=al({...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,r){return r?this.engine.getObjectEditContext(t,n,r):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 Gs(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.engine.getCompositionEntryFiles()})}getSourceFile(t){return Ys(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.engine.getCompositionEntryFiles()})}resolveSourceLocation(t){return Zs(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 kn.readFile(Ft.join(n,r),"utf8")},async readFileBytes(r){return kn.readFile(Ft.join(n,r))},async getFileInfo(r){let o=Ft.join(n,...r.split("/"));try{let i=await kn.lstat(o);return!i.isFile()||i.isSymbolicLink()?null:{path:r,sizeBytes:i.size}}catch{return null}},async writeFile(r,o){await ha(Ft.join(n,r),o)},async createExclusive(r,o){let i=Ft.join(n,r);await kn.mkdir(Ft.dirname(i),{recursive:!0});let s=await kn.open(i,"wx");try{await s.writeFile(o,"utf8")}catch(a){throw await s.close(),await kn.rm(i,{force:!0}),a}await s.close()},async deleteFile(r){await kn.rm(Ft.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=Ft.join(n,i),a=Ft.dirname(Ft.join(n,o));for(;a!==s&&a.startsWith(`${s}${Ft.sep}`);){try{await kn.rmdir(a)}catch(c){if(c instanceof Error&&"code"in c&&c.code==="ENOENT"){a=Ft.dirname(a);continue}break}a=Ft.dirname(a)}},async exists(r){try{return await kn.access(Ft.join(n,r)),!0}catch{return!1}},async listFiles(r={}){let o=r.roots??[...bD,...xD],i=[],s=new Set,a=new Set,c=0;for(let d of o)await u(d,i,1);let l=i.sort((d,f)=>d.path.localeCompare(f.path));return a.size>0?{files:l,truncated:{reasons:[...a]}}:{files:l};async function u(d,f,g){if(r.maxDepth!==void 0&&g>r.maxDepth){a.add("max-depth");return}let p=Ft.join(n,...d.split("/")),m;try{m=await kn.lstat(p)}catch{return}if(m.isSymbolicLink())return;if(m.isFile()){let x=m.ino>0?`${String(m.dev)}:${String(m.ino)}`:null;if(x&&s.has(x))return;if(r.maxFiles!==void 0&&f.length>=r.maxFiles){a.add("max-files");return}if(r.maxTotalBytes!==void 0&&c+m.size>r.maxTotalBytes){a.add("max-total-bytes");return}x&&s.add(x),f.push({path:d,sizeBytes:m.size}),c+=m.size;return}if(!m.isDirectory())return;if(r.maxFiles!==void 0&&f.length>=r.maxFiles){a.add("max-files");return}let y=await kn.readdir(p,{withFileTypes:!0});for(let x of y)x.isSymbolicLink()||await u(`${d}/${x.name}`,f,g+1)}},getVersion(r){return t.get(r)??1},bumpVersion(r){let o=(t.get(r)??1)+1;return t.set(r,o),o}}}};function Tp(e){return new ll(e)}var ul=class{constructor(t){this.options=t,this.listeners=new Set,this.engine=Tp({projectRoot:t.projectRoot,fileSystem:t.fileSystem,compositions:t.compositions,onEvent:n=>{let r=Hs(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:Xs(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,r){return{ok:!0,composition:this.engine.getCompositionContext(n),data:zs(r?this.engine.getObjectEditContext(t,n,r):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=ED.safeParse(r);if(!o.success)return Js(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,...s.details?{details:s.details}:{}},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:Gr(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:Gr(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:Gr(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 SD(e){return new ul(e)}import{GeneratedSiteCapabilitiesSchema as RD}from"@vcp-dev/contracts";import{GeneratedSiteCapabilitiesSchema as ID}from"@vcp-dev/contracts";function dl(e){let t=kD(e.host_capabilities),n=e.platform_managed_paths??[],r=new Set(e.platform_managed_packages??[]);return e.node.kind==="external"?r.has(e.node.path)?er(e.node,"platform-managed","controlled platform package"):t?_D(e.node.path,t)?er(e.node,"host-public","declared Starter runtime dependency"):er(e.node,"unsupported-external-private","external package is not declared by the trusted Starter contract"):er(e.node,"unknown","trusted host capability contract is invalid"):II(e.node.path,n)?er(e.node,"platform-managed","controlled platform path"):t?kI(e.node.path,t.generated_sections_path)?er(e.node,"private","site-generated section path"):II(e.node.path,t.public_paths)?er(e.node,"host-public","declared Starter public path"):er(e.node,"private","site-local file outside host public paths"):er(e.node,"unknown","trusted host capability contract is invalid")}function vD(e){return e.nodes.map(t=>dl({...e,node:t})).sort((t,n)=>t.path===n.path?t.ownership.localeCompare(n.ownership):t.path.localeCompare(n.path))}function er(e,t,n){return{path:e.path,kind:e.kind,ownership:t,reason:n}}function kD(e){let t=ID.safeParse(e);return t.success?t.data:null}function _D(e,t){return t.runtime_dependencies.some(({name:n})=>e===n||e.startsWith(`${n}/`))}function II(e,t){return t.some(n=>kI(e,n))}function kI(e,t){let n=CD(t),r=_I(e);return n.endsWith("/*")?r.startsWith(n.slice(0,-1)):vI(r)===vI(n)}function CD(e){return _I(e.split("#",1)[0]??e)}function _I(e){return e.replace(/^@\//u,"").replace(/\\/g,"/").replace(/^\.\//u,"")}function vI(e){return e.replace(/\.(?:jsx?|tsx?|json)$/iu,"")}function fl(e){let t=RD.safeParse(e.host_capabilities).success,n=[];t||n.push({code:"HOST_CAPABILITIES_INVALID",path:"<host-capabilities>",message:"Portable dependency audit requires the schema-validated Starter host contract."}),e.closure.complete||n.push({code:"INCOMPLETE_SOURCE_NODE",path:"<closure>",message:"Portable source closure is not complete."});for(let i of e.closure.errors)n.push({...i});let r=e.closure.nodes.map(i=>{let s=dl({node:i,host_capabilities:e.host_capabilities,platform_managed_paths:e.platform_managed_paths,platform_managed_packages:e.platform_managed_packages});return s.ownership==="unknown"?n.push({code:"UNKNOWN_DEPENDENCY_OWNERSHIP",path:i.path,message:`Portable dependency ownership is not proven for ${i.path}.`}):s.ownership==="unsupported-external-private"&&n.push({code:"UNSUPPORTED_EXTERNAL_DEPENDENCY",path:i.path,message:`Portable source closure depends on unsupported external package ${i.path}.`}),i.status!=="complete"&&n.push({code:"INCOMPLETE_SOURCE_NODE",path:i.path,message:`Portable source node ${i.path} is ${i.status}.`}),{...i,ownership:s.ownership,ownership_reason:s.reason}}),o=ND(n).sort(PD);return{complete:o.length===0,nodes:r.sort(AD),edges:[...e.closure.edges].sort(TD),errors:o}}function ND(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function PD(e,t){return Zt(e.path,t.path)||Zt(e.code,t.code)||Zt(e.specifier??"",t.specifier??"")||Zt(e.message,t.message)}function AD(e,t){return Zt(e.path,t.path)||Zt(e.kind,t.kind)||Zt(e.ownership,t.ownership)||Zt(e.status,t.status)}function TD(e,t){return Zt(e.from,t.from)||Zt(e.target??"",t.target??"")||Zt(e.specifier??"",t.specifier??"")||Zt(e.kind,t.kind)||Zt(e.resolution,t.resolution)}function Zt(e,t){return e<t?-1:e>t?1:0}import{createHash as vm}from"node:crypto";import{BlockRenderRefSchema as $j,GeneratedSiteCapabilitiesSchema as Vj,PORTABLE_BLOCK_LOCAL_ASSET_CHUNK_BYTES as Av,PORTABLE_BLOCK_LOCAL_ASSET_MAX_BYTES as Uj,SiteEditPageBlockTargetSchema as Kj}from"@vcp-dev/contracts";import{SiteEditPageBlockTargetSchema as wD,SiteIdSchema as OD,SnapshotIdSchema as FD}from"@vcp-dev/contracts";async function Op(e){if(!OD.safeParse(e.site_id).success||!FD.safeParse(e.base_snapshot_id).success||!wD.safeParse(e.target).success)return Vn("INVALID_PARAMS","Invalid site, snapshot, or page block identity.");if(!MD(e.composition,e.target.composition))return Vn("INVALID_TARGET","The target selector does not match the requested composition.");let t=new Map,n=new Map;for(let[u,d]of e.files){if(!wp(u))return Vn("INVALID_PARAMS","Snapshot contains an unsafe source path.");let f=typeof d=="string"?d:LD(u,d);f!==null&&(n.set(u,f),/\.(?:[cm]?[jt]sx?)$/i.test(u)&&t.set(u,f))}let r;try{r=ac({files:n})}catch{return Vn("INVALID_TARGET","Snapshot composition inventory is invalid.")}let o=r.find(u=>u.context.routeId===e.composition.routeId&&u.context.effectiveTemplateId===e.composition.templateId);if(!o)return Vn("INVALID_TARGET","The requested route/template is absent from this snapshot.");let i=t.get(o.entryFile);if(i===void 0)return Vn("INVALID_TARGET","The selected composition entry is unavailable.");let s=await Ca(o.entryFile,i,async u=>{if(!wp(u)||!/\.(?:[cm]?[jt]sx?)$/i.test(u))throw new Error("Unsafe imported source path");let d=t.get(u);if(d===void 0)throw new Error("Source file unavailable");return d},async u=>wp(u)&&t.has(u),{version:e.document_version});if(s.diagnostics.length>0||!s.entryModule)return Vn("INVALID_TARGET","The selected snapshot source graph is incomplete.");s.graph.routeId=e.composition.routeId,s.graph.composition={routeId:e.composition.routeId,...e.composition.templateId!==void 0?{effectiveTemplateId:e.composition.templateId}:{}};let a=yn({route:e.composition.routeId,composition:s.graph.composition,entryFile:o.entryFile,version:e.document_version,source:i,ast:s.entryModule.ast});if(!a.ok)return Vn("INVALID_TARGET","The selected snapshot page composition is unsupported.");let c=ec({composition:s.graph.composition,entryFile:o.entryFile,graph:s.graph,parsedModules:s.parsedModules,projection:a.projection});if(c.diagnostics.length>0)return Vn("INVALID_TARGET","The selected snapshot has unproven page block roots.");let l=Hi({composition:s.graph.composition,entryFile:o.entryFile,graph:s.graph,parsedModules:s.parsedModules,projection:a.projection,documentVersion:e.document_version,roots:c.roots});return l.diagnostics.length>0?{...Vn("INVALID_TARGET","The selected snapshot block index is incomplete."),index:l}:{...jo(l,e.target,e.document_version,e.selection_ref),index:l}}function LD(e,t){if(!/\.(?:[cm]?[jt]sx?)$/i.test(e))return null;try{return new TextDecoder("utf-8",{fatal:!0}).decode(t)}catch{return null}}function wp(e){return e.length>0&&!e.startsWith("/")&&!e.includes("\\")&&!e.includes("\0")&&e.split("/").every(t=>t.length>0&&t!=="."&&t!=="..")}function MD(e,t){return e.routeId===t.routeId&&e.templateId===t.templateId}function Vn(e,t){return{ok:!1,code:e,message:t}}import{createHash as YD}from"node:crypto";import Cs from"node:path";import Dp from"@babel/generator";import{parse as ZD}from"@babel/parser";import qD from"@babel/traverse";import*as O from"@babel/types";import{SiteEditSourcePathSchema as QD}from"@vcp-dev/contracts";import*as Lt from"@babel/types";var CI=[".tsx",".ts",".jsx",".js"],DD=new Set(["json","css","scss","sass","less","svg","png","jpg","jpeg","gif","webp","avif","ico","bmp","woff","woff2","ttf","otf","eot","mp4","webm","mp3","wav","ogg","pdf","txt","md","csv","xml","yaml","yml"]);function Lr(e){let t=$D(e.files),n=NI(e.max_depth??32,"max_depth"),r=NI(e.max_nodes??512,"max_nodes"),o=[...new Set(e.entry_files.map(TI).filter(Boolean))],i=new Map,s=[],a=[],c=new Set,l=new Set,u=new Set,d=[];o.length===0&&a.push({code:"SOURCE_ENTRY_UNRESOLVED",path:"<entry>",message:"Portable source closure requires at least one entry file."});for(let m of o)if(!(!m||l.has(m))){if(!oi(m,c,r)){a.push({code:"SOURCE_NODE_BUDGET_EXHAUSTED",path:m,message:"Portable source closure node budget was exhausted."});continue}l.add(m),d.push({path:m,depth:0})}for(;d.length>0;){let m=d.shift();if(u.has(m.path))continue;u.add(m.path);let y=t.get(m.path);if(y===void 0){let I=o.includes(m.path)?"SOURCE_ENTRY_UNRESOLVED":ii(m.path)?"SOURCE_ASSET_UNRESOLVED":"SOURCE_FILE_UNRESOLVED";Fr(i,{path:m.path,kind:ii(m.path)?"asset":"source",depth:m.depth,status:"unresolved"}),a.push({code:I,path:m.path,message:`Portable source closure could not read ${m.path}.`});continue}let x=ii(m.path)?"asset":"source";if(x==="asset"){let I=VD(m.path,y);Fr(i,{path:m.path,kind:x,depth:m.depth,status:I?"parse-failed":"complete"}),I&&a.push(I);continue}let S=Lp(y),b=je(m.path,S);if(!b.ok){Fr(i,{path:m.path,kind:x,depth:m.depth,status:"parse-failed"}),a.push({code:"SOURCE_PARSE_FAILED",path:m.path,message:b.diagnostic.message});continue}let E=jD(b.module.ast),k=!1;for(let I of E){let v=BD({from:m.path,depth:m.depth,reference:I,files:t,nodes:i,errors:a,maxDepth:n,maxNodes:r,visited:u,queued:l,discovered:c});s.push(v.edge),v.next&&(v.next.depth>n?k=!0:!u.has(v.next.path)&&!l.has(v.next.path)&&(l.add(v.next.path),d.push(v.next))),v.depthExhausted&&(k=!0)}Fr(i,{path:m.path,kind:x,depth:m.depth,status:k?"depth-exhausted":"complete"}),k&&a.push({code:"SOURCE_DEPTH_EXHAUSTED",path:m.path,message:`Portable source closure reached max_depth=${n} before closing all dependencies.`})}let f=[...i.values()].sort(HD),g=XD(s).sort(WD),p=zD(a).sort(GD);return{entry_files:o.sort(Un),nodes:f,edges:g,errors:p,complete:p.length===0,budget:{max_depth:n,max_nodes:r}}}function BD(e){let{reference:t}=e;if(t.specifier===null)return e.errors.push({code:"SOURCE_DYNAMIC_IMPORT_UNRESOLVED",path:e.from,message:"Portable source closure cannot resolve a non-literal dynamic import."}),{edge:{from:e.from,specifier:null,kind:t.kind,target:null,resolution:"non-literal"},depthExhausted:!1};if(!nt(t.specifier)){let o=KD(t.specifier);return oi(o,e.discovered,e.maxNodes)?(Fr(e.nodes,{path:o,kind:"external",depth:null,status:"complete"}),{edge:{from:e.from,specifier:t.specifier,kind:t.kind,target:o,resolution:"external"},depthExhausted:!1}):(e.errors.push({code:"SOURCE_NODE_BUDGET_EXHAUSTED",path:o,specifier:t.specifier,message:"Portable source closure node budget was exhausted."}),{edge:{from:e.from,specifier:t.specifier,kind:t.kind,target:o,resolution:"budget-exhausted"},depthExhausted:!1})}let n=Mp(e.from,t.specifier);if(wI(e.from,t.specifier,n))return e.errors.push({code:"SOURCE_UNSAFE_IMPORT",path:n,specifier:t.specifier,message:`Portable source closure rejected unsafe local import ${t.specifier} from ${e.from}.`}),oi(n,e.discovered,e.maxNodes)?Fr(e.nodes,{path:n,kind:ii(n)?"asset":"source",depth:e.depth+1,status:"unresolved"}):e.errors.push({code:"SOURCE_NODE_BUDGET_EXHAUSTED",path:n,specifier:t.specifier,message:"Portable source closure node budget was exhausted."}),{edge:{from:e.from,specifier:t.specifier,kind:t.kind,target:n,resolution:"unresolved"},depthExhausted:!1};let r=AI(e.from,t.specifier,e.files);if(!r){let o=ii(n);return e.errors.push({code:o?"SOURCE_ASSET_UNRESOLVED":"SOURCE_FILE_UNRESOLVED",path:n,specifier:t.specifier,message:`Portable source closure could not resolve ${t.specifier} from ${e.from}.`}),oi(n,e.discovered,e.maxNodes)?Fr(e.nodes,{path:n,kind:o?"asset":"source",depth:e.depth+1,status:"unresolved"}):e.errors.push({code:"SOURCE_NODE_BUDGET_EXHAUSTED",path:n,specifier:t.specifier,message:"Portable source closure node budget was exhausted."}),{edge:{from:e.from,specifier:t.specifier,kind:t.kind,target:n,resolution:"unresolved"},depthExhausted:!1}}if(e.depth>=e.maxDepth&&!e.visited.has(r)&&!e.queued.has(r)){let o=ii(r)?"asset":"source";return oi(r,e.discovered,e.maxNodes)?Fr(e.nodes,{path:r,kind:o,depth:e.depth+1,status:"depth-exhausted"}):e.errors.push({code:"SOURCE_NODE_BUDGET_EXHAUSTED",path:r,specifier:t.specifier,message:"Portable source closure node budget was exhausted."}),{edge:{from:e.from,specifier:t.specifier,kind:t.kind,target:r,resolution:"budget-exhausted"},depthExhausted:!0}}return oi(r,e.discovered,e.maxNodes)?{edge:{from:e.from,specifier:t.specifier,kind:t.kind,target:r,resolution:"resolved"},next:{path:r,depth:e.depth+1},depthExhausted:!1}:(e.errors.push({code:"SOURCE_NODE_BUDGET_EXHAUSTED",path:r,specifier:t.specifier,message:"Portable source closure node budget was exhausted."}),{edge:{from:e.from,specifier:t.specifier,kind:t.kind,target:r,resolution:"budget-exhausted"},depthExhausted:!1})}function jD(e){let t=[];for(let n of e.program.body)Lt.isImportDeclaration(n)?t.push({specifier:n.source.value,kind:n.importKind==="type"?"type":"import"}):Lt.isExportNamedDeclaration(n)&&n.source?t.push({specifier:n.source.value,kind:"export"}):Lt.isExportAllDeclaration(n)&&t.push({specifier:n.source.value,kind:"export"});return Fp(e.program,n=>{if(Lt.isCallExpression(n)&&Lt.isImport(n.callee)){let r=n.arguments[0];Lt.isStringLiteral(r)?t.push({specifier:r.value,kind:"dynamic"}):t.push({specifier:null,kind:"dynamic"})}Lt.isTSImportType(n)&&t.push({specifier:Lt.isStringLiteral(n.argument)?n.argument.value:null,kind:"type"})}),JD(t)}function Fp(e,t){t(e);for(let n of Object.values(e))if(Array.isArray(n))for(let r of n)PI(r)&&Fp(r,t);else PI(n)&&Fp(n,t)}function Mr(e,t,n){let r=Mp(e,t);return!nt(t)||wI(e,t,r)?null:AI(e,t,n)}function AI(e,t,n){let r=Mp(e,t);if(!r||r.startsWith("../")||r==="..")return null;if(n.has(r))return r;let o=r.replace(/[?#].*$/u,"");if(o!==r&&n.has(o))return o;if(UD(o))return null;for(let i of CI){let s=`${o}${i}`;if(n.has(s))return s}for(let i of CI){let s=`${o}/index${i}`;if(n.has(s))return s}return null}function Mp(e,t){let n=Cn(e,t);return TI(n)}function TI(e){let t=e.replace(/\\/g,"/"),n=[];for(let r of t.split("/"))if(!(!r||r===".")){if(r===".."){n.length>0&&n.at(-1)!==".."?n.pop():n.push("..");continue}n.push(r)}return n.join("/")}function $D(e){return e instanceof Map?e:new Map(Object.entries(e))}function Lp(e){return typeof e=="string"?e:Buffer.from(e).toString("utf8")}function VD(e,t){if(e.toLowerCase().endsWith(".css")&&/[@\\]|url\s*\(/iu.test(Lp(t)))return{code:"SOURCE_ASSET_INVALID",path:e,message:"Stylesheet dependencies or escaped/dynamic CSS are not statically closed."};if(e.replace(/[?#].*$/u,"").toLowerCase().endsWith(".json"))try{JSON.parse(Lp(t))}catch{return{code:"SOURCE_ASSET_INVALID",path:e,message:`Portable source closure found invalid JSON asset: ${e}.`}}return null}function Fr(e,t){let n=e.get(t.path);(!n||RI(t.status)>RI(n.status))&&e.set(t.path,t)}function oi(e,t,n){return t.has(e)?!0:t.size>=n?!1:(t.add(e),!0)}function RI(e){return e==="complete"?1:0}function ii(e){let n=e.replace(/[?#].*$/u,"").split(".").pop()?.toLowerCase();return n!==void 0&&DD.has(n)}function UD(e){return/\.[a-z0-9]+$/iu.test(e)}function KD(e){return e.startsWith("@")?e.split("/").slice(0,2).join("/"):e.split("/")[0]??e}function JD(e){let t=new Set;return e.filter(n=>{let r=`${n.kind}\0${n.specifier??"<dynamic>"}`;return t.has(r)?!1:(t.add(r),!0)})}function XD(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function zD(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function HD(e,t){return Un(e.path,t.path)||Un(e.kind,t.kind)}function WD(e,t){return Un(e.from,t.from)||Un(e.target??"",t.target??"")||Un(e.specifier??"",t.specifier??"")||Un(e.kind,t.kind)}function GD(e,t){return Un(e.path,t.path)||Un(e.code,t.code)||Un(e.specifier??"",t.specifier??"")}function Un(e,t){return e<t?-1:e>t?1:0}function NI(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`Portable source closure ${t} must be a positive safe integer.`);return e}function PI(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}function wI(e,t,n){if(t.includes("\0")||t.includes("\\")||n.startsWith("../")||n===".."||n.startsWith("/"))return!0;if(t.startsWith("@/")){let r=t.slice(2);return r.length===0||r.split("/").some(o=>o==="..")}return e.startsWith("/")}var Bp=qD,Kp=typeof Bp=="function"?Bp:Bp.default,eB=typeof Dp=="function"?Dp:Dp.default,OI=new Set(["Array","Boolean","Infinity","JSON","Math","NaN","Number","Object","String","undefined"]),BI=new Map([["JSON",new Set(["stringify"])],["Object",new Set(["keys","values","entries","getOwnPropertyNames"])],["Array",new Set(["isArray"])]]),jI=new Set(["Boolean","Number","String"]),tB=new Set(["assign","values","entries"]);function Jp(e){let{selection:t,files:n}=e,r=t.strategy==="extract-jsx"||t.strategy==="collection-container"?t.entry_file:t.source_file;if(!Up(r))return vt("SOURCE_INPUT_INVALID",r,"The selected Portable entry path is not safe.");if(!QD.safeParse(t.source_file).success)return vt("SOURCE_ENTRY_NOT_FOUND",t.source_file,"The selected root source is outside the allowed Snapshot source paths.");if(t.call_chain.length>1)return vt("SOURCE_NOT_PORTABLE",t.source_file,"Nested component invocation bindings are not yet a proven independent entry.");if(t.invocation&&!t.invocation.complete)return vt("SOURCE_NOT_PORTABLE",t.source_file,"The selected root has an incomplete invocation binding set.");if(t.strategy==="reuse-entry"){if(t.entry_file!==t.source_file)return vt("SOURCE_INPUT_INVALID",t.entry_file,"A reusable entry must point at the proven selected component source.");let i=hl(n,t.source_file);return i===null||!DI(t,i)?vt("SOURCE_ENTRY_NOT_FOUND",t.source_file,"The reusable selected source is missing or does not match its pinned hash."):pl({entryFile:r,entryContent:i,files:n,selection:t})}let o=hl(n,t.source_file);if(o===null||!DI(t,o))return vt("SOURCE_ENTRY_NOT_FOUND",t.source_file,"The selected source is missing or does not match its pinned hash.");if(t.strategy==="managed-thin-entry"){let i={generated_path:r,source_file:t.source_file,structural_path:t.structural_path};return pl({entryFile:r,entryContent:o,files:n,selection:t,sourceMapping:i})}if(t.strategy==="collection-container"){let i=t.collection_container_file;if(!i||!Up(i)||!n.has(i)||n.has(r)||!t.invocation?.complete)return vt("SOURCE_INPUT_INVALID",r,"The proven collection container or isolated entry is unavailable.");let s=yr({component:"PortableCollection",bindings:t.invocation.bindings,targetBlockId:"portable-captured-collection"});if(!s.ok)return vt("SOURCE_NOT_PORTABLE",r,"The collection invocation has unsupported bindings.");let a=s.plan.requiresRouteSearchParams?"{searchParams}: {searchParams?: Promise<Record<string, string | string[] | undefined>>}":"",c=`import PortableCollection from ${JSON.stringify(`@/${i.replace(/\.[cm]?[jt]sx?$/u,"")}`)};
15
15
  export default function PortableCollectionEntry(${a}) { return ${s.plan.jsx}; }
16
- `;return pl({entryFile:r,entryContent:c,files:n,selection:t,sourceMapping:{generated_path:t.source_file,source_file:t.source_file,structural_path:t.structural_path}})}return n.has(r)?vt("SOURCE_INPUT_INVALID",r,"The deterministic extracted entry path collides with the fixed Snapshot map."):nB(t,o,n)}function nB(e,t,n){let r;try{r=ZM(t,{sourceType:"module",sourceFilename:e.source_file,plugins:["jsx","typescript"]})}catch(A){return vt("SOURCE_PARSE_FAILED",e.source_file,A instanceof Error?A.message:String(A))}let o=rB(r,e);if(o.length!==1)return vt("SOURCE_NOT_PORTABLE",e.source_file,"The pinned source range must identify exactly one current JSX root.");let i=o[0],s=i.findParent(A=>A.isFunction());if(!s||!XI(s.node))return vt("SOURCE_NOT_PORTABLE",e.source_file,"The selected JSX root is not inside one statically bounded component function.");let a=s,c=SB(a);if(!c.ok)return vt("SOURCE_NOT_PORTABLE",e.source_file,"The containing component has hook calls whose order cannot be proven for an isolated root.");let l={imports:new Set,moduleDeclarations:new Set,functionDeclarations:new Set,props:new Map,propsObjectName:null,errors:[]},u=new Set;for(let A of r.program.body){if(!O.isImportDeclaration(A)||A.specifiers.length||A.importKind==="type")continue;let w=A.source.value,F=w.startsWith(".")||w.startsWith("@/")?yl(e.source_file,w,n):null;if(!F?.endsWith(".css"))return vt("SOURCE_NOT_PORTABLE",e.source_file,"A bare module effect is not a proven portable stylesheet dependency.");u.has(F)||l.imports.add(A),u.add(F)}let d=oB(a,e);if(!d.ok)return{complete:!1,errors:[d.error]};if(iB(i,i.node,a,d.value,e,c.translationBinding??null,l,n),l.errors.length>0)return{complete:!1,errors:l.errors};if(c.translationBinding&&![...l.functionDeclarations].some(A=>O.isVariableDeclaration(A)&&A.declarations.some(w=>O.isIdentifier(w.id,{name:c.translationBinding}))))return vt("SOURCE_NOT_PORTABLE",e.source_file,"The containing component's i18n hook is not part of the selected dependency closure.");let f=_B(r,"__vcpPortableProps"),g=O.cloneNode(i.node,!0),p=[];for(let A of[...l.imports].sort(jp)){let w=bB(A,e.source_file,e.entry_file,n);if(!w.ok)return{complete:!1,errors:[w.error]};p.push(w.node)}let m=[...l.moduleDeclarations].sort(jp).map(A=>O.cloneNode(A,!0)),y=[...l.functionDeclarations].sort(jp).map(A=>O.cloneNode(A,!0)),x=O.returnStatement(g),S=[...l.props].filter(([A])=>!A.startsWith("@")).map(([A,w])=>O.variableDeclaration("const",[O.variableDeclarator(O.identifier(A),O.memberExpression(O.identifier(f),O.identifier(w)))]));l.propsObjectName&&S.push(O.variableDeclaration("const",[O.variableDeclarator(O.identifier(l.propsObjectName),O.identifier(f))]));let b=O.blockStatement([...S,...y,x]),E=l.props.size?[xB(f)]:[],k=O.functionDeclaration(O.identifier("PortableBlockEntry"),E,b),I=O.program([...p,...m,k,O.exportDefaultDeclaration(O.identifier("PortableBlockEntry"))]);I.directives=r.program.directives.map(A=>O.cloneNode(A,!0));let v=eB(O.file(I),{jsescOption:{minimal:!0}}).code,N={generated_path:e.entry_file,source_file:e.source_file,structural_path:e.structural_path};return pl({entryFile:e.entry_file,entryContent:v,files:n,selection:e,sourceMapping:N,invocationBindings:kB(e,l.props)})}function rB(e,t){let n=[];return Kp(e,{JSXElement(r){r.node.start===t.source_range.start_offset&&r.node.end===t.source_range.end_offset&&n.push(r)}}),n}function oB(e,t){let n=e.node.params;if(n.length>1)return{ok:!1,error:at("SOURCE_NOT_PORTABLE",t.source_file,"Multiple component parameters are not a proven portable invocation surface.")};let r=new Map,o=n[0];if(!o)return{ok:!0,value:{bindingByLocalName:r,propsParameter:null}};if(O.isIdentifier(o))return{ok:!0,value:{bindingByLocalName:r,propsParameter:o}};if(!O.isObjectPattern(o))return{ok:!1,error:at("SOURCE_NOT_PORTABLE",t.source_file,"Component props must use one identifier or a static object pattern.")};for(let i of o.properties){if(!O.isObjectProperty(i)||i.computed||!(O.isIdentifier(i.key)||O.isStringLiteral(i.key))||!(O.isIdentifier(i.value)||O.isAssignmentPattern(i.value)&&O.isIdentifier(i.value.left)))return{ok:!1,error:at("SOURCE_NOT_PORTABLE",t.source_file,"Rest, computed, or nested component prop destructuring is not supported.")};let s=O.isIdentifier(i.key)?i.key.name:i.key.value,a=i.value,c=O.isIdentifier(a)?a.name:O.isAssignmentPattern(a)&&O.isIdentifier(a.left)?a.left.name:"";r.set(c,s)}return{ok:!0,value:{bindingByLocalName:r,propsParameter:null}}}function iB(e,t,n,r,o,i,s,a){let c=new Set,l=new Map,u=p=>{let m=l.get(p);if(m!==void 0)return m;let y=aB(n,r,p,o,a);return l.set(p,y),y||s.errors.push(at("SOURCE_NOT_PORTABLE",o.source_file,`Selected prop ${p} is mutated or escapes its proven invocation value.`)),y},d=p=>{let m=p.node.name,y=p.scope.getBinding(m);if(!y){TI.has(m)||s.errors.push(at("SOURCE_NOT_PORTABLE",o.source_file,`The selected root references unbound identifier ${m}.`));return}if(!gl(y.path.node,t)){if(r.bindingByLocalName.has(m)&&y.scope===n.scope){let x=r.bindingByLocalName.get(m);OI(o,x)?u(x)&&s.props.set(m,x):s.errors.push(at("SOURCE_NOT_PORTABLE",o.source_file,`The selected root prop ${x} has no proven invocation binding.`));return}if(r.propsParameter&&y.path.node===r.propsParameter&&p.parentPath?.isMemberExpression()&&p.parentPath.node.object===p.node){let x=p.parentPath.node,S=!x.computed&&O.isIdentifier(x.property)?x.property.name:x.computed&&O.isStringLiteral(x.property)?x.property.value:null;S&&OI(o,S)?u(S)&&(s.propsObjectName=m,s.props.set(`@${m}.${S}`,S)):s.errors.push(at("SOURCE_NOT_PORTABLE",o.source_file,`The selected root reads an unproven dynamic prop through ${m}.`));return}c.has(y)||(c.add(y),wI(y,n,o,s,d,f,a))}},f=(p,m)=>{let y=JI(p);if(!y||/^[a-z]/u.test(y.name))return;let x=m.scope.getBinding(y.name);if(!x){TI.has(y.name)||s.errors.push(at("SOURCE_NOT_PORTABLE",o.source_file,`The selected root component ${y.name} has no proven import or declaration.`));return}c.has(x)||gl(x.path.node,t)||(c.add(x),wI(x,n,o,s,d,f,a))};(p=>{p.isIdentifier()&&p.isReferencedIdentifier()&&d(p),p.isJSXElement()&&f(p.node.openingElement.name,p),p.traverse({ReferencedIdentifier(m){d(m)},JSXOpeningElement(m){f(m.node.name,m)},CallExpression(m){KI(m,i)||s.errors.push(at("SOURCE_NOT_PORTABLE",o.source_file,"A selected-root call is not a proven pure helper or statically bound translation."))},AssignmentExpression(m){s.errors.push(at("SOURCE_NOT_PORTABLE",o.source_file,"Assignments inside a selected root are not a closed Portable dependency.")),m.stop()},UpdateExpression(m){s.errors.push(at("SOURCE_NOT_PORTABLE",o.source_file,"Updates inside a selected root are not a closed Portable dependency.")),m.stop()},NewExpression(m){s.errors.push(at("SOURCE_NOT_PORTABLE",o.source_file,"Dynamic object construction inside a selected root is not proven portable.")),m.stop()}})})(e)}function wI(e,t,n,r,o,i,s){let a=e.path;if(vB(a,t)||a.isFunctionDeclaration()&&a.node===t.node){r.errors.push(at("SOURCE_NOT_PORTABLE",n.source_file,`The selected root captures unsupported component-local binding ${e.identifier.name}.`));return}if(e.constantViolations.length>0){r.errors.push(at("SOURCE_NOT_PORTABLE",n.source_file,`Captured binding ${e.identifier.name} is rebound outside its declaration.`));return}if(dB(e)){r.errors.push(at("SOURCE_NOT_PORTABLE",n.source_file,`Captured binding ${e.identifier.name} has a member write outside its declaration.`));return}let c=new ml(s),l=new Map,u=a.parentPath,d=u?.isImportDeclaration(),f=!1;if(d&&(u.node.source.value.startsWith(".")||u.node.source.value.startsWith("@/"))){let y=yl(n.source_file,u.node.source.value,s),x=y?c.get(y):void 0,S=a.isImportDefaultSpecifier()?"default":a.isImportSpecifier()&&a.node.importKind!=="type"?Jt(a.node.imported,!1):null,b=x&&S&&u.node.importKind!=="type"?br(x,S,c):null,E=b?Kt(b):null;if(!E?.length){r.errors.push(at("SOURCE_NOT_PORTABLE",n.source_file,"The imported value has no bounded unique Snapshot source."));return}l.set(e.identifier,E),f=E.every(k=>k.isFunctionDeclaration()||k.isFunctionExpression()||k.isArrowFunctionExpression())}else d&&(f=e.referencePaths.every(y=>y.parentPath?.isJSXOpeningElement()||y.parentPath?.isJSXClosingElement()||y.parentPath?.isCallExpression()&&y.parentPath.node.callee===y.node));if((d&&!f||sB(e))&&!Ns(e,{bindings:new Set,activeBindings:new Set,jsxCalls:new Set,inputs:l,files:s,modules:c},!1)){r.errors.push(at("SOURCE_NOT_PORTABLE",n.source_file,`Captured binding ${e.identifier.name} is mutated or escapes its static object shape.`));return}let g=a.isImportDeclaration()?a:a.findParent(y=>y.isImportDeclaration());if(g?.isImportDeclaration()){r.imports.add(g.node);return}let p=a.isVariableDeclarator()?a:a.findParent(y=>y.isVariableDeclarator());if(p?.isVariableDeclarator()){let y=p.parentPath,x=p.get("init");if(!y?.isVariableDeclaration()||y.node.kind!=="const"||!x.node||!ro(p.node.id)||!ro(x.node)&&!IB(x)){r.errors.push(at("SOURCE_NOT_PORTABLE",n.source_file,`Captured binding ${e.identifier.name} is not a side-effect-free const.`));return}let b=y.findParent(k=>k.isFunction())===t?r.functionDeclarations:r.moduleDeclarations,E=O.variableDeclaration("const",[O.cloneNode(p.node,!0)]);FI(b,E,p.node),p.traverse({ReferencedIdentifier(k){k.isIdentifier()&&o(k)},JSXOpeningElement(k){i(k.node.name,k)}});return}let m=a.isFunctionDeclaration()?a:a.findParent(y=>y.isFunction());if(m?.isFunctionDeclaration()&&Ga(m.node)){let x=m.findParent(S=>S.isFunction())===t?r.functionDeclarations:r.moduleDeclarations;FI(x,O.cloneNode(m.node,!0),m.node),m.traverse({ReferencedIdentifier(S){S.isIdentifier()&&o(S)},JSXOpeningElement(S){i(S.node.name,S)}});return}r.errors.push(at("SOURCE_NOT_PORTABLE",n.source_file,`Captured binding ${e.identifier.name} is not a statically portable declaration.`))}function sB(e){let t=e.path;if(!t.isVariableDeclarator())return!1;let n=t.get("init");if(!n.node)return!0;let r=yB(n.node);return O.isFunctionExpression(r)||O.isArrowFunctionExpression(r)||O.isCallExpression(r)&&Ya(r)?!1:!Ud(e)?.every(i=>i.isFunctionExpression()||i.isArrowFunctionExpression()||Kd(i,new Map))}var ml=class extends Map{constructor(t){super(),this.files=t,this.attempted=new Set}has(t){return this.files.has(t)}get(t){let n=super.get(t);if(n||this.attempted.has(t)||this.attempted.size>=64)return n;this.attempted.add(t);let r=hl(this.files,t);if(r===null)return;let o=je(t,r);if(o.ok)return super.set(t,o.module),o.module}};function aB(e,t,n,r,o){let i=r.invocation?.bindings.find(l=>l.propName===n);if(!i)return!1;let s=[];if(i.value.kind==="json-literal"){let l=O.file(O.program([O.expressionStatement(O.valueToNode(i.value.value))]));Kp(l,{ExpressionStatement(u){s.push(u.get("expression")),u.stop()}})}let a=new Map,c={bindings:new Set,activeBindings:new Set,jsxCalls:new Set,inputs:a,files:o,modules:new ml(o)};if(t.propsParameter)return $p(e,n,s,c);for(let[l,u]of t.bindingByLocalName){if(u!==n)continue;let d=e.scope.getBinding(l);if(!d||(a.set(d.identifier,s),!Ns(d,c,!0)))return!1}return!0}function cB(e,t){if(Kd(e,t.inputs))return!0;let n=e.parentPath;if(!n)return!1;let r=n.isJSXExpressionContainer()?n.parentPath:n;if(!r)return!1;let o=r.isJSXAttribute()||r.isJSXSpreadAttribute()?r.parentPath:r.isJSXElement()?r.get("openingElement"):null;if(r.isJSXFragment())return!0;if(!o?.isJSXOpeningElement())return!1;let i=o.node.name;if(O.isJSXIdentifier(i)&&/^[a-z]/u.test(i.name))return!0;if(!O.isJSXIdentifier(i)||t.jsxCalls.has(o.node)||t.jsxCalls.size>=32)return!1;let s=lB(o,t);if(!s)return!1;let a={...t,bindings:new Set(t.bindings),jsxCalls:new Set(t.jsxCalls).add(o.node)},c=Kt(e,t.inputs);if(!c)return!1;if(r.isJSXSpreadAttribute()){let u=new Set;for(let d of c){if(!d.isObjectExpression())return!1;for(let f of d.node.properties){if(!O.isObjectProperty(f)||f.computed)return!1;let g=Jt(f.key,!1);if(g===null)return!1;u.add(g)}}return[...u].every(d=>{let f=Za(c,d,t.inputs);return f!==null&&$p(s,d,f,a)})}let l=r.isJSXAttribute()&&O.isJSXIdentifier(r.node.name)?r.node.name.name:"children";return $p(s,l,c,a)}function lB(e,t){let n=e.node.name;if(!O.isJSXIdentifier(n))return null;let r=e.scope.getBinding(n.name);if(!r||r.constantViolations.length)return null;if(r.path.isFunctionDeclaration())return r.path;if(r.path.isVariableDeclarator()){let d=r.path.get("init");return d.isFunctionExpression()||d.isArrowFunctionExpression()?d:null}let o=r.path.parentPath;if(!o?.isImportDeclaration())return null;let i=o.node.source.value,s=o.node.loc?.filename;if(!s||!(i.startsWith(".")||i.startsWith("@/")))return null;let a=yl(s,i,t.files);if(!a)return null;let c=t.modules.get(a);if(!c)return null;let l=r.path.isImportDefaultSpecifier()?"default":r.path.isImportSpecifier()?Jt(r.path.node.imported,!1):null;if(!l)return null;let u=hn({module:c,exportName:l,parsedModules:t.modules});return u.ok?u.roots[0]?.getFunctionParent()??null:null}function $p(e,t,n,r){let o=e.get("params")[0];if(!o)return!0;let i=new Map(r.inputs);if(o.isObjectPattern()){let a=!0;for(let c of o.get("properties")){if(!c.isObjectProperty()||c.node.computed){if(Object.keys(c.getBindingIdentifiers()).some(f=>c.scope.getBinding(f)?.referencePaths.length))return!1;continue}if(Jt(c.node.key,!1)!==t)continue;let l=c.get("value");if(!l.isIdentifier())return!1;let u=l.scope.getBinding(l.node.name);if(!u)return!1;i.set(u.identifier,n),a=Ns(u,{...r,inputs:i},!0)&&a}return a}if(!o.isIdentifier())return!1;let s=o.scope.getBinding(o.node.name);return!s||s.constantViolations.length?!1:s.referencePaths.every(a=>{let c=a.parentPath;if(!(c?.isMemberExpression()||c?.isOptionalMemberExpression())||c.node.object!==a.node)return!1;let l=Jt(c.node.property,c.node.computed);return l===null?!1:l!==t?!0:(i.set(c.node,n),$I(c,{...r,inputs:i},!0))})}function Ns(e,t,n){if(t.bindings.has(e))return!0;if(t.activeBindings.has(e)||t.bindings.size+t.activeBindings.size>=128||e.constantViolations.length>0)return!1;let r={...t,activeBindings:new Set(t.activeBindings).add(e)},o=e.referencePaths.every(i=>$I(i,r,n));return o&&t.bindings.add(e),o}function Xp(e,t,n){let r=e.node.id;if(O.isIdentifier(r)){let o=e.scope.getBinding(r.name);return o?Ns(o,t,n):!1}if(O.isObjectPattern(r)||O.isArrayPattern(r)){let o=[];return si(r,o)?uB(o,e,t):!1}return!1}function si(e,t){if(O.isRestElement(e))return si(e.argument,t);if(O.isIdentifier(e))return t.push(e.name),!0;if(O.isAssignmentPattern(e))return si(e.left,t);if(O.isObjectPattern(e)){for(let n of e.properties){if(O.isRestElement(n)){if(!si(n.argument,t))return!1;continue}if(!O.isObjectProperty(n)||n.computed||!(O.isIdentifier(n.key)||O.isStringLiteral(n.key)||O.isNumericLiteral(n.key))||!si(n.value,t))return!1}return!0}if(O.isArrayPattern(e)){for(let n of e.elements)if(n&&!si(n,t))return!1;return!0}return!1}function uB(e,t,n){return e.every(r=>{let o=t.scope.getBinding(r);return o?Ns(o,n,!0):!1})}function dB(e){return e.referencePaths.some(t=>{let{current:n,memberAccess:r}=jI(t);if(!r)return!1;let o=n.parentPath;return!!(BI(n)||o?.isUpdateExpression()||o?.isUnaryExpression({operator:"delete"}))})}function BI(e){let t=e.findParent(n=>n.isAssignmentExpression()||n.isForXStatement());return t&&(t.isAssignmentExpression()||t.isForXStatement())?gl(e.node,t.node.left):!1}function jI(e){let t=Vp(e),n=!1;for(;t.parentPath&&(t.parentPath.isMemberExpression()||t.parentPath.isOptionalMemberExpression())&&t.parentPath.node.object===t.node;)n=!0,t=Vp(t.parentPath);return{current:t,memberAccess:n}}function $I(e,t,n){if(!mB(e,t))return!1;let{current:r,memberAccess:o}=jI(e),i=r.parentPath;if(!i)return!1;if(i.isVariableDeclarator()&&i.node.init===r.node){let s=i.parentPath;return!s?.isVariableDeclaration()||s.node.kind!=="const"?!1:Xp(i,t,o||n)}return BI(r)||i.isUpdateExpression()||i.isUnaryExpression({operator:"delete"})?!1:i.isCallExpression()||i.isOptionalCallExpression()?i.node.callee===r.node?!1:fB(i,r,t):i.isNewExpression()?!1:i.isExportSpecifier()||i.isExportNamedDeclaration()||i.isExportDefaultDeclaration()||i.isTSTypeQuery()||n&&(i.isJSXOpeningElement()||i.isJSXClosingElement())?!0:i.isJSXExpressionContainer()||i.isJSXSpreadAttribute()?cB(r,t):i.isSpreadElement()||i.isArrayExpression()||i.isObjectExpression()||i.isObjectProperty()||i.isConditionalExpression()||i.isLogicalExpression()||i.isSequenceExpression()||i.isAwaitExpression()?pB(r,o,n,t):i.isJSXAttribute()||i.isJSXSpreadAttribute()||i.isObjectMethod()||i.isReturnStatement()||i.isArrowFunctionExpression()?o||n:i.isTemplateLiteral()&&i.parentPath?.isTaggedTemplateExpression()?!1:(o||n)&&(i.isBinaryExpression()||i.isUnaryExpression()||i.isTemplateLiteral())}function fB(e,t,n){if(!e.node.arguments.some(i=>i===t.node))return!1;let r=e.node.callee;if(O.isIdentifier(r)){if(MI.has(r.name))return e.scope.getBinding(r.name)===void 0;let i=e.scope.getBinding(r.name);return!i||!Mo(i)?!1:Rs(e,n,new Set)}if(!O.isMemberExpression(r)&&!O.isOptionalMemberExpression(r)||!O.isIdentifier(r.property))return!1;let o=zp(r);return!o||e.scope.getBinding(o.name)?!1:o.name==="Object"&&r.property.name==="assign"?e.node.arguments[0]===t.node?!1:Rs(e,n,new Set):DI.get(o.name)?.has(r.property.name)??!1?UI(e)?Rs(e,n,new Set):!0:!1}function pB(e,t,n,r){let o=VI(e);return o.kind==="declarator"?Xp(o.declarator,r,o.directValue):o.kind==="escape"||o.kind==="call"?!1:t||n}function VI(e){let t=Vp(e),n=!0,r=!1;for(;;){let o=t.parentPath;if(!o)return r?{kind:"escape"}:{kind:"read"};if(o.isTSAsExpression()||o.isTSTypeAssertion()||o.isTSNonNullExpression()||o.isTSSatisfiesExpression()||o.isParenthesizedExpression()){t=o;continue}if((o.isMemberExpression()||o.isOptionalMemberExpression())&&o.node.object===t.node){t=o;continue}if(o.isConditionalExpression()){if(o.node.test===t.node)return{kind:"read"};t=o;continue}if(o.isLogicalExpression()||o.isAwaitExpression()){t=o;continue}if(o.isSequenceExpression()){let i=o.node.expressions;if(i[i.length-1]!==t.node)return{kind:"read"};t=o;continue}if(o.isVariableDeclarator()&&o.node.init===t.node)return{kind:"declarator",declarator:o,directValue:n};if(o.isObjectProperty()&&o.node.value===t.node){r=!0,n=!1,t=o;continue}if(o.isObjectExpression()||o.isArrayExpression()){r=!0,n=!1,t=o;continue}if(o.isSpreadElement()){r=!0,n=!1,t=o;continue}return o.isCallExpression()||o.isOptionalCallExpression()?o.node.callee===t.node?{kind:"escape"}:{kind:"call",call:o}:o.isNewExpression()?{kind:"escape"}:o.isJSXExpressionContainer()||o.isJSXAttribute()||o.isJSXSpreadAttribute()||o.isReturnStatement()||o.isArrowFunctionExpression()?r?{kind:"escape"}:{kind:"read"}:r?{kind:"escape"}:{kind:"read"}}}function Rs(e,t,n){if(n.has(e.node))return!0;n.add(e.node);let r=VI(e);return r.kind==="declarator"?Xp(r.declarator,t,r.directValue):r.kind==="escape"?!1:r.kind==="call"?r.call.node.callee===e.node?!1:UI(r.call)?Rs(r.call,t,n):hB(r.call):!0}function mB(e,t){let n=e.findParent(o=>o.isFunction());if(!n||!XI(n.node))return!0;let r=gB(n);return!r||!Mo(r)?!0:r.referencePaths.every(o=>{let i=o.parentPath;return!i?.isCallExpression()||i.node.callee!==o.node?!0:Rs(i,t,new Set)})}function gB(e){let t=e.node,n=null;if(O.isFunctionDeclaration(t)?n=t.id?.name??null:(O.isArrowFunctionExpression(t)||O.isFunctionExpression(t))&&e.parentPath?.isVariableDeclarator()&&O.isIdentifier(e.parentPath.node.id)&&(n=e.parentPath.node.id.name),!n)return null;let r=[e.scope.getBinding(n),e.scope.parent?.getBinding(n),e.parentPath?.scope.getBinding(n)];for(let o of r)if(o&&(o.path.node===t||o.path.node===e.parentPath?.node))return o;return null}function UI(e){let t=e.node.callee;if(O.isIdentifier(t)){let r=e.scope.getBinding(t.name);return!!(r&&Mo(r))}if(!O.isMemberExpression(t)&&!O.isOptionalMemberExpression(t)||!O.isIdentifier(t.property))return!1;let n=zp(t);return!n||e.scope.getBinding(n.name)?!1:n.name==="Object"&&tB.has(t.property.name)}function hB(e){let t=e.node.callee;if(O.isIdentifier(t))return MI.has(t.name)&&e.scope.getBinding(t.name)===void 0;if(!O.isMemberExpression(t)&&!O.isOptionalMemberExpression(t)||!O.isIdentifier(t.property))return!1;let n=zp(t);return!n||e.scope.getBinding(n.name)||n.name==="Object"&&t.property.name==="assign"?!1:DI.get(n.name)?.has(t.property.name)??!1}function Vp(e){let t=e;for(;t.parentPath&&(t.parentPath.isTSAsExpression()||t.parentPath.isTSTypeAssertion()||t.parentPath.isTSNonNullExpression()||t.parentPath.isTSSatisfiesExpression()||t.parentPath.isParenthesizedExpression());)t=t.parentPath;return t}function yB(e){let t=e;for(;t&&(O.isTSAsExpression(t)||O.isTSTypeAssertion(t)||O.isTSNonNullExpression(t)||O.isTSSatisfiesExpression(t)||O.isParenthesizedExpression(t));)t=t.expression;return t&&O.isExpression(t)?t:null}function zp(e){return!e.computed&&O.isIdentifier(e.object)?e.object:null}function xB(e){let t=O.identifier(e);return t.typeAnnotation=O.tsTypeAnnotation(O.tsTypeReference(O.identifier("Record"),O.tsTypeParameterInstantiation([O.tsStringKeyword(),O.tsAnyKeyword()]))),t}function pl(e){let t=new Map(e.files);t.set(e.entryFile,e.entryContent);let n=Lr({entry_files:[e.entryFile],files:t});if(!n.complete)return{complete:!1,errors:n.errors.map(i=>at(CB(i.code),i.path,i.message))};let r=[];for(let i of n.nodes){if(i.kind!=="source"&&i.kind!=="asset")continue;let s=hl(t,i.path);if(s===null)return vt("SOURCE_NOT_PORTABLE",i.path,"A closed dependency is not valid UTF-8 source content.");r.push({path:i.path,content:s})}let o=e.sourceMapping??{generated_path:e.entryFile,source_file:e.selection.source_file,structural_path:e.selection.structural_path};return{complete:!0,entry_file:e.entryFile,source_files:r.sort((i,s)=>i.path.localeCompare(s.path)),source_mapping:[o],invocation_bindings:e.invocationBindings??e.selection.invocation?.bindings??[],selected_root_ref:e.selection.root_ref}}function bB(e,t,n,r){let o=O.cloneNode(e,!0),i=e.source.value;if(i.startsWith("./")||i.startsWith("../")){let s=yl(t,i,r);if(!s)return{ok:!1,error:at("SOURCE_IMPORT_UNRESOLVED",t,`The selected import ${i} cannot be resolved in the fixed Snapshot map.`)};o.source.value=EB(n,s)}return{ok:!0,node:o}}function yl(e,t,n){let r=t.startsWith("@/")?t.slice(2):Cs.posix.normalize(Cs.posix.join(Cs.posix.dirname(e),t));if(!Up(r))return null;let o=/\.[a-z0-9]+$/iu.test(r)?[r]:[".tsx",".ts",".jsx",".js",".json",".css",".svg"].map(s=>`${r}${s}`).concat([".tsx",".ts",".jsx",".js",".json",".css",".svg"].map(s=>`${r}/index${s}`)),i=[...new Set(o.filter(s=>n.has(s)))];return i.length===1?i[0]:null}function EB(e,t){let n=Cs.posix.relative(Cs.posix.dirname(e),t);return n.startsWith(".")?n:`./${n}`}function SB(e){let t=null,n=0,r=!1;return e.traverse({CallExpression(o){let i=o.node.callee;if(!O.isIdentifier(i)||!/^use[A-Z0-9]/u.test(i.name))return;if(i.name!=="useTranslations"||o.node.arguments.length!==1||!O.isStringLiteral(o.node.arguments[0])){r=!0,o.stop();return}let s=o.scope.getBinding(i.name),a=s?.path.findParent(l=>l.isImportDeclaration());if(!s?.path.isImportSpecifier()||!a?.isImportDeclaration()||a.node.source.value!=="next-intl"||!O.isIdentifier(s.path.node.imported,{name:"useTranslations"})){r=!0,o.stop();return}n+=1;let c=o.findParent(l=>l.isVariableDeclarator());if(!c?.isVariableDeclarator()||!O.isIdentifier(c.node.id)){r=!0,o.stop();return}t=c.node.id.name}}),r||n>1?{ok:!1}:t?{ok:!0,translationBinding:t}:{ok:!0}}function KI(e,t){let n=e.node.callee;if(O.isImport(n))return!1;if(t&&O.isIdentifier(n,{name:t})&&e.node.arguments.length>0&&e.node.arguments.every(o=>O.isStringLiteral(o))){let o=e.scope.getBinding(t);if(o&&o.constantViolations.length>0)return!1;let i=o?.path.isVariableDeclarator()?o.path:o?.path.findParent(a=>a.isVariableDeclarator()),s=i?.isVariableDeclarator()?i.node.init:null;return!!(O.isCallExpression(s)&&Ya(s))}if(!O.isIdentifier(n))return!1;let r=e.scope.getBinding(n.name);return r?Mo(r):!1}function IB(e){return e.isCallExpression()&&KI(e,null)&&O.isIdentifier(e.node.callee)&&e.scope.getBinding(e.node.callee.name)?.constantViolations.length===0&&e.node.arguments.every(t=>O.isExpression(t)&&ro(t))}function JI(e){return O.isJSXIdentifier(e)?O.isValidIdentifier(e.name)?O.identifier(e.name):null:O.isJSXMemberExpression(e)?JI(e.object):null}function vB(e,t){return e.scope===t.scope&&(t.node.params.some(n=>n===e.node)||e.isIdentifier()&&t.node.params.some(n=>O.isObjectPattern(n)&&n.properties.some(r=>O.isObjectProperty(r)&&O.isIdentifier(r.value,{name:e.node.name}))))}function gl(e,t){return e===t||typeof e.start=="number"&&typeof e.end=="number"&&typeof t.start=="number"&&typeof t.end=="number"&&e.start>=t.start&&e.end<=t.end}function XI(e){return O.isFunction(e)}function OI(e,t){return!!e.invocation?.bindings.some(n=>n.propName===t)}function kB(e,t){let n=new Set(t.values());return e.invocation?.bindings.filter(r=>n.has(r.propName))??[]}function _B(e,t){let n=new Set;Kp(e,{Identifier(o){n.add(o.node.name)}});let r=t;for(;n.has(r);)r+="_";return r}function FI(e,t,n){if(typeof n.start=="number"){if([...e].some(r=>r.start===n.start))return;t.start=n.start}e.add(t)}function jp(e,t){return(e.start??0)-(t.start??0)}function hl(e,t){let n=e.get(t);if(typeof n=="string")return n;if(!(n instanceof Uint8Array))return null;try{return new TextDecoder("utf-8",{fatal:!0}).decode(n)}catch{return null}}function LI(e,t){let n=YM("sha256").update(t).digest("hex");return e.content_hash===`sha256:${n}`}function Up(e){return!!e&&!e.startsWith("/")&&!e.includes("\\")&&e.split("/").every(t=>t&&t!=="."&&t!==".."&&!t.startsWith("."))}function CB(e){return e==="SOURCE_PARSE_FAILED"?"SOURCE_PARSE_FAILED":e==="SOURCE_ENTRY_UNRESOLVED"?"SOURCE_ENTRY_NOT_FOUND":e==="SOURCE_FILE_UNRESOLVED"||e==="SOURCE_ASSET_UNRESOLVED"?"SOURCE_IMPORT_UNRESOLVED":"SOURCE_NOT_PORTABLE"}function vt(e,t,n){return{complete:!1,errors:[at(e,t,n)]}}function at(e,t,n){return{code:e,path:t,message:n}}import{createHash as uv}from"node:crypto";import sm from"node:path";import am from"@babel/traverse";import*as ze from"@babel/types";import{GeneratedSiteCapabilitiesSchema as pj,SiteEditSourcePathSchema as mj}from"@vcp-dev/contracts";import{parse as Cl}from"@babel/parser";import*as K from"@babel/types";import{PortableCollectionRecipeFactsSchema as WB}from"@vcp-dev/contracts";import{parse as Mr}from"@babel/parser";import Hp from"@babel/traverse";import*as V from"@babel/types";function xl(e){try{let t=typeof e=="string"?e:e instanceof Uint8Array?new TextDecoder("utf-8",{fatal:!0}).decode(e):null;return t!==null&&!t.includes("\0")?t:null}catch{return null}}var Zp=typeof Hp=="function"?Hp:Hp.default;function qp(e){let t=nv(e.files),n=(g,p,m)=>({complete:!1,relation:null,errors:[{code:g,path:p,message:m}]}),r=tr(e.list_entry_file,e.selected_component_source,t),o=r?t.get(r):void 0;if(!r||typeof o!="string")return n("RELATED_COLLECTION_LIST_CONTAINER_UNPROVEN",e.list_entry_file,"The selected Page Unit does not resolve to one Snapshot list container.");if(!TB(o,r,"listStrict"))return{complete:!0,relation:null,errors:[]};let i=AB(o,r),s=i?bl(r,o,i,"listStrict",t):null;if(!i||!s)return n("RELATED_COLLECTION_LIST_CONTAINER_UNPROVEN",r,"The selected list container does not prove one literal CMS collection.");let a=[...t.keys()].filter(g=>/\[slug\]\/page\.(?:[cm]?[jt]sx?)$/u.test(g)),c=a.find(g=>typeof t.get(g)!="string");if(c)return n("RELATED_COLLECTION_DETAIL_CONSUMER_UNPROVEN",c,"A candidate detail route is not valid UTF-8 source, so uniqueness cannot be proven.");let l=a.flatMap(g=>{let p=t.get(g);if(typeof p!="string")return[];let m=bl(g,p,i,"getByUrlStrict",t,e.detail_prefix??`/${i}`);return m&&em(m.ast,e.detail_prefix??`/${i}`)!==null?[m]:[]});if(l.length!==1)return n("RELATED_COLLECTION_DETAIL_CONSUMER_UNPROVEN",e.list_entry_file,"Exactly one dynamic detail route must consume the selected collection.");let u=l[0];if(u.adapter_source!==s.adapter_source||u.interface_name!==s.interface_name)return n("RELATED_COLLECTION_ADAPTER_UNPROVEN",u.path,"The list and detail routes do not share the selected collection adapter and view interface.");let d=qn(u.source,{filePath:u.path,exportName:"default"}).components.flatMap(g=>{let p=tr(u.path,g.source,t),m=p?t.get(p):void 0;return!p||typeof m!="string"||!qI(m,g.export_name)||!El(m,u.adapter_source,u.interface_name)?[]:[{path:p,export_name:g.export_name}]});if(d.length!==1)return n("RELATED_COLLECTION_DETAIL_CONSUMER_UNPROVEN",u.path,"The collection detail route does not prove one private detail view.");let f=d[0];return{complete:!0,relation:{slug:i,requirement_key:`cms-${i}`,list_entry_file:e.list_entry_file,detail_entry_file:u.path,detail_view_file:f.path,detail_view_export:f.export_name},errors:[]}}function Qp(e){let t=nv(e.files),n=[],r=[],o=[],i=null;e.source_closure.complete||n.push({code:"RELATED_SOURCE_CLOSURE_INCOMPLETE",path:e.collection.list_entry_file,message:"The selected Page Unit source closure is incomplete; related entries cannot be proven."});for(let f of e.source_closure.nodes)f.kind==="source"&&typeof t.get(f.path)!="string"&&n.push({code:"RELATED_SOURCE_CLOSURE_INCOMPLETE",path:f.path,message:"A selected source is missing or is not valid UTF-8 text."});Wp(t,e.collection.list_entry_file,"RELATED_LIST_ENTRY_MISSING",n),Wp(t,e.collection.detail_entry_file,"RELATED_DETAIL_ENTRY_MISSING",n),Wp(t,e.collection.detail_view_file,"RELATED_DETAIL_VIEW_MISSING",n),Gp(o,{path:e.collection.list_entry_file,kind:"route",requirementKey:e.collection.requirement_key}),Gp(o,{path:e.collection.detail_entry_file,kind:"route",requirementKey:e.collection.requirement_key});let s=Lr({entry_files:[e.collection.detail_entry_file],files:t});for(let f of s.nodes)f.kind==="source"&&typeof t.get(f.path)!="string"&&n.push({code:"RELATED_DETAIL_SOURCE_INCOMPLETE",path:f.path,message:"A detail source is missing or is not valid UTF-8 text."});s.complete||n.push(...s.errors.map(f=>({code:"RELATED_DETAIL_SOURCE_INCOMPLETE",path:f.path,message:f.message})));let a=s.nodes.find(f=>f.path===e.collection.detail_view_file);!a||a.status!=="complete"?n.push({code:"RELATED_DETAIL_VIEW_NOT_REACHED",path:e.collection.detail_view_file,message:"The trusted detail route does not reach the declared detail-view entry."}):r.push({path:e.collection.detail_view_file,export:e.collection.detail_view_export==="default"?{kind:"default"}:{kind:"named",name:e.collection.detail_view_export},purpose:"collection-detail-view"});for(let f of s.nodes)if(f.kind!=="external"&&f.path!==e.collection.detail_entry_file&&f.path!==e.collection.detail_view_file){if(jB(f.path,e.collection)){Gp(o,{path:f.path,kind:f.path.includes("/page.")?"route":"adapter",requirementKey:e.collection.requirement_key});continue}$B(f.path,e.collection.detail_view_file,e.collection.slug)&&r.push({path:f.path,export:{kind:"default"},purpose:"i18n-companion"})}let c=t.get(e.collection.detail_view_file);typeof c=="string"&&MB(c,e.collection.detail_view_file,s.nodes,t,r),e.page_template&&(i=BB(e.page_template,t,n));let l=e.trusted_schema===void 0?null:RB(e,t,n,e.trusted_schema),u=KB(r).map((f,g)=>({key:XB(f,g),pathTemplate:f.path,export:f.export,purpose:f.purpose,requirementKey:e.collection.requirement_key})),d=zB(n).sort(HB);return{complete:d.length===0,entries:u.sort((f,g)=>f.pathTemplate.localeCompare(g.pathTemplate)||f.purpose.localeCompare(g.purpose)||f.key.localeCompare(g.key)),managed_requirements:o.sort(JB),thin_entry_plan:i,collection_wiring:l,errors:d}}function RB(e,t,n,r){let o=n.length,i=r.fields.map(E=>({...E}));(r.source_slug!==e.collection.slug||!r.evidence_path.trim()||i.length===0)&&n.push({code:"RELATED_COLLECTION_SCHEMA_UNPROVEN",path:r.evidence_path||`trusted-schema:${e.collection.slug}`,message:"Collection recipe facts require a non-empty trusted CMS schema with matching source identity."});let s=e.source_closure.nodes.filter(E=>E.kind==="source"&&E.status==="complete"&&E.path!==e.collection.list_entry_file).flatMap(E=>{let k=t.get(E.path);if(typeof k!="string")return[];let I=bl(E.path,k,e.collection.slug,"listStrict",t);return I?[I]:[]});s.length!==1&&n.push({code:"RELATED_COLLECTION_LIST_CONTAINER_UNPROVEN",path:e.collection.list_entry_file,message:"Exactly one rendered source module must prove the selected collection listStrict wiring."});let a=s[0]??null,c=a?zI(a,t,E=>E!==e.collection.detail_view_file):null;c?a&&!El(t.get(c.source_path),a.adapter_source,a.interface_name)&&n.push({code:"RELATED_COLLECTION_LIST_VIEW_UNPROVEN",path:c.source_path,message:"The rendered list view does not consume the generated collection interface."}):n.push({code:"RELATED_COLLECTION_LIST_VIEW_UNPROVEN",path:a?.path??e.collection.list_entry_file,message:"The generated list container must render one resolvable private list view."});let l=t.get(e.collection.detail_entry_file),u=typeof l=="string"?bl(e.collection.detail_entry_file,l,e.collection.slug,"getByUrlStrict",t):null,d=u?zI(u,t,E=>E===e.collection.detail_view_file):null;!u||!d||d.export_name!==e.collection.detail_view_export?n.push({code:"RELATED_COLLECTION_DETAIL_CONSUMER_UNPROVEN",path:e.collection.detail_entry_file,message:"The trusted detail route must consume the declared detail view through the same collection adapter."}):El(t.get(d.source_path),u.adapter_source,u.interface_name)||n.push({code:"RELATED_COLLECTION_DETAIL_CONSUMER_UNPROVEN",path:d.source_path,message:"The rendered detail view does not consume the generated collection interface."}),a&&u&&(a.adapter_source!==u.adapter_source||a.interface_name!==u.interface_name)&&n.push({code:"RELATED_COLLECTION_ADAPTER_UNPROVEN",path:e.collection.detail_entry_file,message:"List and detail consumers must use the same generated collection adapter and view interface."});let f=new Set(i.map(E=>E.name)),g=a?tr(a.path,a.adapter_source,t):null,p=g?t.get(g):null,m=[...e.required_fields??i.filter(E=>E.required).map(E=>E.name)].sort(Yp),y=[...e.force_multi_media??(typeof p=="string"?QI(p):[])].sort(Yp);for(let E of[...m,...y])f.has(E)||n.push({code:"RELATED_COLLECTION_FIELD_UNPROVEN",path:`trusted-schema:${e.collection.slug}.${E}`,message:`Collection field ${E} is not present in the trusted schema.`});if(a&&y.length)for(let E of y)(typeof p!="string"||!DB(p,E))&&n.push({code:"RELATED_COLLECTION_FIELD_UNPROVEN",path:g??a.adapter_source,message:`The generated adapter does not prove multi-media handling for ${E}.`});let x=u?em(u.ast,`/${e.collection.slug}`):null;x||n.push({code:"RELATED_COLLECTION_DETAIL_CONSUMER_UNPROVEN",path:e.collection.detail_entry_file,message:"The detail route does not prove a literal getByUrlStrict prefix."});let S=u?FB(u.ast):null;S||n.push({code:"RELATED_COLLECTION_DETAIL_CONSUMER_UNPROVEN",path:e.collection.detail_entry_file,message:"The generated detail route must expose a literal PAGE_SEO title."});let b=u?LB(u,t,x):null;return b==="unproven"&&n.push({code:"RELATED_COLLECTION_BREADCRUMB_UNPROVEN",path:e.collection.detail_entry_file,message:"The rendered collection breadcrumb exists but its fallback labels are not literal."}),n.length!==o||!a||!c||!u||!d||!x?null:{source_slug:e.collection.slug,detail_prefix:x,schema:i,schema_evidence_path:r.evidence_path,list_container_file:a.path,list_view:{...c,interface_name:a.interface_name},detail_view:{...d,interface_name:u.interface_name},...S?{title:S}:{},...b&&b!=="unproven"?{breadcrumb:b}:{},...m.length>0?{required_fields:m}:{},...y.length>0?{force_multi_media:y}:{}}}function bl(e,t,n,r,o,i=`/${n}`){let s;try{s=Mr(t,{sourceType:"module",sourceFilename:e,plugins:["jsx","typescript"]})}catch{return null}let a=bo(s,u=>V.isCallExpression(u)&&Eo(u.callee,r));if(!PB(s,e,o,r)||r==="listStrict"&&(a.length!==1||!V.isStringLiteral(a[0]?.arguments[0],{value:n}))||r==="getByUrlStrict"&&(a.length===0||em(s,i)===null))return null;let l=s.program.body.flatMap(u=>V.isImportDeclaration(u)?u.specifiers.flatMap(d=>{if(!V.isImportSpecifier(d))return[];let f=V.isIdentifier(d.imported)?d.imported.name:d.imported.value,g=/^to([A-Za-z_$][A-Za-z0-9_$]*View)$/u.exec(f);return g?[{source:u.source.value,local_name:d.local.name,interface_name:g[1]}]:[]}):[]).filter(u=>bo(s,d=>V.isIdentifier(d,{name:u.local_name})).length>1);return l.length!==1||!NB(s,e,o,l[0],r,n)?null:{path:e,source:t,ast:s,adapter_source:l[0].source,interface_name:l[0].interface_name}}function NB(e,t,n,r,o,i){let s=!1;return Zp(e,{JSXOpeningElement(a){let c=a.getFunctionParent();if(!c?.isFunctionDeclaration()||!c.parentPath.isExportDefaultDeclaration()||!V.isJSXIdentifier(a.node.name)||a.node.attributes.some(y=>V.isJSXSpreadAttribute(y)))return;let l=a.parentPath;for(;l&&!l.isReturnStatement()&&!l.isFunction();){if(l.isVariableDeclarator()||l.isJSXAttribute()||l.isConditionalExpression()||l.isLogicalExpression()||l.isCallExpression()||l.isJSXElement()&&l.node!==a.parentPath.node&&(!V.isJSXIdentifier(l.node.openingElement.name)||!/^[a-z]/u.test(l.node.openingElement.name.name)))return;l=l.parentPath}if(!l?.isReturnStatement()||l.getFunctionParent()!==c||l.parentPath!==c.get("body"))return;let u=a.scope.getBinding(a.node.name.name),d=u?.path,f=d?.parentPath;if(!u?.constant||!f?.isImportDeclaration()||f.node.importKind==="type"||d?.isImportSpecifier()&&d.node.importKind==="type"||!(d?.isImportDefaultSpecifier()||d?.isImportSpecifier()))return;let g=tr(t,f.node.source.value,n);if(!g||!El(n.get(g),r.source,r.interface_name))return;let p=a.get("attributes").filter(y=>y.isJSXAttribute()&&V.isJSXIdentifier(y.node.name,{name:o==="listStrict"?"records":"record"}));if(p.length!==1||!p[0].isJSXAttribute())return;let m=p[0].get("value");m.isJSXExpressionContainer()&&(o==="listStrict"?GI(m.get("expression"),c,r,i,new Set):YI(m.get("expression"),c,r,new Set))&&(s=!0)}}),s}function GI(e,t,n,r,o){if(!e.node||o.has(e.node)||o.size>=32)return!1;if(o.add(e.node),e.isIdentifier()){let g=e.scope.getBinding(e.node.name);return!g?.constant||!g.path.isVariableDeclarator()||g.path.getFunctionParent()!==t||!g.path.parentPath.isVariableDeclaration({kind:"const"})||Ps(g.referencePaths)?!1:GI(g.path.get("init"),t,n,r,o)}if(!e.isCallExpression()||e.node.arguments.length!==1)return!1;let i=e.get("callee");if(!i.isMemberExpression()||i.node.computed||!V.isIdentifier(i.node.property,{name:"map"}))return!1;let s=e.get("arguments")[0];if(!s||!ZI(s,n))return!1;let a=i.get("object");if(a.isConditionalExpression()){let g=a.get("consequent"),p=a.get("alternate"),m=y=>y.isArrayExpression()&&y.node.elements.length===0;if(m(g))a=p;else if(m(p))a=g;else return!1}if(!a.isMemberExpression()||a.node.computed||!V.isIdentifier(a.node.property,{name:"items"}))return!1;let c=a.get("object");if(!c.isMemberExpression()||c.node.computed||!V.isIdentifier(c.node.property,{name:"data"}))return!1;let l=c.get("object");if(!l.isIdentifier())return!1;let u=l.scope.getBinding(l.node.name);if(!u?.constant||!u.path.isVariableDeclarator()||u.path.getFunctionParent()!==t||!u.path.parentPath.isVariableDeclaration({kind:"const"})||Ps(u.referencePaths))return!1;let d=u.path.get("init");if(!d.isAwaitExpression())return!1;let f=d.get("argument");return f.isCallExpression()&&Eo(f.node.callee,"listStrict")&&V.isStringLiteral(f.node.arguments[0],{value:r})}function YI(e,t,n,r){if(!e.node||r.has(e.node)||r.size>=32)return!1;if(r.add(e.node),e.isIdentifier()){let u=e.scope.getBinding(e.node.name);return!u?.constant||!u.path.isVariableDeclarator()||u.path.getFunctionParent()!==t||!u.path.parentPath.isVariableDeclaration({kind:"const"})||Ps(u.referencePaths)?!1:YI(u.path.get("init"),t,n,r)}if(!e.isCallExpression()||e.node.arguments.length!==1)return!1;let o=e.get("callee");if(!ZI(o,n))return!1;let i=e.get("arguments")[0];if(!i?.isMemberExpression()||i.node.computed||!V.isIdentifier(i.node.property,{name:"data"}))return!1;let s=i.get("object");if(!s.isIdentifier())return!1;let a=s.scope.getBinding(s.node.name);if(!a?.constant||!a.path.isVariableDeclarator()||a.path.getFunctionParent()!==t||!a.path.parentPath.isVariableDeclaration({kind:"const"})||Ps(a.referencePaths))return!1;let c=a.path.get("init");if(!c.isAwaitExpression())return!1;let l=c.get("argument");return l.isCallExpression()&&Eo(l.node.callee,"getByUrlStrict")}function ZI(e,t){if(!e.isIdentifier({name:t.local_name}))return!1;let n=e.scope.getBinding(e.node.name),r=n?.path,o=r?.parentPath;return!(!n?.constant||!r?.isImportSpecifier()||r.node.importKind==="type"||!V.isIdentifier(r.node.imported,{name:`to${t.interface_name}`})||!o?.isImportDeclaration()||o.node.importKind==="type"||o.node.source.value!==t.source)}function Ps(e,t=new Set){return t.size>=32?!0:e.some(n=>{let r=n;for(;(r.parentPath?.isMemberExpression()||r.parentPath?.isOptionalMemberExpression())&&r.parentPath.node.object===r.node;)r=r.parentPath;let o=r.parentPath;if(o?.isVariableDeclarator()&&o.node.init===r.node){if(!V.isIdentifier(o.node.id))return!0;let i=o.scope.getBinding(o.node.id.name);return i?.constant?t.has(i.identifier)?!1:(t.add(i.identifier),Ps(i.referencePaths,t)):!0}return!!(o?.isAssignmentExpression()&&o.node.left===r.node||o?.isUpdateExpression()||o?.isUnaryExpression()&&o.node.operator==="delete")})}function PB(e,t,n,r){let o=0,i=Nr(e,"cms");for(let s of e.program.body){if(!V.isImportDeclaration(s)||s.importKind==="type")continue;let a=tr(t,s.source.value,n);!a||!/^(?:src\/)?lib\/cms(?:\/index|\/collections)?\.[cm]?[jt]s$/u.test(a)||s.specifiers.some(c=>{if(V.isImportSpecifier(c)&&c.importKind==="type")return!1;if(!V.isImportSpecifier(c))return!0;let l=V.isIdentifier(c.imported)?c.imported.name:c.imported.value;return l==="collections"||l==="cms"&&c.local.name!=="cms"})&&(i=!0)}return Zp(e,{CallExpression(s){if(!Eo(s.node.callee,r))return;o+=1;let a=s.scope.getBinding("cms"),c=a?.path,l=c?.parentPath;if(!a?.constant||!c?.isImportSpecifier()||c.node.importKind==="type"||!V.isIdentifier(c.node.imported,{name:"cms"})||!l?.isImportDeclaration()||l.node.importKind==="type"){i=!0;return}let u=tr(t,l.node.source.value,n);(!u||!/^(?:src\/)?lib\/cms(?:\/index)?\.[cm]?[jt]s$/u.test(u)||a.referencePaths.some(d=>{let f=d.parentPath,g=f?.parentPath,p=g?.parentPath;return!(f?.isMemberExpression()&&f.node.object===d.node&&!f.node.computed&&V.isIdentifier(f.node.property,{name:"collections"})&&g?.isMemberExpression()&&g.node.object===f.node&&!g.node.computed&&V.isIdentifier(g.node.property)&&p?.isCallExpression()&&p.node.callee===g.node)}))&&(i=!0)}}),o>0&&!i}function AB(e,t){let n;try{n=Mr(e,{sourceType:"module",sourceFilename:t,plugins:["jsx","typescript"]})}catch{return null}let r=bo(n,o=>V.isCallExpression(o)&&Eo(o.callee,"listStrict")&&V.isStringLiteral(o.arguments[0])).map(o=>o.arguments[0].value);return r.length===1&&/^[a-z0-9][a-z0-9_-]{0,123}$/u.test(r[0])?r[0]:null}function TB(e,t,n){let r;try{r=Mr(e,{sourceType:"module",sourceFilename:t,plugins:["jsx","typescript"]})}catch{return!1}return bo(r,o=>V.isCallExpression(o)&&Eo(o.callee,n)).length>0}function zI(e,t,n){let r=qn(e.source,{filePath:e.path,exportName:"default"});if(r.diagnostics.length>0)return null;let o=r.components.flatMap(i=>{let s=tr(e.path,i.source,t),a=s?t.get(s):null;return!s||!n(s)||typeof a!="string"||!qI(a,i.export_name)?[]:[{source_path:s,target_path:s,export_name:i.export_name,import_specifier:i.source}]});return o.length===1?o[0]:null}function qI(e,t){let n;try{n=Mr(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return!1}for(let r of n.program.body){if(t==="default"&&V.isExportDefaultDeclaration(r))return!0;if(V.isExportNamedDeclaration(r)&&(r.declaration&&(V.isFunctionDeclaration(r.declaration)||V.isClassDeclaration(r.declaration)||V.isTSInterfaceDeclaration(r.declaration)||V.isTSTypeAliasDeclaration(r.declaration))&&r.declaration.id?.name===t||V.isVariableDeclaration(r.declaration)&&r.declaration.declarations.some(o=>V.isIdentifier(o.id,{name:t}))||r.specifiers.some(o=>V.isExportSpecifier(o)?(V.isIdentifier(o.exported)?o.exported.name:o.exported.value)===t:!1)))return!0}return!1}function El(e,t,n){if(typeof e!="string")return!1;let r;try{r=Mr(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return!1}return r.program.body.flatMap(i=>!V.isImportDeclaration(i)||i.source.value!==t?[]:i.specifiers.flatMap(s=>V.isImportSpecifier(s)?(V.isIdentifier(s.imported)?s.imported.name:s.imported.value)===n?[s.local.name]:[]:[])).some(i=>bo(r,s=>V.isIdentifier(s,{name:i})).length>1)}function Eo(e,t){return V.isMemberExpression(e)&&!e.computed&&V.isIdentifier(e.property,{name:t})&&V.isMemberExpression(e.object)&&!e.object.computed&&V.isIdentifier(e.object.property,{name:"collections"})&&V.isIdentifier(e.object.object,{name:"cms"})}function em(e,t){let n=[];return Zp(e,{CallExpression(r){Eo(r.node.callee,"getByUrlStrict")&&n.push(wB(r.node.arguments[0],o=>OB(r,o)))}}),n.length===0?null:n.every(r=>r===t)?t:null}function wB(e,t){return V.isBinaryExpression(e,{operator:"+"})&&V.isStringLiteral(e.left)&&V.isIdentifier(e.right)&&t(e.right.name)&&/^\/[A-Za-z0-9_-]+\/$/u.test(e.left.value)?e.left.value.slice(0,-1):V.isTemplateLiteral(e)&&e.expressions.length===1&&V.isIdentifier(e.expressions[0])&&t(e.expressions[0].name)&&e.quasis[1]?.value.cooked===""&&e.quasis.length>0&&/^\/[A-Za-z0-9_-]+\/$/u.test(e.quasis[0].value.cooked??"")?(e.quasis[0].value.cooked??"").slice(0,-1):null}function OB(e,t){let n=e.scope.getBinding(t);if(!n?.constant||!n.path.isVariableDeclarator())return!1;let r=n.path.node;if(V.isObjectPattern(r.id)&&V.isAwaitExpression(r.init)&&V.isIdentifier(r.init.argument))return r.id.properties.some(a=>V.isObjectProperty(a)&&!a.computed&&Sl(a.key)==="slug"&&V.isIdentifier(a.value,{name:t}))&&HI(n.path,r.init.argument.name);let o=r.init;if(!V.isIdentifier(r.id,{name:t})||!V.isCallExpression(o)||!V.isIdentifier(o.callee)||o.arguments.length!==1)return!1;let i=n.path.scope.getBinding(o.callee.name);if(!i?.constant||!i.path.isImportSpecifier()||!V.isIdentifier(i.path.node.imported,{name:"decodeRouteSlug"})||!i.path.parentPath.isImportDeclaration()||i.path.parentPath.node.source.value!=="@/lib/cms")return!1;let s=o.arguments[0];return V.isMemberExpression(s)&&!s.computed&&V.isIdentifier(s.property,{name:"slug"})&&V.isAwaitExpression(s.object)&&V.isIdentifier(s.object.argument)&&HI(n.path,s.object.argument.name)}function HI(e,t){let n=e.scope.getBinding(t);if(!n?.constant||n.kind!=="param")return!1;let r=n.path.getFunctionParent();if(!r||!r.isFunctionDeclaration())return!1;let o=r.parentPath;return!o.isExportDefaultDeclaration()&&!(o.isExportNamedDeclaration()&&r.node.id?.name==="generateMetadata")?!1:r.node.params.some(i=>V.isObjectPattern(i)&&i.properties.some(s=>V.isObjectProperty(s)&&!s.computed&&Sl(s.key)==="params"&&V.isIdentifier(s.value,{name:t})))}function FB(e){for(let t of e.program.body)if(V.isVariableDeclaration(t))for(let n of t.declarations){if(!V.isIdentifier(n.id,{name:"PAGE_SEO"}))continue;let r=ev(n.init);if(!V.isObjectExpression(r))return null;let o=r.properties.find(i=>V.isObjectProperty(i)&&!i.computed&&Sl(i.key)==="title");return o&&V.isStringLiteral(o.value)?o.value.value:null}return null}function LB(e,t,n){let o=qn(e.source,{filePath:e.path,exportName:"default"}).components.filter(c=>/(?:^|\/)components\/site\/generated\/[A-Za-z0-9_-]+-breadcrumb$/u.test(c.source));if(o.length===0)return null;if(o.length!==1||!n)return"unproven";let i=tr(e.path,o[0].source,t),s=i?t.get(i):null;if(typeof s!="string")return"unproven";let a;try{a=Mr(s,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return"unproven"}for(let c of bo(a,l=>V.isArrayExpression(l))){let l=c.elements.flatMap(f=>{if(!V.isObjectExpression(f))return[];let g=new Map;for(let p of f.properties){if(!V.isObjectProperty(p)||p.computed)continue;let m=Sl(p.key);m&&V.isStringLiteral(p.value)&&g.set(m,p.value.value)}return g.has("name")&&g.has("href")?[g]:[]}),u=l.find(f=>f.get("href")==="/"),d=l.find(f=>f.get("href")===n);if(u&&d)return{homeLabel:u.get("name"),collectionLabel:d.get("name")}}return"unproven"}function QI(e){let t;try{t=Mr(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return[]}return[...new Set(bo(t,n=>{if(!V.isCallExpression(n))return!1;let r=n.callee;if(!V.isMemberExpression(r)||r.computed||!V.isIdentifier(r.property,{name:"images"}))return!1;let o=n.arguments[0];return V.isMemberExpression(o)&&!o.computed&&V.isIdentifier(o.object,{name:"d"})&&V.isIdentifier(o.property)}).flatMap(n=>{let r=n.arguments[0];return V.isMemberExpression(r)&&!r.computed&&V.isIdentifier(r.property)?[r.property.name]:[]}))].sort(Yp)}function DB(e,t){return QI(e).includes(t)}function bo(e,t){let n=[],r=o=>{t(o)&&n.push(o);for(let i of Object.values(o))if(Array.isArray(i))for(let s of i)WI(s)&&r(s);else WI(i)&&r(i)};return r(e),n}function WI(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}function ev(e){return e?V.isTSAsExpression(e)||V.isTSTypeAssertion(e)||V.isTSNonNullExpression(e)?ev(e.expression):e:null}function Sl(e){return V.isIdentifier(e)?e.name:V.isStringLiteral(e)?e.value:null}function Yp(e,t){return e.localeCompare(t)}function MB(e,t,n,r,o){let i=qn(e,{filePath:t,exportName:"default"});for(let s of i.components){let a=tr(t,s.source,r);if(!a)continue;let c=n.find(u=>u.path===a),l=r.get(a);!c||c.kind==="external"||typeof l!="string"||VB(l)&&o.push({path:a,export:s.export_name==="default"?{kind:"default"}:{kind:"named",name:s.export_name},purpose:"client-importer"})}}function BB(e,t,n){let r=t.get(e.entry_file);if(typeof r!="string")return n.push({code:"RELATED_PAGE_TEMPLATE_PARSE_FAILED",path:e.entry_file,message:"The PageTemplate entry source is not available as text."}),null;let o=qn(r,{filePath:e.entry_file,exportName:"default"});if(o.diagnostics.length>0)return n.push({code:"RELATED_PAGE_TEMPLATE_PARSE_FAILED",path:e.entry_file,message:o.diagnostics[0]?.message??"PageTemplate AST is incomplete."}),null;let i=o.rendered_component_openings;if(i.length!==1)return n.push({code:"RELATED_PAGE_TEMPLATE_NOT_SEPARABLE",path:e.entry_file,message:"A single-file PageTemplate is portable only when one real component call can be isolated; the whole page cannot be copied."}),null;let s=i[0];return e.component_source&&s.source!==e.component_source||e.component_export&&s.export_name!==e.component_export?(n.push({code:"RELATED_PAGE_TEMPLATE_NOT_SEPARABLE",path:e.entry_file,message:"The declared PageTemplate root does not match its real rendered component call."}),null):{kind:"managed-root-thin-entry",source_file:e.entry_file,component_source:s.source,component_export:s.export_name,adds_dom:!1}}function Wp(e,t,n,r){typeof e.get(t)!="string"&&r.push({code:n,path:t,message:`Portable related-entry analysis could not read ${t}.`})}function jB(e,t){return e===t.list_entry_file||e===t.detail_entry_file||e.startsWith("lib/cms/")||e===`components/site/generated/${t.slug}-list.tsx`||e===`components/site/generated/${t.slug}-list.ts`||e===`components/site/generated/${t.slug}-list.jsx`||e===`components/site/generated/${t.slug}-list.js`||e===`components/site/generated/${t.slug}-breadcrumb.tsx`||e===`components/site/generated/${t.slug}-breadcrumb.ts`||e===`components/site/generated/${t.slug}-breadcrumb.jsx`||e===`components/site/generated/${t.slug}-breadcrumb.js`}function $B(e,t,n){let r=e.replace(/\\/g,"/"),o=t.replace(/\.(?:tsx?|jsx?)$/u,""),i=tv(t),s=o.slice(o.lastIndexOf("/")+1),a=s.endsWith("-detail-view")?s.slice(0,-12):n;return r===`${o}.i18n.json`||r===`${o}.messages.json`||r===`${i}/${a}.i18n.json`||r===`${i}/${a}.messages.json`||/(?:^|\/)(?:i18n|locales?)\/[^/]+\.json$/u.test(r)||/\.(?:i18n|messages)\.[^/]+\.json$/u.test(r)}function VB(e){try{return Mr(e,{sourceType:"module",plugins:["jsx","typescript"]}).program.directives.some(n=>n.value.value==="use client")}catch{return!1}}function tr(e,t,n){let r=t.startsWith("@/")?t.slice(2):UB(`${tv(e)}/${t}`);return[r,`${r}.tsx`,`${r}.ts`,`${r}.jsx`,`${r}.js`,`${r}/index.tsx`,`${r}/index.ts`,`${r}/index.jsx`,`${r}/index.js`].find(i=>n.has(i))??null}function tv(e){let t=e.lastIndexOf("/");return t<0?"":e.slice(0,t)}function UB(e){let t=[];for(let n of e.replace(/\\/g,"/").split("/"))!n||n==="."||(n===".."?t.length>0&&t.at(-1)!==".."?t.pop():t.push(".."):t.push(n));return t.join("/")}function nv(e){let t=e instanceof Map?e.entries():Object.entries(e);return new class extends Map{get(n){let r=super.get(n);if(r===void 0||!/\.[cm]?[jt]sx?$/iu.test(n))return r;let o=xl(r);return o!==null?(super.set(n,o),o):typeof r=="string"?new TextEncoder().encode(r):r}}(t)}function KB(e){let t=new Set;return e.filter(n=>{let r=`${n.path}\0${n.purpose}\0${JSON.stringify(n.export)}`;return t.has(r)?!1:(t.add(r),!0)})}function Gp(e,t){e.some(r=>r.path===t.path&&r.kind===t.kind)||e.push(t)}function JB(e,t){return e.path.localeCompare(t.path)||e.kind.localeCompare(t.kind)||e.requirementKey.localeCompare(t.requirementKey)}function XB(e,t){return`${`related.${e.purpose}.${e.path.replace(/[^A-Za-z0-9]+/gu,"-").replace(/^-|-$/gu,"")}`.slice(0,112)}.${t}`}function zB(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function HB(e,t){return e.path.localeCompare(t.path)||e.code.localeCompare(t.code)||e.message.localeCompare(t.message)}var GB=new Set(["blockId","block_id","targetBlockId","target_block_id","sourceBlockId","source_block_id"]),YB=new Set(["data-vcp-block-id","data-vcp-edit-key"]),ZB=new Set(["data-vcp-order","sourceOrder","source_order"]);function ai(e){let t=f=>({complete:!1,entry_file:e.file_path,target:e.target,call:null,bindings:[],original_block_id:null,original_order:null,semantic_props:{},errors:[...f].sort(Ts)}),n;try{n=Cl(e.source,{sourceType:"module",sourceFilename:e.file_path,plugins:["jsx","typescript"]})}catch(f){return t([{code:"INVOCATION_PARSE_FAILED",path:e.file_path,message:f instanceof Error?f.message:String(f)}])}let r=aj(n),o=qn(e.source,{filePath:e.file_path,exportName:e.export_name??"default"}),i=o.diagnostics.map(f=>({code:"INVOCATION_RENDER_GRAPH_INCOMPLETE",path:f.file_path||e.file_path,message:f.message})),s=new Set(o.rendered_component_openings.filter(f=>f.source===e.target.source&&f.export_name===e.target.export_name).map(f=>f.start_offset)),a=[],c=0;if(kl(n,new Set,(f,g)=>{if(!K.isJSXElement(f))return;let p=f.openingElement,m=p.start;if(typeof m!="number"||e.call_source_range&&(p.loc?.start.line!==e.call_source_range.start_line||p.loc.start.column!==e.call_source_range.start_column))return;let y=lv(p.name);if(!y)return;let x=uj(p.name,r);x&&(e.target.local_name&&e.target.local_name!==y||x.source!==e.target.source||x.export_name!==e.target.export_name||s.has(m)&&a.push({node:p,element:f,local:x,context:g,ordinal:c++}))}),a.length===0)return t([...i,{code:"INVOCATION_TARGET_NOT_RENDERED",path:e.file_path,message:`The selected component call is not a statically rendered Page Unit in ${e.file_path}.`}]);let l=a.map(f=>sv(e,f.node,f.element,{kind:"import",component_source:f.local.source,export_name:f.local.export_name,local_name:f.local.local_name},f.context,f.ordinal)),u=av(l,e.target.original_block_id);if(!u)return t([...i,{code:"INVOCATION_TARGET_AMBIGUOUS",path:e.file_path,message:"The selected component is rendered more than once and no unique original block identity was provided."}]);let d=[...i,...u.errors];return{complete:d.length===0,entry_file:e.file_path,target:e.target,call:u.call,bindings:d.length===0?u.bindings:[],original_block_id:u.original_block_id,original_order:u.original_order,semantic_props:u.semantic_props,errors:im(d).sort(Ts)}}function iv(e){let t=a=>({complete:!1,entry_file:e.file_path,target:e.target,call:null,bindings:[],original_block_id:null,original_order:null,semantic_props:{},errors:[...a].sort(Ts)}),n;try{n=Cl(e.source,{sourceType:"module",sourceFilename:e.file_path,plugins:["jsx","typescript"]})}catch(a){return t([{code:"INVOCATION_PARSE_FAILED",path:e.file_path,message:a instanceof Error?a.message:String(a)}])}let r=[],o=0;if(kl(n,new Set,(a,c)=>{if(!K.isJSXElement(a))return;let l=a.openingElement;if(typeof l.start!="number"||lv(l.name)!==e.target.local_name)return;let u=o++;e.call_source_range&&(l.loc?.start.line!==e.call_source_range.start_line||l.loc.start.column!==e.call_source_range.start_column)||r.push({node:l,element:a,context:c,ordinal:u})}),r.length===0)return t([{code:"INVOCATION_TARGET_NOT_RENDERED",path:e.file_path,message:`The selected local component call is not a statically rendered Page Unit in ${e.file_path}.`}]);let i=r.map(a=>sv(e,a.node,a.element,{kind:"local",local_name:e.target.local_name},a.context,a.ordinal)),s=av(i,e.target.original_block_id);return s?{complete:s.errors.length===0,entry_file:e.file_path,target:e.target,call:s.call,bindings:s.errors.length===0?s.bindings:[],original_block_id:s.original_block_id,original_order:s.original_order,semantic_props:s.semantic_props,errors:im(s.errors).sort(Ts)}:t([{code:"INVOCATION_TARGET_AMBIGUOUS",path:e.file_path,message:"The selected local component is rendered more than once and no unique original block identity was provided."}])}function qB(e){let t;try{t=Cl(e.source,{sourceType:"module",sourceFilename:e.file_path,plugins:["jsx","typescript"]})}catch(a){return{invocation:null,errors:[{code:"INVOCATION_PARSE_FAILED",path:e.file_path,message:a instanceof Error?a.message:String(a)}]}}let n=yn({route:e.route,composition:e.composition.templateId===void 0?{routeId:e.composition.routeId}:{routeId:e.composition.routeId,effectiveTemplateId:e.composition.templateId},entryFile:e.file_path,version:e.document_version,source:e.source,ast:t});if(!n.ok)return{invocation:null,errors:n.projection.diagnostics.map(a=>({code:"INVOCATION_PAGE_UNIT_UNSUPPORTED",path:e.file_path,message:a.message}))};let r=n.projection.placementUnitByKey.get(e.placement_unit_key),o=r?.sourceRange;if(!r||!o)return{invocation:null,errors:[{code:"INVOCATION_PAGE_UNIT_NOT_FOUND",path:e.file_path,message:"The selected Page Unit key does not belong to the pinned document version."}]};let i=qn(e.source,{filePath:e.file_path,exportName:"default"});if(i.components.length===0)return{invocation:null,errors:[]};let s=i.components.map(a=>ai({file_path:e.file_path,source:e.source,target:a,call_source_range:{start_line:o.startLine,start_column:o.startColumn}})).filter(a=>a.call!==null);return s.length!==1?{invocation:null,errors:[{code:"INVOCATION_PAGE_UNIT_NOT_FOUND",path:e.file_path,message:"The selected Page Unit does not resolve to exactly one rendered imported component."}]}:{invocation:s[0],errors:s[0].errors}}function QB(e){let t=ai(e),n=Qp({files:e.files,source_closure:e.source_closure,collection:e.collection,trusted_schema:e.trusted_schema,...e.required_fields?{required_fields:e.required_fields}:{},...e.force_multi_media?{force_multi_media:e.force_multi_media}:{}}),r=[...t.errors],o=[];e.source_closure.complete||r.push({code:"COLLECTION_SOURCE_CLOSURE_INCOMPLETE",path:e.collection.list_entry_file,message:"Collection recipe analysis requires a complete selected source closure."});for(let f of n.errors)r.push({code:nj(f.code),path:f.path,message:f.message});t.call&&o.push({fact:"invocation",path:t.call.source_file,reason:"The selected rendered component call supplies the portable invocation bindings.",source_range:t.call.source_range});let i=rj(e.files),s=n.collection_wiring,a=oj(e.file_path,e.target.source,i),c=a?xl(i.get(a)):null,l=a&&typeof c=="string"?ej(c,a,e.collection.slug):null;if(!a)r.push({code:"COLLECTION_LIST_CONTAINER_UNPROVEN",path:e.file_path,message:"The selected invocation target does not resolve to a Snapshot source file."});else if(!l)r.push({code:"COLLECTION_PAGINATION_UNPROVEN",path:a,message:"The collection list container must expose one literal pageSize with statically provable searchParams behavior."});else{o.push({fact:"pagination",path:a,reason:l.paginate?`listStrict consumes route searchParams with literal pageSize ${l.limit}.`:`listStrict is embedded and uses literal top-N ${l.limit}.`});let f=t.bindings.filter(g=>g.propName==="searchParams"&&g.value.kind==="route-search-params");(l.paginate&&f.length!==1||!l.paginate&&f.length!==0)&&r.push({code:"COLLECTION_SEARCH_PARAMS_MISMATCH",path:`${e.file_path}:searchParams`,message:l.paginate?"A paginated collection must receive the selected route searchParams exactly once.":"An embedded collection cannot carry a route searchParams binding.",source_range:t.call?.source_range})}s&&a!==s.list_container_file&&r.push({code:"COLLECTION_LIST_CONTAINER_UNPROVEN",path:e.file_path,message:"The selected invocation does not resolve to the proven collection list container."});let u=null;if(s&&l&&r.length===0){let f={source_slug:s.source_slug,list_mode:l.paginate?"page":"embedded",paginate:l.paginate,...l.paginate?{page_size:l.limit}:{top_n:l.limit},detail_prefix:s.detail_prefix,schema:s.schema.map(p=>({...p})),list_view:{...s.list_view},detail_view:{...s.detail_view},...s.title?{title:s.title}:{},...s.breadcrumb?{breadcrumb:{...s.breadcrumb}}:{},...s.required_fields?{required_fields:[...s.required_fields]}:{},...s.force_multi_media?{force_multi_media:[...s.force_multi_media]}:{},list_route_required:l.paginate},g=WB.safeParse(f);g.success?(u=g.data,o.push({fact:"detail-route",path:e.collection.detail_entry_file,reason:`The rendered detail consumer proves literal prefix ${s.detail_prefix}.`},{fact:"list-view",path:s.list_view.source_path,reason:`The list container renders ${s.list_view.export_name} with ${s.list_view.interface_name}.`},{fact:"detail-view",path:s.detail_view.source_path,reason:`The detail route renders ${s.detail_view.export_name} with ${s.detail_view.interface_name}.`},{fact:"schema",path:s.schema_evidence_path,reason:"The complete CMS schema is supplied by the trusted application projection."})):r.push({code:"COLLECTION_RECIPE_INVALID",path:`collection-recipe:${s.source_slug}`,message:g.error.issues[0]?.message??"Observed collection facts do not satisfy the portable recipe contract."})}let d=im(r).sort(Ts);return{...t,complete:d.length===0&&u!==null,errors:d,collection_recipe:u,collection_evidence:o.sort(sj),related_entries:n}}function ej(e,t,n){let r;try{r=Cl(e,{sourceType:"module",sourceFilename:t,plugins:["jsx","typescript"]})}catch{return null}let o=tj(r);if(!o)return null;let i=tm(o,f=>{if(!K.isCallExpression(f))return!1;let g=f.callee;return K.isMemberExpression(g)&&!g.computed&&K.isIdentifier(g.property,{name:"listStrict"})&&K.isMemberExpression(g.object)&&!g.object.computed&&K.isIdentifier(g.object.property,{name:"collections"})&&K.isIdentifier(g.object.object,{name:"cms"})&&K.isStringLiteral(f.arguments[0],{value:n})});if(i.length!==1)return null;let s=i[0].arguments[1];if(!K.isObjectExpression(s)||s.properties.some(f=>K.isSpreadElement(f)))return null;let a=s.properties.find(f=>K.isObjectProperty(f)&&!f.computed&&vl(f.key)==="pageSize");if(!a||!K.isNumericLiteral(a.value)||!Number.isSafeInteger(a.value.value)||a.value.value<=0||!s.properties.some(f=>K.isObjectProperty(f)&&!f.computed&&vl(f.key)==="page"))return null;let l=s.properties.some(f=>K.isObjectProperty(f)&&!f.computed&&vl(f.key)==="category"),u=tm(o,f=>K.isAwaitExpression(f)&&K.isIdentifier(f.argument,{name:"searchParams"})).length;if(u>1)return null;let d=tm(o,f=>{if(!K.isCallExpression(f))return!1;let g=f.callee;return K.isMemberExpression(g)&&!g.computed&&K.isIdentifier(g.property,{name:"categories"})&&K.isMemberExpression(g.object)&&!g.object.computed&&K.isIdentifier(g.object.property,{name:"collections"})&&K.isIdentifier(g.object.object,{name:"cms"})&&K.isStringLiteral(f.arguments[0],{value:n})}).length;return u===1&&(!l||d!==1)||u===0&&(l||d!==0)?null:{paginate:u===1,limit:a.value.value}}function tj(e){let t=e.program.body.find(n=>K.isExportDefaultDeclaration(n));return K.isExportDefaultDeclaration(t)&&(K.isFunctionDeclaration(t.declaration)||K.isFunctionExpression(t.declaration)||K.isArrowFunctionExpression(t.declaration))?t.declaration:null}function tm(e,t){let n=[],r=o=>{if(!(o!==e&&om(o))){t(o)&&n.push(o);for(let i of Object.values(o))if(Array.isArray(i))for(let s of i)_l(s)&&r(s);else _l(i)&&r(i)}};return r(e),n}function nj(e){return e==="RELATED_COLLECTION_SCHEMA_UNPROVEN"?"COLLECTION_SCHEMA_UNPROVEN":e==="RELATED_COLLECTION_LIST_CONTAINER_UNPROVEN"?"COLLECTION_LIST_CONTAINER_UNPROVEN":e==="RELATED_COLLECTION_DETAIL_CONSUMER_UNPROVEN"||e==="RELATED_DETAIL_ENTRY_MISSING"||e==="RELATED_DETAIL_VIEW_MISSING"||e==="RELATED_DETAIL_VIEW_NOT_REACHED"||e==="RELATED_DETAIL_SOURCE_INCOMPLETE"?"COLLECTION_DETAIL_CONSUMER_UNPROVEN":"COLLECTION_VIEW_UNPROVEN"}function rj(e){return e instanceof Map?e:new Map(Object.entries(e))}function oj(e,t,n){let r=e.includes("/")?e.slice(0,e.lastIndexOf("/")):"",o=t.startsWith("@/")?t.slice(2):ij(`${r}/${t}`);return[o,`${o}.tsx`,`${o}.ts`,`${o}.jsx`,`${o}.js`,`${o}/index.tsx`,`${o}/index.ts`,`${o}/index.jsx`,`${o}/index.js`].find(i=>n.has(i))??null}function ij(e){let t=[];for(let n of e.split("/"))!n||n==="."||(n===".."?t.pop():t.push(n));return t.join("/")}function sj(e,t){return e.fact.localeCompare(t.fact)||e.path.localeCompare(t.path)}function aj(e){let t=new Map;for(let n of e.program.body){if(!K.isImportDeclaration(n))continue;let r=n.source.value;for(let o of n.specifiers)if(K.isIdentifier(o.local)){if(K.isImportDefaultSpecifier(o))t.set(o.local.name,{source:r,export_name:"default",local_name:o.local.name});else if(K.isImportNamespaceSpecifier(o))t.set(o.local.name,{source:r,export_name:"*",local_name:o.local.name});else if(K.isImportSpecifier(o)){let i=K.isIdentifier(o.imported)?o.imported.name:o.imported.value;t.set(o.local.name,{source:r,export_name:i,local_name:o.local.name})}}}return t}function sv(e,t,n,r,o,i){let s=fj(t),a=[],c=[],l={},u=new Set,d=null,f=null,g=(m,y)=>{if(u.has(m)){a.push({code:"INVOCATION_DUPLICATE_PROP",path:`${e.file_path}:${m}`,message:`Portable invocation contains duplicate prop ${m}.`,source_range:s});return}u.add(m),c.push({propName:m,value:y}),(m==="type"||m==="variant")&&y.kind==="json-literal"&&(l[m]=y.value)};for(let m of t.attributes){if(K.isJSXSpreadAttribute(m)){let E=Br(m.argument);if(!E.ok||!cv(E.value)){a.push({code:"INVOCATION_SPREAD_UNRESOLVED",path:`${e.file_path}:spread`,message:"Portable invocation cannot prove the props supplied by a spread expression.",source_range:s});continue}for(let[k,I]of Object.entries(E.value)){if(!ov(k)){a.push({code:"INVOCATION_VALUE_UNRESOLVED",path:`${e.file_path}:${k}`,message:`Portable invocation cannot encode prop ${k}.`,source_range:s});continue}g(k,nm(I))}continue}let y=dj(m.name);if(!y)continue;let x=m.value,S=x&&K.isJSXExpressionContainer(x)?x.expression:null;if(YB.has(y)){let E=x?Il(x):{ok:!0,value:!0};!E.ok||typeof E.value!="string"?a.push({code:"INVOCATION_BLOCK_ID_UNRESOLVED",path:`${e.file_path}:${y}`,message:"Portable invocation requires a literal original block identity.",source_range:s}):d=E.value;continue}if(ZB.has(y)){let E=x?Il(x):{ok:!0,value:!0};!E.ok||typeof E.value!="number"||!Number.isSafeInteger(E.value)?a.push({code:"INVOCATION_ORDER_UNRESOLVED",path:`${e.file_path}:${y}`,message:"Portable invocation requires a literal original order.",source_range:s}):f=E.value;continue}if(!ov(y)){a.push({code:"INVOCATION_VALUE_UNRESOLVED",path:`${e.file_path}:${y}`,message:`Portable invocation cannot encode prop ${y}.`,source_range:s});continue}if(GB.has(y)){let E=x?Il(x):{ok:!0,value:!0};E.ok&&typeof E.value=="string"?d=E.value:S&&rv(S,o)&&a.push({code:"INVOCATION_BLOCK_ID_UNRESOLVED",path:`${e.file_path}:${y}`,message:"A target block identity cannot be supplied by route search params.",source_range:s}),g(y,{kind:"target-block-id"});continue}if(S&&rv(S,o)){g(y,{kind:"route-search-params"});continue}let b=x?Il(x):{ok:!0,value:!0};if(!b.ok){a.push({code:"INVOCATION_VALUE_UNRESOLVED",path:`${e.file_path}:${y}`,message:`Portable invocation cannot prove a JSON-literal value for ${y}.`,source_range:s});continue}g(y,nm(b.value))}let p=cj(n);return p.ok?p.value!==void 0&&g("children",nm(p.value)):a.push({code:"INVOCATION_CHILDREN_UNRESOLVED",path:`${e.file_path}:children`,message:p.message,source_range:s}),{call:r.kind==="local"?{kind:"local",source_file:e.file_path,local_name:r.local_name,ordinal:i,source_range:s}:{source_file:e.file_path,component_source:r.component_source,export_name:r.export_name,local_name:r.local_name,ordinal:i,source_range:s},bindings:c,original_block_id:d??e.target.original_block_id??null,original_order:f,semantic_props:l,errors:a}}function av(e,t){if(e.length===1)return e[0]??null;if(!t)return null;let n=e.filter(r=>r.original_block_id===t);return n.length===1?n[0]??null:null}function Il(e){return e===null?{ok:!0,value:!0}:K.isStringLiteral(e)?{ok:!0,value:e.value}:K.isJSXExpressionContainer(e)?Br(e.expression):{ok:!1}}function Br(e){if(!e)return{ok:!1};if(K.isStringLiteral(e))return{ok:!0,value:e.value};if(K.isNumericLiteral(e)&&Number.isFinite(e.value))return{ok:!0,value:e.value};if(K.isBooleanLiteral(e))return{ok:!0,value:e.value};if(K.isNullLiteral(e))return{ok:!0,value:null};if(K.isTemplateLiteral(e)&&e.expressions.length===0)return{ok:!0,value:e.quasis[0]?.value.cooked??""};if(K.isTSAsExpression(e)||K.isTSTypeAssertion(e)||K.isTSNonNullExpression(e))return Br(e.expression);if(K.isUnaryExpression(e)){let t=Br(e.argument);return!t.ok||e.operator==="+"&&typeof t.value=="number"?t:e.operator==="-"&&typeof t.value=="number"?{ok:!0,value:-t.value}:e.operator==="!"&&typeof t.value=="boolean"?{ok:!0,value:!t.value}:{ok:!1}}if(K.isArrayExpression(e)){let t=[];for(let n of e.elements){let r=Br(n);if(!r.ok)return{ok:!1};t.push(r.value)}return{ok:!0,value:t}}if(K.isObjectExpression(e)){let t={};for(let n of e.properties){if(K.isSpreadElement(n)){let i=Br(n.argument);if(!i.ok||!cv(i.value))return{ok:!1};Object.assign(t,i.value);continue}if(!K.isObjectProperty(n)||n.computed)return{ok:!1};let r=vl(n.key);if(!r)return{ok:!1};let o=Br(n.value);if(!o.ok)return{ok:!1};t[r]=o.value}return{ok:!0,value:t}}return{ok:!1}}function cj(e){if(e.children.length===0)return{ok:!0,value:void 0};let t=[];for(let n of K.react.buildChildren(e)){let r=Br(n);if(!r.ok)return{ok:!1,message:"Portable invocation cannot preserve dynamic JSX children."};t.push(r.value)}return t.length===0?{ok:!0,value:void 0}:{ok:!0,value:t.length===1?t[0]:t}}function kl(e,t,n){let r=om(e)?new Set([...t,...lj(e)]):t;n(e,{names:r});for(let o of Object.values(e))if(Array.isArray(o))for(let i of o)_l(i)&&kl(i,r,n);else _l(o)&&kl(o,r,n)}function lj(e){if(!om(e))return[];let t=[];for(let n of e.params)As(n,t);return t}function As(e,t){if(K.isIdentifier(e)){t.push(e.name);return}if(K.isAssignmentPattern(e)){As(e.left,t);return}if(K.isObjectPattern(e)){for(let n of e.properties)K.isRestElement(n)?As(n.argument,t):K.isObjectProperty(n)&&As(n.value,t);return}if(K.isArrayPattern(e))for(let n of e.elements)n&&As(n,t)}function rv(e,t){return K.isIdentifier(e)?e.name==="searchParams"&&t.names.has(e.name):K.isMemberExpression(e)&&!e.computed&&K.isIdentifier(e.property)&&e.property.name==="searchParams"&&K.isIdentifier(e.object)&&t.names.has(e.object.name)}function nm(e){return{kind:"json-literal",value:e}}function cv(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ov(e){return/^[A-Za-z][A-Za-z0-9_]{0,127}$/u.test(e)}function lv(e){if(K.isJSXIdentifier(e))return e.name;if(!K.isJSXMemberExpression(e))return null;let t=rm(e.object);return t?`${t}.${e.property.name}`:null}function rm(e){if(K.isJSXIdentifier(e))return e.name;if(!K.isJSXMemberExpression(e))return null;let t=rm(e.object);return t?`${t}.${e.property.name}`:null}function uj(e,t){if(K.isJSXIdentifier(e))return t.get(e.name)??null;if(!K.isJSXMemberExpression(e))return null;let n=rm(e.object);if(!n)return null;let r=t.get(n);return!r||r.export_name!=="*"?null:{source:r.source,export_name:e.property.name,local_name:`${n}.${e.property.name}`}}function dj(e){return K.isJSXIdentifier(e)?e.name:K.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function vl(e){return K.isIdentifier(e)?e.name:K.isStringLiteral(e)||K.isNumericLiteral(e)?String(e.value):null}function om(e){return K.isFunctionDeclaration(e)||K.isFunctionExpression(e)||K.isArrowFunctionExpression(e)}function _l(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}function fj(e){return{start_offset:e.start??0,end_offset:e.end??e.start??0,start_line:e.loc?.start.line??1,start_column:e.loc?.start.column??0,end_line:e.loc?.end.line??e.loc?.start.line??1,end_column:e.loc?.end.column??e.loc?.start.column??0}}function im(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function Ts(e,t){return e.path.localeCompare(t.path)||e.code.localeCompare(t.code)||e.message.localeCompare(t.message)}var gj=typeof am=="function"?am:am.default,cm=class extends Map{constructor(t){super(),this.files=t,this.failures=new Map}read(t){let n=super.get(t);if(n)return{ok:!0,module:n};let r=this.failures.get(t);if(r)return{ok:!1,missing:!1,message:r};let o=Rl(this.files,t);if(o===null)return{ok:!1,missing:!0,message:"A re-exported source is missing or is not valid UTF-8 text."};let i=je(t,o);return i.ok?(super.set(t,i.module),{ok:!0,module:i.module}):(this.failures.set(t,i.diagnostic.message),{ok:!1,missing:!1,message:i.diagnostic.message})}get(t){let n=this.read(t);return n.ok?n.module:void 0}has(t){return super.has(t)||this.files.has(t)}};function pm(e){let{binding:t,files:n}=e;if(e.hostCapabilities!==null&&!pj.safeParse(e.hostCapabilities).success)return ct("INVOCATION_VALUE_UNRESOLVED","generated-site-capabilities","Trusted host capabilities failed their strict schema.");if(!ws(t.descriptor.source.file)||!ws(t.ownerFile))return ct("INVOCATION_TARGET_NOT_RENDERED",t.descriptor.source.file,"The resolved block source path is not a safe Snapshot source path.");let r=Rl(n,t.descriptor.source.file),o=Rl(n,t.ownerFile);if(r===null||o===null)return ct("INVOCATION_TARGET_NOT_RENDERED",r===null?t.descriptor.source.file:t.ownerFile,"The resolved block or owner source is missing or is not valid UTF-8 text.");if(ke(r)!==t.descriptor.source.contentHash||ke(r)!==t.sourceHash||ke(o)!==t.ownerSourceHash)return ct("INVOCATION_TARGET_NOT_RENDERED",t.descriptor.source.file,"The pinned block or owner source hash no longer matches the resolved binding.");let i=je(t.descriptor.source.file,r);if(!i.ok)return ct("INVOCATION_PARSE_FAILED",t.descriptor.source.file,i.diagnostic.message);let s=Nl(i.module.ast,t.rootLocator.sourceRange);if(s.length!==1)return ct("INVOCATION_TARGET_AMBIGUOUS",t.descriptor.source.file,"The selected block source range does not identify exactly one JSX element.");let a=s[0],c=fv(a.node);if(!c)return ct("INVOCATION_TARGET_NOT_RENDERED",t.descriptor.source.file,"The selected JSX element has no complete source range.");let l=[],u=t.root.callChain,d=new cm(n),f=hj(e,c,d);if(f)return f;if(u.some(y=>(y.alternativeLocators?.length??0)>1))return ct("INVOCATION_TARGET_NOT_RENDERED",t.descriptor.source.file,"The conditional invocation has no single statically proven props binding.");for(let[y,x]of u.entries()){let S=Rl(n,x.sourceFile);if(S===null||!ws(x.sourceFile))return ct("INVOCATION_TARGET_NOT_RENDERED",x.sourceFile,"A statically proven call-chain source is missing from the fixed Snapshot map.");let b=je(x.sourceFile,S);if(!b.ok)return ct("INVOCATION_PARSE_FAILED",x.sourceFile,b.diagnostic.message);let E=Nl(b.module.ast,x.callLocator.sourceRange);if(E.length!==1)return ct("INVOCATION_TARGET_AMBIGUOUS",x.sourceFile,"A call-chain locator does not identify exactly one current JSX element.");let k=u[y+1]?.sourceFile??t.descriptor.source.file,I=u[y+1]?.callLocator.sourceRange??t.rootLocator.sourceRange,v=gr({module:b.module,componentName:x.component,callSourceRange:x.callLocator.sourceRange});if(v.ok){if(v.sourceFile!==k)return ct("INVOCATION_TARGET_NOT_RENDERED",x.sourceFile,"The selected local component does not resolve to the source definition proven by the block graph.");if(v.roots.filter(fe=>ci(fe.node,I)).length!==1)return ct("INVOCATION_TARGET_NOT_RENDERED",v.sourceFile,"The local component definition does not select exactly one proven JSX root.");let M=iv({file_path:x.sourceFile,source:S,target:{kind:"local",local_name:x.component},call_source_range:{start_line:x.callLocator.sourceRange.startLine,start_column:x.callLocator.sourceRange.startColumn}});if(!M.call||!M.complete)return{complete:!1,errors:M.errors.length>0?M.errors:[{code:"INVOCATION_TARGET_NOT_RENDERED",path:x.sourceFile,message:"The selected local call did not produce a complete invocation binding."}]};l.push({kind:"local",call:M.call,invocation:M,definition:v,entryExport:null});continue}let N=lm(b.module.ast,E[0].node.openingElement.name,x.component,x.exportName);if(!N)return ct("INVOCATION_TARGET_NOT_RENDERED",x.sourceFile,"The statically proven component call no longer resolves through one exact import.");let A=um(x.sourceFile,N.source,n);if(!A)return ct("INVOCATION_TARGET_NOT_RENDERED",x.sourceFile,"The selected component import is not a resolvable local Snapshot source.");let w=d.read(A);if(!w.ok)return ct(w.missing?"INVOCATION_TARGET_NOT_RENDERED":"INVOCATION_PARSE_FAILED",A,w.message);let F=hn({module:w.module,exportName:N.exportName,parsedModules:d});if(!F.ok)return ct("INVOCATION_TARGET_NOT_RENDERED",F.diagnostic.file,F.diagnostic.message);if(F.sourceFile!==k)return ct("INVOCATION_TARGET_NOT_RENDERED",x.sourceFile,"The selected component import does not resolve to the source definition proven by the block graph.");let B=F.roots.filter(G=>ci(G.node,I));if(B.length!==1)return ct("INVOCATION_TARGET_NOT_RENDERED",F.sourceFile,"The unique component export does not select exactly one proven JSX root.");let X=null;if(y===u.length-1&&u.length===1&&!mv(t.ownerFile)&&ci(B[0].node,t.rootLocator.sourceRange)){let G=d.read(F.sourceFile);if(!G.ok)return ct(G.missing?"INVOCATION_TARGET_NOT_RENDERED":"INVOCATION_PARSE_FAILED",F.sourceFile,G.message);if(X=dv(G.module,F.componentName,N.exportName),!X)return ct("INVOCATION_TARGET_AMBIGUOUS",F.sourceFile,"The proven component definition has no unique final export for a Portable entry.")}let $=ai({file_path:x.sourceFile,source:S,target:{source:N.source,export_name:N.exportName,local_name:N.localName},call_source_range:{start_line:x.callLocator.sourceRange.startLine,start_column:x.callLocator.sourceRange.startColumn}});if(!$.call||!$.complete)return{complete:!1,errors:$.errors.length>0?$.errors:[{code:"INVOCATION_TARGET_NOT_RENDERED",path:x.sourceFile,message:"The selected call did not produce a complete invocation binding."}]};l.push({kind:"import",call:$.call,invocation:$,definition:F,entryExport:X})}let g={kind:"page-block",composition:pv(t.composition),blockKey:t.blockKey},p=yj(t,a,l,n,e.hostCapabilities);if(!p.ok)return{complete:!1,errors:[p.error]};let m=l[0]?.invocation??null;return{complete:!0,selection:{target:g,root_ref:t.root.rootRef,source_file:t.descriptor.source.file,structural_path:t.descriptor.source.structuralPath,content_hash:t.descriptor.source.contentHash,source_range:c,owner:t.descriptor.owner,call_chain:l.map(({call:y})=>y),strategy:p.strategy,entry_file:p.entryFile,entry_export:p.entryExport,invocation:m}}}function hj(e,t,n){let{binding:r,files:o}=e,i=r.root.callChain;if(i.length!==2)return null;let[s,a]=i;if(!s||!a||(s.alternativeLocators?.length??0)>1)return null;let c=n.get(s.sourceFile);if(!c)return null;let l=Nl(c.ast,s.callLocator.sourceRange);if(l.length!==1)return null;let u=lm(c.ast,l[0].node.openingElement.name,s.component,s.exportName);if(!u)return null;let d=um(s.sourceFile,u.source,o),f=d?n.get(d):void 0;if(!f)return null;let g=hn({module:f,exportName:u.exportName,parsedModules:n});if(!g.ok||g.sourceFile!==a.sourceFile)return null;let p=n.get(g.sourceFile);if(!p||dv(p,g.componentName,"default")?.kind!=="default")return null;let m=qp({files:o,list_entry_file:s.sourceFile,selected_component_source:`@/${g.sourceFile.replace(/\.[cm]?[jt]sx?$/u,"")}`});if(!m.complete||!m.relation)return null;let y=a.alternativeLocators?.length?a.alternativeLocators:[a.callLocator],x=g.returnAlternatives?.length?g.returnAlternatives:g.roots;if(x.length!==y.length||!x.every(k=>y.filter(I=>ci(k.node,I.sourceRange)).length===1))return null;for(let k of y){let I=Nl(p.ast,k.sourceRange);if(I.length!==1)return null;let v=lm(p.ast,I[0].node.openingElement.name,a.component,a.exportName);if(!v)return null;let N=um(g.sourceFile,v.source,o),A=N?n.get(N):void 0;if(!A)return null;let w=hn({module:A,exportName:v.exportName,parsedModules:n});if(!w.ok||w.sourceFile!==r.descriptor.source.file||w.roots.length!==1||!ci(w.roots[0].node,r.rootLocator.sourceRange))return null}let S=ai({file_path:s.sourceFile,source:c.source,target:{source:u.source,export_name:u.exportName,local_name:u.localName},call_source_range:{start_line:s.callLocator.sourceRange.startLine,start_column:s.callLocator.sourceRange.startColumn}});if(!S.complete||!S.call)return{complete:!1,errors:S.errors};let E=`components/site/portable/${uv("sha256").update(JSON.stringify(["collection-container",r.composition,r.blockKey,r.sourceHash,ke(p.source)])).digest("hex").slice(0,24)}/page.tsx`;return o.has(E)?ct("INVOCATION_TARGET_AMBIGUOUS",E,"The isolated collection entry collides with a pinned Snapshot source."):{complete:!0,selection:{target:{kind:"page-block",composition:pv(r.composition),blockKey:r.blockKey},root_ref:r.root.rootRef,source_file:r.descriptor.source.file,structural_path:r.descriptor.source.structuralPath,content_hash:r.descriptor.source.contentHash,source_range:t,owner:r.descriptor.owner,call_chain:[S.call],strategy:"collection-container",collection_container_file:g.sourceFile,entry_file:E,entry_export:{kind:"default"},invocation:S}}}function yj(e,t,n,r,o){let i=n.at(-1);if(i?.kind==="import"){let l=i.definition.roots.length===1&&ci(i.definition.roots[0].node,e.rootLocator.sourceRange),u=mv(e.ownerFile);if(n.length===1&&l&&u)return{ok:!0,strategy:"managed-thin-entry",entryFile:e.ownerFile,entryExport:{kind:"default"}};if(n.length===1&&l&&i.entryExport)return{ok:!0,strategy:"reuse-entry",entryFile:i.definition.sourceFile,entryExport:i.entryExport}}if(!fv(t.node))return{ok:!1,error:{code:"INVOCATION_TARGET_NOT_RENDERED",path:e.descriptor.source.file,message:"Cannot derive a portable entry identity without an exact root range."}};let c=`components/site/portable/${uv("sha256").update(JSON.stringify([e.composition,e.blockKey,e.descriptor.source.file,e.descriptor.source.structuralPath,e.descriptor.source.contentHash,o?.host_contract_digest??null])).digest("hex").slice(0,24)}/page.tsx`;return!ws(c)||r.has(c)?{ok:!1,error:{code:"INVOCATION_TARGET_AMBIGUOUS",path:c,message:"The deterministic in-memory Portable entry path collides with an existing Snapshot file."}}:{ok:!0,strategy:"extract-jsx",entryFile:c,entryExport:{kind:"default"}}}function dv(e,t,n){let r=new Set;for(let i of e.ast.program.body){if(ze.isExportDefaultDeclaration(i)){let s=i.declaration;(ze.isFunctionDeclaration(s)&&(s.id?.name===t||t==="default")||ze.isIdentifier(s)&&s.name===t)&&r.add("default");continue}if(!(!ze.isExportNamedDeclaration(i)||i.exportKind==="type")){if(i.declaration){let s=xj(i.declaration,t);s&&r.add(s)}if(!i.source)for(let s of i.specifiers)ze.isExportSpecifier(s)&&s.exportKind!=="type"&&fm(s.local)===t&&r.add(fm(s.exported))}}if(r.size===0)return null;let o=r.has(n)?n:r.size===1?r.values().next().value:r.has("default")?"default":null;return o?o==="default"?{kind:"default"}:{kind:"named",name:o}:null}function xj(e,t){return ze.isFunctionDeclaration(e)?e.id?.name===t?t:null:ze.isVariableDeclaration(e)&&e.declarations.some(n=>ze.isIdentifier(n.id)&&n.id.name===t)?t:null}function lm(e,t,n,r){let o=dm(t);if(!o||o!==n)return null;let i=ze.isJSXMemberExpression(t)?dm(t.object):ze.isJSXNamespacedName(t)?t.namespace.name:o,s=ze.isJSXMemberExpression(t)?t.property.name:null;for(let a of e.program.body)if(ze.isImportDeclaration(a))for(let c of a.specifiers){if(ze.isImportDefaultSpecifier(c)&&c.local.name===i)return r==="default"&&!s?{source:a.source.value,exportName:"default",localName:o}:null;if(ze.isImportSpecifier(c)&&c.local.name===i){let l=fm(c.imported);return l===r&&!s?{source:a.source.value,exportName:l,localName:o}:null}if(ze.isImportNamespaceSpecifier(c)&&c.local.name===i&&s)return s===r?{source:a.source.value,exportName:s,localName:o}:null}return null}function Nl(e,t){let n=[];return gj(e,{JSXElement(r){let o=r.node.loc;o&&o.start.line===t.startLine&&o.start.column===t.startColumn&&o.end.line===t.endLine&&o.end.column===t.endColumn&&n.push(r)}}),n}function fv(e){let t=e.loc;return typeof e.start!="number"||typeof e.end!="number"||!t?null:{start_offset:e.start,end_offset:e.end,start_line:t.start.line,start_column:t.start.column,end_line:t.end.line,end_column:t.end.column}}function ci(e,t){let n=e.loc;return!!(n&&n.start.line===t.startLine&&n.start.column===t.startColumn&&n.end.line===t.endLine&&n.end.column===t.endColumn)}function Rl(e,t){let n=e.get(t);if(typeof n=="string")return n;if(!(n instanceof Uint8Array))return null;try{return new TextDecoder("utf-8",{fatal:!0}).decode(n)}catch{return null}}function um(e,t,n){let r=t.startsWith("@/")?t.slice(2):t.startsWith("./")||t.startsWith("../")?sm.posix.normalize(sm.posix.join(sm.posix.dirname(e),t)):null;return!r||r===".."||r.startsWith("../")||r.startsWith("/")?null:(/\.(?:[cm]?[jt]sx?)$/u.test(r)?[r]:[".tsx",".ts",".jsx",".js",".mts",".cts"].map(i=>`${r}${i}`).concat([".tsx",".ts",".jsx",".js",".mts",".cts"].map(i=>`${r}/index${i}`))).find(i=>ws(i)&&n.has(i))??null}function dm(e){if(ze.isJSXIdentifier(e))return e.name;if(ze.isJSXMemberExpression(e)){let t=dm(e.object);return t?`${t}.${e.property.name}`:null}return null}function fm(e){return ze.isIdentifier(e)?e.name:e.value}function pv(e){return{routeId:e.routeId,...e.effectiveTemplateId!==void 0?{templateId:e.effectiveTemplateId}:{}}}function ws(e){return mj.safeParse(e).success}function mv(e){return/(?:^|\/)\.vcp\/page-templates\//u.test(e)}function ct(e,t,n){return{complete:!1,errors:[{code:e,path:t,message:n}]}}import mm from"@babel/traverse";import*as Pe from"@babel/types";var bj=typeof mm=="function"?mm:mm.default,gv=256,hv=16;function xv(e){let t=[],n=new Map,r=new Map,o=new Set,i=new Set,s=0;class a extends Map{constructor(){super(...arguments),this.attempted=new Set}has(E){return e.files.has(E)}get(E){let k=super.get(E);if(k||this.attempted.has(E))return k;this.attempted.add(E);let I=e.files.get(E),v;try{if(typeof I=="string")v=I;else if(I instanceof Uint8Array)v=new TextDecoder("utf-8",{fatal:!0}).decode(I);else return}catch{return}let N=je(E,v);if(N.ok)return super.set(E,N.module),r.set(N.module.ast.program,N.module),N.module}}let c=new a;function l(b,E,k,I){let v=I?.loc?.start;t.push({code:b,source_path:E,message:k,...v?{call_site:{line:v.line,column:v.column}}:{}})}function u(b){if(!o.has(b.file)){if(o.size>=gv){l("CMS_MODULE_BUDGET_EXHAUSTED",b.file,"The module analysis budget was exhausted.");return}o.add(b.file);for(let E of b.ast.program.body){let k=null;if(Pe.isImportDeclaration(E)&&E.importKind!=="type"){if(E.specifiers.length&&E.specifiers.every(N=>Pe.isImportSpecifier(N)&&N.importKind==="type"))continue;k=E.source.value}else if(Pe.isExportNamedDeclaration(E)&&E.source&&E.exportKind!=="type"){if(E.specifiers.length&&E.specifiers.every(N=>Pe.isExportSpecifier(N)&&N.exportKind==="type"))continue;k=E.source.value}else Pe.isExportAllDeclaration(E)&&E.exportKind!=="type"&&(k=E.source.value);if(!k)continue;if(!nt(k)){l("CMS_EXTERNAL_MODULE_UNRESOLVED",b.file,"An external module's initialization effects cannot be proven safe.",E);continue}let I=Dr(b.file,k,e.files);if(!I){l("CMS_IMPORT_UNRESOLVED",b.file,`The local import ${k} is unavailable.`,E);continue}if(!/\.[cm]?[jt]sx?$/iu.test(I)||yv(I))continue;let v=c.get(I);v?u(v):l("CMS_SOURCE_UNAVAILABLE",I,"The imported source cannot be parsed.",E)}bj(b.ast,{Program(E){d(E,b,new Map),E.stop()}})}}function d(b,E,k){b.traverse({Function(I){(I.isObjectMethod()||I.isClassMethod()||I.isClassPrivateMethod())&&I.node.computed&&!jr(I.get("key"),k)&&l("CMS_IMPLICIT_EXECUTION_UNRESOLVED",E.file,"A computed method key may execute an unproven coercion.",I.node),I.skip()},BinaryExpression(I){(I.node.operator==="instanceof"||I.node.operator==="in"||I.node.operator!=="==="&&I.node.operator!=="!=="&&(!jr(I.get("left"),k)||!jr(I.get("right"),k)))&&l("CMS_IMPLICIT_EXECUTION_UNRESOLVED",E.file,"An operator may execute an unproven coercion or proxy trap.",I.node)},TemplateLiteral(I){I.get("expressions").some(v=>!jr(v,k))&&l("CMS_IMPLICIT_EXECUTION_UNRESOLVED",E.file,"Template interpolation may execute an unproven coercion.",I.node)},UnaryExpression(I){["+","-","~"].includes(I.node.operator)&&!jr(I.get("argument"),k)&&l("CMS_IMPLICIT_EXECUTION_UNRESOLVED",E.file,"A unary operator may execute an unproven coercion.",I.node)},UpdateExpression(I){l("CMS_IMPLICIT_EXECUTION_UNRESOLVED",E.file,"An update may execute an unproven coercion or proxy trap.",I.node)},ObjectProperty(I){I.node.computed&&!jr(I.get("key"),k)&&l("CMS_IMPLICIT_EXECUTION_UNRESOLVED",E.file,"A computed property key may execute an unproven coercion.",I.node)},ForInStatement(I){l("CMS_IMPLICIT_EXECUTION_UNRESOLVED",E.file,"Property enumeration may execute an unproven proxy trap.",I.node)},JSXOpeningElement(I){let v=I.node.name;if(Pe.isJSXIdentifier(v)&&/^[a-z]/u.test(v.name))return;if(Ej(I)){l("CMS_COMPONENT_REACHABILITY_UNPROVEN",E.file,"A component value is not proven to be rendered by the selected root.",I.node);return}if(!Pe.isJSXIdentifier(v)){l("CMS_COMPONENT_UNRESOLVED",E.file,"A dynamic or namespace component target is not proven.",I.node);return}let N=p(I.scope.getBinding(v.name),E);if(!N){l("CMS_COMPONENT_UNRESOLVED",E.file,"A rendered component target is not proven.",I.node);return}g(N,f(N,I,k))},JSXExpressionContainer(I){let v=I.get("expression");if(v.isFunctionExpression()||v.isArrowFunctionExpression())g(v,k);else if(v.isIdentifier()){let N=p(v.scope.getBinding(v.node.name),E);N?g(N,k):I.parentPath?.isJSXAttribute()&&Pe.isJSXIdentifier(I.parentPath.node.name)&&/^on[A-Z]/u.test(I.parentPath.node.name.name)&&l("CMS_CALL_TARGET_UNRESOLVED",E.file,"An event handler target cannot be proven.",v.node)}},MemberExpression(I){let v=I.parentPath;v?.isMemberExpression()&&v.node.object===I.node||(v?.isCallExpression()||v?.isOptionalCallExpression())&&v.node.callee===I.node||v?.isVariableDeclarator()&&v.node.init===I.node&&m(I,E,new Set)||l("CMS_PROPERTY_ACCESS_UNRESOLVED",E.file,"A property read may invoke an unproven getter or proxy.",I.node)},OptionalMemberExpression(I){l("CMS_PROPERTY_ACCESS_UNRESOLVED",E.file,"An optional property read may invoke an unproven getter or proxy.",I.node)},VariableDeclarator(I){(Pe.isObjectPattern(I.node.id)||Pe.isArrayPattern(I.node.id))&&l("CMS_DESTRUCTURING_UNRESOLVED",E.file,"Destructuring can invoke an unproven getter or iterator.",I.node)},ForOfStatement(I){l("CMS_ITERATION_UNRESOLVED",E.file,"An iterable may invoke an unproven iterator.",I.node)},SpreadElement(I){l("CMS_ITERATION_UNRESOLVED",E.file,"A spread may invoke an unproven iterator or getter.",I.node)},JSXSpreadAttribute(I){l("CMS_PROPERTY_ACCESS_UNRESOLVED",E.file,"A JSX spread may invoke an unproven getter or proxy.",I.node)},CallExpression(I){if(Pe.isImport(I.node.callee)){l("CMS_DYNAMIC_IMPORT_UNRESOLVED",E.file,"A dynamic import cannot prove the selected call closure.",I.node);return}for(let A of I.get("arguments"))(A.isFunctionExpression()||A.isArrowFunctionExpression())&&g(A,new Map);let v=I.get("callee"),N=m(v,E,new Set);if(N){if(Nr(E.ast,N.originalName)){l("CMS_BINDING_MUTATED",E.file,"The trusted CMS binding or one of its aliases is modified.",I.node);return}let w=I.get("arguments")[0],F=w?qt(w,k,new Set):null;if(!F||F.length===0){l("CMS_IDENTITY_UNRESOLVED",E.file,"The CMS application identity is not statically bounded.",I.node);return}let B=Sj(N.name);for(let X of F){let $=Ac(Pe.callExpression(B,[Pe.stringLiteral(X)]),{file:E.file,imports:new Map([["__vcpCms",{source:N.source,importedName:N.importedName}]])}),M=$?.operation==="getByUrl"||$?.operation==="getByUrlStrict"?/^\/([a-z0-9][a-z0-9_-]*)\/[a-z0-9][a-z0-9._~-]*$/iu.exec(X)?.[1]:$?.collection;if(!$||$.sourceKind!=="vcp-cms-collection"||!M||!/^[a-z0-9][a-z0-9_-]*$/iu.test(M)){l("CMS_OPERATION_UNRESOLVED",E.file,"The CMS operation or application identity cannot be proven.",I.node);continue}let fe=I.node.loc?.start;if(!fe){l("CMS_CALL_SITE_UNAVAILABLE",E.file,"The CMS call has no source location.",I.node);continue}let Fe={source_path:E.file,operation:$.operation,binding:"trusted-cms",call_site:{line:fe.line,column:fe.column}},ot=n.get(M)??[];ot.some(Tt=>JSON.stringify(Tt)===JSON.stringify(Fe))||ot.push(Fe),n.set(M,ot)}return}if(v.isIdentifier()){let A=v.scope.getBinding(v.node.name),w=p(A,E);if(w){let F=new Map,B=w.get("params");for(let[X,$]of B.entries()){if(!$.isIdentifier())continue;let G=w.scope.getBinding($.node.name),M=I.get("arguments")[X];G&&F.set(G.identifier,M?qt(M,k,new Set):null)}g(w,F);return}if(!A&&v.node.name==="Boolean"||!A&&["String","Number"].includes(v.node.name)&&I.get("arguments").every(F=>jr(F,k)))return}Ij(I,k,A=>!!m(A,E,new Set))||l("CMS_CALL_TARGET_UNRESOLVED",E.file,"A reachable call target cannot be proven free of hidden CMS access.",I.node)},OptionalCallExpression(I){l("CMS_CALL_TARGET_UNRESOLVED",E.file,"An optional call target cannot be proven.",I.node)},NewExpression(I){l("CMS_CALL_TARGET_UNRESOLVED",E.file,"A constructor's effects cannot be proven.",I.node)},TaggedTemplateExpression(I){l("CMS_CALL_TARGET_UNRESOLVED",E.file,"A tagged template's effects cannot be proven.",I.node)}})}function f(b,E,k){let I=new Map,v=b.get("params")[0];if(!v?.isObjectPattern())return I;let N=E.get("attributes"),A=N.some(w=>w.isJSXSpreadAttribute());for(let w of v.get("properties")){if(!w.isObjectProperty()||w.node.computed)continue;let F=w.node.key,B=Pe.isIdentifier(F)?F.name:Pe.isStringLiteral(F)?F.value:null,X=w.get("value"),$=X.isIdentifier()?X:X.isAssignmentPattern()&&X.get("left").isIdentifier()?X.get("left"):null;if(!B||!$?.isIdentifier())continue;let G=b.scope.getBinding($.node.name);if(!G)continue;let M=N.filter(ot=>ot.isJSXAttribute()&&Pe.isJSXIdentifier(ot.node.name,{name:B})),fe=null,Fe=M[0];if(!A&&M.length===1&&Fe?.isJSXAttribute()){let ot=Fe.get("value");ot.isStringLiteral()?fe=[ot.node.value]:ot.isJSXExpressionContainer()&&(fe=qt(ot.get("expression"),k,new Set))}I.set(G.identifier,fe)}return I}function g(b,E){let k=b.findParent(v=>v.isProgram()),I=k&&Pe.isProgram(k.node)?r.get(k.node):void 0;if(!I){l("CMS_FUNCTION_UNRESOLVED",e.entry_file,"A callable has no proven source module.",b.node);return}if(i.has(b.node)||s++>=gv){l("CMS_CALL_BUDGET_EXHAUSTED",I.file,"Recursive or excessive reachable calls are not proven.",b.node);return}i.add(b.node),d(b,I,E),i.delete(b.node)}function p(b,E){if(!b||b.constantViolations.length)return null;let k=b.path;if(k.isFunctionDeclaration())return k;if(k.isVariableDeclarator()){let B=k.get("init");return B.isFunctionExpression()||B.isArrowFunctionExpression()?B:null}let I=k.parentPath;if(!I?.isImportDeclaration()||I.node.importKind==="type")return null;let v=I.node.source.value;if(!nt(v))return null;let N=Dr(E.file,v,e.files),A=N&&c.get(N),w=k.isImportDefaultSpecifier()?"default":k.isImportSpecifier()&&Pe.isIdentifier(k.node.imported)?k.node.imported.name:null;if(!A||!w)return null;let F=br(A,w,c);return F&&(F.isFunctionDeclaration()||F.isFunctionExpression()||F.isArrowFunctionExpression())?F:null}function m(b,E,k){if(!b.node||k.has(b.node)||k.size>=32)return null;if(k.add(b.node),b.isMemberExpression()&&!b.node.optional){let F=!b.node.computed&&Pe.isIdentifier(b.node.property)?b.node.property.name:b.node.computed&&Pe.isStringLiteral(b.node.property)?b.node.property.value:null,B=m(b.get("object"),E,k);return B&&F?{...B,name:`${B.name}.${F}`}:null}if(!b.isIdentifier())return null;let I=b.scope.getBinding(b.node.name);if(!I||I.constantViolations.length)return null;if(I.path.isVariableDeclarator())return m(I.path.get("init"),E,k);let v=I.path.parentPath;if(!v?.isImportDeclaration()||!I.path.isImportSpecifier())return null;let N=I.path.node.imported,A=Pe.isIdentifier(N)?N.name:N.value,w=Dr(E.file,v.node.source.value,e.files);return!w||!yv(w)||!["cms","collections","cmsFetch","cmsFetchResult","cmsFetchEnvelope"].includes(A)?null:{name:"__vcpCms",source:w,importedName:A,originalName:I.identifier.name}}let y=c.get(e.entry_file);if(!y)l("CMS_ENTRY_UNAVAILABLE",e.entry_file,"The selected entry is missing or invalid.");else{u(y);let b=br(y,e.entry_export.kind==="default"?"default":e.entry_export.name,c);!b||!(b.isFunctionDeclaration()||b.isFunctionExpression()||b.isArrowFunctionExpression())?l("CMS_ENTRY_UNRESOLVED",e.entry_file,"The selected entry export is not one proven function."):g(b,new Map)}let x=[...n.entries()].sort(([b],[E])=>b.localeCompare(E)).map(([b,E])=>({requirement_key:`cms-${b}`,slug:b,evidence:E.sort((k,I)=>k.source_path.localeCompare(I.source_path)||k.call_site.line-I.call_site.line||k.call_site.column-I.call_site.column)})),S=[...new Map(t.map(b=>[JSON.stringify(b),b])).values()];return{complete:S.length===0,dependencies:x,unresolved:S}}function yv(e){return/^(?:src\/)?lib\/cms(?:\/index|\/collections|\/client)?\.[cm]?[jt]s$/u.test(e)}function Ej(e){let t=e.parentPath?.parentPath;for(;t&&!t.isFunction()&&!t.isProgram();){if(t.isVariableDeclarator()||t.isJSXAttribute())return!0;if(t.isJSXElement()){let n=t.node.openingElement.name;if(!Pe.isJSXIdentifier(n)||!/^[a-z]/u.test(n.name))return!0}t=t.parentPath}return!1}function Sj(e){let[t,...n]=e.split(".");return n.reduce((r,o)=>Pe.memberExpression(r,Pe.identifier(o)),Pe.identifier(t))}function Ij(e,t,n){let r=e.node.callee;if(!(Pe.isMemberExpression(r)&&!r.computed&&Pe.isIdentifier(r.object,{name:"Promise"})&&!e.scope.getBinding("Promise")&&Pe.isIdentifier(r.property,{name:"all"})))return!1;let o=e.get("arguments")[0];return o?.isArrayExpression()?o.get("elements").every(i=>!i.node||jr(i,t)||i.isCallExpression()&&n(i.get("callee"))):!1}function jr(e,t){return e.isStringLiteral()||e.isNumericLiteral()||e.isBooleanLiteral()||e.isNullLiteral()||qt(e,t,new Set)!==null}function qt(e,t,n){if(!e.node||n.has(e.node)||n.size>=32)return null;let r=new Set(n).add(e.node);if(e.isStringLiteral())return[e.node.value];if(e.isIdentifier()){let o=e.scope.getBinding(e.node.name);return!o||o.constantViolations.length?null:t.has(o.identifier)?t.get(o.identifier)??null:o.path.isVariableDeclarator()&&o.path.parentPath.isVariableDeclaration({kind:"const"})?qt(o.path.get("init"),t,r):null}if(e.isTSAsExpression()||e.isTSSatisfiesExpression()||e.isTSNonNullExpression()||e.isParenthesizedExpression())return qt(e.get("expression"),t,r);if(e.isConditionalExpression()){let o=qt(e.get("consequent"),t,r),i=qt(e.get("alternate"),t,r);if(!o||!i)return null;let s=[...new Set([...o,...i])];return s.length<=hv?s:null}if(e.isBinaryExpression({operator:"+"})){let o=qt(e.get("left"),t,r),i=qt(e.get("right"),t,r);return!o||!i||o.length*i.length>hv?null:[...new Set(o.flatMap(s=>i.map(a=>s+a)))]}return null}import gm from"@babel/generator";import hm from"@babel/traverse";import*as oe from"@babel/types";var bv=typeof hm=="function"?hm:hm.default,vj=typeof gm=="function"?gm:gm.default;function Sv(e){let t=new Map(e.files),n=new Set(e.private_paths),r=[];for(let o of e.private_paths){let i=vv(t.get(o));if(i===null||!/\.[jt]sx?$/iu.test(o))continue;let s=je(o,i);if(!s.ok){r.push({code:"SOURCE_PARSE_FAILED",path:o,message:s.diagnostic.message});continue}let a=!1;bv(s.module.ast,{Function:{exit(c){let l=c.get("body");l.isBlockStatement()&&(l.scope.crawl(),Ev(l)&&(a=!0))}}}),bv(s.module.ast,{Program(c){let l;do{c.scope.crawl(),l=Ev(c),l&&(a=!0),l&&c.scope.crawl();for(let d of c.get("body"))(d.isFunctionDeclaration()&&d.node.id&&!c.scope.getBinding(d.node.id.name)?.referenced||d.isVariableDeclaration({kind:"const"})&&d.node.declarations.every(f=>oe.isIdentifier(f.id)&&!c.scope.getBinding(f.id.name)?.referenced&&(!f.init||li(f.init))))&&(d.remove(),l=a=!0)}while(l);c.scope.crawl();let u=0;for(let d of c.node.body)oe.isExportDefaultDeclaration(d)?u+=1:oe.isExportAllDeclaration(d)&&d.exportKind!=="type"?u+=2:oe.isExportNamedDeclaration(d)&&d.exportKind!=="type"&&(d.declaration&&!oe.isTSInterfaceDeclaration(d.declaration)&&!oe.isTSTypeAliasDeclaration(d.declaration)&&(u+=Object.keys(oe.getOuterBindingIdentifiers(d.declaration)).length),u+=d.specifiers.filter(f=>!oe.isExportSpecifier(f)||f.exportKind!=="type").length);u>1&&r.push({code:"SOURCE_EXPORT_ISOLATION_UNPROVEN",path:o,message:"Multiple value exports cannot yet be isolated from unselected source."});for(let d of c.get("body")){if(!d.isImportDeclaration()||d.node.importKind==="type"||d.node.specifiers.length===0||!nt(d.node.source.value))continue;let f=Dr(o,d.node.source.value,t);if(!(!f||!n.has(f))&&!d.node.specifiers.some(g=>c.scope.getBinding(g.local.name)?.referenced)){if(!Iv(f,t,new Set)){r.push({code:"SOURCE_UNUSED_IMPORT_UNPROVEN",path:o,message:`The unused import ${d.node.source.value} may have initialization effects.`});continue}d.remove(),a=!0}}c.stop()}}),a&&t.set(o,vj(s.module.ast).code)}return{files:t,errors:r}}function Ev(e){let t=new Map;for(let c of e.get("body")){let l=null,u=null;if(c.isFunctionDeclaration()&&c.node.id)l=c.node.id.name,u=c.node;else if(c.isVariableDeclaration({kind:"const"})&&c.node.declarations.length===1){let f=c.node.declarations[0];oe.isIdentifier(f.id)&&(oe.isFunctionExpression(f.init)||oe.isArrowFunctionExpression(f.init))&&(l=f.id.name,u=f.init)}let d=l?e.scope.getBinding(l):void 0;l&&u&&d&&d.constantViolations.length===0&&t.set(l,{definition:u,declaration:c,binding:d})}let n=new Map([...t].map(([c,l])=>[l.definition,c])),r=new Set,o=new Map;for(let[c,l]of t)for(let u of l.binding.referencePaths){let d=u.findParent(g=>n.has(g.node)),f=d?n.get(d.node):void 0;if(!f)r.add(c);else{let g=o.get(f)??new Set;g.add(c),o.set(f,g)}}let i=new Set,s=[...r];for(;s.length;){let c=s.pop();i.has(c)||(i.add(c),s.push(...o.get(c)??[]))}let a=!1;for(let[c,l]of t)i.has(c)||(l.declaration.remove(),a=!0);return a}function Iv(e,t,n){if(n.has(e)||n.size>=64)return!1;let r=vv(t.get(e));if(r===null)return!1;let o=je(e,r);if(!o.ok)return!1;let i=new Set(n).add(e),s=a=>{if(!nt(a))return!1;let c=Dr(e,a,t);return c!==null&&Iv(c,t,i)};return o.module.ast.program.body.every(a=>oe.isImportDeclaration(a)?a.importKind==="type"||a.specifiers.length>0&&a.specifiers.every(c=>oe.isImportSpecifier(c)&&c.importKind==="type")?!0:s(a.source.value):oe.isExportAllDeclaration(a)?a.exportKind==="type"||s(a.source.value):oe.isExportNamedDeclaration(a)?a.exportKind==="type"?!0:a.source?s(a.source.value):a.declaration?ym(a.declaration):!0:oe.isExportDefaultDeclaration(a)?ym(a.declaration):ym(a))}function ym(e){return oe.isFunctionDeclaration(e)||oe.isTSInterfaceDeclaration(e)||oe.isTSTypeAliasDeclaration(e)||oe.isTSDeclareFunction(e)||oe.isEmptyStatement(e)?!0:oe.isVariableDeclaration(e)&&e.kind==="const"?e.declarations.every(t=>oe.isIdentifier(t.id)&&(!t.init||li(t.init))):li(e)}function li(e){return oe.isStringLiteral(e)||oe.isNumericLiteral(e)||oe.isBooleanLiteral(e)||oe.isNullLiteral(e)||oe.isFunctionExpression(e)||oe.isArrowFunctionExpression(e)?!0:oe.isArrayExpression(e)?e.elements.every(t=>t===null||!oe.isSpreadElement(t)&&li(t)):oe.isObjectExpression(e)?e.properties.every(t=>oe.isObjectProperty(t)&&!t.computed&&!t.shorthand&&li(t.value)):oe.isTSAsExpression(e)||oe.isTSSatisfiesExpression(e)||oe.isTSNonNullExpression(e)||oe.isParenthesizedExpression(e)?li(e.expression):!1}function vv(e){if(typeof e=="string")return e;if(!(e instanceof Uint8Array))return null;try{return new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch{return null}}import{createHash as kj}from"node:crypto";import _j from"@babel/traverse";import*as Be from"@babel/types";var xm=_j,Cj=typeof xm=="function"?xm:xm.default,Rj=new Set(["avif","bmp","gif","jpeg","jpg","mp3","mp4","ogg","png","svg","wav","webm","webp"]),ui=new Set(["backgroundimage","image","imageurl","media","mediaurl","poster","src","srcset","thumbnail","thumbnailurl"]),Nj=/(?:asset|avatar|gallery|image|media|photo|poster|thumbnail|video)/iu,Pj=/^(?:audio|img|image|picture|safeimage|source|video|media|.*(?:audio|image|video))$/iu;function bm(e){let t=je(e.file_path,e.source);if(!t.ok)return{complete:!1,references:[],errors:[{code:"MEDIA_SOURCE_PARSE_FAILED",file_path:e.file_path,message:t.diagnostic.message}]};let n=[],r=[],o=new Set,i=c=>{let l=_v(c.node),u=Dj(e.source,l),d=`${l.start_offset}:${l.end_offset}:${c.kind}:${c.value??"<unknown>"}`;o.has(d)||(o.add(d),n.push({file_path:e.file_path,occurrence:n.length,kind:c.kind,source:c.source,value:c.value,expression:u,asset_key:c.assetKey??null,source_range:l,content_digest:Mj(u),complete:c.complete}),c.complete||r.push({code:"MEDIA_VALUE_UNKNOWN",file_path:e.file_path,message:"The media expression cannot be resolved without executing user code.",source_range:l}))},s=(c,l)=>{if(!l){i({node:c,kind:"manifest",source:"media-manifest",value:null,complete:!1});return}let u=e.media_manifest?.[l];if(u===void 0){let d=_v(c);r.push({code:"MEDIA_MANIFEST_KEY_UNKNOWN",file_path:e.file_path,message:`The media manifest key ${l} is not available in the supplied snapshot.`,source_range:d})}i({node:c,kind:"manifest",source:"media-manifest",value:u??null,assetKey:l,complete:u!==void 0})};Cj(t.module.ast,{ImportDeclaration(c){let l=c.node.source.value;Aj(l)&&i({node:c.node.source,kind:"import",source:"import",value:l,complete:!0})},JSXOpeningElement(c){let l=Cv(c.node.name),u=Pj.test(l);for(let d of c.node.attributes){if(Be.isJSXSpreadAttribute(d)){u&&i({node:d.argument,kind:"object",source:"jsx-attribute",value:null,complete:!1});continue}let f=wj(d);if(!f||!Tj(f,u))continue;let g=$r(d.value);i({node:d.value??d,kind:kv(f),source:"jsx-attribute",value:g.value,complete:g.complete})}},ObjectProperty(c){let l=Tl(c.node.key);if(!l||!ui.has(l)&&!(Lj(c)&&Rv(l))||ui.has(l)&&Pl(c.node.value)&&Al(c.node.value))return;let u=$r(c.node.value);i({node:c.node.value,kind:kv(l),source:"object-property",value:u.value,complete:u.complete})},ArrayExpression(c){if(Fj(c))for(let l of c.node.elements){if(!l||Pl(l)&&Al(l))continue;let u=$r(l);(u.value!==null||!u.complete)&&i({node:l,kind:"array-item",source:"array-item",value:u.value,complete:u.complete})}},CallExpression(c){let l=c.node.callee;if(!Be.isIdentifier(l,{name:"mediaAsset"})||c.node.arguments.length!==1)return;let u=c.node.arguments[0];if(!Be.isExpression(u)){s(c.node,null);return}let d=$r(u);s(c.node,d.complete?d.value:null)},MemberExpression(c){if(!Oj(c.node.object))return;let l=c.node.computed?$r(c.node.property):Be.isIdentifier(c.node.property)?{value:c.node.property.name,complete:!0}:{value:null,complete:!1};s(c.node,l.complete?l.value:null)}});let a=Bj(r).sort(jj);return{complete:a.length===0,references:n.map((c,l)=>({...c,occurrence:l})),errors:a}}function Aj(e){let n=(e.split(/[?#]/u,1)[0]??"").split(".").pop()?.toLowerCase();return n!==void 0&&Rj.has(n)}function Tj(e,t){return e!=="src"||t?ui.has(e):!1}function kv(e){return e==="srcset"?"srcset":e==="poster"?"poster":e.startsWith("thumbnail")?"thumbnail":e==="src"?"src":"object"}function wj(e){return Be.isJSXIdentifier(e.name)?e.name.name.toLowerCase():Be.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`.toLowerCase():null}function Cv(e){return Be.isJSXIdentifier(e)?e.name:Be.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:`${Cv(e.object)}.${e.property.name}`}function Tl(e){return Be.isIdentifier(e)?e.name.toLowerCase():Be.isStringLiteral(e)?e.value.toLowerCase():null}function Oj(e){return Be.isIdentifier(e,{name:"mediaAssets"})}function Fj(e){let t=e.parentPath;if(t?.isObjectProperty()){let n=Tl(t.node.key);return n!==null&&ui.has(n)}return t?.isVariableDeclarator()&&Be.isIdentifier(t.node.id)?Nj.test(t.node.id.name):!1}function Lj(e){let n=e.parentPath?.parentPath;if(!n?.isObjectProperty())return!1;let r=Tl(n.node.key);return r!==null&&ui.has(r)}function Rv(e){return e==="src"||e==="srcset"||e==="url"||e==="thumbnail_url"}function Pl(e){return Be.isObjectExpression(e)||Be.isArrayExpression(e)}function Al(e){if(Be.isArrayExpression(e))return e.elements.some(n=>n!==null&&(Pl(n)?Al(n):!0));let t=!1;for(let n of e.properties){if(!Be.isObjectProperty(n))return!1;let r=Tl(n.key);if(r!==null&&(ui.has(r)||Rv(r))){t=!0;continue}Pl(n.value)&&Al(n.value)&&(t=!0)}return t}function $r(e){return e?Be.isStringLiteral(e)?{value:e.value,complete:!0}:Be.isJSXExpressionContainer(e)?$r(e.expression):Be.isTemplateLiteral(e)&&e.expressions.length===0?{value:e.quasis.map(t=>t.value.cooked??t.value.raw).join(""),complete:!0}:Be.isTSAsExpression(e)||Be.isTSTypeAssertion(e)||Be.isParenthesizedExpression(e)?$r(e.expression):{value:null,complete:!1}:{value:null,complete:!1}}function _v(e){let t=e.start??0,n=e.end??t;return{start_offset:t,end_offset:n,start_line:e.loc?.start.line??1,start_column:e.loc?.start.column??0,end_line:e.loc?.end.line??e.loc?.start.line??1,end_column:e.loc?.end.column??e.loc?.start.column??0}}function Dj(e,t){return e.slice(t.start_offset,t.end_offset)}function Mj(e){return`sha256:${kj("sha256").update(e).digest("hex")}`}function Bj(e){let t=new Set;return e.filter(n=>{let r=`${n.code}:${n.file_path}:${n.source_range?.start_offset??-1}`;return t.has(r)?!1:(t.add(r),!0)})}function jj(e,t){return e.file_path.localeCompare(t.file_path)||(e.source_range?.start_offset??0)-(t.source_range?.start_offset??0)||e.code.localeCompare(t.code)}var Pv=512,Jj=1024*1024,Xj=8*1024*1024,Av=256;function zj(e){let t=()=>({complete:!1,unresolved:[{code:"PORTABLE_LOCAL_ASSET_UNAVAILABLE",path:"<asset>",message:"The selected local image could not be verified."}]});if(!e.exported.complete||e.snapshot_digest!==e.exported.snapshot_digest||Ov(e.snapshot_files)!==e.snapshot_digest||!Number.isSafeInteger(e.occurrence)||e.occurrence<0||!Number.isSafeInteger(e.offset)||e.offset<0||e.offset%Nv!==0)return t();let n=e.exported.media.filter(u=>u.file_path===e.file_path&&u.occurrence===e.occurrence);if(n.length!==1)return t();let r=n[0],o=r.value;if(!r.complete||!o||r.kind==="srcset"||!o.startsWith("/")||o.startsWith("//")||/[\\\0%?#]/u.test(o))return t();let i=o.slice(1).split("/");if(i.some(u=>!u||u.startsWith(".")||u==="node_modules"))return t();let s=`public/${i.join("/")}`,a=e.snapshot_files.get(s);if(!(a instanceof Uint8Array)||!a.byteLength||a.byteLength>Uj||e.offset>=a.byteLength)return t();let c=Hj(s,a);if(!c)return t();let l=Buffer.from(a);return{complete:!0,snapshot_digest:e.snapshot_digest,file_path:e.file_path,occurrence:e.occurrence,path:s,mime_type:c,byte_size:l.byteLength,digest_sha256:Sm("sha256").update(l).digest("hex"),offset:e.offset,data_base64:l.subarray(e.offset,e.offset+Nv).toString("base64")}}function Hj(e,t){let n=e.toLowerCase(),r=o=>o.every((i,s)=>t[s]===i);return n.endsWith(".png")&&r([137,80,78,71,13,10,26,10])?"image/png":/\.jpe?g$/u.test(n)&&r([255,216,255])?"image/jpeg":n.endsWith(".gif")&&(r([71,73,70,56,55,97])||r([71,73,70,56,57,97]))?"image/gif":n.endsWith(".webp")&&r([82,73,70,70])&&t[8]===87&&t[9]===69&&t[10]===66&&t[11]===80?"image/webp":null}async function Wj(e){if(e.snapshot.site_id!==e.site_id||e.snapshot.snapshot_id!==e.base_snapshot_id)return Qt("SNAPSHOT_MISMATCH","<snapshot>","The authoritative Snapshot does not match the requested site and version.");let t=e.site_id,n=e.base_snapshot_id,r=e.document_version,o=e.read_current_identity,i=new Map(e.trusted_host_file_hashes??[]),s=Kj.safeParse(e.target),a=$j.safeParse(e.selection_ref);if(!s.success||!a.success)return Qt("BLOCK_SELECTION_INVALID","<selection>","The block target or render occurrence is invalid.");let c=s.data,l=a.data,u=Tv(o,t,n,r);if(u)return u;let d=Vj.safeParse(e.host_capabilities);if(!d.success)return Qt("HOST_CAPABILITIES_INVALID","<host-capabilities>","The host capability contract is invalid.");let f=new Map;for(let[M,fe]of e.snapshot.files){if(typeof fe!="string"&&!(fe instanceof Uint8Array))return Qt("SNAPSHOT_CONTENT_MISMATCH",M,"A Snapshot file has an unsupported content type.");f.set(M,typeof fe=="string"?fe:new Uint8Array(fe))}if(!Yj(e.snapshot.manifest,t,n,f))return Qt("SNAPSHOT_CONTENT_MISMATCH","<snapshot>","The file mapping does not match the authenticated Snapshot manifest.");let g=Ov(f),p=await Op({site_id:t,base_snapshot_id:n,composition:c.composition,document_version:r,target:c,selection_ref:l,files:f});if(!p.ok)return Qt(`BLOCK_${p.code}`,c.blockKey,p.message);if(!p.binding.descriptor.capabilities.save)return Qt("BLOCK_EXPORT_NOT_ALLOWED",c.blockKey,"The selected block is not exportable.");let m=pm({binding:p.binding,files:f,hostCapabilities:d.data});if(!m.complete)return Em(m.errors.map(({code:M,path:fe,message:Fe})=>({code:M,path:fe,message:Fe})));let y=Jp({selection:m.selection,files:f});if(!y.complete)return Em(y.errors.map(({code:M,path:fe,message:Fe})=>({code:M,path:fe,message:Fe})));let x=new Map(f);for(let M of y.source_files){let fe=x.get(M.path);if(fe!==void 0&&!Gj(fe,M.content))return Qt("SOURCE_COLLISION",M.path,"An extracted entry conflicts with the pinned Snapshot.");x.set(M.path,M.content)}let S=Lr({entry_files:[y.entry_file],files:x,max_nodes:Pv}),b=S.nodes.filter(M=>wv(M.path)&&i.get(M.path)===Fv(x.get(M.path))).map(M=>M.path),E=fl({closure:S,host_capabilities:d.data,platform_managed_paths:b,platform_managed_packages:["server-only"]}),k=Sv({files:x,private_paths:E.nodes.filter(M=>M.ownership==="private").map(M=>M.path)});x=new Map(k.files);let I=Lr({entry_files:[y.entry_file],files:x,max_nodes:Pv}),v=fl({closure:I,host_capabilities:d.data,platform_managed_paths:b,platform_managed_packages:["server-only"]}),N=xv({entry_file:y.entry_file,entry_export:m.selection.entry_export,files:x}),A=[...k.errors.filter(M=>I.nodes.some(fe=>fe.path===M.path)),...v.errors.map(({code:M,path:fe,message:Fe})=>({code:M,path:fe,message:Fe})),...N.unresolved.map(({code:M,source_path:fe,message:Fe,call_site:ot})=>({code:M,path:fe,message:Fe,...ot?{call_site:ot}:{}}))],w=new Set(b);for(let M of I.nodes)wv(M.path)&&!w.has(M.path)&&A.push({code:"HOST_CMS_IMPLEMENTATION_UNPROVEN",path:M.path,message:"A CMS host implementation requires trusted matching provenance regardless of its declared ownership."});let F=new Map(v.nodes.map(M=>[M.path,M.ownership])),B=[];for(let M of I.nodes){if(F.get(M.path)!=="private")continue;let fe=x.get(M.path),Fe=null;try{typeof fe=="string"?Fe=fe:fe instanceof Uint8Array&&(Fe=new TextDecoder("utf-8",{fatal:!0}).decode(fe))}catch{}Fe===null?A.push({code:"SOURCE_TEXT_UNSUPPORTED",path:M.path,message:"A private source dependency is not valid UTF-8 text."}):B.push({path:M.path,content:Fe})}for(let M of B)(/^(?:src\/)?components\/site\/generated\/(?:forms|product-search)\//u.test(M.path)||M.path==="lib/generated/product-search-config.json")&&A.push({code:"MANAGED_REQUIREMENT_UNPROVEN",path:M.path,message:"A managed capability requires a proven requirement before exporting the block."});B.some(M=>M.path===y.entry_file)||A.push({code:"ENTRY_NOT_PRIVATE",path:y.entry_file,message:"The selected entry is not site-owned source."});let X=0,$=[];for(let M of B){let fe=Buffer.byteLength(M.content,"utf8");if(X+=fe,(fe>Jj||X>Xj)&&A.push({code:"SOURCE_BUDGET_EXCEEDED",path:M.path,message:"The selected source exceeds its export byte budget."}),/\.[jt]sx?$/iu.test(M.path)){let Fe=bm({file_path:M.path,source:M.content});$.push(...Fe.references),A.push(...Fe.errors.map(({code:ot,file_path:Tt,message:Vr})=>({code:ot,path:Tt,message:Vr})))}}if(A.length>0||!I.complete||!v.complete||!N.complete)return Em(A);let G=Tv(o,t,n,r);return G||{complete:!0,site_id:t,base_snapshot_id:n,snapshot_digest:g,document_version:r,target:m.selection.target,selection_ref:y.selected_root_ref,entry:{file:y.entry_file,export:m.selection.entry_export},files:B.map(({path:M,content:fe})=>({path:M,content:fe})),source_closure:I,dependency_audit:v,cms:N,media:$,invocation_bindings:y.invocation_bindings,host_contract_digest:d.data.host_contract_digest}}function Tv(e,t,n,r){if(!Number.isSafeInteger(r)||r<0)return Qt("DOCUMENT_VERSION_STALE","<document>","The selected document version is invalid.");try{let o=e();return o.site_id!==t||o.snapshot_id!==n?Qt("SNAPSHOT_MISMATCH","<snapshot>","The live runtime no longer matches the requested Snapshot."):o.document_version!==r?Qt("DOCUMENT_VERSION_STALE","<document>","The live document version changed during export."):null}catch{return Qt("RUNTIME_IDENTITY_UNAVAILABLE","<document>","The live runtime identity could not be verified.")}}function Ov(e){let t=Sm("sha256");for(let[n,r]of[...e.entries()].sort(([o],[i])=>o.localeCompare(i))){let o=typeof r=="string"?Buffer.from(r,"utf8"):r;t.update(`${n.length}:${n}:${o.byteLength}:`),t.update(o)}return`sha256:${t.digest("hex")}`}function Gj(e,t){return typeof e=="string"?e===t:Buffer.from(e).equals(Buffer.from(t,"utf8"))}function wv(e){return/^(?:src\/)?lib\/cms\/(?!generated\/)/u.test(e)}function Fv(e){return e===void 0?null:`sha256:${Sm("sha256").update(e).digest("hex")}`}function Yj(e,t,n,r){if(!e||e.version!==1||e.site_id!==t||e.snapshot_id!==n||!Array.isArray(e.files)||e.files.length!==r.size)return!1;let o=new Set;for(let i of e.files){if(!i||typeof i.path!="string"||!i.path||i.path.startsWith("/")||i.path.includes("\\")||i.path.includes("\0")||i.path.split("/").some(a=>!a||a==="."||a==="..")||o.has(i.path)||!/^sha256:[a-f0-9]{64}$/u.test(i.hash)||!Number.isSafeInteger(i.size_bytes)||i.size_bytes<0)return!1;o.add(i.path);let s=r.get(i.path);if(s===void 0||Fv(s)!==i.hash||(typeof s=="string"?Buffer.byteLength(s,"utf8"):s.byteLength)!==i.size_bytes)return!1}return!0}function Qt(e,t,n){return{complete:!1,unresolved:[{code:e,path:t,message:n}]}}function Em(e){return e.length?e.length<=Av?{complete:!1,unresolved:e}:{complete:!1,unresolved:[...e.slice(0,Av-1),{code:"PORTABLE_DIAGNOSTICS_TRUNCATED",path:"<selection>",message:"Additional unresolved export diagnostics were omitted."}]}:Qt("PORTABLE_EXPORT_INCOMPLETE","<selection>","The selected block's export proof is incomplete.")}import Im from"@babel/generator";import{parse as Zj}from"@babel/parser";import qj from"@babel/traverse";import*as gt from"@babel/types";var vm=qj,Qj=typeof vm=="function"?vm:vm.default,e0=typeof Im=="function"?Im:Im.default,$v="components/site/generated/{{$INSTANCE}}/",Vv=new Set([".tsx",".ts",".jsx",".js"]),Lv=new Set(["data-site-block-id","data-vcp-block-id","data-vcp-edit-key"]),t0=new Set(["data-site-block-order","data-vcp-order"]);function n0(e){let t=[],n=new Map,r=new Map;/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/u.test(e.instance_base_name)||t.push({code:"SOURCE_INPUT_INVALID",path:"instance_base_name",message:"The portable instance base name is not safe."});for(let b of e.source_files){let E=nr(b.path);if(!E||n.has(E)){t.push({code:"SOURCE_INPUT_INVALID",path:b.path,message:"Portable source files must have unique safe paths."});continue}n.set(E,{...b,path:E})}for(let b of e.ownership){let E=nr(b.path);if(!E||r.has(E)){t.push({code:"SOURCE_INPUT_INVALID",path:b.path,message:"Portable source ownership entries must be unique and safe."});continue}r.set(E,{...b,path:E})}let o=nr(e.entry_file);n.get(o)?r.get(o)?.ownership!=="private"&&t.push({code:"SOURCE_ENTRY_NOT_PRIVATE",path:o,message:"The selected portable source entry must be private source."}):t.push({code:"SOURCE_ENTRY_NOT_FOUND",path:e.entry_file,message:"The selected portable source entry is not present."});for(let b of n.keys())r.has(b)||t.push({code:"SOURCE_OWNERSHIP_MISSING",path:b,message:"Every source closure file requires an ownership decision."});let s=[...n.keys()].filter(b=>r.get(b)?.ownership==="private").sort((b,E)=>b.localeCompare(E)),a=s.map(b=>({source_path:b,path_template:u0(b)})),c=new Map(a.map(b=>[b.source_path,b.path_template])),l=r0(e.source_mapping??[],c,t),u=o0(e.required_source_paths??[],c,t),d=[],f=new Map,g=[];for(let b of s){let E=n.get(b);if(!E)continue;let k=s0(b,E.content,r,c,d,f,t);k!==null&&g.push({path_template:c.get(b),content:k,...E.role?{role:E.role}:{}})}let p=Bv(t).sort(jv);if(p.length>0)return{complete:!1,entry_path_template:null,files:[],source_path_mappings:[],required_path_mappings:[],source_mapping:[],managed_rebindings:[],block_metadata:[],errors:p};let m=g.map(b=>{let E=a.find(I=>I.path_template===b.path_template)?.source_path,k=n.get(E)?.content??"";return{source_path:E,path_template:b.path_template,original_byte_size:Dv(k),output_byte_size:Dv(b.content),original_line_count:Mv(k),output_line_count:Mv(b.content)}}),y=[...f.values()].map(b=>({...b,normalized:!0})).sort((b,E)=>b.source_path.localeCompare(E.source_path)),x=c.get(o)??null;if(e.thin_entry_plan){let b=i0(e.thin_entry_plan,c,t);b&&(g.push(b),x=b.path_template)}let S=Bv(t).sort(jv);return S.length>0?{complete:!1,entry_path_template:null,files:[],source_path_mappings:[],required_path_mappings:[],source_mapping:[],managed_rebindings:[],block_metadata:[],errors:S}:{complete:!0,entry_path_template:x,files:g.sort((b,E)=>b.path_template.localeCompare(E.path_template)),source_path_mappings:m.sort((b,E)=>b.path_template.localeCompare(E.path_template)),required_path_mappings:u,source_mapping:l,managed_rebindings:d.sort(g0),block_metadata:y,errors:[]}}function r0(e,t,n){let r=new Set,o=[];for(let[i,s]of e.entries()){let a=nr(s.generated_path),c=nr(s.source_file),l=a,u=t.get(a);if(!a||a!==s.generated_path||!c||c!==s.source_file||!s.structural_path||r.has(l)){n.push({code:"SOURCE_REQUIRED_PATH_INVALID",path:`source_mapping.${i}`,message:"Portable selected-source mappings require unique safe paths and structural identities."});continue}if(r.add(l),!u){n.push({code:"SOURCE_REQUIRED_PATH_UNMAPPED",path:s.generated_path,message:"A selected-source mapping must resolve to one private normalized entry path."});continue}o.push({...s,path_template:u})}return o.sort((i,s)=>i.path_template.localeCompare(s.path_template)||i.source_file.localeCompare(s.source_file)||i.structural_path.localeCompare(s.structural_path))}function o0(e,t,n){let r=new Set,o=new Set,i=[];for(let[s,a]of e.entries()){let c=nr(a.source_path);if(!/^[a-z][a-z0-9-]{0,127}$/u.test(a.key)||!c||r.has(a.key)||o.has(c)){n.push({code:"SOURCE_REQUIRED_PATH_INVALID",path:`required_source_paths.${s}`,message:"Required portable source paths must use unique safe keys and source identities."});continue}r.add(a.key),o.add(c);let l=t.get(c);if(!l){n.push({code:"SOURCE_REQUIRED_PATH_UNMAPPED",path:a.source_path,message:"A required portable source identity must map to exactly one private package path."});continue}i.push({key:a.key,source_path:c,path_template:l})}return i.sort((s,a)=>s.key.localeCompare(a.key)||s.source_path.localeCompare(a.source_path))}function i0(e,t,n){if(e.adds_dom!==!1)return n.push({code:"SOURCE_THIN_ENTRY_INVALID",path:e.source_file,message:"A managed-root thin entry must not add DOM."}),null;let r=t.get(nr(e.component_source));if(!r)return n.push({code:"SOURCE_THIN_ENTRY_TARGET_MISSING",path:e.component_source,message:"The managed-root thin entry target is not private materialized source."}),null;if(!/^(?:default|[A-Za-z_$][A-Za-z0-9_$]*)$/u.test(e.component_export))return n.push({code:"SOURCE_THIN_ENTRY_INVALID",path:e.component_export,message:"The managed-root thin entry export is not a safe export name."}),null;let o=`${$v}__managed-root-entry.tsx`,i=Uv(o,r,"./component"),s=e.component_export==="default"?`import Root from ${JSON.stringify(i)};`:`import { ${e.component_export} as Root } from ${JSON.stringify(i)};`;return{path_template:o,role:"managed-root-thin-entry",content:`${s}
16
+ `;return pl({entryFile:r,entryContent:c,files:n,selection:t,sourceMapping:{generated_path:t.source_file,source_file:t.source_file,structural_path:t.structural_path}})}return n.has(r)?vt("SOURCE_INPUT_INVALID",r,"The deterministic extracted entry path collides with the fixed Snapshot map."):nB(t,o,n)}function nB(e,t,n){let r;try{r=ZD(t,{sourceType:"module",sourceFilename:e.source_file,plugins:["jsx","typescript"]})}catch(A){return vt("SOURCE_PARSE_FAILED",e.source_file,A instanceof Error?A.message:String(A))}let o=rB(r,e);if(o.length!==1)return vt("SOURCE_NOT_PORTABLE",e.source_file,"The pinned source range must identify exactly one current JSX root.");let i=o[0],s=i.findParent(A=>A.isFunction());if(!s||!HI(s.node))return vt("SOURCE_NOT_PORTABLE",e.source_file,"The selected JSX root is not inside one statically bounded component function.");let a=s,c=SB(a);if(!c.ok)return vt("SOURCE_NOT_PORTABLE",e.source_file,"The containing component has hook calls whose order cannot be proven for an isolated root.");let l={imports:new Set,moduleDeclarations:new Set,functionDeclarations:new Set,props:new Map,propsObjectName:null,errors:[]},u=new Set;for(let A of r.program.body){if(!O.isImportDeclaration(A)||A.specifiers.length||A.importKind==="type")continue;let w=A.source.value,F=w.startsWith(".")||w.startsWith("@/")?yl(e.source_file,w,n):null;if(!F?.endsWith(".css"))return vt("SOURCE_NOT_PORTABLE",e.source_file,"A bare module effect is not a proven portable stylesheet dependency.");u.has(F)||l.imports.add(A),u.add(F)}let d=oB(a,e);if(!d.ok)return{complete:!1,errors:[d.error]};if(iB(i,i.node,a,d.value,e,c.translationBinding??null,l,n),l.errors.length>0)return{complete:!1,errors:l.errors};if(c.translationBinding&&![...l.functionDeclarations].some(A=>O.isVariableDeclaration(A)&&A.declarations.some(w=>O.isIdentifier(w.id,{name:c.translationBinding}))))return vt("SOURCE_NOT_PORTABLE",e.source_file,"The containing component's i18n hook is not part of the selected dependency closure.");let f=_B(r,"__vcpPortableProps"),g=O.cloneNode(i.node,!0),p=[];for(let A of[...l.imports].sort(jp)){let w=bB(A,e.source_file,e.entry_file,n);if(!w.ok)return{complete:!1,errors:[w.error]};p.push(w.node)}let m=[...l.moduleDeclarations].sort(jp).map(A=>O.cloneNode(A,!0)),y=[...l.functionDeclarations].sort(jp).map(A=>O.cloneNode(A,!0)),x=O.returnStatement(g),S=[...l.props].filter(([A])=>!A.startsWith("@")).map(([A,w])=>O.variableDeclaration("const",[O.variableDeclarator(O.identifier(A),O.memberExpression(O.identifier(f),O.identifier(w)))]));l.propsObjectName&&S.push(O.variableDeclaration("const",[O.variableDeclarator(O.identifier(l.propsObjectName),O.identifier(f))]));let b=O.blockStatement([...S,...y,x]),E=l.props.size?[xB(f)]:[],k=O.functionDeclaration(O.identifier("PortableBlockEntry"),E,b),I=O.program([...p,...m,k,O.exportDefaultDeclaration(O.identifier("PortableBlockEntry"))]);I.directives=r.program.directives.map(A=>O.cloneNode(A,!0));let v=eB(O.file(I),{jsescOption:{minimal:!0}}).code,N={generated_path:e.entry_file,source_file:e.source_file,structural_path:e.structural_path};return pl({entryFile:e.entry_file,entryContent:v,files:n,selection:e,sourceMapping:N,invocationBindings:kB(e,l.props)})}function rB(e,t){let n=[];return Kp(e,{JSXElement(r){r.node.start===t.source_range.start_offset&&r.node.end===t.source_range.end_offset&&n.push(r)}}),n}function oB(e,t){let n=e.node.params;if(n.length>1)return{ok:!1,error:at("SOURCE_NOT_PORTABLE",t.source_file,"Multiple component parameters are not a proven portable invocation surface.")};let r=new Map,o=n[0];if(!o)return{ok:!0,value:{bindingByLocalName:r,propsParameter:null}};if(O.isIdentifier(o))return{ok:!0,value:{bindingByLocalName:r,propsParameter:o}};if(!O.isObjectPattern(o))return{ok:!1,error:at("SOURCE_NOT_PORTABLE",t.source_file,"Component props must use one identifier or a static object pattern.")};for(let i of o.properties){if(!O.isObjectProperty(i)||i.computed||!(O.isIdentifier(i.key)||O.isStringLiteral(i.key))||!(O.isIdentifier(i.value)||O.isAssignmentPattern(i.value)&&O.isIdentifier(i.value.left)))return{ok:!1,error:at("SOURCE_NOT_PORTABLE",t.source_file,"Rest, computed, or nested component prop destructuring is not supported.")};let s=O.isIdentifier(i.key)?i.key.name:i.key.value,a=i.value,c=O.isIdentifier(a)?a.name:O.isAssignmentPattern(a)&&O.isIdentifier(a.left)?a.left.name:"";r.set(c,s)}return{ok:!0,value:{bindingByLocalName:r,propsParameter:null}}}function iB(e,t,n,r,o,i,s,a){let c=new Set,l=new Map,u=p=>{let m=l.get(p);if(m!==void 0)return m;let y=aB(n,r,p,o,a);return l.set(p,y),y||s.errors.push(at("SOURCE_NOT_PORTABLE",o.source_file,`Selected prop ${p} is mutated or escapes its proven invocation value.`)),y},d=p=>{let m=p.node.name,y=p.scope.getBinding(m);if(!y){OI.has(m)||s.errors.push(at("SOURCE_NOT_PORTABLE",o.source_file,`The selected root references unbound identifier ${m}.`));return}if(!gl(y.path.node,t)){if(r.bindingByLocalName.has(m)&&y.scope===n.scope){let x=r.bindingByLocalName.get(m);LI(o,x)?u(x)&&s.props.set(m,x):s.errors.push(at("SOURCE_NOT_PORTABLE",o.source_file,`The selected root prop ${x} has no proven invocation binding.`));return}if(r.propsParameter&&y.path.node===r.propsParameter&&p.parentPath?.isMemberExpression()&&p.parentPath.node.object===p.node){let x=p.parentPath.node,S=!x.computed&&O.isIdentifier(x.property)?x.property.name:x.computed&&O.isStringLiteral(x.property)?x.property.value:null;S&&LI(o,S)?u(S)&&(s.propsObjectName=m,s.props.set(`@${m}.${S}`,S)):s.errors.push(at("SOURCE_NOT_PORTABLE",o.source_file,`The selected root reads an unproven dynamic prop through ${m}.`));return}c.has(y)||(c.add(y),FI(y,n,o,s,d,f,a))}},f=(p,m)=>{let y=zI(p);if(!y||/^[a-z]/u.test(y.name))return;let x=m.scope.getBinding(y.name);if(!x){OI.has(y.name)||s.errors.push(at("SOURCE_NOT_PORTABLE",o.source_file,`The selected root component ${y.name} has no proven import or declaration.`));return}c.has(x)||gl(x.path.node,t)||(c.add(x),FI(x,n,o,s,d,f,a))};(p=>{p.isIdentifier()&&p.isReferencedIdentifier()&&d(p),p.isJSXElement()&&f(p.node.openingElement.name,p),p.traverse({ReferencedIdentifier(m){d(m)},JSXOpeningElement(m){f(m.node.name,m)},CallExpression(m){XI(m,i)||s.errors.push(at("SOURCE_NOT_PORTABLE",o.source_file,"A selected-root call is not a proven pure helper or statically bound translation."))},AssignmentExpression(m){s.errors.push(at("SOURCE_NOT_PORTABLE",o.source_file,"Assignments inside a selected root are not a closed Portable dependency.")),m.stop()},UpdateExpression(m){s.errors.push(at("SOURCE_NOT_PORTABLE",o.source_file,"Updates inside a selected root are not a closed Portable dependency.")),m.stop()},NewExpression(m){s.errors.push(at("SOURCE_NOT_PORTABLE",o.source_file,"Dynamic object construction inside a selected root is not proven portable.")),m.stop()}})})(e)}function FI(e,t,n,r,o,i,s){let a=e.path;if(vB(a,t)||a.isFunctionDeclaration()&&a.node===t.node){r.errors.push(at("SOURCE_NOT_PORTABLE",n.source_file,`The selected root captures unsupported component-local binding ${e.identifier.name}.`));return}if(e.constantViolations.length>0){r.errors.push(at("SOURCE_NOT_PORTABLE",n.source_file,`Captured binding ${e.identifier.name} is rebound outside its declaration.`));return}if(dB(e)){r.errors.push(at("SOURCE_NOT_PORTABLE",n.source_file,`Captured binding ${e.identifier.name} has a member write outside its declaration.`));return}let c=new ml(s),l=new Map,u=a.parentPath,d=u?.isImportDeclaration(),f=!1;if(d&&(u.node.source.value.startsWith(".")||u.node.source.value.startsWith("@/"))){let y=yl(n.source_file,u.node.source.value,s),x=y?c.get(y):void 0,S=a.isImportDefaultSpecifier()?"default":a.isImportSpecifier()&&a.node.importKind!=="type"?Jt(a.node.imported,!1):null,b=x&&S&&u.node.importKind!=="type"?br(x,S,c):null,E=b?Kt(b):null;if(!E?.length){r.errors.push(at("SOURCE_NOT_PORTABLE",n.source_file,"The imported value has no bounded unique Snapshot source."));return}l.set(e.identifier,E),f=E.every(k=>k.isFunctionDeclaration()||k.isFunctionExpression()||k.isArrowFunctionExpression())}else d&&(f=e.referencePaths.every(y=>y.parentPath?.isJSXOpeningElement()||y.parentPath?.isJSXClosingElement()||y.parentPath?.isCallExpression()&&y.parentPath.node.callee===y.node));if((d&&!f||sB(e))&&!Ns(e,{bindings:new Set,activeBindings:new Set,jsxCalls:new Set,inputs:l,files:s,modules:c},!1)){r.errors.push(at("SOURCE_NOT_PORTABLE",n.source_file,`Captured binding ${e.identifier.name} is mutated or escapes its static object shape.`));return}let g=a.isImportDeclaration()?a:a.findParent(y=>y.isImportDeclaration());if(g?.isImportDeclaration()){r.imports.add(g.node);return}let p=a.isVariableDeclarator()?a:a.findParent(y=>y.isVariableDeclarator());if(p?.isVariableDeclarator()){let y=p.parentPath,x=p.get("init");if(!y?.isVariableDeclaration()||y.node.kind!=="const"||!x.node||!ro(p.node.id)||!ro(x.node)&&!IB(x)){r.errors.push(at("SOURCE_NOT_PORTABLE",n.source_file,`Captured binding ${e.identifier.name} is not a side-effect-free const.`));return}let b=y.findParent(k=>k.isFunction())===t?r.functionDeclarations:r.moduleDeclarations,E=O.variableDeclaration("const",[O.cloneNode(p.node,!0)]);MI(b,E,p.node),p.traverse({ReferencedIdentifier(k){k.isIdentifier()&&o(k)},JSXOpeningElement(k){i(k.node.name,k)}});return}let m=a.isFunctionDeclaration()?a:a.findParent(y=>y.isFunction());if(m?.isFunctionDeclaration()&&Ga(m.node)){let x=m.findParent(S=>S.isFunction())===t?r.functionDeclarations:r.moduleDeclarations;MI(x,O.cloneNode(m.node,!0),m.node),m.traverse({ReferencedIdentifier(S){S.isIdentifier()&&o(S)},JSXOpeningElement(S){i(S.node.name,S)}});return}r.errors.push(at("SOURCE_NOT_PORTABLE",n.source_file,`Captured binding ${e.identifier.name} is not a statically portable declaration.`))}function sB(e){let t=e.path;if(!t.isVariableDeclarator())return!1;let n=t.get("init");if(!n.node)return!0;let r=yB(n.node);return O.isFunctionExpression(r)||O.isArrowFunctionExpression(r)||O.isCallExpression(r)&&Ya(r)?!1:!Ud(e)?.every(i=>i.isFunctionExpression()||i.isArrowFunctionExpression()||Kd(i,new Map))}var ml=class extends Map{constructor(t){super(),this.files=t,this.attempted=new Set}has(t){return this.files.has(t)}get(t){let n=super.get(t);if(n||this.attempted.has(t)||this.attempted.size>=64)return n;this.attempted.add(t);let r=hl(this.files,t);if(r===null)return;let o=je(t,r);if(o.ok)return super.set(t,o.module),o.module}};function aB(e,t,n,r,o){let i=r.invocation?.bindings.find(l=>l.propName===n);if(!i)return!1;let s=[];if(i.value.kind==="json-literal"){let l=O.file(O.program([O.expressionStatement(O.valueToNode(i.value.value))]));Kp(l,{ExpressionStatement(u){s.push(u.get("expression")),u.stop()}})}let a=new Map,c={bindings:new Set,activeBindings:new Set,jsxCalls:new Set,inputs:a,files:o,modules:new ml(o)};if(t.propsParameter)return $p(e,n,s,c);for(let[l,u]of t.bindingByLocalName){if(u!==n)continue;let d=e.scope.getBinding(l);if(!d||(a.set(d.identifier,s),!Ns(d,c,!0)))return!1}return!0}function cB(e,t){if(Kd(e,t.inputs))return!0;let n=e.parentPath;if(!n)return!1;let r=n.isJSXExpressionContainer()?n.parentPath:n;if(!r)return!1;let o=r.isJSXAttribute()||r.isJSXSpreadAttribute()?r.parentPath:r.isJSXElement()?r.get("openingElement"):null;if(r.isJSXFragment())return!0;if(!o?.isJSXOpeningElement())return!1;let i=o.node.name;if(O.isJSXIdentifier(i)&&/^[a-z]/u.test(i.name))return!0;if(!O.isJSXIdentifier(i)||t.jsxCalls.has(o.node)||t.jsxCalls.size>=32)return!1;let s=lB(o,t);if(!s)return!1;let a={...t,bindings:new Set(t.bindings),jsxCalls:new Set(t.jsxCalls).add(o.node)},c=Kt(e,t.inputs);if(!c)return!1;if(r.isJSXSpreadAttribute()){let u=new Set;for(let d of c){if(!d.isObjectExpression())return!1;for(let f of d.node.properties){if(!O.isObjectProperty(f)||f.computed)return!1;let g=Jt(f.key,!1);if(g===null)return!1;u.add(g)}}return[...u].every(d=>{let f=Za(c,d,t.inputs);return f!==null&&$p(s,d,f,a)})}let l=r.isJSXAttribute()&&O.isJSXIdentifier(r.node.name)?r.node.name.name:"children";return $p(s,l,c,a)}function lB(e,t){let n=e.node.name;if(!O.isJSXIdentifier(n))return null;let r=e.scope.getBinding(n.name);if(!r||r.constantViolations.length)return null;if(r.path.isFunctionDeclaration())return r.path;if(r.path.isVariableDeclarator()){let d=r.path.get("init");return d.isFunctionExpression()||d.isArrowFunctionExpression()?d:null}let o=r.path.parentPath;if(!o?.isImportDeclaration())return null;let i=o.node.source.value,s=o.node.loc?.filename;if(!s||!(i.startsWith(".")||i.startsWith("@/")))return null;let a=yl(s,i,t.files);if(!a)return null;let c=t.modules.get(a);if(!c)return null;let l=r.path.isImportDefaultSpecifier()?"default":r.path.isImportSpecifier()?Jt(r.path.node.imported,!1):null;if(!l)return null;let u=hn({module:c,exportName:l,parsedModules:t.modules});return u.ok?u.roots[0]?.getFunctionParent()??null:null}function $p(e,t,n,r){let o=e.get("params")[0];if(!o)return!0;let i=new Map(r.inputs);if(o.isObjectPattern()){let a=!0;for(let c of o.get("properties")){if(!c.isObjectProperty()||c.node.computed){if(Object.keys(c.getBindingIdentifiers()).some(f=>c.scope.getBinding(f)?.referencePaths.length))return!1;continue}if(Jt(c.node.key,!1)!==t)continue;let l=c.get("value");if(!l.isIdentifier())return!1;let u=l.scope.getBinding(l.node.name);if(!u)return!1;i.set(u.identifier,n),a=Ns(u,{...r,inputs:i},!0)&&a}return a}if(!o.isIdentifier())return!1;let s=o.scope.getBinding(o.node.name);return!s||s.constantViolations.length?!1:s.referencePaths.every(a=>{let c=a.parentPath;if(!(c?.isMemberExpression()||c?.isOptionalMemberExpression())||c.node.object!==a.node)return!1;let l=Jt(c.node.property,c.node.computed);return l===null?!1:l!==t?!0:(i.set(c.node,n),UI(c,{...r,inputs:i},!0))})}function Ns(e,t,n){if(t.bindings.has(e))return!0;if(t.activeBindings.has(e)||t.bindings.size+t.activeBindings.size>=128||e.constantViolations.length>0)return!1;let r={...t,activeBindings:new Set(t.activeBindings).add(e)},o=e.referencePaths.every(i=>UI(i,r,n));return o&&t.bindings.add(e),o}function Xp(e,t,n){let r=e.node.id;if(O.isIdentifier(r)){let o=e.scope.getBinding(r.name);return o?Ns(o,t,n):!1}if(O.isObjectPattern(r)||O.isArrayPattern(r)){let o=[];return si(r,o)?uB(o,e,t):!1}return!1}function si(e,t){if(O.isRestElement(e))return si(e.argument,t);if(O.isIdentifier(e))return t.push(e.name),!0;if(O.isAssignmentPattern(e))return si(e.left,t);if(O.isObjectPattern(e)){for(let n of e.properties){if(O.isRestElement(n)){if(!si(n.argument,t))return!1;continue}if(!O.isObjectProperty(n)||n.computed||!(O.isIdentifier(n.key)||O.isStringLiteral(n.key)||O.isNumericLiteral(n.key))||!si(n.value,t))return!1}return!0}if(O.isArrayPattern(e)){for(let n of e.elements)if(n&&!si(n,t))return!1;return!0}return!1}function uB(e,t,n){return e.every(r=>{let o=t.scope.getBinding(r);return o?Ns(o,n,!0):!1})}function dB(e){return e.referencePaths.some(t=>{let{current:n,memberAccess:r}=VI(t);if(!r)return!1;let o=n.parentPath;return!!($I(n)||o?.isUpdateExpression()||o?.isUnaryExpression({operator:"delete"}))})}function $I(e){let t=e.findParent(n=>n.isAssignmentExpression()||n.isForXStatement());return t&&(t.isAssignmentExpression()||t.isForXStatement())?gl(e.node,t.node.left):!1}function VI(e){let t=Vp(e),n=!1;for(;t.parentPath&&(t.parentPath.isMemberExpression()||t.parentPath.isOptionalMemberExpression())&&t.parentPath.node.object===t.node;)n=!0,t=Vp(t.parentPath);return{current:t,memberAccess:n}}function UI(e,t,n){if(!mB(e,t))return!1;let{current:r,memberAccess:o}=VI(e),i=r.parentPath;if(!i)return!1;if(i.isVariableDeclarator()&&i.node.init===r.node){let s=i.parentPath;return!s?.isVariableDeclaration()||s.node.kind!=="const"?!1:Xp(i,t,o||n)}return $I(r)||i.isUpdateExpression()||i.isUnaryExpression({operator:"delete"})?!1:i.isCallExpression()||i.isOptionalCallExpression()?i.node.callee===r.node?!1:fB(i,r,t):i.isNewExpression()?!1:i.isExportSpecifier()||i.isExportNamedDeclaration()||i.isExportDefaultDeclaration()||i.isTSTypeQuery()||n&&(i.isJSXOpeningElement()||i.isJSXClosingElement())?!0:i.isJSXExpressionContainer()||i.isJSXSpreadAttribute()?cB(r,t):i.isSpreadElement()||i.isArrayExpression()||i.isObjectExpression()||i.isObjectProperty()||i.isConditionalExpression()||i.isLogicalExpression()||i.isSequenceExpression()||i.isAwaitExpression()?pB(r,o,n,t):i.isJSXAttribute()||i.isJSXSpreadAttribute()||i.isObjectMethod()||i.isReturnStatement()||i.isArrowFunctionExpression()?o||n:i.isTemplateLiteral()&&i.parentPath?.isTaggedTemplateExpression()?!1:(o||n)&&(i.isBinaryExpression()||i.isUnaryExpression()||i.isTemplateLiteral())}function fB(e,t,n){if(!e.node.arguments.some(i=>i===t.node))return!1;let r=e.node.callee;if(O.isIdentifier(r)){if(jI.has(r.name))return e.scope.getBinding(r.name)===void 0;let i=e.scope.getBinding(r.name);return!i||!Do(i)?!1:Rs(e,n,new Set)}if(!O.isMemberExpression(r)&&!O.isOptionalMemberExpression(r)||!O.isIdentifier(r.property))return!1;let o=zp(r);return!o||e.scope.getBinding(o.name)?!1:o.name==="Object"&&r.property.name==="assign"?e.node.arguments[0]===t.node?!1:Rs(e,n,new Set):BI.get(o.name)?.has(r.property.name)??!1?JI(e)?Rs(e,n,new Set):!0:!1}function pB(e,t,n,r){let o=KI(e);return o.kind==="declarator"?Xp(o.declarator,r,o.directValue):o.kind==="escape"||o.kind==="call"?!1:t||n}function KI(e){let t=Vp(e),n=!0,r=!1;for(;;){let o=t.parentPath;if(!o)return r?{kind:"escape"}:{kind:"read"};if(o.isTSAsExpression()||o.isTSTypeAssertion()||o.isTSNonNullExpression()||o.isTSSatisfiesExpression()||o.isParenthesizedExpression()){t=o;continue}if((o.isMemberExpression()||o.isOptionalMemberExpression())&&o.node.object===t.node){t=o;continue}if(o.isConditionalExpression()){if(o.node.test===t.node)return{kind:"read"};t=o;continue}if(o.isLogicalExpression()||o.isAwaitExpression()){t=o;continue}if(o.isSequenceExpression()){let i=o.node.expressions;if(i[i.length-1]!==t.node)return{kind:"read"};t=o;continue}if(o.isVariableDeclarator()&&o.node.init===t.node)return{kind:"declarator",declarator:o,directValue:n};if(o.isObjectProperty()&&o.node.value===t.node){r=!0,n=!1,t=o;continue}if(o.isObjectExpression()||o.isArrayExpression()){r=!0,n=!1,t=o;continue}if(o.isSpreadElement()){r=!0,n=!1,t=o;continue}return o.isCallExpression()||o.isOptionalCallExpression()?o.node.callee===t.node?{kind:"escape"}:{kind:"call",call:o}:o.isNewExpression()?{kind:"escape"}:o.isJSXExpressionContainer()||o.isJSXAttribute()||o.isJSXSpreadAttribute()||o.isReturnStatement()||o.isArrowFunctionExpression()?r?{kind:"escape"}:{kind:"read"}:r?{kind:"escape"}:{kind:"read"}}}function Rs(e,t,n){if(n.has(e.node))return!0;n.add(e.node);let r=KI(e);return r.kind==="declarator"?Xp(r.declarator,t,r.directValue):r.kind==="escape"?!1:r.kind==="call"?r.call.node.callee===e.node?!1:JI(r.call)?Rs(r.call,t,n):hB(r.call):!0}function mB(e,t){let n=e.findParent(o=>o.isFunction());if(!n||!HI(n.node))return!0;let r=gB(n);return!r||!Do(r)?!0:r.referencePaths.every(o=>{let i=o.parentPath;return!i?.isCallExpression()||i.node.callee!==o.node?!0:Rs(i,t,new Set)})}function gB(e){let t=e.node,n=null;if(O.isFunctionDeclaration(t)?n=t.id?.name??null:(O.isArrowFunctionExpression(t)||O.isFunctionExpression(t))&&e.parentPath?.isVariableDeclarator()&&O.isIdentifier(e.parentPath.node.id)&&(n=e.parentPath.node.id.name),!n)return null;let r=[e.scope.getBinding(n),e.scope.parent?.getBinding(n),e.parentPath?.scope.getBinding(n)];for(let o of r)if(o&&(o.path.node===t||o.path.node===e.parentPath?.node))return o;return null}function JI(e){let t=e.node.callee;if(O.isIdentifier(t)){let r=e.scope.getBinding(t.name);return!!(r&&Do(r))}if(!O.isMemberExpression(t)&&!O.isOptionalMemberExpression(t)||!O.isIdentifier(t.property))return!1;let n=zp(t);return!n||e.scope.getBinding(n.name)?!1:n.name==="Object"&&tB.has(t.property.name)}function hB(e){let t=e.node.callee;if(O.isIdentifier(t))return jI.has(t.name)&&e.scope.getBinding(t.name)===void 0;if(!O.isMemberExpression(t)&&!O.isOptionalMemberExpression(t)||!O.isIdentifier(t.property))return!1;let n=zp(t);return!n||e.scope.getBinding(n.name)||n.name==="Object"&&t.property.name==="assign"?!1:BI.get(n.name)?.has(t.property.name)??!1}function Vp(e){let t=e;for(;t.parentPath&&(t.parentPath.isTSAsExpression()||t.parentPath.isTSTypeAssertion()||t.parentPath.isTSNonNullExpression()||t.parentPath.isTSSatisfiesExpression()||t.parentPath.isParenthesizedExpression());)t=t.parentPath;return t}function yB(e){let t=e;for(;t&&(O.isTSAsExpression(t)||O.isTSTypeAssertion(t)||O.isTSNonNullExpression(t)||O.isTSSatisfiesExpression(t)||O.isParenthesizedExpression(t));)t=t.expression;return t&&O.isExpression(t)?t:null}function zp(e){return!e.computed&&O.isIdentifier(e.object)?e.object:null}function xB(e){let t=O.identifier(e);return t.typeAnnotation=O.tsTypeAnnotation(O.tsTypeReference(O.identifier("Record"),O.tsTypeParameterInstantiation([O.tsStringKeyword(),O.tsAnyKeyword()]))),t}function pl(e){let t=new Map(e.files);t.set(e.entryFile,e.entryContent);let n=Lr({entry_files:[e.entryFile],files:t});if(!n.complete)return{complete:!1,errors:n.errors.map(i=>at(CB(i.code),i.path,i.message))};let r=[];for(let i of n.nodes){if(i.kind!=="source"&&i.kind!=="asset")continue;let s=hl(t,i.path);if(s===null)return vt("SOURCE_NOT_PORTABLE",i.path,"A closed dependency is not valid UTF-8 source content.");r.push({path:i.path,content:s})}let o=e.sourceMapping??{generated_path:e.entryFile,source_file:e.selection.source_file,structural_path:e.selection.structural_path};return{complete:!0,entry_file:e.entryFile,source_files:r.sort((i,s)=>i.path.localeCompare(s.path)),source_mapping:[o],invocation_bindings:e.invocationBindings??e.selection.invocation?.bindings??[],selected_root_ref:e.selection.root_ref}}function bB(e,t,n,r){let o=O.cloneNode(e,!0),i=e.source.value;if(i.startsWith("./")||i.startsWith("../")){let s=yl(t,i,r);if(!s)return{ok:!1,error:at("SOURCE_IMPORT_UNRESOLVED",t,`The selected import ${i} cannot be resolved in the fixed Snapshot map.`)};o.source.value=EB(n,s)}return{ok:!0,node:o}}function yl(e,t,n){let r=t.startsWith("@/")?t.slice(2):Cs.posix.normalize(Cs.posix.join(Cs.posix.dirname(e),t));if(!Up(r))return null;let o=/\.[a-z0-9]+$/iu.test(r)?[r]:[".tsx",".ts",".jsx",".js",".json",".css",".svg"].map(s=>`${r}${s}`).concat([".tsx",".ts",".jsx",".js",".json",".css",".svg"].map(s=>`${r}/index${s}`)),i=[...new Set(o.filter(s=>n.has(s)))];return i.length===1?i[0]:null}function EB(e,t){let n=Cs.posix.relative(Cs.posix.dirname(e),t);return n.startsWith(".")?n:`./${n}`}function SB(e){let t=null,n=0,r=!1;return e.traverse({CallExpression(o){let i=o.node.callee;if(!O.isIdentifier(i)||!/^use[A-Z0-9]/u.test(i.name))return;if(i.name!=="useTranslations"||o.node.arguments.length!==1||!O.isStringLiteral(o.node.arguments[0])){r=!0,o.stop();return}let s=o.scope.getBinding(i.name),a=s?.path.findParent(l=>l.isImportDeclaration());if(!s?.path.isImportSpecifier()||!a?.isImportDeclaration()||a.node.source.value!=="next-intl"||!O.isIdentifier(s.path.node.imported,{name:"useTranslations"})){r=!0,o.stop();return}n+=1;let c=o.findParent(l=>l.isVariableDeclarator());if(!c?.isVariableDeclarator()||!O.isIdentifier(c.node.id)){r=!0,o.stop();return}t=c.node.id.name}}),r||n>1?{ok:!1}:t?{ok:!0,translationBinding:t}:{ok:!0}}function XI(e,t){let n=e.node.callee;if(O.isImport(n))return!1;if(t&&O.isIdentifier(n,{name:t})&&e.node.arguments.length>0&&e.node.arguments.every(o=>O.isStringLiteral(o))){let o=e.scope.getBinding(t);if(o&&o.constantViolations.length>0)return!1;let i=o?.path.isVariableDeclarator()?o.path:o?.path.findParent(a=>a.isVariableDeclarator()),s=i?.isVariableDeclarator()?i.node.init:null;return!!(O.isCallExpression(s)&&Ya(s))}if(!O.isIdentifier(n))return!1;let r=e.scope.getBinding(n.name);return r?Do(r):!1}function IB(e){return e.isCallExpression()&&XI(e,null)&&O.isIdentifier(e.node.callee)&&e.scope.getBinding(e.node.callee.name)?.constantViolations.length===0&&e.node.arguments.every(t=>O.isExpression(t)&&ro(t))}function zI(e){return O.isJSXIdentifier(e)?O.isValidIdentifier(e.name)?O.identifier(e.name):null:O.isJSXMemberExpression(e)?zI(e.object):null}function vB(e,t){return e.scope===t.scope&&(t.node.params.some(n=>n===e.node)||e.isIdentifier()&&t.node.params.some(n=>O.isObjectPattern(n)&&n.properties.some(r=>O.isObjectProperty(r)&&O.isIdentifier(r.value,{name:e.node.name}))))}function gl(e,t){return e===t||typeof e.start=="number"&&typeof e.end=="number"&&typeof t.start=="number"&&typeof t.end=="number"&&e.start>=t.start&&e.end<=t.end}function HI(e){return O.isFunction(e)}function LI(e,t){return!!e.invocation?.bindings.some(n=>n.propName===t)}function kB(e,t){let n=new Set(t.values());return e.invocation?.bindings.filter(r=>n.has(r.propName))??[]}function _B(e,t){let n=new Set;Kp(e,{Identifier(o){n.add(o.node.name)}});let r=t;for(;n.has(r);)r+="_";return r}function MI(e,t,n){if(typeof n.start=="number"){if([...e].some(r=>r.start===n.start))return;t.start=n.start}e.add(t)}function jp(e,t){return(e.start??0)-(t.start??0)}function hl(e,t){let n=e.get(t);if(typeof n=="string")return n;if(!(n instanceof Uint8Array))return null;try{return new TextDecoder("utf-8",{fatal:!0}).decode(n)}catch{return null}}function DI(e,t){let n=YD("sha256").update(t).digest("hex");return e.content_hash===`sha256:${n}`}function Up(e){return!!e&&!e.startsWith("/")&&!e.includes("\\")&&e.split("/").every(t=>t&&t!=="."&&t!==".."&&!t.startsWith("."))}function CB(e){return e==="SOURCE_PARSE_FAILED"?"SOURCE_PARSE_FAILED":e==="SOURCE_ENTRY_UNRESOLVED"?"SOURCE_ENTRY_NOT_FOUND":e==="SOURCE_FILE_UNRESOLVED"||e==="SOURCE_ASSET_UNRESOLVED"?"SOURCE_IMPORT_UNRESOLVED":"SOURCE_NOT_PORTABLE"}function vt(e,t,n){return{complete:!1,errors:[at(e,t,n)]}}function at(e,t,n){return{code:e,path:t,message:n}}import{createHash as fv}from"node:crypto";import sm from"node:path";import am from"@babel/traverse";import*as ze from"@babel/types";import{GeneratedSiteCapabilitiesSchema as pj,SiteEditSourcePathSchema as mj}from"@vcp-dev/contracts";import{parse as Cl}from"@babel/parser";import*as K from"@babel/types";import{PortableCollectionRecipeFactsSchema as WB}from"@vcp-dev/contracts";import{parse as Dr}from"@babel/parser";import Hp from"@babel/traverse";import*as V from"@babel/types";function xl(e){try{let t=typeof e=="string"?e:e instanceof Uint8Array?new TextDecoder("utf-8",{fatal:!0}).decode(e):null;return t!==null&&!t.includes("\0")?t:null}catch{return null}}var Zp=typeof Hp=="function"?Hp:Hp.default;function qp(e){let t=ov(e.files),n=(g,p,m)=>({complete:!1,relation:null,errors:[{code:g,path:p,message:m}]}),r=tr(e.list_entry_file,e.selected_component_source,t),o=r?t.get(r):void 0;if(!r||typeof o!="string")return n("RELATED_COLLECTION_LIST_CONTAINER_UNPROVEN",e.list_entry_file,"The selected Page Unit does not resolve to one Snapshot list container.");if(!TB(o,r,"listStrict"))return{complete:!0,relation:null,errors:[]};let i=AB(o,r),s=i?bl(r,o,i,"listStrict",t):null;if(!i||!s)return n("RELATED_COLLECTION_LIST_CONTAINER_UNPROVEN",r,"The selected list container does not prove one literal CMS collection.");let a=[...t.keys()].filter(g=>/\[slug\]\/page\.(?:[cm]?[jt]sx?)$/u.test(g)),c=a.find(g=>typeof t.get(g)!="string");if(c)return n("RELATED_COLLECTION_DETAIL_CONSUMER_UNPROVEN",c,"A candidate detail route is not valid UTF-8 source, so uniqueness cannot be proven.");let l=a.flatMap(g=>{let p=t.get(g);if(typeof p!="string")return[];let m=bl(g,p,i,"getByUrlStrict",t,e.detail_prefix??`/${i}`);return m&&em(m.ast,e.detail_prefix??`/${i}`)!==null?[m]:[]});if(l.length!==1)return n("RELATED_COLLECTION_DETAIL_CONSUMER_UNPROVEN",e.list_entry_file,"Exactly one dynamic detail route must consume the selected collection.");let u=l[0];if(u.adapter_source!==s.adapter_source||u.interface_name!==s.interface_name)return n("RELATED_COLLECTION_ADAPTER_UNPROVEN",u.path,"The list and detail routes do not share the selected collection adapter and view interface.");let d=qn(u.source,{filePath:u.path,exportName:"default"}).components.flatMap(g=>{let p=tr(u.path,g.source,t),m=p?t.get(p):void 0;return!p||typeof m!="string"||!ev(m,g.export_name)||!El(m,u.adapter_source,u.interface_name)?[]:[{path:p,export_name:g.export_name}]});if(d.length!==1)return n("RELATED_COLLECTION_DETAIL_CONSUMER_UNPROVEN",u.path,"The collection detail route does not prove one private detail view.");let f=d[0];return{complete:!0,relation:{slug:i,requirement_key:`cms-${i}`,list_entry_file:e.list_entry_file,detail_entry_file:u.path,detail_view_file:f.path,detail_view_export:f.export_name},errors:[]}}function Qp(e){let t=ov(e.files),n=[],r=[],o=[],i=null;e.source_closure.complete||n.push({code:"RELATED_SOURCE_CLOSURE_INCOMPLETE",path:e.collection.list_entry_file,message:"The selected Page Unit source closure is incomplete; related entries cannot be proven."});for(let f of e.source_closure.nodes)f.kind==="source"&&typeof t.get(f.path)!="string"&&n.push({code:"RELATED_SOURCE_CLOSURE_INCOMPLETE",path:f.path,message:"A selected source is missing or is not valid UTF-8 text."});Wp(t,e.collection.list_entry_file,"RELATED_LIST_ENTRY_MISSING",n),Wp(t,e.collection.detail_entry_file,"RELATED_DETAIL_ENTRY_MISSING",n),Wp(t,e.collection.detail_view_file,"RELATED_DETAIL_VIEW_MISSING",n),Gp(o,{path:e.collection.list_entry_file,kind:"route",requirementKey:e.collection.requirement_key}),Gp(o,{path:e.collection.detail_entry_file,kind:"route",requirementKey:e.collection.requirement_key});let s=Lr({entry_files:[e.collection.detail_entry_file],files:t});for(let f of s.nodes)f.kind==="source"&&typeof t.get(f.path)!="string"&&n.push({code:"RELATED_DETAIL_SOURCE_INCOMPLETE",path:f.path,message:"A detail source is missing or is not valid UTF-8 text."});s.complete||n.push(...s.errors.map(f=>({code:"RELATED_DETAIL_SOURCE_INCOMPLETE",path:f.path,message:f.message})));let a=s.nodes.find(f=>f.path===e.collection.detail_view_file);!a||a.status!=="complete"?n.push({code:"RELATED_DETAIL_VIEW_NOT_REACHED",path:e.collection.detail_view_file,message:"The trusted detail route does not reach the declared detail-view entry."}):r.push({path:e.collection.detail_view_file,export:e.collection.detail_view_export==="default"?{kind:"default"}:{kind:"named",name:e.collection.detail_view_export},purpose:"collection-detail-view"});for(let f of s.nodes)if(f.kind!=="external"&&f.path!==e.collection.detail_entry_file&&f.path!==e.collection.detail_view_file){if(jB(f.path,e.collection)){Gp(o,{path:f.path,kind:f.path.includes("/page.")?"route":"adapter",requirementKey:e.collection.requirement_key});continue}$B(f.path,e.collection.detail_view_file,e.collection.slug)&&r.push({path:f.path,export:{kind:"default"},purpose:"i18n-companion"})}let c=t.get(e.collection.detail_view_file);typeof c=="string"&&DB(c,e.collection.detail_view_file,s.nodes,t,r),e.page_template&&(i=BB(e.page_template,t,n));let l=e.trusted_schema===void 0?null:RB(e,t,n,e.trusted_schema),u=KB(r).map((f,g)=>({key:XB(f,g),pathTemplate:f.path,export:f.export,purpose:f.purpose,requirementKey:e.collection.requirement_key})),d=zB(n).sort(HB);return{complete:d.length===0,entries:u.sort((f,g)=>f.pathTemplate.localeCompare(g.pathTemplate)||f.purpose.localeCompare(g.purpose)||f.key.localeCompare(g.key)),managed_requirements:o.sort(JB),thin_entry_plan:i,collection_wiring:l,errors:d}}function RB(e,t,n,r){let o=n.length,i=r.fields.map(E=>({...E}));(r.source_slug!==e.collection.slug||!r.evidence_path.trim()||i.length===0)&&n.push({code:"RELATED_COLLECTION_SCHEMA_UNPROVEN",path:r.evidence_path||`trusted-schema:${e.collection.slug}`,message:"Collection recipe facts require a non-empty trusted CMS schema with matching source identity."});let s=e.source_closure.nodes.filter(E=>E.kind==="source"&&E.status==="complete"&&E.path!==e.collection.list_entry_file).flatMap(E=>{let k=t.get(E.path);if(typeof k!="string")return[];let I=bl(E.path,k,e.collection.slug,"listStrict",t);return I?[I]:[]});s.length!==1&&n.push({code:"RELATED_COLLECTION_LIST_CONTAINER_UNPROVEN",path:e.collection.list_entry_file,message:"Exactly one rendered source module must prove the selected collection listStrict wiring."});let a=s[0]??null,c=a?WI(a,t,E=>E!==e.collection.detail_view_file):null;c?a&&!El(t.get(c.source_path),a.adapter_source,a.interface_name)&&n.push({code:"RELATED_COLLECTION_LIST_VIEW_UNPROVEN",path:c.source_path,message:"The rendered list view does not consume the generated collection interface."}):n.push({code:"RELATED_COLLECTION_LIST_VIEW_UNPROVEN",path:a?.path??e.collection.list_entry_file,message:"The generated list container must render one resolvable private list view."});let l=t.get(e.collection.detail_entry_file),u=typeof l=="string"?bl(e.collection.detail_entry_file,l,e.collection.slug,"getByUrlStrict",t):null,d=u?WI(u,t,E=>E===e.collection.detail_view_file):null;!u||!d||d.export_name!==e.collection.detail_view_export?n.push({code:"RELATED_COLLECTION_DETAIL_CONSUMER_UNPROVEN",path:e.collection.detail_entry_file,message:"The trusted detail route must consume the declared detail view through the same collection adapter."}):El(t.get(d.source_path),u.adapter_source,u.interface_name)||n.push({code:"RELATED_COLLECTION_DETAIL_CONSUMER_UNPROVEN",path:d.source_path,message:"The rendered detail view does not consume the generated collection interface."}),a&&u&&(a.adapter_source!==u.adapter_source||a.interface_name!==u.interface_name)&&n.push({code:"RELATED_COLLECTION_ADAPTER_UNPROVEN",path:e.collection.detail_entry_file,message:"List and detail consumers must use the same generated collection adapter and view interface."});let f=new Set(i.map(E=>E.name)),g=a?tr(a.path,a.adapter_source,t):null,p=g?t.get(g):null,m=[...e.required_fields??i.filter(E=>E.required).map(E=>E.name)].sort(Yp),y=[...e.force_multi_media??(typeof p=="string"?tv(p):[])].sort(Yp);for(let E of[...m,...y])f.has(E)||n.push({code:"RELATED_COLLECTION_FIELD_UNPROVEN",path:`trusted-schema:${e.collection.slug}.${E}`,message:`Collection field ${E} is not present in the trusted schema.`});if(a&&y.length)for(let E of y)(typeof p!="string"||!MB(p,E))&&n.push({code:"RELATED_COLLECTION_FIELD_UNPROVEN",path:g??a.adapter_source,message:`The generated adapter does not prove multi-media handling for ${E}.`});let x=u?em(u.ast,`/${e.collection.slug}`):null;x||n.push({code:"RELATED_COLLECTION_DETAIL_CONSUMER_UNPROVEN",path:e.collection.detail_entry_file,message:"The detail route does not prove a literal getByUrlStrict prefix."});let S=u?FB(u.ast):null;S||n.push({code:"RELATED_COLLECTION_DETAIL_CONSUMER_UNPROVEN",path:e.collection.detail_entry_file,message:"The generated detail route must expose a literal PAGE_SEO title."});let b=u?LB(u,t,x):null;return b==="unproven"&&n.push({code:"RELATED_COLLECTION_BREADCRUMB_UNPROVEN",path:e.collection.detail_entry_file,message:"The rendered collection breadcrumb exists but its fallback labels are not literal."}),n.length!==o||!a||!c||!u||!d||!x?null:{source_slug:e.collection.slug,detail_prefix:x,schema:i,schema_evidence_path:r.evidence_path,list_container_file:a.path,list_view:{...c,interface_name:a.interface_name},detail_view:{...d,interface_name:u.interface_name},...S?{title:S}:{},...b&&b!=="unproven"?{breadcrumb:b}:{},...m.length>0?{required_fields:m}:{},...y.length>0?{force_multi_media:y}:{}}}function bl(e,t,n,r,o,i=`/${n}`){let s;try{s=Dr(t,{sourceType:"module",sourceFilename:e,plugins:["jsx","typescript"]})}catch{return null}let a=bo(s,u=>V.isCallExpression(u)&&Eo(u.callee,r));if(!PB(s,e,o,r)||r==="listStrict"&&(a.length!==1||!V.isStringLiteral(a[0]?.arguments[0],{value:n}))||r==="getByUrlStrict"&&(a.length===0||em(s,i)===null))return null;let l=s.program.body.flatMap(u=>V.isImportDeclaration(u)?u.specifiers.flatMap(d=>{if(!V.isImportSpecifier(d))return[];let f=V.isIdentifier(d.imported)?d.imported.name:d.imported.value,g=/^to([A-Za-z_$][A-Za-z0-9_$]*View)$/u.exec(f);return g?[{source:u.source.value,local_name:d.local.name,interface_name:g[1]}]:[]}):[]).filter(u=>bo(s,d=>V.isIdentifier(d,{name:u.local_name})).length>1);return l.length!==1||!NB(s,e,o,l[0],r,n)?null:{path:e,source:t,ast:s,adapter_source:l[0].source,interface_name:l[0].interface_name}}function NB(e,t,n,r,o,i){let s=!1;return Zp(e,{JSXOpeningElement(a){let c=a.getFunctionParent();if(!c?.isFunctionDeclaration()||!c.parentPath.isExportDefaultDeclaration()||!V.isJSXIdentifier(a.node.name)||a.node.attributes.some(y=>V.isJSXSpreadAttribute(y)))return;let l=a.parentPath;for(;l&&!l.isReturnStatement()&&!l.isFunction();){if(l.isVariableDeclarator()||l.isJSXAttribute()||l.isConditionalExpression()||l.isLogicalExpression()||l.isCallExpression()||l.isJSXElement()&&l.node!==a.parentPath.node&&(!V.isJSXIdentifier(l.node.openingElement.name)||!/^[a-z]/u.test(l.node.openingElement.name.name)))return;l=l.parentPath}if(!l?.isReturnStatement()||l.getFunctionParent()!==c||l.parentPath!==c.get("body"))return;let u=a.scope.getBinding(a.node.name.name),d=u?.path,f=d?.parentPath;if(!u?.constant||!f?.isImportDeclaration()||f.node.importKind==="type"||d?.isImportSpecifier()&&d.node.importKind==="type"||!(d?.isImportDefaultSpecifier()||d?.isImportSpecifier()))return;let g=tr(t,f.node.source.value,n);if(!g||!El(n.get(g),r.source,r.interface_name))return;let p=a.get("attributes").filter(y=>y.isJSXAttribute()&&V.isJSXIdentifier(y.node.name,{name:o==="listStrict"?"records":"record"}));if(p.length!==1||!p[0].isJSXAttribute())return;let m=p[0].get("value");m.isJSXExpressionContainer()&&(o==="listStrict"?ZI(m.get("expression"),c,r,i,new Set):qI(m.get("expression"),c,r,new Set))&&(s=!0)}}),s}function ZI(e,t,n,r,o){if(!e.node||o.has(e.node)||o.size>=32)return!1;if(o.add(e.node),e.isIdentifier()){let g=e.scope.getBinding(e.node.name);return!g?.constant||!g.path.isVariableDeclarator()||g.path.getFunctionParent()!==t||!g.path.parentPath.isVariableDeclaration({kind:"const"})||Ps(g.referencePaths)?!1:ZI(g.path.get("init"),t,n,r,o)}if(!e.isCallExpression()||e.node.arguments.length!==1)return!1;let i=e.get("callee");if(!i.isMemberExpression()||i.node.computed||!V.isIdentifier(i.node.property,{name:"map"}))return!1;let s=e.get("arguments")[0];if(!s||!QI(s,n))return!1;let a=i.get("object");if(a.isConditionalExpression()){let g=a.get("consequent"),p=a.get("alternate"),m=y=>y.isArrayExpression()&&y.node.elements.length===0;if(m(g))a=p;else if(m(p))a=g;else return!1}if(!a.isMemberExpression()||a.node.computed||!V.isIdentifier(a.node.property,{name:"items"}))return!1;let c=a.get("object");if(!c.isMemberExpression()||c.node.computed||!V.isIdentifier(c.node.property,{name:"data"}))return!1;let l=c.get("object");if(!l.isIdentifier())return!1;let u=l.scope.getBinding(l.node.name);if(!u?.constant||!u.path.isVariableDeclarator()||u.path.getFunctionParent()!==t||!u.path.parentPath.isVariableDeclaration({kind:"const"})||Ps(u.referencePaths))return!1;let d=u.path.get("init");if(!d.isAwaitExpression())return!1;let f=d.get("argument");return f.isCallExpression()&&Eo(f.node.callee,"listStrict")&&V.isStringLiteral(f.node.arguments[0],{value:r})}function qI(e,t,n,r){if(!e.node||r.has(e.node)||r.size>=32)return!1;if(r.add(e.node),e.isIdentifier()){let u=e.scope.getBinding(e.node.name);return!u?.constant||!u.path.isVariableDeclarator()||u.path.getFunctionParent()!==t||!u.path.parentPath.isVariableDeclaration({kind:"const"})||Ps(u.referencePaths)?!1:qI(u.path.get("init"),t,n,r)}if(!e.isCallExpression()||e.node.arguments.length!==1)return!1;let o=e.get("callee");if(!QI(o,n))return!1;let i=e.get("arguments")[0];if(!i?.isMemberExpression()||i.node.computed||!V.isIdentifier(i.node.property,{name:"data"}))return!1;let s=i.get("object");if(!s.isIdentifier())return!1;let a=s.scope.getBinding(s.node.name);if(!a?.constant||!a.path.isVariableDeclarator()||a.path.getFunctionParent()!==t||!a.path.parentPath.isVariableDeclaration({kind:"const"})||Ps(a.referencePaths))return!1;let c=a.path.get("init");if(!c.isAwaitExpression())return!1;let l=c.get("argument");return l.isCallExpression()&&Eo(l.node.callee,"getByUrlStrict")}function QI(e,t){if(!e.isIdentifier({name:t.local_name}))return!1;let n=e.scope.getBinding(e.node.name),r=n?.path,o=r?.parentPath;return!(!n?.constant||!r?.isImportSpecifier()||r.node.importKind==="type"||!V.isIdentifier(r.node.imported,{name:`to${t.interface_name}`})||!o?.isImportDeclaration()||o.node.importKind==="type"||o.node.source.value!==t.source)}function Ps(e,t=new Set){return t.size>=32?!0:e.some(n=>{let r=n;for(;(r.parentPath?.isMemberExpression()||r.parentPath?.isOptionalMemberExpression())&&r.parentPath.node.object===r.node;)r=r.parentPath;let o=r.parentPath;if(o?.isVariableDeclarator()&&o.node.init===r.node){if(!V.isIdentifier(o.node.id))return!0;let i=o.scope.getBinding(o.node.id.name);return i?.constant?t.has(i.identifier)?!1:(t.add(i.identifier),Ps(i.referencePaths,t)):!0}return!!(o?.isAssignmentExpression()&&o.node.left===r.node||o?.isUpdateExpression()||o?.isUnaryExpression()&&o.node.operator==="delete")})}function PB(e,t,n,r){let o=0,i=Nr(e,"cms");for(let s of e.program.body){if(!V.isImportDeclaration(s)||s.importKind==="type")continue;let a=tr(t,s.source.value,n);!a||!/^(?:src\/)?lib\/cms(?:\/index|\/collections)?\.[cm]?[jt]s$/u.test(a)||s.specifiers.some(c=>{if(V.isImportSpecifier(c)&&c.importKind==="type")return!1;if(!V.isImportSpecifier(c))return!0;let l=V.isIdentifier(c.imported)?c.imported.name:c.imported.value;return l==="collections"||l==="cms"&&c.local.name!=="cms"})&&(i=!0)}return Zp(e,{CallExpression(s){if(!Eo(s.node.callee,r))return;o+=1;let a=s.scope.getBinding("cms"),c=a?.path,l=c?.parentPath;if(!a?.constant||!c?.isImportSpecifier()||c.node.importKind==="type"||!V.isIdentifier(c.node.imported,{name:"cms"})||!l?.isImportDeclaration()||l.node.importKind==="type"){i=!0;return}let u=tr(t,l.node.source.value,n);(!u||!/^(?:src\/)?lib\/cms(?:\/index)?\.[cm]?[jt]s$/u.test(u)||a.referencePaths.some(d=>{let f=d.parentPath,g=f?.parentPath,p=g?.parentPath;return!(f?.isMemberExpression()&&f.node.object===d.node&&!f.node.computed&&V.isIdentifier(f.node.property,{name:"collections"})&&g?.isMemberExpression()&&g.node.object===f.node&&!g.node.computed&&V.isIdentifier(g.node.property)&&p?.isCallExpression()&&p.node.callee===g.node)}))&&(i=!0)}}),o>0&&!i}function AB(e,t){let n;try{n=Dr(e,{sourceType:"module",sourceFilename:t,plugins:["jsx","typescript"]})}catch{return null}let r=bo(n,o=>V.isCallExpression(o)&&Eo(o.callee,"listStrict")&&V.isStringLiteral(o.arguments[0])).map(o=>o.arguments[0].value);return r.length===1&&/^[a-z0-9][a-z0-9_-]{0,123}$/u.test(r[0])?r[0]:null}function TB(e,t,n){let r;try{r=Dr(e,{sourceType:"module",sourceFilename:t,plugins:["jsx","typescript"]})}catch{return!1}return bo(r,o=>V.isCallExpression(o)&&Eo(o.callee,n)).length>0}function WI(e,t,n){let r=qn(e.source,{filePath:e.path,exportName:"default"});if(r.diagnostics.length>0)return null;let o=r.components.flatMap(i=>{let s=tr(e.path,i.source,t),a=s?t.get(s):null;return!s||!n(s)||typeof a!="string"||!ev(a,i.export_name)?[]:[{source_path:s,target_path:s,export_name:i.export_name,import_specifier:i.source}]});return o.length===1?o[0]:null}function ev(e,t){let n;try{n=Dr(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return!1}for(let r of n.program.body){if(t==="default"&&V.isExportDefaultDeclaration(r))return!0;if(V.isExportNamedDeclaration(r)&&(r.declaration&&(V.isFunctionDeclaration(r.declaration)||V.isClassDeclaration(r.declaration)||V.isTSInterfaceDeclaration(r.declaration)||V.isTSTypeAliasDeclaration(r.declaration))&&r.declaration.id?.name===t||V.isVariableDeclaration(r.declaration)&&r.declaration.declarations.some(o=>V.isIdentifier(o.id,{name:t}))||r.specifiers.some(o=>V.isExportSpecifier(o)?(V.isIdentifier(o.exported)?o.exported.name:o.exported.value)===t:!1)))return!0}return!1}function El(e,t,n){if(typeof e!="string")return!1;let r;try{r=Dr(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return!1}return r.program.body.flatMap(i=>!V.isImportDeclaration(i)||i.source.value!==t?[]:i.specifiers.flatMap(s=>V.isImportSpecifier(s)?(V.isIdentifier(s.imported)?s.imported.name:s.imported.value)===n?[s.local.name]:[]:[])).some(i=>bo(r,s=>V.isIdentifier(s,{name:i})).length>1)}function Eo(e,t){return V.isMemberExpression(e)&&!e.computed&&V.isIdentifier(e.property,{name:t})&&V.isMemberExpression(e.object)&&!e.object.computed&&V.isIdentifier(e.object.property,{name:"collections"})&&V.isIdentifier(e.object.object,{name:"cms"})}function em(e,t){let n=[];return Zp(e,{CallExpression(r){Eo(r.node.callee,"getByUrlStrict")&&n.push(wB(r.node.arguments[0],o=>OB(r,o)))}}),n.length===0?null:n.every(r=>r===t)?t:null}function wB(e,t){return V.isBinaryExpression(e,{operator:"+"})&&V.isStringLiteral(e.left)&&V.isIdentifier(e.right)&&t(e.right.name)&&/^\/[A-Za-z0-9_-]+\/$/u.test(e.left.value)?e.left.value.slice(0,-1):V.isTemplateLiteral(e)&&e.expressions.length===1&&V.isIdentifier(e.expressions[0])&&t(e.expressions[0].name)&&e.quasis[1]?.value.cooked===""&&e.quasis.length>0&&/^\/[A-Za-z0-9_-]+\/$/u.test(e.quasis[0].value.cooked??"")?(e.quasis[0].value.cooked??"").slice(0,-1):null}function OB(e,t){let n=e.scope.getBinding(t);if(!n?.constant||!n.path.isVariableDeclarator())return!1;let r=n.path.node;if(V.isObjectPattern(r.id)&&V.isAwaitExpression(r.init)&&V.isIdentifier(r.init.argument))return r.id.properties.some(a=>V.isObjectProperty(a)&&!a.computed&&Sl(a.key)==="slug"&&V.isIdentifier(a.value,{name:t}))&&GI(n.path,r.init.argument.name);let o=r.init;if(!V.isIdentifier(r.id,{name:t})||!V.isCallExpression(o)||!V.isIdentifier(o.callee)||o.arguments.length!==1)return!1;let i=n.path.scope.getBinding(o.callee.name);if(!i?.constant||!i.path.isImportSpecifier()||!V.isIdentifier(i.path.node.imported,{name:"decodeRouteSlug"})||!i.path.parentPath.isImportDeclaration()||i.path.parentPath.node.source.value!=="@/lib/cms")return!1;let s=o.arguments[0];return V.isMemberExpression(s)&&!s.computed&&V.isIdentifier(s.property,{name:"slug"})&&V.isAwaitExpression(s.object)&&V.isIdentifier(s.object.argument)&&GI(n.path,s.object.argument.name)}function GI(e,t){let n=e.scope.getBinding(t);if(!n?.constant||n.kind!=="param")return!1;let r=n.path.getFunctionParent();if(!r||!r.isFunctionDeclaration())return!1;let o=r.parentPath;return!o.isExportDefaultDeclaration()&&!(o.isExportNamedDeclaration()&&r.node.id?.name==="generateMetadata")?!1:r.node.params.some(i=>V.isObjectPattern(i)&&i.properties.some(s=>V.isObjectProperty(s)&&!s.computed&&Sl(s.key)==="params"&&V.isIdentifier(s.value,{name:t})))}function FB(e){for(let t of e.program.body)if(V.isVariableDeclaration(t))for(let n of t.declarations){if(!V.isIdentifier(n.id,{name:"PAGE_SEO"}))continue;let r=nv(n.init);if(!V.isObjectExpression(r))return null;let o=r.properties.find(i=>V.isObjectProperty(i)&&!i.computed&&Sl(i.key)==="title");return o&&V.isStringLiteral(o.value)?o.value.value:null}return null}function LB(e,t,n){let o=qn(e.source,{filePath:e.path,exportName:"default"}).components.filter(c=>/(?:^|\/)components\/site\/generated\/[A-Za-z0-9_-]+-breadcrumb$/u.test(c.source));if(o.length===0)return null;if(o.length!==1||!n)return"unproven";let i=tr(e.path,o[0].source,t),s=i?t.get(i):null;if(typeof s!="string")return"unproven";let a;try{a=Dr(s,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return"unproven"}for(let c of bo(a,l=>V.isArrayExpression(l))){let l=c.elements.flatMap(f=>{if(!V.isObjectExpression(f))return[];let g=new Map;for(let p of f.properties){if(!V.isObjectProperty(p)||p.computed)continue;let m=Sl(p.key);m&&V.isStringLiteral(p.value)&&g.set(m,p.value.value)}return g.has("name")&&g.has("href")?[g]:[]}),u=l.find(f=>f.get("href")==="/"),d=l.find(f=>f.get("href")===n);if(u&&d)return{homeLabel:u.get("name"),collectionLabel:d.get("name")}}return"unproven"}function tv(e){let t;try{t=Dr(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return[]}return[...new Set(bo(t,n=>{if(!V.isCallExpression(n))return!1;let r=n.callee;if(!V.isMemberExpression(r)||r.computed||!V.isIdentifier(r.property,{name:"images"}))return!1;let o=n.arguments[0];return V.isMemberExpression(o)&&!o.computed&&V.isIdentifier(o.object,{name:"d"})&&V.isIdentifier(o.property)}).flatMap(n=>{let r=n.arguments[0];return V.isMemberExpression(r)&&!r.computed&&V.isIdentifier(r.property)?[r.property.name]:[]}))].sort(Yp)}function MB(e,t){return tv(e).includes(t)}function bo(e,t){let n=[],r=o=>{t(o)&&n.push(o);for(let i of Object.values(o))if(Array.isArray(i))for(let s of i)YI(s)&&r(s);else YI(i)&&r(i)};return r(e),n}function YI(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}function nv(e){return e?V.isTSAsExpression(e)||V.isTSTypeAssertion(e)||V.isTSNonNullExpression(e)?nv(e.expression):e:null}function Sl(e){return V.isIdentifier(e)?e.name:V.isStringLiteral(e)?e.value:null}function Yp(e,t){return e.localeCompare(t)}function DB(e,t,n,r,o){let i=qn(e,{filePath:t,exportName:"default"});for(let s of i.components){let a=tr(t,s.source,r);if(!a)continue;let c=n.find(u=>u.path===a),l=r.get(a);!c||c.kind==="external"||typeof l!="string"||VB(l)&&o.push({path:a,export:s.export_name==="default"?{kind:"default"}:{kind:"named",name:s.export_name},purpose:"client-importer"})}}function BB(e,t,n){let r=t.get(e.entry_file);if(typeof r!="string")return n.push({code:"RELATED_PAGE_TEMPLATE_PARSE_FAILED",path:e.entry_file,message:"The PageTemplate entry source is not available as text."}),null;let o=qn(r,{filePath:e.entry_file,exportName:"default"});if(o.diagnostics.length>0)return n.push({code:"RELATED_PAGE_TEMPLATE_PARSE_FAILED",path:e.entry_file,message:o.diagnostics[0]?.message??"PageTemplate AST is incomplete."}),null;let i=o.rendered_component_openings;if(i.length!==1)return n.push({code:"RELATED_PAGE_TEMPLATE_NOT_SEPARABLE",path:e.entry_file,message:"A single-file PageTemplate is portable only when one real component call can be isolated; the whole page cannot be copied."}),null;let s=i[0];return e.component_source&&s.source!==e.component_source||e.component_export&&s.export_name!==e.component_export?(n.push({code:"RELATED_PAGE_TEMPLATE_NOT_SEPARABLE",path:e.entry_file,message:"The declared PageTemplate root does not match its real rendered component call."}),null):{kind:"managed-root-thin-entry",source_file:e.entry_file,component_source:s.source,component_export:s.export_name,adds_dom:!1}}function Wp(e,t,n,r){typeof e.get(t)!="string"&&r.push({code:n,path:t,message:`Portable related-entry analysis could not read ${t}.`})}function jB(e,t){return e===t.list_entry_file||e===t.detail_entry_file||e.startsWith("lib/cms/")||e===`components/site/generated/${t.slug}-list.tsx`||e===`components/site/generated/${t.slug}-list.ts`||e===`components/site/generated/${t.slug}-list.jsx`||e===`components/site/generated/${t.slug}-list.js`||e===`components/site/generated/${t.slug}-breadcrumb.tsx`||e===`components/site/generated/${t.slug}-breadcrumb.ts`||e===`components/site/generated/${t.slug}-breadcrumb.jsx`||e===`components/site/generated/${t.slug}-breadcrumb.js`}function $B(e,t,n){let r=e.replace(/\\/g,"/"),o=t.replace(/\.(?:tsx?|jsx?)$/u,""),i=rv(t),s=o.slice(o.lastIndexOf("/")+1),a=s.endsWith("-detail-view")?s.slice(0,-12):n;return r===`${o}.i18n.json`||r===`${o}.messages.json`||r===`${i}/${a}.i18n.json`||r===`${i}/${a}.messages.json`||/(?:^|\/)(?:i18n|locales?)\/[^/]+\.json$/u.test(r)||/\.(?:i18n|messages)\.[^/]+\.json$/u.test(r)}function VB(e){try{return Dr(e,{sourceType:"module",plugins:["jsx","typescript"]}).program.directives.some(n=>n.value.value==="use client")}catch{return!1}}function tr(e,t,n){let r=t.startsWith("@/")?t.slice(2):UB(`${rv(e)}/${t}`);return[r,`${r}.tsx`,`${r}.ts`,`${r}.jsx`,`${r}.js`,`${r}/index.tsx`,`${r}/index.ts`,`${r}/index.jsx`,`${r}/index.js`].find(i=>n.has(i))??null}function rv(e){let t=e.lastIndexOf("/");return t<0?"":e.slice(0,t)}function UB(e){let t=[];for(let n of e.replace(/\\/g,"/").split("/"))!n||n==="."||(n===".."?t.length>0&&t.at(-1)!==".."?t.pop():t.push(".."):t.push(n));return t.join("/")}function ov(e){let t=e instanceof Map?e.entries():Object.entries(e);return new class extends Map{get(n){let r=super.get(n);if(r===void 0||!/\.[cm]?[jt]sx?$/iu.test(n))return r;let o=xl(r);return o!==null?(super.set(n,o),o):typeof r=="string"?new TextEncoder().encode(r):r}}(t)}function KB(e){let t=new Set;return e.filter(n=>{let r=`${n.path}\0${n.purpose}\0${JSON.stringify(n.export)}`;return t.has(r)?!1:(t.add(r),!0)})}function Gp(e,t){e.some(r=>r.path===t.path&&r.kind===t.kind)||e.push(t)}function JB(e,t){return e.path.localeCompare(t.path)||e.kind.localeCompare(t.kind)||e.requirementKey.localeCompare(t.requirementKey)}function XB(e,t){return`${`related.${e.purpose}.${e.path.replace(/[^A-Za-z0-9]+/gu,"-").replace(/^-|-$/gu,"")}`.slice(0,112)}.${t}`}function zB(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function HB(e,t){return e.path.localeCompare(t.path)||e.code.localeCompare(t.code)||e.message.localeCompare(t.message)}var GB=new Set(["blockId","block_id","targetBlockId","target_block_id","sourceBlockId","source_block_id"]),YB=new Set(["data-vcp-block-id","data-vcp-edit-key"]),ZB=new Set(["data-vcp-order","sourceOrder","source_order"]);function ai(e){let t=f=>({complete:!1,entry_file:e.file_path,target:e.target,call:null,bindings:[],original_block_id:null,original_order:null,semantic_props:{},errors:[...f].sort(Ts)}),n;try{n=Cl(e.source,{sourceType:"module",sourceFilename:e.file_path,plugins:["jsx","typescript"]})}catch(f){return t([{code:"INVOCATION_PARSE_FAILED",path:e.file_path,message:f instanceof Error?f.message:String(f)}])}let r=aj(n),o=qn(e.source,{filePath:e.file_path,exportName:e.export_name??"default"}),i=o.diagnostics.map(f=>({code:"INVOCATION_RENDER_GRAPH_INCOMPLETE",path:f.file_path||e.file_path,message:f.message})),s=new Set(o.rendered_component_openings.filter(f=>f.source===e.target.source&&f.export_name===e.target.export_name).map(f=>f.start_offset)),a=[],c=0;if(kl(n,new Set,(f,g)=>{if(!K.isJSXElement(f))return;let p=f.openingElement,m=p.start;if(typeof m!="number"||e.call_source_range&&(p.loc?.start.line!==e.call_source_range.start_line||p.loc.start.column!==e.call_source_range.start_column))return;let y=dv(p.name);if(!y)return;let x=uj(p.name,r);x&&(e.target.local_name&&e.target.local_name!==y||x.source!==e.target.source||x.export_name!==e.target.export_name||s.has(m)&&a.push({node:p,element:f,local:x,context:g,ordinal:c++}))}),a.length===0)return t([...i,{code:"INVOCATION_TARGET_NOT_RENDERED",path:e.file_path,message:`The selected component call is not a statically rendered Page Unit in ${e.file_path}.`}]);let l=a.map(f=>cv(e,f.node,f.element,{kind:"import",component_source:f.local.source,export_name:f.local.export_name,local_name:f.local.local_name},f.context,f.ordinal)),u=lv(l,e.target.original_block_id);if(!u)return t([...i,{code:"INVOCATION_TARGET_AMBIGUOUS",path:e.file_path,message:"The selected component is rendered more than once and no unique original block identity was provided."}]);let d=[...i,...u.errors];return{complete:d.length===0,entry_file:e.file_path,target:e.target,call:u.call,bindings:d.length===0?u.bindings:[],original_block_id:u.original_block_id,original_order:u.original_order,semantic_props:u.semantic_props,errors:im(d).sort(Ts)}}function av(e){let t=a=>({complete:!1,entry_file:e.file_path,target:e.target,call:null,bindings:[],original_block_id:null,original_order:null,semantic_props:{},errors:[...a].sort(Ts)}),n;try{n=Cl(e.source,{sourceType:"module",sourceFilename:e.file_path,plugins:["jsx","typescript"]})}catch(a){return t([{code:"INVOCATION_PARSE_FAILED",path:e.file_path,message:a instanceof Error?a.message:String(a)}])}let r=[],o=0;if(kl(n,new Set,(a,c)=>{if(!K.isJSXElement(a))return;let l=a.openingElement;if(typeof l.start!="number"||dv(l.name)!==e.target.local_name)return;let u=o++;e.call_source_range&&(l.loc?.start.line!==e.call_source_range.start_line||l.loc.start.column!==e.call_source_range.start_column)||r.push({node:l,element:a,context:c,ordinal:u})}),r.length===0)return t([{code:"INVOCATION_TARGET_NOT_RENDERED",path:e.file_path,message:`The selected local component call is not a statically rendered Page Unit in ${e.file_path}.`}]);let i=r.map(a=>cv(e,a.node,a.element,{kind:"local",local_name:e.target.local_name},a.context,a.ordinal)),s=lv(i,e.target.original_block_id);return s?{complete:s.errors.length===0,entry_file:e.file_path,target:e.target,call:s.call,bindings:s.errors.length===0?s.bindings:[],original_block_id:s.original_block_id,original_order:s.original_order,semantic_props:s.semantic_props,errors:im(s.errors).sort(Ts)}:t([{code:"INVOCATION_TARGET_AMBIGUOUS",path:e.file_path,message:"The selected local component is rendered more than once and no unique original block identity was provided."}])}function qB(e){let t;try{t=Cl(e.source,{sourceType:"module",sourceFilename:e.file_path,plugins:["jsx","typescript"]})}catch(a){return{invocation:null,errors:[{code:"INVOCATION_PARSE_FAILED",path:e.file_path,message:a instanceof Error?a.message:String(a)}]}}let n=yn({route:e.route,composition:e.composition.templateId===void 0?{routeId:e.composition.routeId}:{routeId:e.composition.routeId,effectiveTemplateId:e.composition.templateId},entryFile:e.file_path,version:e.document_version,source:e.source,ast:t});if(!n.ok)return{invocation:null,errors:n.projection.diagnostics.map(a=>({code:"INVOCATION_PAGE_UNIT_UNSUPPORTED",path:e.file_path,message:a.message}))};let r=n.projection.placementUnitByKey.get(e.placement_unit_key),o=r?.sourceRange;if(!r||!o)return{invocation:null,errors:[{code:"INVOCATION_PAGE_UNIT_NOT_FOUND",path:e.file_path,message:"The selected Page Unit key does not belong to the pinned document version."}]};let i=qn(e.source,{filePath:e.file_path,exportName:"default"});if(i.components.length===0)return{invocation:null,errors:[]};let s=i.components.map(a=>ai({file_path:e.file_path,source:e.source,target:a,call_source_range:{start_line:o.startLine,start_column:o.startColumn}})).filter(a=>a.call!==null);return s.length!==1?{invocation:null,errors:[{code:"INVOCATION_PAGE_UNIT_NOT_FOUND",path:e.file_path,message:"The selected Page Unit does not resolve to exactly one rendered imported component."}]}:{invocation:s[0],errors:s[0].errors}}function QB(e){let t=ai(e),n=Qp({files:e.files,source_closure:e.source_closure,collection:e.collection,trusted_schema:e.trusted_schema,...e.required_fields?{required_fields:e.required_fields}:{},...e.force_multi_media?{force_multi_media:e.force_multi_media}:{}}),r=[...t.errors],o=[];e.source_closure.complete||r.push({code:"COLLECTION_SOURCE_CLOSURE_INCOMPLETE",path:e.collection.list_entry_file,message:"Collection recipe analysis requires a complete selected source closure."});for(let f of n.errors)r.push({code:nj(f.code),path:f.path,message:f.message});t.call&&o.push({fact:"invocation",path:t.call.source_file,reason:"The selected rendered component call supplies the portable invocation bindings.",source_range:t.call.source_range});let i=rj(e.files),s=n.collection_wiring,a=oj(e.file_path,e.target.source,i),c=a?xl(i.get(a)):null,l=a&&typeof c=="string"?ej(c,a,e.collection.slug):null;if(!a)r.push({code:"COLLECTION_LIST_CONTAINER_UNPROVEN",path:e.file_path,message:"The selected invocation target does not resolve to a Snapshot source file."});else if(!l)r.push({code:"COLLECTION_PAGINATION_UNPROVEN",path:a,message:"The collection list container must expose one literal pageSize with statically provable searchParams behavior."});else{o.push({fact:"pagination",path:a,reason:l.paginate?`listStrict consumes route searchParams with literal pageSize ${l.limit}.`:`listStrict is embedded and uses literal top-N ${l.limit}.`});let f=t.bindings.filter(g=>g.propName==="searchParams"&&g.value.kind==="route-search-params");(l.paginate&&f.length!==1||!l.paginate&&f.length!==0)&&r.push({code:"COLLECTION_SEARCH_PARAMS_MISMATCH",path:`${e.file_path}:searchParams`,message:l.paginate?"A paginated collection must receive the selected route searchParams exactly once.":"An embedded collection cannot carry a route searchParams binding.",source_range:t.call?.source_range})}s&&a!==s.list_container_file&&r.push({code:"COLLECTION_LIST_CONTAINER_UNPROVEN",path:e.file_path,message:"The selected invocation does not resolve to the proven collection list container."});let u=null;if(s&&l&&r.length===0){let f={source_slug:s.source_slug,list_mode:l.paginate?"page":"embedded",paginate:l.paginate,...l.paginate?{page_size:l.limit}:{top_n:l.limit},detail_prefix:s.detail_prefix,schema:s.schema.map(p=>({...p})),list_view:{...s.list_view},detail_view:{...s.detail_view},...s.title?{title:s.title}:{},...s.breadcrumb?{breadcrumb:{...s.breadcrumb}}:{},...s.required_fields?{required_fields:[...s.required_fields]}:{},...s.force_multi_media?{force_multi_media:[...s.force_multi_media]}:{},list_route_required:l.paginate},g=WB.safeParse(f);g.success?(u=g.data,o.push({fact:"detail-route",path:e.collection.detail_entry_file,reason:`The rendered detail consumer proves literal prefix ${s.detail_prefix}.`},{fact:"list-view",path:s.list_view.source_path,reason:`The list container renders ${s.list_view.export_name} with ${s.list_view.interface_name}.`},{fact:"detail-view",path:s.detail_view.source_path,reason:`The detail route renders ${s.detail_view.export_name} with ${s.detail_view.interface_name}.`},{fact:"schema",path:s.schema_evidence_path,reason:"The complete CMS schema is supplied by the trusted application projection."})):r.push({code:"COLLECTION_RECIPE_INVALID",path:`collection-recipe:${s.source_slug}`,message:g.error.issues[0]?.message??"Observed collection facts do not satisfy the portable recipe contract."})}let d=im(r).sort(Ts);return{...t,complete:d.length===0&&u!==null,errors:d,collection_recipe:u,collection_evidence:o.sort(sj),related_entries:n}}function ej(e,t,n){let r;try{r=Cl(e,{sourceType:"module",sourceFilename:t,plugins:["jsx","typescript"]})}catch{return null}let o=tj(r);if(!o)return null;let i=tm(o,f=>{if(!K.isCallExpression(f))return!1;let g=f.callee;return K.isMemberExpression(g)&&!g.computed&&K.isIdentifier(g.property,{name:"listStrict"})&&K.isMemberExpression(g.object)&&!g.object.computed&&K.isIdentifier(g.object.property,{name:"collections"})&&K.isIdentifier(g.object.object,{name:"cms"})&&K.isStringLiteral(f.arguments[0],{value:n})});if(i.length!==1)return null;let s=i[0].arguments[1];if(!K.isObjectExpression(s)||s.properties.some(f=>K.isSpreadElement(f)))return null;let a=s.properties.find(f=>K.isObjectProperty(f)&&!f.computed&&vl(f.key)==="pageSize");if(!a||!K.isNumericLiteral(a.value)||!Number.isSafeInteger(a.value.value)||a.value.value<=0||!s.properties.some(f=>K.isObjectProperty(f)&&!f.computed&&vl(f.key)==="page"))return null;let l=s.properties.some(f=>K.isObjectProperty(f)&&!f.computed&&vl(f.key)==="category"),u=tm(o,f=>K.isAwaitExpression(f)&&K.isIdentifier(f.argument,{name:"searchParams"})).length;if(u>1)return null;let d=tm(o,f=>{if(!K.isCallExpression(f))return!1;let g=f.callee;return K.isMemberExpression(g)&&!g.computed&&K.isIdentifier(g.property,{name:"categories"})&&K.isMemberExpression(g.object)&&!g.object.computed&&K.isIdentifier(g.object.property,{name:"collections"})&&K.isIdentifier(g.object.object,{name:"cms"})&&K.isStringLiteral(f.arguments[0],{value:n})}).length;return u===1&&(!l||d!==1)||u===0&&(l||d!==0)?null:{paginate:u===1,limit:a.value.value}}function tj(e){let t=e.program.body.find(n=>K.isExportDefaultDeclaration(n));return K.isExportDefaultDeclaration(t)&&(K.isFunctionDeclaration(t.declaration)||K.isFunctionExpression(t.declaration)||K.isArrowFunctionExpression(t.declaration))?t.declaration:null}function tm(e,t){let n=[],r=o=>{if(!(o!==e&&om(o))){t(o)&&n.push(o);for(let i of Object.values(o))if(Array.isArray(i))for(let s of i)_l(s)&&r(s);else _l(i)&&r(i)}};return r(e),n}function nj(e){return e==="RELATED_COLLECTION_SCHEMA_UNPROVEN"?"COLLECTION_SCHEMA_UNPROVEN":e==="RELATED_COLLECTION_LIST_CONTAINER_UNPROVEN"?"COLLECTION_LIST_CONTAINER_UNPROVEN":e==="RELATED_COLLECTION_DETAIL_CONSUMER_UNPROVEN"||e==="RELATED_DETAIL_ENTRY_MISSING"||e==="RELATED_DETAIL_VIEW_MISSING"||e==="RELATED_DETAIL_VIEW_NOT_REACHED"||e==="RELATED_DETAIL_SOURCE_INCOMPLETE"?"COLLECTION_DETAIL_CONSUMER_UNPROVEN":"COLLECTION_VIEW_UNPROVEN"}function rj(e){return e instanceof Map?e:new Map(Object.entries(e))}function oj(e,t,n){let r=e.includes("/")?e.slice(0,e.lastIndexOf("/")):"",o=t.startsWith("@/")?t.slice(2):ij(`${r}/${t}`);return[o,`${o}.tsx`,`${o}.ts`,`${o}.jsx`,`${o}.js`,`${o}/index.tsx`,`${o}/index.ts`,`${o}/index.jsx`,`${o}/index.js`].find(i=>n.has(i))??null}function ij(e){let t=[];for(let n of e.split("/"))!n||n==="."||(n===".."?t.pop():t.push(n));return t.join("/")}function sj(e,t){return e.fact.localeCompare(t.fact)||e.path.localeCompare(t.path)}function aj(e){let t=new Map;for(let n of e.program.body){if(!K.isImportDeclaration(n))continue;let r=n.source.value;for(let o of n.specifiers)if(K.isIdentifier(o.local)){if(K.isImportDefaultSpecifier(o))t.set(o.local.name,{source:r,export_name:"default",local_name:o.local.name});else if(K.isImportNamespaceSpecifier(o))t.set(o.local.name,{source:r,export_name:"*",local_name:o.local.name});else if(K.isImportSpecifier(o)){let i=K.isIdentifier(o.imported)?o.imported.name:o.imported.value;t.set(o.local.name,{source:r,export_name:i,local_name:o.local.name})}}}return t}function cv(e,t,n,r,o,i){let s=fj(t),a=[],c=[],l={},u=new Set,d=null,f=null,g=(m,y)=>{if(u.has(m)){a.push({code:"INVOCATION_DUPLICATE_PROP",path:`${e.file_path}:${m}`,message:`Portable invocation contains duplicate prop ${m}.`,source_range:s});return}u.add(m),c.push({propName:m,value:y}),(m==="type"||m==="variant")&&y.kind==="json-literal"&&(l[m]=y.value)};for(let m of t.attributes){if(K.isJSXSpreadAttribute(m)){let E=Br(m.argument);if(!E.ok||!uv(E.value)){a.push({code:"INVOCATION_SPREAD_UNRESOLVED",path:`${e.file_path}:spread`,message:"Portable invocation cannot prove the props supplied by a spread expression.",source_range:s});continue}for(let[k,I]of Object.entries(E.value)){if(!sv(k)){a.push({code:"INVOCATION_VALUE_UNRESOLVED",path:`${e.file_path}:${k}`,message:`Portable invocation cannot encode prop ${k}.`,source_range:s});continue}g(k,nm(I))}continue}let y=dj(m.name);if(!y)continue;let x=m.value,S=x&&K.isJSXExpressionContainer(x)?x.expression:null;if(YB.has(y)){let E=x?Il(x):{ok:!0,value:!0};!E.ok||typeof E.value!="string"?a.push({code:"INVOCATION_BLOCK_ID_UNRESOLVED",path:`${e.file_path}:${y}`,message:"Portable invocation requires a literal original block identity.",source_range:s}):d=E.value;continue}if(ZB.has(y)){let E=x?Il(x):{ok:!0,value:!0};!E.ok||typeof E.value!="number"||!Number.isSafeInteger(E.value)?a.push({code:"INVOCATION_ORDER_UNRESOLVED",path:`${e.file_path}:${y}`,message:"Portable invocation requires a literal original order.",source_range:s}):f=E.value;continue}if(!sv(y)){a.push({code:"INVOCATION_VALUE_UNRESOLVED",path:`${e.file_path}:${y}`,message:`Portable invocation cannot encode prop ${y}.`,source_range:s});continue}if(GB.has(y)){let E=x?Il(x):{ok:!0,value:!0};E.ok&&typeof E.value=="string"?d=E.value:S&&iv(S,o)&&a.push({code:"INVOCATION_BLOCK_ID_UNRESOLVED",path:`${e.file_path}:${y}`,message:"A target block identity cannot be supplied by route search params.",source_range:s}),g(y,{kind:"target-block-id"});continue}if(S&&iv(S,o)){g(y,{kind:"route-search-params"});continue}let b=x?Il(x):{ok:!0,value:!0};if(!b.ok){a.push({code:"INVOCATION_VALUE_UNRESOLVED",path:`${e.file_path}:${y}`,message:`Portable invocation cannot prove a JSON-literal value for ${y}.`,source_range:s});continue}g(y,nm(b.value))}let p=cj(n);return p.ok?p.value!==void 0&&g("children",nm(p.value)):a.push({code:"INVOCATION_CHILDREN_UNRESOLVED",path:`${e.file_path}:children`,message:p.message,source_range:s}),{call:r.kind==="local"?{kind:"local",source_file:e.file_path,local_name:r.local_name,ordinal:i,source_range:s}:{source_file:e.file_path,component_source:r.component_source,export_name:r.export_name,local_name:r.local_name,ordinal:i,source_range:s},bindings:c,original_block_id:d??e.target.original_block_id??null,original_order:f,semantic_props:l,errors:a}}function lv(e,t){if(e.length===1)return e[0]??null;if(!t)return null;let n=e.filter(r=>r.original_block_id===t);return n.length===1?n[0]??null:null}function Il(e){return e===null?{ok:!0,value:!0}:K.isStringLiteral(e)?{ok:!0,value:e.value}:K.isJSXExpressionContainer(e)?Br(e.expression):{ok:!1}}function Br(e){if(!e)return{ok:!1};if(K.isStringLiteral(e))return{ok:!0,value:e.value};if(K.isNumericLiteral(e)&&Number.isFinite(e.value))return{ok:!0,value:e.value};if(K.isBooleanLiteral(e))return{ok:!0,value:e.value};if(K.isNullLiteral(e))return{ok:!0,value:null};if(K.isTemplateLiteral(e)&&e.expressions.length===0)return{ok:!0,value:e.quasis[0]?.value.cooked??""};if(K.isTSAsExpression(e)||K.isTSTypeAssertion(e)||K.isTSNonNullExpression(e))return Br(e.expression);if(K.isUnaryExpression(e)){let t=Br(e.argument);return!t.ok||e.operator==="+"&&typeof t.value=="number"?t:e.operator==="-"&&typeof t.value=="number"?{ok:!0,value:-t.value}:e.operator==="!"&&typeof t.value=="boolean"?{ok:!0,value:!t.value}:{ok:!1}}if(K.isArrayExpression(e)){let t=[];for(let n of e.elements){let r=Br(n);if(!r.ok)return{ok:!1};t.push(r.value)}return{ok:!0,value:t}}if(K.isObjectExpression(e)){let t={};for(let n of e.properties){if(K.isSpreadElement(n)){let i=Br(n.argument);if(!i.ok||!uv(i.value))return{ok:!1};Object.assign(t,i.value);continue}if(!K.isObjectProperty(n)||n.computed)return{ok:!1};let r=vl(n.key);if(!r)return{ok:!1};let o=Br(n.value);if(!o.ok)return{ok:!1};t[r]=o.value}return{ok:!0,value:t}}return{ok:!1}}function cj(e){if(e.children.length===0)return{ok:!0,value:void 0};let t=[];for(let n of K.react.buildChildren(e)){let r=Br(n);if(!r.ok)return{ok:!1,message:"Portable invocation cannot preserve dynamic JSX children."};t.push(r.value)}return t.length===0?{ok:!0,value:void 0}:{ok:!0,value:t.length===1?t[0]:t}}function kl(e,t,n){let r=om(e)?new Set([...t,...lj(e)]):t;n(e,{names:r});for(let o of Object.values(e))if(Array.isArray(o))for(let i of o)_l(i)&&kl(i,r,n);else _l(o)&&kl(o,r,n)}function lj(e){if(!om(e))return[];let t=[];for(let n of e.params)As(n,t);return t}function As(e,t){if(K.isIdentifier(e)){t.push(e.name);return}if(K.isAssignmentPattern(e)){As(e.left,t);return}if(K.isObjectPattern(e)){for(let n of e.properties)K.isRestElement(n)?As(n.argument,t):K.isObjectProperty(n)&&As(n.value,t);return}if(K.isArrayPattern(e))for(let n of e.elements)n&&As(n,t)}function iv(e,t){return K.isIdentifier(e)?e.name==="searchParams"&&t.names.has(e.name):K.isMemberExpression(e)&&!e.computed&&K.isIdentifier(e.property)&&e.property.name==="searchParams"&&K.isIdentifier(e.object)&&t.names.has(e.object.name)}function nm(e){return{kind:"json-literal",value:e}}function uv(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function sv(e){return/^[A-Za-z][A-Za-z0-9_]{0,127}$/u.test(e)}function dv(e){if(K.isJSXIdentifier(e))return e.name;if(!K.isJSXMemberExpression(e))return null;let t=rm(e.object);return t?`${t}.${e.property.name}`:null}function rm(e){if(K.isJSXIdentifier(e))return e.name;if(!K.isJSXMemberExpression(e))return null;let t=rm(e.object);return t?`${t}.${e.property.name}`:null}function uj(e,t){if(K.isJSXIdentifier(e))return t.get(e.name)??null;if(!K.isJSXMemberExpression(e))return null;let n=rm(e.object);if(!n)return null;let r=t.get(n);return!r||r.export_name!=="*"?null:{source:r.source,export_name:e.property.name,local_name:`${n}.${e.property.name}`}}function dj(e){return K.isJSXIdentifier(e)?e.name:K.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function vl(e){return K.isIdentifier(e)?e.name:K.isStringLiteral(e)||K.isNumericLiteral(e)?String(e.value):null}function om(e){return K.isFunctionDeclaration(e)||K.isFunctionExpression(e)||K.isArrowFunctionExpression(e)}function _l(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}function fj(e){return{start_offset:e.start??0,end_offset:e.end??e.start??0,start_line:e.loc?.start.line??1,start_column:e.loc?.start.column??0,end_line:e.loc?.end.line??e.loc?.start.line??1,end_column:e.loc?.end.column??e.loc?.start.column??0}}function im(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function Ts(e,t){return e.path.localeCompare(t.path)||e.code.localeCompare(t.code)||e.message.localeCompare(t.message)}var gj=typeof am=="function"?am:am.default,cm=class extends Map{constructor(t){super(),this.files=t,this.failures=new Map}read(t){let n=super.get(t);if(n)return{ok:!0,module:n};let r=this.failures.get(t);if(r)return{ok:!1,missing:!1,message:r};let o=Rl(this.files,t);if(o===null)return{ok:!1,missing:!0,message:"A re-exported source is missing or is not valid UTF-8 text."};let i=je(t,o);return i.ok?(super.set(t,i.module),{ok:!0,module:i.module}):(this.failures.set(t,i.diagnostic.message),{ok:!1,missing:!1,message:i.diagnostic.message})}get(t){let n=this.read(t);return n.ok?n.module:void 0}has(t){return super.has(t)||this.files.has(t)}};function pm(e){let{binding:t,files:n}=e;if(e.hostCapabilities!==null&&!pj.safeParse(e.hostCapabilities).success)return ct("INVOCATION_VALUE_UNRESOLVED","generated-site-capabilities","Trusted host capabilities failed their strict schema.");if(!ws(t.descriptor.source.file)||!ws(t.ownerFile))return ct("INVOCATION_TARGET_NOT_RENDERED",t.descriptor.source.file,"The resolved block source path is not a safe Snapshot source path.");let r=Rl(n,t.descriptor.source.file),o=Rl(n,t.ownerFile);if(r===null||o===null)return ct("INVOCATION_TARGET_NOT_RENDERED",r===null?t.descriptor.source.file:t.ownerFile,"The resolved block or owner source is missing or is not valid UTF-8 text.");if(ke(r)!==t.descriptor.source.contentHash||ke(r)!==t.sourceHash||ke(o)!==t.ownerSourceHash)return ct("INVOCATION_TARGET_NOT_RENDERED",t.descriptor.source.file,"The pinned block or owner source hash no longer matches the resolved binding.");let i=je(t.descriptor.source.file,r);if(!i.ok)return ct("INVOCATION_PARSE_FAILED",t.descriptor.source.file,i.diagnostic.message);let s=Nl(i.module.ast,t.rootLocator.sourceRange);if(s.length!==1)return ct("INVOCATION_TARGET_AMBIGUOUS",t.descriptor.source.file,"The selected block source range does not identify exactly one JSX element.");let a=s[0],c=mv(a.node);if(!c)return ct("INVOCATION_TARGET_NOT_RENDERED",t.descriptor.source.file,"The selected JSX element has no complete source range.");let l=[],u=t.root.callChain,d=new cm(n),f=hj(e,c,d);if(f)return f;if(u.some(y=>(y.alternativeLocators?.length??0)>1))return ct("INVOCATION_TARGET_NOT_RENDERED",t.descriptor.source.file,"The conditional invocation has no single statically proven props binding.");for(let[y,x]of u.entries()){let S=Rl(n,x.sourceFile);if(S===null||!ws(x.sourceFile))return ct("INVOCATION_TARGET_NOT_RENDERED",x.sourceFile,"A statically proven call-chain source is missing from the fixed Snapshot map.");let b=je(x.sourceFile,S);if(!b.ok)return ct("INVOCATION_PARSE_FAILED",x.sourceFile,b.diagnostic.message);let E=Nl(b.module.ast,x.callLocator.sourceRange);if(E.length!==1)return ct("INVOCATION_TARGET_AMBIGUOUS",x.sourceFile,"A call-chain locator does not identify exactly one current JSX element.");let k=u[y+1]?.sourceFile??t.descriptor.source.file,I=u[y+1]?.callLocator.sourceRange??t.rootLocator.sourceRange,v=gr({module:b.module,componentName:x.component,callSourceRange:x.callLocator.sourceRange});if(v.ok){if(v.sourceFile!==k)return ct("INVOCATION_TARGET_NOT_RENDERED",x.sourceFile,"The selected local component does not resolve to the source definition proven by the block graph.");if(v.roots.filter(fe=>ci(fe.node,I)).length!==1)return ct("INVOCATION_TARGET_NOT_RENDERED",v.sourceFile,"The local component definition does not select exactly one proven JSX root.");let D=av({file_path:x.sourceFile,source:S,target:{kind:"local",local_name:x.component},call_source_range:{start_line:x.callLocator.sourceRange.startLine,start_column:x.callLocator.sourceRange.startColumn}});if(!D.call||!D.complete)return{complete:!1,errors:D.errors.length>0?D.errors:[{code:"INVOCATION_TARGET_NOT_RENDERED",path:x.sourceFile,message:"The selected local call did not produce a complete invocation binding."}]};l.push({kind:"local",call:D.call,invocation:D,definition:v,entryExport:null});continue}let N=lm(b.module.ast,E[0].node.openingElement.name,x.component,x.exportName);if(!N)return ct("INVOCATION_TARGET_NOT_RENDERED",x.sourceFile,"The statically proven component call no longer resolves through one exact import.");let A=um(x.sourceFile,N.source,n);if(!A)return ct("INVOCATION_TARGET_NOT_RENDERED",x.sourceFile,"The selected component import is not a resolvable local Snapshot source.");let w=d.read(A);if(!w.ok)return ct(w.missing?"INVOCATION_TARGET_NOT_RENDERED":"INVOCATION_PARSE_FAILED",A,w.message);let F=hn({module:w.module,exportName:N.exportName,parsedModules:d});if(!F.ok)return ct("INVOCATION_TARGET_NOT_RENDERED",F.diagnostic.file,F.diagnostic.message);if(F.sourceFile!==k)return ct("INVOCATION_TARGET_NOT_RENDERED",x.sourceFile,"The selected component import does not resolve to the source definition proven by the block graph.");let B=F.roots.filter(G=>ci(G.node,I));if(B.length!==1)return ct("INVOCATION_TARGET_NOT_RENDERED",F.sourceFile,"The unique component export does not select exactly one proven JSX root.");let X=null;if(y===u.length-1&&u.length===1&&!hv(t.ownerFile)&&ci(B[0].node,t.rootLocator.sourceRange)){let G=d.read(F.sourceFile);if(!G.ok)return ct(G.missing?"INVOCATION_TARGET_NOT_RENDERED":"INVOCATION_PARSE_FAILED",F.sourceFile,G.message);if(X=pv(G.module,F.componentName,N.exportName),!X)return ct("INVOCATION_TARGET_AMBIGUOUS",F.sourceFile,"The proven component definition has no unique final export for a Portable entry.")}let $=ai({file_path:x.sourceFile,source:S,target:{source:N.source,export_name:N.exportName,local_name:N.localName},call_source_range:{start_line:x.callLocator.sourceRange.startLine,start_column:x.callLocator.sourceRange.startColumn}});if(!$.call||!$.complete)return{complete:!1,errors:$.errors.length>0?$.errors:[{code:"INVOCATION_TARGET_NOT_RENDERED",path:x.sourceFile,message:"The selected call did not produce a complete invocation binding."}]};l.push({kind:"import",call:$.call,invocation:$,definition:F,entryExport:X})}let g={kind:"page-block",composition:gv(t.composition),blockKey:t.blockKey},p=yj(t,a,l,n,e.hostCapabilities);if(!p.ok)return{complete:!1,errors:[p.error]};let m=l[0]?.invocation??null;return{complete:!0,selection:{target:g,root_ref:t.root.rootRef,source_file:t.descriptor.source.file,structural_path:t.descriptor.source.structuralPath,content_hash:t.descriptor.source.contentHash,source_range:c,owner:t.descriptor.owner,call_chain:l.map(({call:y})=>y),strategy:p.strategy,entry_file:p.entryFile,entry_export:p.entryExport,invocation:m}}}function hj(e,t,n){let{binding:r,files:o}=e,i=r.root.callChain;if(i.length!==2)return null;let[s,a]=i;if(!s||!a||(s.alternativeLocators?.length??0)>1)return null;let c=n.get(s.sourceFile);if(!c)return null;let l=Nl(c.ast,s.callLocator.sourceRange);if(l.length!==1)return null;let u=lm(c.ast,l[0].node.openingElement.name,s.component,s.exportName);if(!u)return null;let d=um(s.sourceFile,u.source,o),f=d?n.get(d):void 0;if(!f)return null;let g=hn({module:f,exportName:u.exportName,parsedModules:n});if(!g.ok||g.sourceFile!==a.sourceFile)return null;let p=n.get(g.sourceFile);if(!p||pv(p,g.componentName,"default")?.kind!=="default")return null;let m=qp({files:o,list_entry_file:s.sourceFile,selected_component_source:`@/${g.sourceFile.replace(/\.[cm]?[jt]sx?$/u,"")}`});if(!m.complete||!m.relation)return null;let y=a.alternativeLocators?.length?a.alternativeLocators:[a.callLocator],x=g.returnAlternatives?.length?g.returnAlternatives:g.roots;if(x.length!==y.length||!x.every(k=>y.filter(I=>ci(k.node,I.sourceRange)).length===1))return null;for(let k of y){let I=Nl(p.ast,k.sourceRange);if(I.length!==1)return null;let v=lm(p.ast,I[0].node.openingElement.name,a.component,a.exportName);if(!v)return null;let N=um(g.sourceFile,v.source,o),A=N?n.get(N):void 0;if(!A)return null;let w=hn({module:A,exportName:v.exportName,parsedModules:n});if(!w.ok||w.sourceFile!==r.descriptor.source.file||w.roots.length!==1||!ci(w.roots[0].node,r.rootLocator.sourceRange))return null}let S=ai({file_path:s.sourceFile,source:c.source,target:{source:u.source,export_name:u.exportName,local_name:u.localName},call_source_range:{start_line:s.callLocator.sourceRange.startLine,start_column:s.callLocator.sourceRange.startColumn}});if(!S.complete||!S.call)return{complete:!1,errors:S.errors};let E=`components/site/portable/${fv("sha256").update(JSON.stringify(["collection-container",r.composition,r.blockKey,r.sourceHash,ke(p.source)])).digest("hex").slice(0,24)}/page.tsx`;return o.has(E)?ct("INVOCATION_TARGET_AMBIGUOUS",E,"The isolated collection entry collides with a pinned Snapshot source."):{complete:!0,selection:{target:{kind:"page-block",composition:gv(r.composition),blockKey:r.blockKey},root_ref:r.root.rootRef,source_file:r.descriptor.source.file,structural_path:r.descriptor.source.structuralPath,content_hash:r.descriptor.source.contentHash,source_range:t,owner:r.descriptor.owner,call_chain:[S.call],strategy:"collection-container",collection_container_file:g.sourceFile,entry_file:E,entry_export:{kind:"default"},invocation:S}}}function yj(e,t,n,r,o){let i=n.at(-1);if(i?.kind==="import"){let l=i.definition.roots.length===1&&ci(i.definition.roots[0].node,e.rootLocator.sourceRange),u=hv(e.ownerFile);if(n.length===1&&l&&u)return{ok:!0,strategy:"managed-thin-entry",entryFile:e.ownerFile,entryExport:{kind:"default"}};if(n.length===1&&l&&i.entryExport)return{ok:!0,strategy:"reuse-entry",entryFile:i.definition.sourceFile,entryExport:i.entryExport}}if(!mv(t.node))return{ok:!1,error:{code:"INVOCATION_TARGET_NOT_RENDERED",path:e.descriptor.source.file,message:"Cannot derive a portable entry identity without an exact root range."}};let c=`components/site/portable/${fv("sha256").update(JSON.stringify([e.composition,e.blockKey,e.descriptor.source.file,e.descriptor.source.structuralPath,e.descriptor.source.contentHash,o?.host_contract_digest??null])).digest("hex").slice(0,24)}/page.tsx`;return!ws(c)||r.has(c)?{ok:!1,error:{code:"INVOCATION_TARGET_AMBIGUOUS",path:c,message:"The deterministic in-memory Portable entry path collides with an existing Snapshot file."}}:{ok:!0,strategy:"extract-jsx",entryFile:c,entryExport:{kind:"default"}}}function pv(e,t,n){let r=new Set;for(let i of e.ast.program.body){if(ze.isExportDefaultDeclaration(i)){let s=i.declaration;(ze.isFunctionDeclaration(s)&&(s.id?.name===t||t==="default")||ze.isIdentifier(s)&&s.name===t)&&r.add("default");continue}if(!(!ze.isExportNamedDeclaration(i)||i.exportKind==="type")){if(i.declaration){let s=xj(i.declaration,t);s&&r.add(s)}if(!i.source)for(let s of i.specifiers)ze.isExportSpecifier(s)&&s.exportKind!=="type"&&fm(s.local)===t&&r.add(fm(s.exported))}}if(r.size===0)return null;let o=r.has(n)?n:r.size===1?r.values().next().value:r.has("default")?"default":null;return o?o==="default"?{kind:"default"}:{kind:"named",name:o}:null}function xj(e,t){return ze.isFunctionDeclaration(e)?e.id?.name===t?t:null:ze.isVariableDeclaration(e)&&e.declarations.some(n=>ze.isIdentifier(n.id)&&n.id.name===t)?t:null}function lm(e,t,n,r){let o=dm(t);if(!o||o!==n)return null;let i=ze.isJSXMemberExpression(t)?dm(t.object):ze.isJSXNamespacedName(t)?t.namespace.name:o,s=ze.isJSXMemberExpression(t)?t.property.name:null;for(let a of e.program.body)if(ze.isImportDeclaration(a))for(let c of a.specifiers){if(ze.isImportDefaultSpecifier(c)&&c.local.name===i)return r==="default"&&!s?{source:a.source.value,exportName:"default",localName:o}:null;if(ze.isImportSpecifier(c)&&c.local.name===i){let l=fm(c.imported);return l===r&&!s?{source:a.source.value,exportName:l,localName:o}:null}if(ze.isImportNamespaceSpecifier(c)&&c.local.name===i&&s)return s===r?{source:a.source.value,exportName:s,localName:o}:null}return null}function Nl(e,t){let n=[];return gj(e,{JSXElement(r){let o=r.node.loc;o&&o.start.line===t.startLine&&o.start.column===t.startColumn&&o.end.line===t.endLine&&o.end.column===t.endColumn&&n.push(r)}}),n}function mv(e){let t=e.loc;return typeof e.start!="number"||typeof e.end!="number"||!t?null:{start_offset:e.start,end_offset:e.end,start_line:t.start.line,start_column:t.start.column,end_line:t.end.line,end_column:t.end.column}}function ci(e,t){let n=e.loc;return!!(n&&n.start.line===t.startLine&&n.start.column===t.startColumn&&n.end.line===t.endLine&&n.end.column===t.endColumn)}function Rl(e,t){let n=e.get(t);if(typeof n=="string")return n;if(!(n instanceof Uint8Array))return null;try{return new TextDecoder("utf-8",{fatal:!0}).decode(n)}catch{return null}}function um(e,t,n){let r=t.startsWith("@/")?t.slice(2):t.startsWith("./")||t.startsWith("../")?sm.posix.normalize(sm.posix.join(sm.posix.dirname(e),t)):null;return!r||r===".."||r.startsWith("../")||r.startsWith("/")?null:(/\.(?:[cm]?[jt]sx?)$/u.test(r)?[r]:[".tsx",".ts",".jsx",".js",".mts",".cts"].map(i=>`${r}${i}`).concat([".tsx",".ts",".jsx",".js",".mts",".cts"].map(i=>`${r}/index${i}`))).find(i=>ws(i)&&n.has(i))??null}function dm(e){if(ze.isJSXIdentifier(e))return e.name;if(ze.isJSXMemberExpression(e)){let t=dm(e.object);return t?`${t}.${e.property.name}`:null}return null}function fm(e){return ze.isIdentifier(e)?e.name:e.value}function gv(e){return{routeId:e.routeId,...e.effectiveTemplateId!==void 0?{templateId:e.effectiveTemplateId}:{}}}function ws(e){return mj.safeParse(e).success}function hv(e){return/(?:^|\/)\.vcp\/page-templates\//u.test(e)}function ct(e,t,n){return{complete:!1,errors:[{code:e,path:t,message:n}]}}import mm from"@babel/traverse";import*as Pe from"@babel/types";var bj=typeof mm=="function"?mm:mm.default,yv=256,xv=16;function Ev(e){let t=[],n=new Map,r=new Map,o=new Set,i=new Set,s=0;class a extends Map{constructor(){super(...arguments),this.attempted=new Set}has(E){return e.files.has(E)}get(E){let k=super.get(E);if(k||this.attempted.has(E))return k;this.attempted.add(E);let I=e.files.get(E),v;try{if(typeof I=="string")v=I;else if(I instanceof Uint8Array)v=new TextDecoder("utf-8",{fatal:!0}).decode(I);else return}catch{return}let N=je(E,v);if(N.ok)return super.set(E,N.module),r.set(N.module.ast.program,N.module),N.module}}let c=new a;function l(b,E,k,I){let v=I?.loc?.start;t.push({code:b,source_path:E,message:k,...v?{call_site:{line:v.line,column:v.column}}:{}})}function u(b){if(!o.has(b.file)){if(o.size>=yv){l("CMS_MODULE_BUDGET_EXHAUSTED",b.file,"The module analysis budget was exhausted.");return}o.add(b.file);for(let E of b.ast.program.body){let k=null;if(Pe.isImportDeclaration(E)&&E.importKind!=="type"){if(E.specifiers.length&&E.specifiers.every(N=>Pe.isImportSpecifier(N)&&N.importKind==="type"))continue;k=E.source.value}else if(Pe.isExportNamedDeclaration(E)&&E.source&&E.exportKind!=="type"){if(E.specifiers.length&&E.specifiers.every(N=>Pe.isExportSpecifier(N)&&N.exportKind==="type"))continue;k=E.source.value}else Pe.isExportAllDeclaration(E)&&E.exportKind!=="type"&&(k=E.source.value);if(!k)continue;if(!nt(k)){l("CMS_EXTERNAL_MODULE_UNRESOLVED",b.file,"An external module's initialization effects cannot be proven safe.",E);continue}let I=Mr(b.file,k,e.files);if(!I){l("CMS_IMPORT_UNRESOLVED",b.file,`The local import ${k} is unavailable.`,E);continue}if(!/\.[cm]?[jt]sx?$/iu.test(I)||bv(I))continue;let v=c.get(I);v?u(v):l("CMS_SOURCE_UNAVAILABLE",I,"The imported source cannot be parsed.",E)}bj(b.ast,{Program(E){d(E,b,new Map),E.stop()}})}}function d(b,E,k){b.traverse({Function(I){(I.isObjectMethod()||I.isClassMethod()||I.isClassPrivateMethod())&&I.node.computed&&!jr(I.get("key"),k)&&l("CMS_IMPLICIT_EXECUTION_UNRESOLVED",E.file,"A computed method key may execute an unproven coercion.",I.node),I.skip()},BinaryExpression(I){(I.node.operator==="instanceof"||I.node.operator==="in"||I.node.operator!=="==="&&I.node.operator!=="!=="&&(!jr(I.get("left"),k)||!jr(I.get("right"),k)))&&l("CMS_IMPLICIT_EXECUTION_UNRESOLVED",E.file,"An operator may execute an unproven coercion or proxy trap.",I.node)},TemplateLiteral(I){I.get("expressions").some(v=>!jr(v,k))&&l("CMS_IMPLICIT_EXECUTION_UNRESOLVED",E.file,"Template interpolation may execute an unproven coercion.",I.node)},UnaryExpression(I){["+","-","~"].includes(I.node.operator)&&!jr(I.get("argument"),k)&&l("CMS_IMPLICIT_EXECUTION_UNRESOLVED",E.file,"A unary operator may execute an unproven coercion.",I.node)},UpdateExpression(I){l("CMS_IMPLICIT_EXECUTION_UNRESOLVED",E.file,"An update may execute an unproven coercion or proxy trap.",I.node)},ObjectProperty(I){I.node.computed&&!jr(I.get("key"),k)&&l("CMS_IMPLICIT_EXECUTION_UNRESOLVED",E.file,"A computed property key may execute an unproven coercion.",I.node)},ForInStatement(I){l("CMS_IMPLICIT_EXECUTION_UNRESOLVED",E.file,"Property enumeration may execute an unproven proxy trap.",I.node)},JSXOpeningElement(I){let v=I.node.name;if(Pe.isJSXIdentifier(v)&&/^[a-z]/u.test(v.name))return;if(Ej(I)){l("CMS_COMPONENT_REACHABILITY_UNPROVEN",E.file,"A component value is not proven to be rendered by the selected root.",I.node);return}if(!Pe.isJSXIdentifier(v)){l("CMS_COMPONENT_UNRESOLVED",E.file,"A dynamic or namespace component target is not proven.",I.node);return}let N=p(I.scope.getBinding(v.name),E);if(!N){l("CMS_COMPONENT_UNRESOLVED",E.file,"A rendered component target is not proven.",I.node);return}g(N,f(N,I,k))},JSXExpressionContainer(I){let v=I.get("expression");if(v.isFunctionExpression()||v.isArrowFunctionExpression())g(v,k);else if(v.isIdentifier()){let N=p(v.scope.getBinding(v.node.name),E);N?g(N,k):I.parentPath?.isJSXAttribute()&&Pe.isJSXIdentifier(I.parentPath.node.name)&&/^on[A-Z]/u.test(I.parentPath.node.name.name)&&l("CMS_CALL_TARGET_UNRESOLVED",E.file,"An event handler target cannot be proven.",v.node)}},MemberExpression(I){let v=I.parentPath;v?.isMemberExpression()&&v.node.object===I.node||(v?.isCallExpression()||v?.isOptionalCallExpression())&&v.node.callee===I.node||v?.isVariableDeclarator()&&v.node.init===I.node&&m(I,E,new Set)||l("CMS_PROPERTY_ACCESS_UNRESOLVED",E.file,"A property read may invoke an unproven getter or proxy.",I.node)},OptionalMemberExpression(I){l("CMS_PROPERTY_ACCESS_UNRESOLVED",E.file,"An optional property read may invoke an unproven getter or proxy.",I.node)},VariableDeclarator(I){(Pe.isObjectPattern(I.node.id)||Pe.isArrayPattern(I.node.id))&&l("CMS_DESTRUCTURING_UNRESOLVED",E.file,"Destructuring can invoke an unproven getter or iterator.",I.node)},ForOfStatement(I){l("CMS_ITERATION_UNRESOLVED",E.file,"An iterable may invoke an unproven iterator.",I.node)},SpreadElement(I){l("CMS_ITERATION_UNRESOLVED",E.file,"A spread may invoke an unproven iterator or getter.",I.node)},JSXSpreadAttribute(I){l("CMS_PROPERTY_ACCESS_UNRESOLVED",E.file,"A JSX spread may invoke an unproven getter or proxy.",I.node)},CallExpression(I){if(Pe.isImport(I.node.callee)){l("CMS_DYNAMIC_IMPORT_UNRESOLVED",E.file,"A dynamic import cannot prove the selected call closure.",I.node);return}for(let A of I.get("arguments"))(A.isFunctionExpression()||A.isArrowFunctionExpression())&&g(A,new Map);let v=I.get("callee"),N=m(v,E,new Set);if(N){if(Nr(E.ast,N.originalName)){l("CMS_BINDING_MUTATED",E.file,"The trusted CMS binding or one of its aliases is modified.",I.node);return}let w=I.get("arguments")[0],F=w?qt(w,k,new Set):null;if(!F||F.length===0){l("CMS_IDENTITY_UNRESOLVED",E.file,"The CMS application identity is not statically bounded.",I.node);return}let B=Sj(N.name);for(let X of F){let $=Ac(Pe.callExpression(B,[Pe.stringLiteral(X)]),{file:E.file,imports:new Map([["__vcpCms",{source:N.source,importedName:N.importedName}]])}),D=$?.operation==="getByUrl"||$?.operation==="getByUrlStrict"?/^\/([a-z0-9][a-z0-9_-]*)\/[a-z0-9][a-z0-9._~-]*$/iu.exec(X)?.[1]:$?.collection;if(!$||$.sourceKind!=="vcp-cms-collection"||!D||!/^[a-z0-9][a-z0-9_-]*$/iu.test(D)){l("CMS_OPERATION_UNRESOLVED",E.file,"The CMS operation or application identity cannot be proven.",I.node);continue}let fe=I.node.loc?.start;if(!fe){l("CMS_CALL_SITE_UNAVAILABLE",E.file,"The CMS call has no source location.",I.node);continue}let Fe={source_path:E.file,operation:$.operation,binding:"trusted-cms",call_site:{line:fe.line,column:fe.column}},ot=n.get(D)??[];ot.some(Tt=>JSON.stringify(Tt)===JSON.stringify(Fe))||ot.push(Fe),n.set(D,ot)}return}if(v.isIdentifier()){let A=v.scope.getBinding(v.node.name),w=p(A,E);if(w){let F=new Map,B=w.get("params");for(let[X,$]of B.entries()){if(!$.isIdentifier())continue;let G=w.scope.getBinding($.node.name),D=I.get("arguments")[X];G&&F.set(G.identifier,D?qt(D,k,new Set):null)}g(w,F);return}if(!A&&v.node.name==="Boolean"||!A&&["String","Number"].includes(v.node.name)&&I.get("arguments").every(F=>jr(F,k)))return}Ij(I,k,A=>!!m(A,E,new Set))||l("CMS_CALL_TARGET_UNRESOLVED",E.file,"A reachable call target cannot be proven free of hidden CMS access.",I.node)},OptionalCallExpression(I){l("CMS_CALL_TARGET_UNRESOLVED",E.file,"An optional call target cannot be proven.",I.node)},NewExpression(I){l("CMS_CALL_TARGET_UNRESOLVED",E.file,"A constructor's effects cannot be proven.",I.node)},TaggedTemplateExpression(I){l("CMS_CALL_TARGET_UNRESOLVED",E.file,"A tagged template's effects cannot be proven.",I.node)}})}function f(b,E,k){let I=new Map,v=b.get("params")[0];if(!v?.isObjectPattern())return I;let N=E.get("attributes"),A=N.some(w=>w.isJSXSpreadAttribute());for(let w of v.get("properties")){if(!w.isObjectProperty()||w.node.computed)continue;let F=w.node.key,B=Pe.isIdentifier(F)?F.name:Pe.isStringLiteral(F)?F.value:null,X=w.get("value"),$=X.isIdentifier()?X:X.isAssignmentPattern()&&X.get("left").isIdentifier()?X.get("left"):null;if(!B||!$?.isIdentifier())continue;let G=b.scope.getBinding($.node.name);if(!G)continue;let D=N.filter(ot=>ot.isJSXAttribute()&&Pe.isJSXIdentifier(ot.node.name,{name:B})),fe=null,Fe=D[0];if(!A&&D.length===1&&Fe?.isJSXAttribute()){let ot=Fe.get("value");ot.isStringLiteral()?fe=[ot.node.value]:ot.isJSXExpressionContainer()&&(fe=qt(ot.get("expression"),k,new Set))}I.set(G.identifier,fe)}return I}function g(b,E){let k=b.findParent(v=>v.isProgram()),I=k&&Pe.isProgram(k.node)?r.get(k.node):void 0;if(!I){l("CMS_FUNCTION_UNRESOLVED",e.entry_file,"A callable has no proven source module.",b.node);return}if(i.has(b.node)||s++>=yv){l("CMS_CALL_BUDGET_EXHAUSTED",I.file,"Recursive or excessive reachable calls are not proven.",b.node);return}i.add(b.node),d(b,I,E),i.delete(b.node)}function p(b,E){if(!b||b.constantViolations.length)return null;let k=b.path;if(k.isFunctionDeclaration())return k;if(k.isVariableDeclarator()){let B=k.get("init");return B.isFunctionExpression()||B.isArrowFunctionExpression()?B:null}let I=k.parentPath;if(!I?.isImportDeclaration()||I.node.importKind==="type")return null;let v=I.node.source.value;if(!nt(v))return null;let N=Mr(E.file,v,e.files),A=N&&c.get(N),w=k.isImportDefaultSpecifier()?"default":k.isImportSpecifier()&&Pe.isIdentifier(k.node.imported)?k.node.imported.name:null;if(!A||!w)return null;let F=br(A,w,c);return F&&(F.isFunctionDeclaration()||F.isFunctionExpression()||F.isArrowFunctionExpression())?F:null}function m(b,E,k){if(!b.node||k.has(b.node)||k.size>=32)return null;if(k.add(b.node),b.isMemberExpression()&&!b.node.optional){let F=!b.node.computed&&Pe.isIdentifier(b.node.property)?b.node.property.name:b.node.computed&&Pe.isStringLiteral(b.node.property)?b.node.property.value:null,B=m(b.get("object"),E,k);return B&&F?{...B,name:`${B.name}.${F}`}:null}if(!b.isIdentifier())return null;let I=b.scope.getBinding(b.node.name);if(!I||I.constantViolations.length)return null;if(I.path.isVariableDeclarator())return m(I.path.get("init"),E,k);let v=I.path.parentPath;if(!v?.isImportDeclaration()||!I.path.isImportSpecifier())return null;let N=I.path.node.imported,A=Pe.isIdentifier(N)?N.name:N.value,w=Mr(E.file,v.node.source.value,e.files);return!w||!bv(w)||!["cms","collections","cmsFetch","cmsFetchResult","cmsFetchEnvelope"].includes(A)?null:{name:"__vcpCms",source:w,importedName:A,originalName:I.identifier.name}}let y=c.get(e.entry_file);if(!y)l("CMS_ENTRY_UNAVAILABLE",e.entry_file,"The selected entry is missing or invalid.");else{u(y);let b=br(y,e.entry_export.kind==="default"?"default":e.entry_export.name,c);!b||!(b.isFunctionDeclaration()||b.isFunctionExpression()||b.isArrowFunctionExpression())?l("CMS_ENTRY_UNRESOLVED",e.entry_file,"The selected entry export is not one proven function."):g(b,new Map)}let x=[...n.entries()].sort(([b],[E])=>b.localeCompare(E)).map(([b,E])=>({requirement_key:`cms-${b}`,slug:b,evidence:E.sort((k,I)=>k.source_path.localeCompare(I.source_path)||k.call_site.line-I.call_site.line||k.call_site.column-I.call_site.column)})),S=[...new Map(t.map(b=>[JSON.stringify(b),b])).values()];return{complete:S.length===0,dependencies:x,unresolved:S}}function bv(e){return/^(?:src\/)?lib\/cms(?:\/index|\/collections|\/client)?\.[cm]?[jt]s$/u.test(e)}function Ej(e){let t=e.parentPath?.parentPath;for(;t&&!t.isFunction()&&!t.isProgram();){if(t.isVariableDeclarator()||t.isJSXAttribute())return!0;if(t.isJSXElement()){let n=t.node.openingElement.name;if(!Pe.isJSXIdentifier(n)||!/^[a-z]/u.test(n.name))return!0}t=t.parentPath}return!1}function Sj(e){let[t,...n]=e.split(".");return n.reduce((r,o)=>Pe.memberExpression(r,Pe.identifier(o)),Pe.identifier(t))}function Ij(e,t,n){let r=e.node.callee;if(!(Pe.isMemberExpression(r)&&!r.computed&&Pe.isIdentifier(r.object,{name:"Promise"})&&!e.scope.getBinding("Promise")&&Pe.isIdentifier(r.property,{name:"all"})))return!1;let o=e.get("arguments")[0];return o?.isArrayExpression()?o.get("elements").every(i=>!i.node||jr(i,t)||i.isCallExpression()&&n(i.get("callee"))):!1}function jr(e,t){return e.isStringLiteral()||e.isNumericLiteral()||e.isBooleanLiteral()||e.isNullLiteral()||qt(e,t,new Set)!==null}function qt(e,t,n){if(!e.node||n.has(e.node)||n.size>=32)return null;let r=new Set(n).add(e.node);if(e.isStringLiteral())return[e.node.value];if(e.isIdentifier()){let o=e.scope.getBinding(e.node.name);return!o||o.constantViolations.length?null:t.has(o.identifier)?t.get(o.identifier)??null:o.path.isVariableDeclarator()&&o.path.parentPath.isVariableDeclaration({kind:"const"})?qt(o.path.get("init"),t,r):null}if(e.isTSAsExpression()||e.isTSSatisfiesExpression()||e.isTSNonNullExpression()||e.isParenthesizedExpression())return qt(e.get("expression"),t,r);if(e.isConditionalExpression()){let o=qt(e.get("consequent"),t,r),i=qt(e.get("alternate"),t,r);if(!o||!i)return null;let s=[...new Set([...o,...i])];return s.length<=xv?s:null}if(e.isBinaryExpression({operator:"+"})){let o=qt(e.get("left"),t,r),i=qt(e.get("right"),t,r);return!o||!i||o.length*i.length>xv?null:[...new Set(o.flatMap(s=>i.map(a=>s+a)))]}return null}import gm from"@babel/generator";import hm from"@babel/traverse";import*as oe from"@babel/types";var Sv=typeof hm=="function"?hm:hm.default,vj=typeof gm=="function"?gm:gm.default;function vv(e){let t=new Map(e.files),n=new Set(e.private_paths),r=[];for(let o of e.private_paths){let i=_v(t.get(o));if(i===null||!/\.[jt]sx?$/iu.test(o))continue;let s=je(o,i);if(!s.ok){r.push({code:"SOURCE_PARSE_FAILED",path:o,message:s.diagnostic.message});continue}let a=!1;Sv(s.module.ast,{Function:{exit(c){let l=c.get("body");l.isBlockStatement()&&(l.scope.crawl(),Iv(l)&&(a=!0))}}}),Sv(s.module.ast,{Program(c){let l;do{c.scope.crawl(),l=Iv(c),l&&(a=!0),l&&c.scope.crawl();for(let d of c.get("body"))(d.isFunctionDeclaration()&&d.node.id&&!c.scope.getBinding(d.node.id.name)?.referenced||d.isVariableDeclaration({kind:"const"})&&d.node.declarations.every(f=>oe.isIdentifier(f.id)&&!c.scope.getBinding(f.id.name)?.referenced&&(!f.init||li(f.init))))&&(d.remove(),l=a=!0)}while(l);c.scope.crawl();let u=0;for(let d of c.node.body)oe.isExportDefaultDeclaration(d)?u+=1:oe.isExportAllDeclaration(d)&&d.exportKind!=="type"?u+=2:oe.isExportNamedDeclaration(d)&&d.exportKind!=="type"&&(d.declaration&&!oe.isTSInterfaceDeclaration(d.declaration)&&!oe.isTSTypeAliasDeclaration(d.declaration)&&(u+=Object.keys(oe.getOuterBindingIdentifiers(d.declaration)).length),u+=d.specifiers.filter(f=>!oe.isExportSpecifier(f)||f.exportKind!=="type").length);u>1&&r.push({code:"SOURCE_EXPORT_ISOLATION_UNPROVEN",path:o,message:"Multiple value exports cannot yet be isolated from unselected source."});for(let d of c.get("body")){if(!d.isImportDeclaration()||d.node.importKind==="type"||d.node.specifiers.length===0||!nt(d.node.source.value))continue;let f=Mr(o,d.node.source.value,t);if(!(!f||!n.has(f))&&!d.node.specifiers.some(g=>c.scope.getBinding(g.local.name)?.referenced)){if(!kv(f,t,new Set)){r.push({code:"SOURCE_UNUSED_IMPORT_UNPROVEN",path:o,message:`The unused import ${d.node.source.value} may have initialization effects.`});continue}d.remove(),a=!0}}c.stop()}}),a&&t.set(o,vj(s.module.ast).code)}return{files:t,errors:r}}function Iv(e){let t=new Map;for(let c of e.get("body")){let l=null,u=null;if(c.isFunctionDeclaration()&&c.node.id)l=c.node.id.name,u=c.node;else if(c.isVariableDeclaration({kind:"const"})&&c.node.declarations.length===1){let f=c.node.declarations[0];oe.isIdentifier(f.id)&&(oe.isFunctionExpression(f.init)||oe.isArrowFunctionExpression(f.init))&&(l=f.id.name,u=f.init)}let d=l?e.scope.getBinding(l):void 0;l&&u&&d&&d.constantViolations.length===0&&t.set(l,{definition:u,declaration:c,binding:d})}let n=new Map([...t].map(([c,l])=>[l.definition,c])),r=new Set,o=new Map;for(let[c,l]of t)for(let u of l.binding.referencePaths){let d=u.findParent(g=>n.has(g.node)),f=d?n.get(d.node):void 0;if(!f)r.add(c);else{let g=o.get(f)??new Set;g.add(c),o.set(f,g)}}let i=new Set,s=[...r];for(;s.length;){let c=s.pop();i.has(c)||(i.add(c),s.push(...o.get(c)??[]))}let a=!1;for(let[c,l]of t)i.has(c)||(l.declaration.remove(),a=!0);return a}function kv(e,t,n){if(n.has(e)||n.size>=64)return!1;let r=_v(t.get(e));if(r===null)return!1;let o=je(e,r);if(!o.ok)return!1;let i=new Set(n).add(e),s=a=>{if(!nt(a))return!1;let c=Mr(e,a,t);return c!==null&&kv(c,t,i)};return o.module.ast.program.body.every(a=>oe.isImportDeclaration(a)?a.importKind==="type"||a.specifiers.length>0&&a.specifiers.every(c=>oe.isImportSpecifier(c)&&c.importKind==="type")?!0:s(a.source.value):oe.isExportAllDeclaration(a)?a.exportKind==="type"||s(a.source.value):oe.isExportNamedDeclaration(a)?a.exportKind==="type"?!0:a.source?s(a.source.value):a.declaration?ym(a.declaration):!0:oe.isExportDefaultDeclaration(a)?ym(a.declaration):ym(a))}function ym(e){return oe.isFunctionDeclaration(e)||oe.isTSInterfaceDeclaration(e)||oe.isTSTypeAliasDeclaration(e)||oe.isTSDeclareFunction(e)||oe.isEmptyStatement(e)?!0:oe.isVariableDeclaration(e)&&e.kind==="const"?e.declarations.every(t=>oe.isIdentifier(t.id)&&(!t.init||li(t.init))):li(e)}function li(e){return oe.isStringLiteral(e)||oe.isNumericLiteral(e)||oe.isBooleanLiteral(e)||oe.isNullLiteral(e)||oe.isFunctionExpression(e)||oe.isArrowFunctionExpression(e)?!0:oe.isArrayExpression(e)?e.elements.every(t=>t===null||!oe.isSpreadElement(t)&&li(t)):oe.isObjectExpression(e)?e.properties.every(t=>oe.isObjectProperty(t)&&!t.computed&&!t.shorthand&&li(t.value)):oe.isTSAsExpression(e)||oe.isTSSatisfiesExpression(e)||oe.isTSNonNullExpression(e)||oe.isParenthesizedExpression(e)?li(e.expression):!1}function _v(e){if(typeof e=="string")return e;if(!(e instanceof Uint8Array))return null;try{return new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch{return null}}import{createHash as kj}from"node:crypto";import _j from"@babel/traverse";import*as Be from"@babel/types";var xm=_j,Cj=typeof xm=="function"?xm:xm.default,Rj=new Set(["avif","bmp","gif","jpeg","jpg","mp3","mp4","ogg","png","svg","wav","webm","webp"]),ui=new Set(["backgroundimage","image","imageurl","media","mediaurl","poster","src","srcset","thumbnail","thumbnailurl"]),Nj=/(?:asset|avatar|gallery|image|media|photo|poster|thumbnail|video)/iu,Pj=/^(?:audio|img|image|picture|safeimage|source|video|media|.*(?:audio|image|video))$/iu;function bm(e){let t=je(e.file_path,e.source);if(!t.ok)return{complete:!1,references:[],errors:[{code:"MEDIA_SOURCE_PARSE_FAILED",file_path:e.file_path,message:t.diagnostic.message}]};let n=[],r=[],o=new Set,i=c=>{let l=Rv(c.node),u=Mj(e.source,l),d=`${l.start_offset}:${l.end_offset}:${c.kind}:${c.value??"<unknown>"}`;o.has(d)||(o.add(d),n.push({file_path:e.file_path,occurrence:n.length,kind:c.kind,source:c.source,value:c.value,expression:u,asset_key:c.assetKey??null,source_range:l,content_digest:Dj(u),complete:c.complete}),c.complete||r.push({code:"MEDIA_VALUE_UNKNOWN",file_path:e.file_path,message:"The media expression cannot be resolved without executing user code.",source_range:l}))},s=(c,l)=>{if(!l){i({node:c,kind:"manifest",source:"media-manifest",value:null,complete:!1});return}let u=e.media_manifest?.[l];if(u===void 0){let d=Rv(c);r.push({code:"MEDIA_MANIFEST_KEY_UNKNOWN",file_path:e.file_path,message:`The media manifest key ${l} is not available in the supplied snapshot.`,source_range:d})}i({node:c,kind:"manifest",source:"media-manifest",value:u??null,assetKey:l,complete:u!==void 0})};Cj(t.module.ast,{ImportDeclaration(c){let l=c.node.source.value;Aj(l)&&i({node:c.node.source,kind:"import",source:"import",value:l,complete:!0})},JSXOpeningElement(c){let l=Nv(c.node.name),u=Pj.test(l);for(let d of c.node.attributes){if(Be.isJSXSpreadAttribute(d)){u&&i({node:d.argument,kind:"object",source:"jsx-attribute",value:null,complete:!1});continue}let f=wj(d);if(!f||!Tj(f,u))continue;let g=$r(d.value);i({node:d.value??d,kind:Cv(f),source:"jsx-attribute",value:g.value,complete:g.complete})}},ObjectProperty(c){let l=Tl(c.node.key);if(!l||!ui.has(l)&&!(Lj(c)&&Pv(l))||ui.has(l)&&Pl(c.node.value)&&Al(c.node.value))return;let u=$r(c.node.value);i({node:c.node.value,kind:Cv(l),source:"object-property",value:u.value,complete:u.complete})},ArrayExpression(c){if(Fj(c))for(let l of c.node.elements){if(!l||Pl(l)&&Al(l))continue;let u=$r(l);(u.value!==null||!u.complete)&&i({node:l,kind:"array-item",source:"array-item",value:u.value,complete:u.complete})}},CallExpression(c){let l=c.node.callee;if(!Be.isIdentifier(l,{name:"mediaAsset"})||c.node.arguments.length!==1)return;let u=c.node.arguments[0];if(!Be.isExpression(u)){s(c.node,null);return}let d=$r(u);s(c.node,d.complete?d.value:null)},MemberExpression(c){if(!Oj(c.node.object))return;let l=c.node.computed?$r(c.node.property):Be.isIdentifier(c.node.property)?{value:c.node.property.name,complete:!0}:{value:null,complete:!1};s(c.node,l.complete?l.value:null)}});let a=Bj(r).sort(jj);return{complete:a.length===0,references:n.map((c,l)=>({...c,occurrence:l})),errors:a}}function Aj(e){let n=(e.split(/[?#]/u,1)[0]??"").split(".").pop()?.toLowerCase();return n!==void 0&&Rj.has(n)}function Tj(e,t){return e!=="src"||t?ui.has(e):!1}function Cv(e){return e==="srcset"?"srcset":e==="poster"?"poster":e.startsWith("thumbnail")?"thumbnail":e==="src"?"src":"object"}function wj(e){return Be.isJSXIdentifier(e.name)?e.name.name.toLowerCase():Be.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`.toLowerCase():null}function Nv(e){return Be.isJSXIdentifier(e)?e.name:Be.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:`${Nv(e.object)}.${e.property.name}`}function Tl(e){return Be.isIdentifier(e)?e.name.toLowerCase():Be.isStringLiteral(e)?e.value.toLowerCase():null}function Oj(e){return Be.isIdentifier(e,{name:"mediaAssets"})}function Fj(e){let t=e.parentPath;if(t?.isObjectProperty()){let n=Tl(t.node.key);return n!==null&&ui.has(n)}return t?.isVariableDeclarator()&&Be.isIdentifier(t.node.id)?Nj.test(t.node.id.name):!1}function Lj(e){let n=e.parentPath?.parentPath;if(!n?.isObjectProperty())return!1;let r=Tl(n.node.key);return r!==null&&ui.has(r)}function Pv(e){return e==="src"||e==="srcset"||e==="url"||e==="thumbnail_url"}function Pl(e){return Be.isObjectExpression(e)||Be.isArrayExpression(e)}function Al(e){if(Be.isArrayExpression(e))return e.elements.some(n=>n!==null&&(Pl(n)?Al(n):!0));let t=!1;for(let n of e.properties){if(!Be.isObjectProperty(n))return!1;let r=Tl(n.key);if(r!==null&&(ui.has(r)||Pv(r))){t=!0;continue}Pl(n.value)&&Al(n.value)&&(t=!0)}return t}function $r(e){return e?Be.isStringLiteral(e)?{value:e.value,complete:!0}:Be.isJSXExpressionContainer(e)?$r(e.expression):Be.isTemplateLiteral(e)&&e.expressions.length===0?{value:e.quasis.map(t=>t.value.cooked??t.value.raw).join(""),complete:!0}:Be.isTSAsExpression(e)||Be.isTSTypeAssertion(e)||Be.isParenthesizedExpression(e)?$r(e.expression):{value:null,complete:!1}:{value:null,complete:!1}}function Rv(e){let t=e.start??0,n=e.end??t;return{start_offset:t,end_offset:n,start_line:e.loc?.start.line??1,start_column:e.loc?.start.column??0,end_line:e.loc?.end.line??e.loc?.start.line??1,end_column:e.loc?.end.column??e.loc?.start.column??0}}function Mj(e,t){return e.slice(t.start_offset,t.end_offset)}function Dj(e){return`sha256:${kj("sha256").update(e).digest("hex")}`}function Bj(e){let t=new Set;return e.filter(n=>{let r=`${n.code}:${n.file_path}:${n.source_range?.start_offset??-1}`;return t.has(r)?!1:(t.add(r),!0)})}function jj(e,t){return e.file_path.localeCompare(t.file_path)||(e.source_range?.start_offset??0)-(t.source_range?.start_offset??0)||e.code.localeCompare(t.code)}var Tv=512,Jj=1024*1024,Xj=8*1024*1024,wv=256;function zj(e){let t=()=>({complete:!1,unresolved:[{code:"PORTABLE_LOCAL_ASSET_UNAVAILABLE",path:"<asset>",message:"The selected local image could not be verified."}]});if(!e.exported.complete||e.snapshot_digest!==e.exported.snapshot_digest||Fv(e.snapshot_files)!==e.snapshot_digest||!Number.isSafeInteger(e.occurrence)||e.occurrence<0||!Number.isSafeInteger(e.offset)||e.offset<0||e.offset%Av!==0)return t();let n=e.exported.media.filter(u=>u.file_path===e.file_path&&u.occurrence===e.occurrence);if(n.length!==1)return t();let r=n[0],o=r.value;if(!r.complete||!o||r.kind==="srcset"||!o.startsWith("/")||o.startsWith("//")||/[\\\0%?#]/u.test(o))return t();let i=o.slice(1).split("/");if(i.some(u=>!u||u.startsWith(".")||u==="node_modules"))return t();let s=`public/${i.join("/")}`,a=e.snapshot_files.get(s);if(!(a instanceof Uint8Array)||!a.byteLength||a.byteLength>Uj||e.offset>=a.byteLength)return t();let c=Hj(s,a);if(!c)return t();let l=Buffer.from(a);return{complete:!0,snapshot_digest:e.snapshot_digest,file_path:e.file_path,occurrence:e.occurrence,path:s,mime_type:c,byte_size:l.byteLength,digest_sha256:vm("sha256").update(l).digest("hex"),offset:e.offset,data_base64:l.subarray(e.offset,e.offset+Av).toString("base64")}}function Hj(e,t){let n=e.toLowerCase(),r=o=>o.every((i,s)=>t[s]===i);return n.endsWith(".png")&&r([137,80,78,71,13,10,26,10])?"image/png":/\.jpe?g$/u.test(n)&&r([255,216,255])?"image/jpeg":n.endsWith(".gif")&&(r([71,73,70,56,55,97])||r([71,73,70,56,57,97]))?"image/gif":n.endsWith(".webp")&&r([82,73,70,70])&&t[8]===87&&t[9]===69&&t[10]===66&&t[11]===80?"image/webp":null}async function Wj(e){if(e.snapshot.site_id!==e.site_id||e.snapshot.snapshot_id!==e.base_snapshot_id)return Qt("SNAPSHOT_MISMATCH","<snapshot>","The authoritative Snapshot does not match the requested site and version.");let t=e.site_id,n=e.base_snapshot_id,r=e.document_version,o=e.read_current_identity,i=new Map(e.trusted_host_file_hashes??[]),s=Kj.safeParse(e.target),a=$j.safeParse(e.selection_ref);if(!s.success||!a.success)return Qt("BLOCK_SELECTION_INVALID","<selection>","The block target or render occurrence is invalid.");let c=s.data,l=a.data,u=Ov(o,t,n,r);if(u)return u;let d=Vj.safeParse(e.host_capabilities);if(!d.success)return Qt("HOST_CAPABILITIES_INVALID","<host-capabilities>","The host capability contract is invalid.");let f=new Map;for(let[D,fe]of e.snapshot.files){if(typeof fe!="string"&&!(fe instanceof Uint8Array))return Qt("SNAPSHOT_CONTENT_MISMATCH",D,"A Snapshot file has an unsupported content type.");f.set(D,typeof fe=="string"?fe:new Uint8Array(fe))}if(!Yj(e.snapshot.manifest,t,n,f))return Qt("SNAPSHOT_CONTENT_MISMATCH","<snapshot>","The file mapping does not match the authenticated Snapshot manifest.");let g=Fv(f),p=await Op({site_id:t,base_snapshot_id:n,composition:c.composition,document_version:r,target:c,selection_ref:l,files:f});if(!p.ok)return Qt(`BLOCK_${p.code}`,c.blockKey,p.message);if(!p.binding.descriptor.capabilities.save)return Qt("BLOCK_EXPORT_NOT_ALLOWED",c.blockKey,"The selected block is not exportable.");let m=pm({binding:p.binding,files:f,hostCapabilities:d.data});if(!m.complete)return Sm(m.errors.map(({code:D,path:fe,message:Fe})=>({code:D,path:fe,message:Fe})));let y=Jp({selection:m.selection,files:f});if(!y.complete)return Sm(y.errors.map(({code:D,path:fe,message:Fe})=>({code:D,path:fe,message:Fe})));let x=new Map(f);for(let D of y.source_files){let fe=x.get(D.path);if(fe!==void 0&&!Gj(fe,D.content))return Qt("SOURCE_COLLISION",D.path,"An extracted entry conflicts with the pinned Snapshot.");x.set(D.path,D.content)}let S=Lr({entry_files:[y.entry_file],files:x,max_nodes:Tv}),b=S.nodes.filter(D=>Em(D.path)&&i.get(D.path)===Im(x.get(D.path))).map(D=>D.path),E=fl({closure:S,host_capabilities:d.data,platform_managed_paths:b,platform_managed_packages:["server-only"]}),k=vv({files:x,private_paths:E.nodes.filter(D=>D.ownership==="private").map(D=>D.path)});x=new Map(k.files);let I=Lr({entry_files:[y.entry_file],files:x,max_nodes:Tv}),v=fl({closure:I,host_capabilities:d.data,platform_managed_paths:b,platform_managed_packages:["server-only"]}),N=Ev({entry_file:y.entry_file,entry_export:m.selection.entry_export,files:x}),A=[...k.errors.filter(D=>I.nodes.some(fe=>fe.path===D.path)),...v.errors.map(({code:D,path:fe,message:Fe})=>({code:D,path:fe,message:Fe})),...N.unresolved.map(({code:D,source_path:fe,message:Fe,call_site:ot})=>({code:D,path:fe,message:Fe,...ot?{call_site:ot}:{}}))],w=new Set(b);for(let D of I.nodes)Em(D.path)&&!w.has(D.path)&&A.push({code:"HOST_CMS_IMPLEMENTATION_UNPROVEN",path:D.path,message:"A CMS host implementation requires trusted matching provenance regardless of its declared ownership."});for(let D of v.nodes)D.kind==="external"||D.ownership!=="host-public"||Em(D.path)||i.get(D.path)!==Im(f.get(D.path))&&A.push({code:"HOST_IMPLEMENTATION_UNPROVEN",path:D.path,message:"A host-public source requires trusted matching provenance before it may be omitted from the export."});let F=new Map(v.nodes.map(D=>[D.path,D.ownership])),B=[];for(let D of I.nodes){if(F.get(D.path)!=="private")continue;let fe=x.get(D.path),Fe=null;try{typeof fe=="string"?Fe=fe:fe instanceof Uint8Array&&(Fe=new TextDecoder("utf-8",{fatal:!0}).decode(fe))}catch{}Fe===null?A.push({code:"SOURCE_TEXT_UNSUPPORTED",path:D.path,message:"A private source dependency is not valid UTF-8 text."}):B.push({path:D.path,content:Fe})}for(let D of B)(/^(?:src\/)?components\/site\/generated\/(?:forms|product-search)\//u.test(D.path)||D.path==="lib/generated/product-search-config.json")&&A.push({code:"MANAGED_REQUIREMENT_UNPROVEN",path:D.path,message:"A managed capability requires a proven requirement before exporting the block."});B.some(D=>D.path===y.entry_file)||A.push({code:"ENTRY_NOT_PRIVATE",path:y.entry_file,message:"The selected entry is not site-owned source."});let X=0,$=[];for(let D of B){let fe=Buffer.byteLength(D.content,"utf8");if(X+=fe,(fe>Jj||X>Xj)&&A.push({code:"SOURCE_BUDGET_EXCEEDED",path:D.path,message:"The selected source exceeds its export byte budget."}),/\.[jt]sx?$/iu.test(D.path)){let Fe=bm({file_path:D.path,source:D.content});$.push(...Fe.references),A.push(...Fe.errors.map(({code:ot,file_path:Tt,message:Vr})=>({code:ot,path:Tt,message:Vr})))}}if(A.length>0||!I.complete||!v.complete||!N.complete)return Sm(A);let G=Ov(o,t,n,r);return G||{complete:!0,site_id:t,base_snapshot_id:n,snapshot_digest:g,document_version:r,target:m.selection.target,selection_ref:y.selected_root_ref,entry:{file:y.entry_file,export:m.selection.entry_export},files:B.map(({path:D,content:fe})=>({path:D,content:fe})),source_closure:I,dependency_audit:v,cms:N,media:$,invocation_bindings:y.invocation_bindings,host_contract_digest:d.data.host_contract_digest}}function Ov(e,t,n,r){if(!Number.isSafeInteger(r)||r<0)return Qt("DOCUMENT_VERSION_STALE","<document>","The selected document version is invalid.");try{let o=e();return o.site_id!==t||o.snapshot_id!==n?Qt("SNAPSHOT_MISMATCH","<snapshot>","The live runtime no longer matches the requested Snapshot."):o.document_version!==r?Qt("DOCUMENT_VERSION_STALE","<document>","The live document version changed during export."):null}catch{return Qt("RUNTIME_IDENTITY_UNAVAILABLE","<document>","The live runtime identity could not be verified.")}}function Fv(e){let t=vm("sha256");for(let[n,r]of[...e.entries()].sort(([o],[i])=>o.localeCompare(i))){let o=typeof r=="string"?Buffer.from(r,"utf8"):r;t.update(`${n.length}:${n}:${o.byteLength}:`),t.update(o)}return`sha256:${t.digest("hex")}`}function Gj(e,t){return typeof e=="string"?e===t:Buffer.from(e).equals(Buffer.from(t,"utf8"))}function Em(e){return/^(?:src\/)?lib\/cms\/(?!generated\/)/u.test(e)}function Im(e){return e===void 0?null:`sha256:${vm("sha256").update(e).digest("hex")}`}function Yj(e,t,n,r){if(!e||e.version!==1||e.site_id!==t||e.snapshot_id!==n||!Array.isArray(e.files)||e.files.length!==r.size)return!1;let o=new Set;for(let i of e.files){if(!i||typeof i.path!="string"||!i.path||i.path.startsWith("/")||i.path.includes("\\")||i.path.includes("\0")||i.path.split("/").some(a=>!a||a==="."||a==="..")||o.has(i.path)||!/^sha256:[a-f0-9]{64}$/u.test(i.hash)||!Number.isSafeInteger(i.size_bytes)||i.size_bytes<0)return!1;o.add(i.path);let s=r.get(i.path);if(s===void 0||Im(s)!==i.hash||(typeof s=="string"?Buffer.byteLength(s,"utf8"):s.byteLength)!==i.size_bytes)return!1}return!0}function Qt(e,t,n){return{complete:!1,unresolved:[{code:e,path:t,message:n}]}}function Sm(e){return e.length?e.length<=wv?{complete:!1,unresolved:e}:{complete:!1,unresolved:[...e.slice(0,wv-1),{code:"PORTABLE_DIAGNOSTICS_TRUNCATED",path:"<selection>",message:"Additional unresolved export diagnostics were omitted."}]}:Qt("PORTABLE_EXPORT_INCOMPLETE","<selection>","The selected block's export proof is incomplete.")}import km from"@babel/generator";import{parse as Zj}from"@babel/parser";import qj from"@babel/traverse";import*as gt from"@babel/types";var _m=qj,Qj=typeof _m=="function"?_m:_m.default,e0=typeof km=="function"?km:km.default,$v="components/site/generated/{{$INSTANCE}}/",Vv=new Set([".tsx",".ts",".jsx",".js"]),Lv=new Set(["data-site-block-id","data-vcp-block-id","data-vcp-edit-key"]),t0=new Set(["data-site-block-order","data-vcp-order"]);function n0(e){let t=[],n=new Map,r=new Map;/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/u.test(e.instance_base_name)||t.push({code:"SOURCE_INPUT_INVALID",path:"instance_base_name",message:"The portable instance base name is not safe."});for(let b of e.source_files){let E=nr(b.path);if(!E||n.has(E)){t.push({code:"SOURCE_INPUT_INVALID",path:b.path,message:"Portable source files must have unique safe paths."});continue}n.set(E,{...b,path:E})}for(let b of e.ownership){let E=nr(b.path);if(!E||r.has(E)){t.push({code:"SOURCE_INPUT_INVALID",path:b.path,message:"Portable source ownership entries must be unique and safe."});continue}r.set(E,{...b,path:E})}let o=nr(e.entry_file);n.get(o)?r.get(o)?.ownership!=="private"&&t.push({code:"SOURCE_ENTRY_NOT_PRIVATE",path:o,message:"The selected portable source entry must be private source."}):t.push({code:"SOURCE_ENTRY_NOT_FOUND",path:e.entry_file,message:"The selected portable source entry is not present."});for(let b of n.keys())r.has(b)||t.push({code:"SOURCE_OWNERSHIP_MISSING",path:b,message:"Every source closure file requires an ownership decision."});let s=[...n.keys()].filter(b=>r.get(b)?.ownership==="private").sort((b,E)=>b.localeCompare(E)),a=s.map(b=>({source_path:b,path_template:u0(b)})),c=new Map(a.map(b=>[b.source_path,b.path_template])),l=r0(e.source_mapping??[],c,t),u=o0(e.required_source_paths??[],c,t),d=[],f=new Map,g=[];for(let b of s){let E=n.get(b);if(!E)continue;let k=s0(b,E.content,r,c,d,f,t);k!==null&&g.push({path_template:c.get(b),content:k,...E.role?{role:E.role}:{}})}let p=Bv(t).sort(jv);if(p.length>0)return{complete:!1,entry_path_template:null,files:[],source_path_mappings:[],required_path_mappings:[],source_mapping:[],managed_rebindings:[],block_metadata:[],errors:p};let m=g.map(b=>{let E=a.find(I=>I.path_template===b.path_template)?.source_path,k=n.get(E)?.content??"";return{source_path:E,path_template:b.path_template,original_byte_size:Mv(k),output_byte_size:Mv(b.content),original_line_count:Dv(k),output_line_count:Dv(b.content)}}),y=[...f.values()].map(b=>({...b,normalized:!0})).sort((b,E)=>b.source_path.localeCompare(E.source_path)),x=c.get(o)??null;if(e.thin_entry_plan){let b=i0(e.thin_entry_plan,c,t);b&&(g.push(b),x=b.path_template)}let S=Bv(t).sort(jv);return S.length>0?{complete:!1,entry_path_template:null,files:[],source_path_mappings:[],required_path_mappings:[],source_mapping:[],managed_rebindings:[],block_metadata:[],errors:S}:{complete:!0,entry_path_template:x,files:g.sort((b,E)=>b.path_template.localeCompare(E.path_template)),source_path_mappings:m.sort((b,E)=>b.path_template.localeCompare(E.path_template)),required_path_mappings:u,source_mapping:l,managed_rebindings:d.sort(g0),block_metadata:y,errors:[]}}function r0(e,t,n){let r=new Set,o=[];for(let[i,s]of e.entries()){let a=nr(s.generated_path),c=nr(s.source_file),l=a,u=t.get(a);if(!a||a!==s.generated_path||!c||c!==s.source_file||!s.structural_path||r.has(l)){n.push({code:"SOURCE_REQUIRED_PATH_INVALID",path:`source_mapping.${i}`,message:"Portable selected-source mappings require unique safe paths and structural identities."});continue}if(r.add(l),!u){n.push({code:"SOURCE_REQUIRED_PATH_UNMAPPED",path:s.generated_path,message:"A selected-source mapping must resolve to one private normalized entry path."});continue}o.push({...s,path_template:u})}return o.sort((i,s)=>i.path_template.localeCompare(s.path_template)||i.source_file.localeCompare(s.source_file)||i.structural_path.localeCompare(s.structural_path))}function o0(e,t,n){let r=new Set,o=new Set,i=[];for(let[s,a]of e.entries()){let c=nr(a.source_path);if(!/^[a-z][a-z0-9-]{0,127}$/u.test(a.key)||!c||r.has(a.key)||o.has(c)){n.push({code:"SOURCE_REQUIRED_PATH_INVALID",path:`required_source_paths.${s}`,message:"Required portable source paths must use unique safe keys and source identities."});continue}r.add(a.key),o.add(c);let l=t.get(c);if(!l){n.push({code:"SOURCE_REQUIRED_PATH_UNMAPPED",path:a.source_path,message:"A required portable source identity must map to exactly one private package path."});continue}i.push({key:a.key,source_path:c,path_template:l})}return i.sort((s,a)=>s.key.localeCompare(a.key)||s.source_path.localeCompare(a.source_path))}function i0(e,t,n){if(e.adds_dom!==!1)return n.push({code:"SOURCE_THIN_ENTRY_INVALID",path:e.source_file,message:"A managed-root thin entry must not add DOM."}),null;let r=t.get(nr(e.component_source));if(!r)return n.push({code:"SOURCE_THIN_ENTRY_TARGET_MISSING",path:e.component_source,message:"The managed-root thin entry target is not private materialized source."}),null;if(!/^(?:default|[A-Za-z_$][A-Za-z0-9_$]*)$/u.test(e.component_export))return n.push({code:"SOURCE_THIN_ENTRY_INVALID",path:e.component_export,message:"The managed-root thin entry export is not a safe export name."}),null;let o=`${$v}__managed-root-entry.tsx`,i=Uv(o,r,"./component"),s=e.component_export==="default"?`import Root from ${JSON.stringify(i)};`:`import { ${e.component_export} as Root } from ${JSON.stringify(i)};`;return{path_template:o,role:"managed-root-thin-entry",content:`${s}
17
17
  export default function PortableManagedRootEntry(props: Parameters<typeof Root>[0]) {
18
18
  return <Root {...props} />;
19
19
  }
20
- `}}function s0(e,t,n,r,o,i,s){if(!m0(e))return t;let a;try{a=Zj(t,{sourceType:"module",sourceFilename:e,plugins:["jsx","typescript"]})}catch(l){return s.push({code:"SOURCE_PARSE_FAILED",path:e,message:l instanceof Error?l.message:String(l)}),null}let c=l=>{let u=l.value,d=a0(e,u,n.keys());if(d.status==="external")return;if(d.status==="unresolved"){s.push({code:"SOURCE_IMPORT_UNRESOLVED",path:e,specifier:u,message:`The local import ${u} cannot be resolved.`});return}if(d.status==="ambiguous"){s.push({code:"SOURCE_IMPORT_AMBIGUOUS",path:e,specifier:u,message:`The local import ${u} resolves to multiple files.`});return}let f=n.get(d.path);if(!f){s.push({code:"SOURCE_IMPORT_TARGET_UNOWNED",path:e,specifier:u,message:`The local import target ${d.path} has no ownership decision.`});return}if(f.ownership==="private"){let m=r.get(d.path);if(!m){s.push({code:"SOURCE_IMPORT_TARGET_UNOWNED",path:e,specifier:u,message:`The private import target ${d.path} was not materialized.`});return}l.value=Uv(r.get(e),m,u);return}if(f.ownership!=="platform-managed"&&f.ownership!=="host-public"){s.push({code:"SOURCE_IMPORT_TARGET_UNOWNED",path:e,specifier:u,message:`The import target ${d.path} is not portable source.`});return}let g=c0(d.path,u);l.value=g;let p=f.requirement_key??"host-public";if(!/^[a-z][a-z0-9._-]{0,127}$/u.test(p)){s.push({code:"SOURCE_MANAGED_REBIND_INVALID",path:e,specifier:u,message:"Managed import rebinding requires a safe requirement key."});return}o.push({source_path:e,original_specifier:u,target_path:d.path,rebound_specifier:g,requirement_key:p})};return Qj(a,{ImportDeclaration(l){c(l.node.source)},ExportNamedDeclaration(l){l.node.source&&c(l.node.source)},ExportAllDeclaration(l){c(l.node.source)},CallExpression(l){let u=l.node.callee,d=l.node.arguments[0];(gt.isImport(u)||gt.isIdentifier(u,{name:"require"})&&l.node.arguments.length===1)&&gt.isStringLiteral(d)&&c(d)},JSXAttribute(l){let u=d0(l.node.name);if(!u||!Lv.has(u)&&!t0.has(u))return;let d=l.parentPath.parentPath?.node,f=typeof d?.start=="number"?d.start:l.node.start??0,g=`${e}:${f}`,p=i.get(g)??{source_path:e,original_block_attribute:null,original_block_id:null,original_order:null};Lv.has(u)?(p.original_block_attribute=u,p.original_block_id=f0(l.node.value)):p.original_order=p0(l.node.value),i.set(g,p),l.remove()}}),e0(a,{jsescOption:{minimal:!0}}).code}function a0(e,t,n){if(!t.startsWith(".")&&!t.startsWith("@/"))return{status:"external"};let r=t.startsWith("@/")?t.slice(2):nr(`${Xv(e)}/${t}`),o=[r,`${r}.tsx`,`${r}.ts`,`${r}.jsx`,`${r}.js`,`${r}.json`,`${r}.css`,`${r}/index.tsx`,`${r}/index.ts`,`${r}/index.jsx`,`${r}/index.js`,`${r}/index.json`],i=new Set(n),s=[...new Set(o.filter(a=>i.has(a)))];return s.length===0?t.startsWith(".")?{status:"unresolved"}:{status:"external"}:s.length>1&&!i.has(r)?{status:"ambiguous"}:{status:"resolved",path:s[0]}}function Uv(e,t,n){let r=Xv(e),o=l0(r,t),i=o.startsWith(".")?o:`./${o}`;return Kv(n)?i:Jv(i)}function c0(e,t){let n=`@/${e}`;return Kv(t)?n:Jv(n)}function l0(e,t){let n=e.split("/").filter(Boolean),r=t.split("/").filter(Boolean);for(;n.length>0&&n[0]===r[0];)n.shift(),r.shift();return`${"../".repeat(n.length)}${r.join("/")}`||"."}function u0(e){let t=nr(e),n="components/site/generated/",r=t.startsWith(n)?t.slice(n.length):`source/${t}`;return`${$v}${r}`}function d0(e){return gt.isJSXIdentifier(e)?e.name:gt.isJSXNamespacedName(e)&&gt.isJSXIdentifier(e.name)?`${e.namespace.name}:${e.name.name}`:null}function f0(e){return e?gt.isStringLiteral(e)?e.value:gt.isJSXExpressionContainer(e)&&gt.isStringLiteral(e.expression)?e.expression.value:null:null}function p0(e){if(!e)return null;if(gt.isStringLiteral(e)){let t=Number(e.value);return Number.isFinite(t)?t:null}return gt.isJSXExpressionContainer(e)&&gt.isNumericLiteral(e.expression)?e.expression.value:null}function m0(e){return[...Vv].some(t=>e.endsWith(t))}function Kv(e){return/\.[a-z0-9]+(?:[?#].*)?$/iu.test(e)}function Jv(e){for(let t of Vv)if(e.endsWith(t))return e.slice(0,-t.length);return e}function nr(e){let t=[];for(let n of e.replace(/\\/gu,"/").split("/"))if(!(!n||n===".")){if(n===".."){if(t.length===0)return"";t.pop();continue}t.push(n)}return t.join("/")}function Xv(e){let t=e.lastIndexOf("/");return t<0?"":e.slice(0,t)}function Dv(e){return new TextEncoder().encode(e).byteLength}function Mv(e){return e.length===0?0:e.split(`
21
- `).length}function Bv(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function jv(e,t){return e.path.localeCompare(t.path)||e.code.localeCompare(t.code)||(e.specifier??"").localeCompare(t.specifier??"")}function g0(e,t){return e.source_path.localeCompare(t.source_path)||e.target_path.localeCompare(t.target_path)||e.original_specifier.localeCompare(t.original_specifier)}import h0 from"node:path";import{GeneratedSiteCapabilitiesSchema as y0,FormDefinitionIdSchema as x0,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as b0,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as E0,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as S0,SiteEditMaterializationExportSchema as I0,SiteEditMaterializationSchema as v0,SiteEditSourcePathSchema as k0}from"@vcp-dev/contracts";var wl="components/site/generated",_0=/^[a-z][a-z0-9._-]{0,127}$/,Fl=/^[a-z][a-z0-9._-]{0,127}$/,C0=new Set(["collection-detail-view","i18n-companion","client-importer"]);function R0(e){if(!di(e))return Je("PORTABLE_INPUT_INVALID","Portable materialization input must be an object.","input");if(typeof e.instanceId!="string"||!_0.test(e.instanceId))return Je("PORTABLE_INSTANCE_INVALID","Portable instanceId must be a single safe directory name.","instanceId");let t=y0.safeParse(e.trustedHostPolicy);if(!t.success)return Je("PORTABLE_INPUT_INVALID","Portable materialization requires valid trusted host capabilities.","trustedHostPolicy");if(!Array.isArray(e.entryConsumers))return Je("PORTABLE_INPUT_INVALID","Portable materialization requires an entry consumer list.","entryConsumers");if(!T0(e.existingSources))return Je("PORTABLE_INPUT_INVALID","Portable materialization requires a read-only existing source index.","existingSources");if(e.trustedManagedImports!==void 0&&(!Array.isArray(e.trustedManagedImports)||e.trustedManagedImports.some(p=>{if(typeof p!="string")return!0;let m=/^@\/components\/site\/generated\/forms\/form-([^/]+)$/u.exec(p)?.[1];return!x0.safeParse(m).success||!Ol(e.existingSources,`${p.slice(2)}.tsx`)})))return Je("PORTABLE_INPUT_INVALID","Trusted managed imports must name exact existing canonical form sources.","trustedManagedImports");let n=N0(e.resolved);if(!n.ok)return n;let r=v0.safeParse(n.materialization);if(!r.success)return Je("PORTABLE_INPUT_INVALID","Resolved portable materialization failed the strict contract.","resolved.materialization");let o=P0(n.relatedEntries,r.data);if(!o.ok)return o;let i=A0(e.entryConsumers,o.data,r.data,e.existingSources);if(!i.ok)return i;let s=h0.posix.join(wl,e.instanceId),a=[],c=new Set;for(let p of r.data.files){let m=Di({pathTemplate:p.pathTemplate,generatedRoot:wl,instanceName:e.instanceId,instanceRoot:s});if(!m.ok)return km(m.error);if(c.has(m.data))return Je("MATERIALIZATION_PATH_INVALID",`Portable materialization resolves duplicate target path: ${m.data}`,m.data);c.add(m.data),a.push({kind:"create-only",path:m.data,content:p.content,...p.role?{role:p.role}:{},sourcePathTemplate:p.pathTemplate})}if(a.length>E0)return Je("MATERIALIZATION_LIMIT_EXCEEDED","Portable materialization file count exceeds the reusable limit.");let l=0;for(let p of a){let m=Buffer.byteLength(p.content,"utf8");if(m>b0)return Je("MATERIALIZATION_LIMIT_EXCEEDED","Portable materialization file exceeds the per-file content limit.",p.path);l+=m}if(l>S0)return Je("MATERIALIZATION_LIMIT_EXCEEDED","Portable materialization exceeds the reusable total content limit.");let u=zv(r.data.entry.pathTemplate,r.data.entry.export,c,e.instanceId,s);if(!u.ok)return u;let d=[],f=[u.data];for(let p of o.data){let m=zv(p.pathTemplate,p.export,c,e.instanceId,s);if(!m.ok)return m;d.push({...p,path:m.data.path}),f.push(m.data)}if(Ol(e.existingSources,s)||a.some(p=>Ol(e.existingSources,p.path)))return Je("PORTABLE_INSTANCE_CONFLICT","Portable materialization cannot overwrite an existing instance source.",s);let g=dd({preserveCapturedStyles:!0,files:a,instanceRoot:s,entries:f,hostCapabilities:t.data,trustedManagedImports:e.trustedManagedImports});return g.ok?(a.sort((p,m)=>p.path.localeCompare(m.path)),{ok:!0,data:{kind:"portable-materialization",instanceId:e.instanceId,generatedRoot:wl,instanceRoot:s,entry:u.data,relatedEntries:d.sort((p,m)=>p.path.localeCompare(m.path)),entryConsumers:i.data,files:a}}):km(g.error)}function N0(e){if(!di(e))return Je("PORTABLE_INPUT_INVALID","Resolved portable materialization must be an object.","resolved");let t=e.relatedEntries,n=e.portable;if(t!==void 0&&!Array.isArray(t))return Je("PORTABLE_INPUT_INVALID","Resolved related entries must be an array.","resolved.relatedEntries");if(n!==void 0&&!di(n))return Je("PORTABLE_INPUT_INVALID","Resolved portable descriptor must be an object.","resolved.portable");let r=n?.relatedEntries;if(r!==void 0&&!Array.isArray(r))return Je("PORTABLE_INPUT_INVALID","Resolved portable related entries must be an array.","resolved.portable.relatedEntries");let o=t,i=r;return o&&i?Je("PORTABLE_INPUT_INVALID","Resolved portable materialization must expose related entries once.","resolved.relatedEntries"):{ok:!0,materialization:e.materialization,relatedEntries:o??i??[]}}function P0(e,t){let n=new Set(t.files.map(a=>a.pathTemplate)),r=new Set((t.dataRequirements??[]).map(a=>a.key)),o=new Set,i=new Set,s=[];for(let[a,c]of e.entries()){if(!di(c))return Je("PORTABLE_INPUT_INVALID","Every related entry must be an object.",`resolved.relatedEntries[${a}]`);let l=c.key,u=c.requirementKey,d=c.pathTemplate,f=c.purpose,g=I0.safeParse(c.export);if(typeof l!="string"||!Fl.test(l)||typeof u!="string"||!Fl.test(u)||typeof d!="string"||typeof f!="string"||!C0.has(f)||!g.success)return Je("PORTABLE_INPUT_INVALID","Every related entry must have a strict key, purpose, path and export.",`resolved.relatedEntries[${a}]`);if(o.has(l)||i.has(d))return Je("MATERIALIZATION_PATH_INVALID","Portable related entry keys and paths must be unique.",d);if(d===t.entry.pathTemplate)return Je("MATERIALIZATION_ENTRY_INVALID","A related entry cannot reuse the primary materialization entry.",d);if(!n.has(d))return Je("MATERIALIZATION_ENTRY_INVALID","Every related entry must reference a materialization file.",d);if(!r.has(u))return Je("PORTABLE_REQUIREMENT_UNRESOLVED","Every related entry must reference a resolved managed requirement.",u);o.add(l),i.add(d),s.push({key:l,pathTemplate:d,export:g.data,purpose:f,requirementKey:u})}return{ok:!0,data:s}}function A0(e,t,n,r){let o=new Map(t.map(l=>[l.key,l])),i=new Set((n.dataRequirements??[]).map(l=>l.key)),s=new Set,a=[];for(let[l,u]of e.entries()){if(!di(u))return Je("PORTABLE_INPUT_INVALID","Every entry consumer must be an object.",`entryConsumers[${l}]`);let d=u.entry_key,f=u.requirement_key,g=u.kind,p=u.consumer_path;if(typeof d!="string"||!Fl.test(d)||typeof f!="string"||!Fl.test(f)||typeof p!="string"||!p.trim()||g!=="route"&&g!=="capability"&&g!=="preserved-route")return Je("PORTABLE_INPUT_INVALID","Entry consumers must declare a strict entry, requirement, kind and path.",`entryConsumers[${l}]`);let m=o.get(d);if(!m)return Je("PORTABLE_ENTRY_UNCONSUMED","An entry consumer must reference a declared related entry.",d);if(g==="preserved-route"&&(m.purpose!=="collection-detail-view"||!k0.safeParse(p).success||!/^app\/.*\/page\.tsx$/u.test(p)||!Ol(r,p)))return Je("PORTABLE_ENTRY_UNCONSUMED","A preserved detail entry requires an existing source route proven by the collection recipe.",d);if(s.has(d))return Je("PORTABLE_ENTRY_UNCONSUMED","A related entry must have exactly one managed consumer.",d);if(m.requirementKey!==f)return Je("PORTABLE_REQUIREMENT_UNRESOLVED","An entry consumer must use the related entry requirement.",d);if(!i.has(f))return Je("PORTABLE_REQUIREMENT_UNRESOLVED","An entry consumer must reference a resolved managed requirement.",f);s.add(d),a.push({entry_key:d,requirement_key:f,kind:g,consumer_path:p})}let c=t.find(l=>!s.has(l.key));return c?Je("PORTABLE_ENTRY_UNCONSUMED","Every related entry must be consumed by its managed route or capability.",c.key):{ok:!0,data:a.sort((l,u)=>l.entry_key.localeCompare(u.entry_key)||l.consumer_path.localeCompare(u.consumer_path))}}function zv(e,t,n,r,o){let i=Di({pathTemplate:e,generatedRoot:wl,instanceName:r,instanceRoot:o});return i.ok?n.has(i.data)?{ok:!0,data:{path:i.data,export:t}}:Je("MATERIALIZATION_ENTRY_INVALID","Portable entry must match one controlled source file.",i.data):km(i.error)}function Ol(e,t){return Array.isArray(e)?e.includes(t):e instanceof Map?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function T0(e){return Array.isArray(e)||e instanceof Map||di(e)}function di(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function km(e){return{ok:!1,error:e}}function Je(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{path:n}:{}}}}import Hv from"node:path";import{SiteEditSourcePathSchema as _m}from"@vcp-dev/contracts";function w0(e){let t=e.resolvedBoundary;if(!e.routeId.trim()||!Number.isSafeInteger(e.documentVersion)||e.documentVersion<0||e.binding.documentVersion!==e.documentVersion||e.binding.composition.routeId!==e.routeId||t.ownerFile!==e.binding.ownerFile||t.sourceHash!==e.binding.ownerSourceHash||(t.placement==="before"?t.afterBlockKey:t.beforeBlockKey)!==e.binding.blockKey||!_m.safeParse(e.entryFile).success||!_m.safeParse(t.ownerFile).success||t.anchorLocator.file!==t.ownerFile||t.parentLocator!==null&&t.parentLocator.file!==t.ownerFile||!/^sha256:[a-f0-9]{64}$/u.test(t.sourceHash))return xt("INVALID_TARGET","The resolved Portable boundary is not a valid source-owner boundary.");let n=e.files.get(t.ownerFile);if(n===void 0)return xt("INVALID_TARGET","The verified Portable owner is absent from the fixed source map.",t.ownerFile);if(ke(n)!==t.sourceHash)return xt("VERSION_STALE","The Portable boundary owner changed after resolution.",t.ownerFile);let r=D0(e);return r||(e.binding.root.ownerNode.kind==="route-member"?t.ownerFile!==e.entryFile?xt("INVALID_TARGET","A route-member block boundary must remain in its route entry file.",t.ownerFile):O0(e,n):L0(e,n))}function O0(e,t){let n=je(e.entryFile,t);if(!n.ok)return xt("PORTABLE_ROUTE_SOURCE_INVALID",n.diagnostic.message,e.entryFile);let r=yn({route:e.routeId,composition:e.binding.composition,entryFile:e.entryFile,version:e.documentVersion,source:t,ast:n.module.ast});if(!r.ok)return xt("PORTABLE_ROUTE_UNSUPPORTED","The route owner does not expose a supported composition boundary.",e.entryFile);let o=F0(r.projection.placements,e.resolvedBoundary.anchorLocator.sourceRange,e.resolvedBoundary.placement);if(!o)return xt("INVALID_TARGET","The exact route-member boundary has no unique page-composition member.",e.entryFile);let i=Nd({routeId:e.routeId,composition:e.binding.composition,entryFile:e.entryFile,documentVersion:e.documentVersion,source:t,anchor:{componentName:o,relation:e.resolvedBoundary.placement,sourceRange:e.resolvedBoundary.anchorLocator.sourceRange},component:e.component,invocation:e.invocation});if(!i.ok)return xt(i.error.code,i.error.message,e.entryFile);if(i.patch.path!==e.resolvedBoundary.ownerFile||i.patch.expectedSourceHash!==e.resolvedBoundary.sourceHash)return xt("INVALID_TARGET","The route planner did not preserve the resolved owner boundary.",e.resolvedBoundary.ownerFile);let s=i.plan.rewriteStep,a=s.kind==="insert-child"&&s.anchorLocator?.strategy==="source-range"?s.anchorLocator.sourceRange:null;return s.kind==="insert-child"&&(!a||!Rm(a,e.resolvedBoundary.anchorLocator.sourceRange))?xt("INVALID_TARGET","The route planner selected a different anchor than the resolved boundary.",e.entryFile):{ok:!0,patches:[{path:i.patch.path,source:i.patch.source,baseContentHash:i.patch.expectedSourceHash}]}}function F0(e,t,n){let r=e.flatMap(o=>o.relation!==n||!o.anchorSourceRange||!Rm(o.anchorSourceRange,t)?[]:Wv(o.members).filter(i=>i.sourceRange!==null&&Rm(i.sourceRange,t)));return r.length===1?r[0].label:null}function Wv(e){return e.flatMap(t=>[t,...Wv(t.children)])}function L0(e,t){let n=e.resolvedBoundary,r=n.parentLocator;if(!r)return xt("UNSUPPORTED_OPERATION","A shared owner root without a JSX parent has no safe sibling boundary.",n.ownerFile);if(r.kind!=="jsx-element"&&r.kind!=="jsx-fragment")return xt("INVALID_TARGET","The verified shared owner parent is not a JSX child container.",n.ownerFile);let o=yr({component:e.component.localName,bindings:e.invocation.bindings,targetBlockId:e.invocation.targetBlockId,targetOrder:e.invocation.targetOrder});if(!o.ok)return xt(o.error.code,o.error.message,n.ownerFile);let i=M0(t,n.ownerFile,r,o.plan.bindings);if(i)return i;let s=on({source:t,locator:Cm(r),anchorLocator:Cm(n.anchorLocator),placement:n.placement,node:{jsx:o.plan.jsx}});if(!s.ok)return xt("PORTABLE_BLOCK_PATCH_FAILED",s.diagnostic.message,n.ownerFile);let a=sn({source:s.source,moduleSpecifier:B0(n.ownerFile,e.component.source),imports:[e.component.exportName==="default"?{kind:"default",local:e.component.localName}:{kind:"named",imported:e.component.exportName,...e.component.localName===e.component.exportName?{}:{local:e.component.localName}}]});return a.ok?{ok:!0,patches:[{path:n.ownerFile,source:a.source,baseContentHash:n.sourceHash}]}:xt("PORTABLE_BLOCK_PATCH_FAILED",a.diagnostic.message,n.ownerFile)}function D0(e){return!_m.safeParse(e.component.source).success||e.component.source===e.resolvedBoundary.ownerFile||e.component.exportName!=="default"&&!/^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(e.component.exportName)?xt("INVALID_TARGET","The Portable component source or export is not a safe materialized reference.",e.component.source):null}function M0(e,t,n,r){if(!r.some(s=>s.value.kind==="route-search-params"))return null;let o=je(t,e);if(!o.ok)return xt("INVOCATION_VALUE_UNRESOLVED",o.diagnostic.message,t);let i=Ie(o.module.ast,Cm(n));return!i.ok||!i.match.path.scope.getBinding("searchParams")?xt("INVOCATION_VALUE_UNRESOLVED","The shared owner has no proven searchParams binding for this invocation.",t):null}function Cm(e){return{kind:"jsx-node",strategy:"source-range",sourceRange:e.sourceRange,...e.structuralPath&&e.componentName?{expectedIdentity:{file:e.file,component:e.componentName,structuralPath:e.structuralPath}}:{}}}function B0(e,t){let n=Hv.posix.relative(Hv.posix.dirname(e),t.replace(/\.(?:tsx?|jsx?)$/u,""));return n=n.replaceAll("\\","/"),n.startsWith(".")?n:`./${n}`}function Rm(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function xt(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{path:n}:{}}}}import{parse as j0}from"@babel/parser";import Nm from"@babel/traverse";import*as ft from"@babel/types";var $0=typeof Nm=="function"?Nm:Nm.default,V0=new Set(["slice","map","trim","toString"]);function U0(e){let t=new Set;try{let n=j0(e,{sourceType:"module",plugins:["jsx","typescript"]});$0(n,{JSXExpressionContainer(r){let o=r.get("expression");Os(o,new Set)==="url"&&t.add(`${r.node.start}:${r.node.end}`)}})}catch{}return t}function Os(e,t){if(e.isMemberExpression()||e.isOptionalMemberExpression()){let a=Os(e.get("object"),t),c=e.node;return!c.computed&&ft.isIdentifier(c.property,{name:"thumbnail"})&&a==="record"?"array":c.computed&&ft.isNumericLiteral(c.property)&&Number.isSafeInteger(c.property.value)&&c.property.value>=0&&a==="array"?"item":!c.computed&&ft.isIdentifier(c.property,{name:"url"})&&a==="item"?"url":null}if(e.isCallExpression()){let a=e.get("callee");return!a.isMemberExpression()||a.node.computed||!ft.isIdentifier(a.node.property,{name:"slice"})||!e.node.arguments.every(c=>ft.isNumericLiteral(c)&&Number.isSafeInteger(c.value)&&c.value>=0)?null:Os(a.get("object"),t)==="array"?"array":null}if(!e.isIdentifier())return null;let n=e.scope.getBinding(e.node.name);if(!n?.constant||t.has(n)||!Pm(n,new Set))return null;let r=new Set(t).add(n);if(n.path.isVariableDeclarator()&&ft.isIdentifier(n.path.node.id))return Os(n.path.get("init"),r);if(n.kind!=="param")return null;let o=n.path.getFunctionParent();if(!o)return null;if(e.node.name==="record"&&o.node.params.some(a=>ft.isObjectPattern(a)&&a.properties.some(c=>ft.isObjectProperty(c)&&!c.computed&&ft.isIdentifier(c.key,{name:"record"})&&ft.isIdentifier(c.value,{name:"record"}))))return"record";if(!o.isArrowFunctionExpression()||!ft.isIdentifier(o.node.params[0],{name:e.node.name})||!o.parentPath.isCallExpression())return null;let i=o.parentPath,s=i.get("callee");return i.node.arguments[0]!==o.node||!s.isMemberExpression()||s.node.computed||!ft.isIdentifier(s.node.property,{name:"map"})?null:Os(s.get("object"),r)==="array"?"item":null}function Pm(e,t){return t.has(e)?!0:(t.add(e),e.constant?e.referencePaths.every(n=>{let r=n;for(;r.parentPath&&(r.parentPath.isMemberExpression()||r.parentPath.isOptionalMemberExpression())&&r.parentPath.node.object===r.node;)r=r.parentPath;let o=r.parentPath;if(!o||o.isAssignmentExpression()||o.isUpdateExpression()||o.isUnaryExpression()&&o.node.operator==="delete"||o.isSpreadElement()||o.isObjectProperty()||o.isReturnStatement())return!1;if(o.isVariableDeclarator()){if(!ft.isIdentifier(o.node.id)||o.node.init!==r.node)return!1;let i=o.scope.getBinding(o.node.id.name);return!!i&&Pm(i,t)}if(o.isCallExpression()||o.isOptionalCallExpression()){if(!(o.node.callee===r.node&&(r.isMemberExpression()||r.isOptionalMemberExpression())&&!r.node.computed&&ft.isIdentifier(r.node.property)&&V0.has(r.node.property.name)))return!1;if((r.isMemberExpression()||r.isOptionalMemberExpression())&&ft.isIdentifier(r.node.property,{name:"map"})){let s=o.get("arguments.0");if(!s?.isArrowFunctionExpression()||!ft.isIdentifier(s.node.params[0]))return!1;let a=s.scope.getBinding(s.node.params[0].name);if(!a||!Pm(a,t))return!1}return!0}return r!==n}):!1)}export{xe as FileHistoryStoreError,Gi as PageTemplateManagedSourceError,ul as PreviewFileSystemSiteEditEngineRuntime,ay as SITE_EDIT_RAW_COLOR_LITERAL_RE,cl as SnapshotSiteEditEngineRuntime,QB as analyzePortableCollectionInvocation,ai as analyzePortableInvocation,Qp as analyzePortableRelatedEntries,ad as auditGeneratedCode,fl as auditPortableDependencies,Hi as buildPageBlockIndex,yr as buildPortableInvocation,R0 as buildPortableMaterializationPlan,Lr as buildPortableSourceClosure,mi as checkComponentI18nHostCompatibility,dl as classifyPortableDependencyOwnership,Px as computeManagedPageTemplatePaths,SM as createPreviewSiteEditEngineRuntime,yM as createSiteEditEngineRuntime,Cx as decodePageTemplateKey,qp as discoverPortableCollectionSourceRelation,Zd as encodePageTemplateId,Wj as exportPortableBlockFromSnapshot,Jp as extractPortableBlockEntry,Dk as instrumentSiteEditRuntimeAttributes,Ax as isManagedPageTemplateSourcePath,vA as normalizePortableBlockMetadata,n0 as normalizePortableSource,Rh as openFileHistoryStore,Ek as parseSourceModule,w0 as planPortableBlockPatch,Nd as planPortableRouteCompositionPatch,$i as planRouteCompositionRewrite,U0 as provenRecordThumbnailRanges,zj as readPortableBlockLocalAssetChunk,Sk as resolveImportBase,uw as resolveManagedPageTemplateComposition,nc as resolvePageBlockBoundary,Op as resolvePageBlockFromSnapshot,jo as resolvePageBlockTarget,yn as resolvePageCompositionProjection,pm as resolvePortableBlockSelection,vM as resolvePortableDependencyOwnership,Dr as resolvePortableSourcePath,sc as scanManagedPageTemplateCandidates,bm as scanPortableMediaReferences,ac as scanSiteEditCompositionsFromFiles,od as scanSiteEditThemeStyleViolations,qB as selectPortablePageUnitInvocation};
20
+ `}}function s0(e,t,n,r,o,i,s){if(!m0(e))return t;let a;try{a=Zj(t,{sourceType:"module",sourceFilename:e,plugins:["jsx","typescript"]})}catch(l){return s.push({code:"SOURCE_PARSE_FAILED",path:e,message:l instanceof Error?l.message:String(l)}),null}let c=l=>{let u=l.value,d=a0(e,u,n.keys());if(d.status==="external")return;if(d.status==="unresolved"){s.push({code:"SOURCE_IMPORT_UNRESOLVED",path:e,specifier:u,message:`The local import ${u} cannot be resolved.`});return}if(d.status==="ambiguous"){s.push({code:"SOURCE_IMPORT_AMBIGUOUS",path:e,specifier:u,message:`The local import ${u} resolves to multiple files.`});return}let f=n.get(d.path);if(!f){s.push({code:"SOURCE_IMPORT_TARGET_UNOWNED",path:e,specifier:u,message:`The local import target ${d.path} has no ownership decision.`});return}if(f.ownership==="private"){let m=r.get(d.path);if(!m){s.push({code:"SOURCE_IMPORT_TARGET_UNOWNED",path:e,specifier:u,message:`The private import target ${d.path} was not materialized.`});return}l.value=Uv(r.get(e),m,u);return}if(f.ownership!=="platform-managed"&&f.ownership!=="host-public"){s.push({code:"SOURCE_IMPORT_TARGET_UNOWNED",path:e,specifier:u,message:`The import target ${d.path} is not portable source.`});return}let g=c0(d.path,u);l.value=g;let p=f.requirement_key??"host-public";if(!/^[a-z][a-z0-9._-]{0,127}$/u.test(p)){s.push({code:"SOURCE_MANAGED_REBIND_INVALID",path:e,specifier:u,message:"Managed import rebinding requires a safe requirement key."});return}o.push({source_path:e,original_specifier:u,target_path:d.path,rebound_specifier:g,requirement_key:p})};return Qj(a,{ImportDeclaration(l){c(l.node.source)},ExportNamedDeclaration(l){l.node.source&&c(l.node.source)},ExportAllDeclaration(l){c(l.node.source)},CallExpression(l){let u=l.node.callee,d=l.node.arguments[0];(gt.isImport(u)||gt.isIdentifier(u,{name:"require"})&&l.node.arguments.length===1)&&gt.isStringLiteral(d)&&c(d)},JSXAttribute(l){let u=d0(l.node.name);if(!u||!Lv.has(u)&&!t0.has(u))return;let d=l.parentPath.parentPath?.node,f=typeof d?.start=="number"?d.start:l.node.start??0,g=`${e}:${f}`,p=i.get(g)??{source_path:e,original_block_attribute:null,original_block_id:null,original_order:null};Lv.has(u)?(p.original_block_attribute=u,p.original_block_id=f0(l.node.value)):p.original_order=p0(l.node.value),i.set(g,p),l.remove()}}),e0(a,{jsescOption:{minimal:!0}}).code}function a0(e,t,n){if(!t.startsWith(".")&&!t.startsWith("@/"))return{status:"external"};let r=t.startsWith("@/")?t.slice(2):nr(`${Xv(e)}/${t}`),o=[r,`${r}.tsx`,`${r}.ts`,`${r}.jsx`,`${r}.js`,`${r}.json`,`${r}.css`,`${r}/index.tsx`,`${r}/index.ts`,`${r}/index.jsx`,`${r}/index.js`,`${r}/index.json`],i=new Set(n),s=[...new Set(o.filter(a=>i.has(a)))];return s.length===0?t.startsWith(".")?{status:"unresolved"}:{status:"external"}:s.length>1&&!i.has(r)?{status:"ambiguous"}:{status:"resolved",path:s[0]}}function Uv(e,t,n){let r=Xv(e),o=l0(r,t),i=o.startsWith(".")?o:`./${o}`;return Kv(n)?i:Jv(i)}function c0(e,t){let n=`@/${e}`;return Kv(t)?n:Jv(n)}function l0(e,t){let n=e.split("/").filter(Boolean),r=t.split("/").filter(Boolean);for(;n.length>0&&n[0]===r[0];)n.shift(),r.shift();return`${"../".repeat(n.length)}${r.join("/")}`||"."}function u0(e){let t=nr(e),n="components/site/generated/",r=t.startsWith(n)?t.slice(n.length):`source/${t}`;return`${$v}${r}`}function d0(e){return gt.isJSXIdentifier(e)?e.name:gt.isJSXNamespacedName(e)&&gt.isJSXIdentifier(e.name)?`${e.namespace.name}:${e.name.name}`:null}function f0(e){return e?gt.isStringLiteral(e)?e.value:gt.isJSXExpressionContainer(e)&&gt.isStringLiteral(e.expression)?e.expression.value:null:null}function p0(e){if(!e)return null;if(gt.isStringLiteral(e)){let t=Number(e.value);return Number.isFinite(t)?t:null}return gt.isJSXExpressionContainer(e)&&gt.isNumericLiteral(e.expression)?e.expression.value:null}function m0(e){return[...Vv].some(t=>e.endsWith(t))}function Kv(e){return/\.[a-z0-9]+(?:[?#].*)?$/iu.test(e)}function Jv(e){for(let t of Vv)if(e.endsWith(t))return e.slice(0,-t.length);return e}function nr(e){let t=[];for(let n of e.replace(/\\/gu,"/").split("/"))if(!(!n||n===".")){if(n===".."){if(t.length===0)return"";t.pop();continue}t.push(n)}return t.join("/")}function Xv(e){let t=e.lastIndexOf("/");return t<0?"":e.slice(0,t)}function Mv(e){return new TextEncoder().encode(e).byteLength}function Dv(e){return e.length===0?0:e.split(`
21
+ `).length}function Bv(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function jv(e,t){return e.path.localeCompare(t.path)||e.code.localeCompare(t.code)||(e.specifier??"").localeCompare(t.specifier??"")}function g0(e,t){return e.source_path.localeCompare(t.source_path)||e.target_path.localeCompare(t.target_path)||e.original_specifier.localeCompare(t.original_specifier)}import h0 from"node:path";import{GeneratedSiteCapabilitiesSchema as y0,FormDefinitionIdSchema as x0,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as b0,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as E0,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as S0,SiteEditMaterializationExportSchema as I0,SiteEditMaterializationSchema as v0,SiteEditSourcePathSchema as k0}from"@vcp-dev/contracts";var wl="components/site/generated",_0=/^[a-z][a-z0-9._-]{0,127}$/,Fl=/^[a-z][a-z0-9._-]{0,127}$/,C0=new Set(["collection-detail-view","i18n-companion","client-importer"]);function R0(e){if(!di(e))return Je("PORTABLE_INPUT_INVALID","Portable materialization input must be an object.","input");if(typeof e.instanceId!="string"||!_0.test(e.instanceId))return Je("PORTABLE_INSTANCE_INVALID","Portable instanceId must be a single safe directory name.","instanceId");let t=y0.safeParse(e.trustedHostPolicy);if(!t.success)return Je("PORTABLE_INPUT_INVALID","Portable materialization requires valid trusted host capabilities.","trustedHostPolicy");if(!Array.isArray(e.entryConsumers))return Je("PORTABLE_INPUT_INVALID","Portable materialization requires an entry consumer list.","entryConsumers");if(!T0(e.existingSources))return Je("PORTABLE_INPUT_INVALID","Portable materialization requires a read-only existing source index.","existingSources");if(e.trustedManagedImports!==void 0&&(!Array.isArray(e.trustedManagedImports)||e.trustedManagedImports.some(p=>{if(typeof p!="string")return!0;let m=/^@\/components\/site\/generated\/forms\/form-([^/]+)$/u.exec(p)?.[1];return!x0.safeParse(m).success||!Ol(e.existingSources,`${p.slice(2)}.tsx`)})))return Je("PORTABLE_INPUT_INVALID","Trusted managed imports must name exact existing canonical form sources.","trustedManagedImports");let n=N0(e.resolved);if(!n.ok)return n;let r=v0.safeParse(n.materialization);if(!r.success)return Je("PORTABLE_INPUT_INVALID","Resolved portable materialization failed the strict contract.","resolved.materialization");let o=P0(n.relatedEntries,r.data);if(!o.ok)return o;let i=A0(e.entryConsumers,o.data,r.data,e.existingSources);if(!i.ok)return i;let s=h0.posix.join(wl,e.instanceId),a=[],c=new Set;for(let p of r.data.files){let m=Mi({pathTemplate:p.pathTemplate,generatedRoot:wl,instanceName:e.instanceId,instanceRoot:s});if(!m.ok)return Cm(m.error);if(c.has(m.data))return Je("MATERIALIZATION_PATH_INVALID",`Portable materialization resolves duplicate target path: ${m.data}`,m.data);c.add(m.data),a.push({kind:"create-only",path:m.data,content:p.content,...p.role?{role:p.role}:{},sourcePathTemplate:p.pathTemplate})}if(a.length>E0)return Je("MATERIALIZATION_LIMIT_EXCEEDED","Portable materialization file count exceeds the reusable limit.");let l=0;for(let p of a){let m=Buffer.byteLength(p.content,"utf8");if(m>b0)return Je("MATERIALIZATION_LIMIT_EXCEEDED","Portable materialization file exceeds the per-file content limit.",p.path);l+=m}if(l>S0)return Je("MATERIALIZATION_LIMIT_EXCEEDED","Portable materialization exceeds the reusable total content limit.");let u=zv(r.data.entry.pathTemplate,r.data.entry.export,c,e.instanceId,s);if(!u.ok)return u;let d=[],f=[u.data];for(let p of o.data){let m=zv(p.pathTemplate,p.export,c,e.instanceId,s);if(!m.ok)return m;d.push({...p,path:m.data.path}),f.push(m.data)}if(Ol(e.existingSources,s)||a.some(p=>Ol(e.existingSources,p.path)))return Je("PORTABLE_INSTANCE_CONFLICT","Portable materialization cannot overwrite an existing instance source.",s);let g=dd({preserveCapturedStyles:!0,files:a,instanceRoot:s,entries:f,hostCapabilities:t.data,trustedManagedImports:e.trustedManagedImports});return g.ok?(a.sort((p,m)=>p.path.localeCompare(m.path)),{ok:!0,data:{kind:"portable-materialization",instanceId:e.instanceId,generatedRoot:wl,instanceRoot:s,entry:u.data,relatedEntries:d.sort((p,m)=>p.path.localeCompare(m.path)),entryConsumers:i.data,files:a}}):Cm(g.error)}function N0(e){if(!di(e))return Je("PORTABLE_INPUT_INVALID","Resolved portable materialization must be an object.","resolved");let t=e.relatedEntries,n=e.portable;if(t!==void 0&&!Array.isArray(t))return Je("PORTABLE_INPUT_INVALID","Resolved related entries must be an array.","resolved.relatedEntries");if(n!==void 0&&!di(n))return Je("PORTABLE_INPUT_INVALID","Resolved portable descriptor must be an object.","resolved.portable");let r=n?.relatedEntries;if(r!==void 0&&!Array.isArray(r))return Je("PORTABLE_INPUT_INVALID","Resolved portable related entries must be an array.","resolved.portable.relatedEntries");let o=t,i=r;return o&&i?Je("PORTABLE_INPUT_INVALID","Resolved portable materialization must expose related entries once.","resolved.relatedEntries"):{ok:!0,materialization:e.materialization,relatedEntries:o??i??[]}}function P0(e,t){let n=new Set(t.files.map(a=>a.pathTemplate)),r=new Set((t.dataRequirements??[]).map(a=>a.key)),o=new Set,i=new Set,s=[];for(let[a,c]of e.entries()){if(!di(c))return Je("PORTABLE_INPUT_INVALID","Every related entry must be an object.",`resolved.relatedEntries[${a}]`);let l=c.key,u=c.requirementKey,d=c.pathTemplate,f=c.purpose,g=I0.safeParse(c.export);if(typeof l!="string"||!Fl.test(l)||typeof u!="string"||!Fl.test(u)||typeof d!="string"||typeof f!="string"||!C0.has(f)||!g.success)return Je("PORTABLE_INPUT_INVALID","Every related entry must have a strict key, purpose, path and export.",`resolved.relatedEntries[${a}]`);if(o.has(l)||i.has(d))return Je("MATERIALIZATION_PATH_INVALID","Portable related entry keys and paths must be unique.",d);if(d===t.entry.pathTemplate)return Je("MATERIALIZATION_ENTRY_INVALID","A related entry cannot reuse the primary materialization entry.",d);if(!n.has(d))return Je("MATERIALIZATION_ENTRY_INVALID","Every related entry must reference a materialization file.",d);if(!r.has(u))return Je("PORTABLE_REQUIREMENT_UNRESOLVED","Every related entry must reference a resolved managed requirement.",u);o.add(l),i.add(d),s.push({key:l,pathTemplate:d,export:g.data,purpose:f,requirementKey:u})}return{ok:!0,data:s}}function A0(e,t,n,r){let o=new Map(t.map(l=>[l.key,l])),i=new Set((n.dataRequirements??[]).map(l=>l.key)),s=new Set,a=[];for(let[l,u]of e.entries()){if(!di(u))return Je("PORTABLE_INPUT_INVALID","Every entry consumer must be an object.",`entryConsumers[${l}]`);let d=u.entry_key,f=u.requirement_key,g=u.kind,p=u.consumer_path;if(typeof d!="string"||!Fl.test(d)||typeof f!="string"||!Fl.test(f)||typeof p!="string"||!p.trim()||g!=="route"&&g!=="capability"&&g!=="preserved-route")return Je("PORTABLE_INPUT_INVALID","Entry consumers must declare a strict entry, requirement, kind and path.",`entryConsumers[${l}]`);let m=o.get(d);if(!m)return Je("PORTABLE_ENTRY_UNCONSUMED","An entry consumer must reference a declared related entry.",d);if(g==="preserved-route"&&(m.purpose!=="collection-detail-view"||!k0.safeParse(p).success||!/^app\/.*\/page\.tsx$/u.test(p)||!Ol(r,p)))return Je("PORTABLE_ENTRY_UNCONSUMED","A preserved detail entry requires an existing source route proven by the collection recipe.",d);if(s.has(d))return Je("PORTABLE_ENTRY_UNCONSUMED","A related entry must have exactly one managed consumer.",d);if(m.requirementKey!==f)return Je("PORTABLE_REQUIREMENT_UNRESOLVED","An entry consumer must use the related entry requirement.",d);if(!i.has(f))return Je("PORTABLE_REQUIREMENT_UNRESOLVED","An entry consumer must reference a resolved managed requirement.",f);s.add(d),a.push({entry_key:d,requirement_key:f,kind:g,consumer_path:p})}let c=t.find(l=>!s.has(l.key));return c?Je("PORTABLE_ENTRY_UNCONSUMED","Every related entry must be consumed by its managed route or capability.",c.key):{ok:!0,data:a.sort((l,u)=>l.entry_key.localeCompare(u.entry_key)||l.consumer_path.localeCompare(u.consumer_path))}}function zv(e,t,n,r,o){let i=Mi({pathTemplate:e,generatedRoot:wl,instanceName:r,instanceRoot:o});return i.ok?n.has(i.data)?{ok:!0,data:{path:i.data,export:t}}:Je("MATERIALIZATION_ENTRY_INVALID","Portable entry must match one controlled source file.",i.data):Cm(i.error)}function Ol(e,t){return Array.isArray(e)?e.includes(t):e instanceof Map?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function T0(e){return Array.isArray(e)||e instanceof Map||di(e)}function di(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Cm(e){return{ok:!1,error:e}}function Je(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{path:n}:{}}}}import Hv from"node:path";import{SiteEditSourcePathSchema as Rm}from"@vcp-dev/contracts";function w0(e){let t=e.resolvedBoundary;if(!e.routeId.trim()||!Number.isSafeInteger(e.documentVersion)||e.documentVersion<0||e.binding.documentVersion!==e.documentVersion||e.binding.composition.routeId!==e.routeId||t.ownerFile!==e.binding.ownerFile||t.sourceHash!==e.binding.ownerSourceHash||(t.placement==="before"?t.afterBlockKey:t.beforeBlockKey)!==e.binding.blockKey||!Rm.safeParse(e.entryFile).success||!Rm.safeParse(t.ownerFile).success||t.anchorLocator.file!==t.ownerFile||t.parentLocator!==null&&t.parentLocator.file!==t.ownerFile||!/^sha256:[a-f0-9]{64}$/u.test(t.sourceHash))return xt("INVALID_TARGET","The resolved Portable boundary is not a valid source-owner boundary.");let n=e.files.get(t.ownerFile);if(n===void 0)return xt("INVALID_TARGET","The verified Portable owner is absent from the fixed source map.",t.ownerFile);if(ke(n)!==t.sourceHash)return xt("VERSION_STALE","The Portable boundary owner changed after resolution.",t.ownerFile);let r=M0(e);return r||(e.binding.root.ownerNode.kind==="route-member"?t.ownerFile!==e.entryFile?xt("INVALID_TARGET","A route-member block boundary must remain in its route entry file.",t.ownerFile):O0(e,n):L0(e,n))}function O0(e,t){let n=je(e.entryFile,t);if(!n.ok)return xt("PORTABLE_ROUTE_SOURCE_INVALID",n.diagnostic.message,e.entryFile);let r=yn({route:e.routeId,composition:e.binding.composition,entryFile:e.entryFile,version:e.documentVersion,source:t,ast:n.module.ast});if(!r.ok)return xt("PORTABLE_ROUTE_UNSUPPORTED","The route owner does not expose a supported composition boundary.",e.entryFile);let o=F0(r.projection.placements,e.resolvedBoundary.anchorLocator.sourceRange,e.resolvedBoundary.placement);if(!o)return xt("INVALID_TARGET","The exact route-member boundary has no unique page-composition member.",e.entryFile);let i=Nd({routeId:e.routeId,composition:e.binding.composition,entryFile:e.entryFile,documentVersion:e.documentVersion,source:t,anchor:{componentName:o,relation:e.resolvedBoundary.placement,sourceRange:e.resolvedBoundary.anchorLocator.sourceRange},component:e.component,invocation:e.invocation});if(!i.ok)return xt(i.error.code,i.error.message,e.entryFile);if(i.patch.path!==e.resolvedBoundary.ownerFile||i.patch.expectedSourceHash!==e.resolvedBoundary.sourceHash)return xt("INVALID_TARGET","The route planner did not preserve the resolved owner boundary.",e.resolvedBoundary.ownerFile);let s=i.plan.rewriteStep,a=s.kind==="insert-child"&&s.anchorLocator?.strategy==="source-range"?s.anchorLocator.sourceRange:null;return s.kind==="insert-child"&&(!a||!Pm(a,e.resolvedBoundary.anchorLocator.sourceRange))?xt("INVALID_TARGET","The route planner selected a different anchor than the resolved boundary.",e.entryFile):{ok:!0,patches:[{path:i.patch.path,source:i.patch.source,baseContentHash:i.patch.expectedSourceHash}]}}function F0(e,t,n){let r=e.flatMap(o=>o.relation!==n||!o.anchorSourceRange||!Pm(o.anchorSourceRange,t)?[]:Wv(o.members).filter(i=>i.sourceRange!==null&&Pm(i.sourceRange,t)));return r.length===1?r[0].label:null}function Wv(e){return e.flatMap(t=>[t,...Wv(t.children)])}function L0(e,t){let n=e.resolvedBoundary,r=n.parentLocator;if(!r)return xt("UNSUPPORTED_OPERATION","A shared owner root without a JSX parent has no safe sibling boundary.",n.ownerFile);if(r.kind!=="jsx-element"&&r.kind!=="jsx-fragment")return xt("INVALID_TARGET","The verified shared owner parent is not a JSX child container.",n.ownerFile);let o=yr({component:e.component.localName,bindings:e.invocation.bindings,targetBlockId:e.invocation.targetBlockId,targetOrder:e.invocation.targetOrder});if(!o.ok)return xt(o.error.code,o.error.message,n.ownerFile);let i=D0(t,n.ownerFile,r,o.plan.bindings);if(i)return i;let s=on({source:t,locator:Nm(r),anchorLocator:Nm(n.anchorLocator),placement:n.placement,node:{jsx:o.plan.jsx}});if(!s.ok)return xt("PORTABLE_BLOCK_PATCH_FAILED",s.diagnostic.message,n.ownerFile);let a=sn({source:s.source,moduleSpecifier:B0(n.ownerFile,e.component.source),imports:[e.component.exportName==="default"?{kind:"default",local:e.component.localName}:{kind:"named",imported:e.component.exportName,...e.component.localName===e.component.exportName?{}:{local:e.component.localName}}]});return a.ok?{ok:!0,patches:[{path:n.ownerFile,source:a.source,baseContentHash:n.sourceHash}]}:xt("PORTABLE_BLOCK_PATCH_FAILED",a.diagnostic.message,n.ownerFile)}function M0(e){return!Rm.safeParse(e.component.source).success||e.component.source===e.resolvedBoundary.ownerFile||e.component.exportName!=="default"&&!/^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(e.component.exportName)?xt("INVALID_TARGET","The Portable component source or export is not a safe materialized reference.",e.component.source):null}function D0(e,t,n,r){if(!r.some(s=>s.value.kind==="route-search-params"))return null;let o=je(t,e);if(!o.ok)return xt("INVOCATION_VALUE_UNRESOLVED",o.diagnostic.message,t);let i=Ie(o.module.ast,Nm(n));return!i.ok||!i.match.path.scope.getBinding("searchParams")?xt("INVOCATION_VALUE_UNRESOLVED","The shared owner has no proven searchParams binding for this invocation.",t):null}function Nm(e){return{kind:"jsx-node",strategy:"source-range",sourceRange:e.sourceRange,...e.structuralPath&&e.componentName?{expectedIdentity:{file:e.file,component:e.componentName,structuralPath:e.structuralPath}}:{}}}function B0(e,t){let n=Hv.posix.relative(Hv.posix.dirname(e),t.replace(/\.(?:tsx?|jsx?)$/u,""));return n=n.replaceAll("\\","/"),n.startsWith(".")?n:`./${n}`}function Pm(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function xt(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{path:n}:{}}}}import{parse as j0}from"@babel/parser";import Am from"@babel/traverse";import*as ft from"@babel/types";var $0=typeof Am=="function"?Am:Am.default,V0=new Set(["slice","map","trim","toString"]);function U0(e){let t=new Set;try{let n=j0(e,{sourceType:"module",plugins:["jsx","typescript"]});$0(n,{JSXExpressionContainer(r){let o=r.get("expression");Os(o,new Set)==="url"&&t.add(`${r.node.start}:${r.node.end}`)}})}catch{}return t}function Os(e,t){if(e.isMemberExpression()||e.isOptionalMemberExpression()){let a=Os(e.get("object"),t),c=e.node;return!c.computed&&ft.isIdentifier(c.property,{name:"thumbnail"})&&a==="record"?"array":c.computed&&ft.isNumericLiteral(c.property)&&Number.isSafeInteger(c.property.value)&&c.property.value>=0&&a==="array"?"item":!c.computed&&ft.isIdentifier(c.property,{name:"url"})&&a==="item"?"url":null}if(e.isCallExpression()){let a=e.get("callee");return!a.isMemberExpression()||a.node.computed||!ft.isIdentifier(a.node.property,{name:"slice"})||!e.node.arguments.every(c=>ft.isNumericLiteral(c)&&Number.isSafeInteger(c.value)&&c.value>=0)?null:Os(a.get("object"),t)==="array"?"array":null}if(!e.isIdentifier())return null;let n=e.scope.getBinding(e.node.name);if(!n?.constant||t.has(n)||!Tm(n,new Set))return null;let r=new Set(t).add(n);if(n.path.isVariableDeclarator()&&ft.isIdentifier(n.path.node.id))return Os(n.path.get("init"),r);if(n.kind!=="param")return null;let o=n.path.getFunctionParent();if(!o)return null;if(e.node.name==="record"&&o.node.params.some(a=>ft.isObjectPattern(a)&&a.properties.some(c=>ft.isObjectProperty(c)&&!c.computed&&ft.isIdentifier(c.key,{name:"record"})&&ft.isIdentifier(c.value,{name:"record"}))))return"record";if(!o.isArrowFunctionExpression()||!ft.isIdentifier(o.node.params[0],{name:e.node.name})||!o.parentPath.isCallExpression())return null;let i=o.parentPath,s=i.get("callee");return i.node.arguments[0]!==o.node||!s.isMemberExpression()||s.node.computed||!ft.isIdentifier(s.node.property,{name:"map"})?null:Os(s.get("object"),r)==="array"?"item":null}function Tm(e,t){return t.has(e)?!0:(t.add(e),e.constant?e.referencePaths.every(n=>{let r=n;for(;r.parentPath&&(r.parentPath.isMemberExpression()||r.parentPath.isOptionalMemberExpression())&&r.parentPath.node.object===r.node;)r=r.parentPath;let o=r.parentPath;if(!o||o.isAssignmentExpression()||o.isUpdateExpression()||o.isUnaryExpression()&&o.node.operator==="delete"||o.isSpreadElement()||o.isObjectProperty()||o.isReturnStatement())return!1;if(o.isVariableDeclarator()){if(!ft.isIdentifier(o.node.id)||o.node.init!==r.node)return!1;let i=o.scope.getBinding(o.node.id.name);return!!i&&Tm(i,t)}if(o.isCallExpression()||o.isOptionalCallExpression()){if(!(o.node.callee===r.node&&(r.isMemberExpression()||r.isOptionalMemberExpression())&&!r.node.computed&&ft.isIdentifier(r.node.property)&&V0.has(r.node.property.name)))return!1;if((r.isMemberExpression()||r.isOptionalMemberExpression())&&ft.isIdentifier(r.node.property,{name:"map"})){let s=o.get("arguments.0");if(!s?.isArrowFunctionExpression()||!ft.isIdentifier(s.node.params[0]))return!1;let a=s.scope.getBinding(s.node.params[0].name);if(!a||!Tm(a,t))return!1}return!0}return r!==n}):!1)}export{xe as FileHistoryStoreError,Gi as PageTemplateManagedSourceError,ul as PreviewFileSystemSiteEditEngineRuntime,ly as SITE_EDIT_RAW_COLOR_LITERAL_RE,cl as SnapshotSiteEditEngineRuntime,QB as analyzePortableCollectionInvocation,ai as analyzePortableInvocation,Qp as analyzePortableRelatedEntries,ad as auditGeneratedCode,fl as auditPortableDependencies,Hi as buildPageBlockIndex,yr as buildPortableInvocation,R0 as buildPortableMaterializationPlan,Lr as buildPortableSourceClosure,mi as checkComponentI18nHostCompatibility,dl as classifyPortableDependencyOwnership,Tx as computeManagedPageTemplatePaths,SD as createPreviewSiteEditEngineRuntime,yD as createSiteEditEngineRuntime,Nx as decodePageTemplateKey,qp as discoverPortableCollectionSourceRelation,Zd as encodePageTemplateId,Wj as exportPortableBlockFromSnapshot,Jp as extractPortableBlockEntry,Mk as instrumentSiteEditRuntimeAttributes,wx as isManagedPageTemplateSourcePath,vA as normalizePortableBlockMetadata,n0 as normalizePortableSource,Ph as openFileHistoryStore,Ek as parseSourceModule,w0 as planPortableBlockPatch,Nd as planPortableRouteCompositionPatch,$i as planRouteCompositionRewrite,U0 as provenRecordThumbnailRanges,zj as readPortableBlockLocalAssetChunk,Sk as resolveImportBase,uw as resolveManagedPageTemplateComposition,nc as resolvePageBlockBoundary,Op as resolvePageBlockFromSnapshot,jo as resolvePageBlockTarget,yn as resolvePageCompositionProjection,pm as resolvePortableBlockSelection,vD as resolvePortableDependencyOwnership,Mr as resolvePortableSourcePath,sc as scanManagedPageTemplateCandidates,bm as scanPortableMediaReferences,ac as scanSiteEditCompositionsFromFiles,od as scanSiteEditThemeStyleViolations,qB as selectPortablePageUnitInvocation};