@vcp-dev/site-edit-engine 0.11.19 → 0.11.20
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.
- package/dist/index.d.ts +2 -0
- package/dist/index.js +17 -17
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
import*as CI from"@babel/parser";import*as St from"@babel/types";import*as qn from"node:path";var _l=[".tsx",".ts",".jsx",".js"],NI=_l.map(e=>`/index${e}`),_I=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 Im(e){let t=e.replace(/[?#].*$/,""),n=/\.([a-z0-9]+)$/i.exec(t);return n!==null&&_I.has(n[1].toLowerCase())}function km(e){let t=[];for(let n of e.program.body)St.isImportDeclaration(n)&&typeof n.source.value=="string"&&mt(n.source.value)&&t.push(n.source.value),St.isExportNamedDeclaration(n)&&n.source&&typeof n.source.value=="string"&&mt(n.source.value)&&t.push(n.source.value),St.isExportAllDeclaration(n)&&typeof n.source.value=="string"&&mt(n.source.value)&&t.push(n.source.value);return St.traverseFast(e.program,n=>{let r=St.isImportExpression(n)?n.source:St.isCallExpression(n)&&St.isImport(n.callee)?n.arguments[0]:null;St.isStringLiteral(r)&&mt(r.value)&&t.push(r.value)}),t}function mt(e){return e.startsWith("./")||e.startsWith("../")||e.startsWith("@/")}function xn(e,t){if(t.startsWith("@/"))return t.slice(2).replace(/\\/g,"/");let n=qn.dirname(e);return qn.join(n,t).replace(/\\/g,"/")}async function PI(e,t){for(let n of Rm(e))if(await t(n))return n;return null}function Rm(e){return[..._l.some(t=>e.endsWith(t))?[e]:[],..._l.map(t=>`${e}${t}`),...NI.map(t=>`${e}${t}`)]}function Qn(e,t,n){let r=xn(e,t);if(!mt(t)||!Cm(e,t,r))return null;for(let o of Rm(r))if(n.has(o))return o;return null}async function Tr(e,t,n){let r=await Ps(e,t,n);return r.ok?r.path:null}async function Ps(e,t,n){let r=xn(e,t);try{if(!Cm(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 PI(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 Cm(e,t,n){if(!mt(t)||t.includes("\0")||t.includes("\\")||qn.posix.isAbsolute(n))return!1;let r=qn.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!qn.posix.isAbsolute(e)}import{createHash as TI}from"node:crypto";import*as Nm from"@babel/parser";function wr(e,t,n,r){return{code:e,message:t,locatorKind:n,details:r}}function q(e,t,n,r,o){return{ok:!1,source:e,diagnostic:wr(t,n,r,o)}}function Pl(e,t,n,r,o){return{ok:!1,source:e,diagnostic:wr(t,n,r,o)}}var AI={"tsx-module":["jsx","typescript"],"ts-module":["typescript"],"next-app-entry":["jsx","typescript"]};function bn(e){let{source:t,profile:n}=e;try{return{ok:!0,ast:Nm.parse(t,{sourceType:"module",plugins:AI[n]})}}catch(r){return{ok:!1,source:t,diagnostic:wr("parse-failed",`AST parse failed: ${r instanceof Error?r.message:String(r)}`)}}}function Al(e,t){return bn({source:e,profile:_m(t.kind)})}function ni(e,t){return bn({source:e,profile:_m(t)})}function _m(e){return"next-app-entry"}function Or(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 Ue=(e,t)=>{let n=bn({source:t,profile:Or({filePath:e,source:t})});return n.ok?{ok:!0,module:{file:e,source:t,sourceHash:`sha256:${TI("sha256").update(t).digest("hex")}`,ast:n.ast,imports:km(n.ast).map(r=>({specifier:r}))}}:{ok:!1,diagnostic:{path:e,code:"parse-failed",message:n.diagnostic.message}}};function wI(e,t){return Ue(e,t)}function OI(e,t){return xn(e,t)}import{COMPONENT_I18N_FILE_SUFFIX as FI,parseComponentI18nResourcesJson as LI,resolveSiteTextDirection as DI,SiteLocaleSchema as MI}from"@vcp-dev/contracts";var BI=["i18next","react-i18next"],jI="components/ui/site-locale-provider.tsx",$I="components/ui/component-i18n-provider.tsx",Pm="app/layout.tsx";async function ri(e){let t=e.files.filter(p=>p.path.endsWith(FI));if(t.length===0)return{ok:!0};for(let p of["package.json",Pm,jI,$I])if(!await e.exists(p))return er(`Target snapshot is missing required i18n host file: ${p}`);let n;try{n=JSON.parse(await e.readFile("package.json"))}catch{return er("Target snapshot package.json is invalid.")}let r=Am(n)&&Am(n.dependencies)?n.dependencies:{},o=BI.filter(p=>typeof r[p]!="string"||r[p].trim().length===0);if(o.length>0)return er(`Target snapshot must already declare: ${o.join(", ")}.`);let i=await e.readFile(Pm),s=Tl(i,"html","lang"),a=Tl(i,"html","dir"),c=Tl(i,"SiteLocaleProvider","locale"),l=MI.safeParse(s);if(!l.success||!a||!c||s!==c||a!==DI(l.data))return er("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 er("Target snapshot root layout is not wired to SiteLocaleProvider.");let u=l.data;if(e.targetLocale&&e.targetLocale!==u)return er("Target snapshot locale does not match the authoritative site language.");let d=u.split("-")[0];for(let p of t){let m=LI(p.content);if(!m.success)return er(`Component i18n resource is invalid: ${p.path}.`);if(!e.deferTargetLocale&&!Object.hasOwn(m.data,u)&&!Object.hasOwn(m.data,d))return er(`Component i18n resource ${p.path} has no locale for ${u} or ${d}.`)}return{ok:!0}}function Tl(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 Am(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function er(e){return{ok:!1,message:e}}import Ol from"@babel/generator";import*as Dm from"@babel/parser";import Fl from"@babel/traverse";import*as Ke from"@babel/types";import{computeSiteEditSourceIdentityKey as UI}from"@vcp-dev/contracts";var Tm="data-vcp-ui-component",As="components/ui";function Mn(e){if(!e)return!1;let t=wl(e);return t===As||t.startsWith(`${As}/`)||t.includes(`/${As}/`)||t.endsWith(`/${As}`)}function Fr(e,t){return e?e.startsWith("@/")||e.startsWith("~/")?Mn(e.slice(2)):e.startsWith("./")||e.startsWith("../")?Mn(wl(`${VI(t)}/${e}`)):Mn(e):!1}function wl(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 VI(e){let t=wl(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}import{stripSiteEditRepeatInstanceKeys as n0}from"@vcp-dev/contracts";import{isSiteEditRuntimeContainerTag as o0,isSiteEditRuntimeTextTag as i0}from"@vcp-dev/contracts/site-edit-runtime-capability";var wm={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 KI=typeof Ol=="function"?Ol:Ol.default,JI=typeof Fl=="function"?Fl:Fl.default,XI=new Set(["base","body","head","html","link","meta","noscript","script","style","template","title"]),zI="suppressHydrationWarning",HI=new Set(["SiteEditBootstrap"]);function WI(e){let t=ZI(e.file,e.projectRoot);if(!YI(e.source)||Mn(t))return{code:e.source,elements:[]};let n=e.attributes??wm,r=Dm.parse(e.source,{sourceType:"module",plugins:["jsx","typescript"]}),o=[],i=QI(r,t);return JI(r,{JSXElement(s){let a=s.node.openingElement,c=a.name;if(!tk(c)||Mm(a,n.key))return;let l=rk(s)??"default",u=ik(s),d=UI(t,l,u),p=ws(c)??"unknown",m=qI(c)?"jsx":"component-call";if(m==="component-call"&&!ok(s.node.children)&&HI.has(p))return;let f=m==="component-call"&&ek(p,i);nk(a,n.key,d),f&&Om(a,Tm),GI(s)&&Om(a,zI),o.push({key:d,tag:p,componentName:l,sourceFile:t,sourceKind:m})}}),o.length===0?{code:e.source,elements:o}:{code:KI(r,{jsescOption:{minimal:!0}}).code,elements:o}}function GI(e){return!e.findParent(t=>t.isJSXElement())}function YI(e){return/(?:^|[=(:,?;\[{>&|\n\r]|return\s+)\s*<(?:[A-Za-z][\w.:-]*|>)(?:\s|>|\/)/m.test(e)}function ZI(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 qI(e){return Ke.isJSXIdentifier(e)&&/^[a-z]/.test(e.name)}function ws(e){return Ke.isJSXIdentifier(e)?e.name:Ke.isJSXMemberExpression(e)?jm(e):null}function QI(e,t){let n=new Set;for(let r of e.program.body)if(!(!Ke.isImportDeclaration(r)||!Fr(r.source.value,t)))for(let o of r.specifiers)n.add(o.local.name);return n}function ek(e,t){let n=e.split(".")[0]??e;return t.has(n)}function tk(e){let t=ws(e);return!t||t==="Fragment"||t.endsWith(".Fragment")?!1:!XI.has(t)}function Mm(e,t){return e.attributes.some(n=>Ke.isJSXAttribute(n)&&Ke.isJSXIdentifier(n.name,{name:t}))}function nk(e,t,n){Bm(e,Ke.jsxAttribute(Ke.jsxIdentifier(t),Ke.stringLiteral(n)))}function Om(e,t){Mm(e,t)||Bm(e,Ke.jsxAttribute(Ke.jsxIdentifier(t),null))}function Bm(e,t){let n=e.attributes.findIndex(r=>Ke.isJSXSpreadAttribute(r));if(n>=0){e.attributes.splice(n,0,t);return}e.attributes.push(t)}function jm(e){return`${Ke.isJSXIdentifier(e.object)?e.object.name:jm(e.object)}.${e.property.name}`}function rk(e){let t=e;for(;t;){if(t.isFunctionDeclaration()||t.isClassDeclaration())return t.node.id?.name??null;if(t.isVariableDeclarator()&&Ke.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 ok(e){return e.some(t=>Ke.isJSXElement(t)||Ke.isJSXFragment(t))}var Fm=new WeakMap,Ts=new WeakMap,Ll=new WeakMap;function ik(e){let t=Fm.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=sk(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return Fm.set(e.node,o),o}function sk(e){let t=ws(e.node.openingElement.name);return!t||t==="Fragment"||t.endsWith(".Fragment")?null:/^[A-Z]/.test(t)?`component:${t}#${Lm(e,t)}`:`${t}#${Lm(e,t)}`}function Lm(e,t){let n=$m(e)??e.getFunctionParent();if(!n)return 0;let r=Ll.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=Ll.get(n.node);o||(o=new Map,Ll.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()?Os(n):ak(n);for(let c of a)if(ws(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 ak(e){let t=Ts.get(e.node);if(t)return t;let n=[];return e.traverse({JSXElement(r){r.getFunctionParent()?.node===e.node&&!$m(r)&&n.push(r)}}),Ts.set(e.node,n),n}function $m(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 Os(e){let t=Ts.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(...Os(o));continue}o.isJSXExpressionContainer()&&n.push(...Lr(o.get("expression")))}return Ts.set(e.node,n),n}function Lr(e){if(e.isJSXElement())return[e];if(e.isJSXFragment())return Os(e);if(e.isParenthesizedExpression())return Lr(e.get("expression"));if(e.isLogicalExpression()&&e.node.operator==="&&")return Lr(e.get("right"));if(e.isConditionalExpression())return[...Lr(e.get("consequent")),...Lr(e.get("alternate"))];if(e.isCallExpression()&&lk(e.node)){let t=e.get("arguments")[0];return ck(t)}return[]}function ck(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return[t];if(t.isJSXFragment())return Os(t);if(t.isParenthesizedExpression())return Lr(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?Lr(r):[]}return[]}function lk(e){return Ke.isMemberExpression(e.callee)&&Ke.isIdentifier(e.callee.property)&&e.callee.property.name==="map"}import{SiteEditOperationRequestSchema as vD,SiteEditPatchPlanSchema as ID}from"@vcp-dev/contracts";function Dr(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 Fs(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 Ls(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 Ds(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:uk(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 Ms(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:Dr(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 uk(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 OL,computeSiteEditCompositionKey as FL,getSiteEditSourceDeleteProtectionReason as LL,isSiteEditTextSourcePath as DL,parseSiteEditRepeatInstanceKey as ML,SITE_EDIT_SOURCE_DELETE_CAPABILITY as BL,stripSiteEditRepeatInstanceKeys as Lt}from"@vcp-dev/contracts";import zc from"node:path";import{parse as jL}from"yaml";import $l from"node:path";import{TextDecoder as fk}from"node:util";import{SITE_EDIT_SOURCE_ALLOWED_APP_FILES as Um,SITE_EDIT_SOURCE_ALLOWED_DIRS as Km,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as Jm,SiteEditCompositionContextSchema as pk,SiteEditSourceFileResponseSchema as Dl,SiteEditSourceLocationSchema as mk,SiteEditSourcePathSchema as Bs,SiteEditSourceTreeResponseSchema as gk,isSiteEditTextSourcePath as hk}from"@vcp-dev/contracts";import{createHash as dk}from"node:crypto";var oi=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 ve(e){return`sha256:${dk("sha256").update(e).digest("hex")}`}var yk=[...Jm,...Um,...Km];function Vl(e){if(!e.composition)throw new Error("Composition unavailable for source access policy.");return pk.parse(e.composition)}var Ml=2e3,Bl=12,jl=24*1024*1024,Vm=512*1024,xk=new Set(["image/avif","image/gif","image/jpeg","image/png","image/webp","image/x-icon"]),bk={".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"},Ek={".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"},Sk=new fk("utf-8",{fatal:!0});async function js(e,t={}){let n=Vl(t),{files:r,truncated:o}=await _k(e,t),i=Tk(r.map(s=>s.metadata));return gk.parse({composition:n,nodes:i,defaultPath:wk(r.map(s=>s.metadata)),totalFiles:r.length,...o?{truncated:o}:{}})}async function $s(e,t,n={}){let r=Vl(n),o=Bs.parse(t.path),i=await Ik(e,o,n);if(!i)throw new Error(`Source file not found: ${o}`);if(Kl(o)){let a=Hm(o),c=await Rk(e,{path:o,sizeBytes:i.sizeBytes,mimeType:a});return Dl.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:i.sizeBytes,mimeType:a,readonly:!0,...c})}let s=await Ul(e,o);return s.ok?Dl.parse({composition:r,path:o,kind:"text",language:Wm(o),sizeBytes:s.sizeBytes,contentHash:ve(s.content),readonly:!1,content:s.content}):Dl.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:s.sizeBytes,mimeType:"application/octet-stream",readonly:!0,previewUnavailableReason:"unsupported-mime"})}async function Ul(e,t){if(e.readFileBytes){let o=await e.readFileBytes(t),i=vk(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 vk(e){if(e.includes(0))return null;try{return Sk.decode(e)}catch{return null}}async function Ik(e,t,n){if(!Ck(t,n))return null;let r=await kk(e,t);return r?{path:t,sizeBytes:r.sizeBytes}:null}async function kk(e,t){if(e.getFileInfo)return e.getFileInfo(t);if(e.listFiles){let o=Xm(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(Kl(t))return{path:t,sizeBytes:0};let n=await e.readFile(t);return{path:t,sizeBytes:Buffer.byteLength(n,"utf8")}}async function Rk(e,t){if(!xk.has(t.mimeType))return{previewUnavailableReason:"unsupported-mime"};if(t.sizeBytes>Vm)return{previewUnavailableReason:"too-large"};if(!e.readFileBytes)return{previewUnavailableReason:"bytes-unavailable"};let n=await e.readFileBytes(t.path);return n.byteLength>Vm?{previewUnavailableReason:"too-large"}:{contentBase64:Buffer.from(n).toString("base64")}}function Ck(e,t){return Jm.some(n=>n===e)||Um.some(n=>n===e)||Km.some(n=>e===n||e.startsWith(`${n}/`))?!0:!e.startsWith("app/")&&!e.startsWith("src/app/")?!1:(t.routeEntryFiles??[]).some(n=>{let r=Bs.safeParse(n);return r.success&&r.data===e})}function Vs(e,t){if(!t.sourceLocator)throw new Error(`Source location not available for key: ${e.key}`);return mk.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 Xm(e){return Array.isArray(e)?{files:e}:e}function Nk(e){return["max-files","max-depth","max-total-bytes"].filter(n=>e.includes(n))}async function _k(e,t){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let n=Xm(await e.listFiles({roots:Pk(t),maxFiles:Ml+1,maxDepth:Bl,maxTotalBytes:jl+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=Bs.safeParse(a.path);if(!c.success)continue;let l=c.data;if(l.split("/").length>Bl){o.add("max-depth");continue}if(r.size>=Ml){o.add("max-files");break}if(i+a.sizeBytes>jl){o.add("max-total-bytes");break}r.set(l,{path:l,sizeBytes:a.sizeBytes,metadata:Ak(l,a.sizeBytes,Vl(t))}),i+=a.sizeBytes}return{files:[...r.values()].sort((a,c)=>a.path.localeCompare(c.path)),...o.size>0?{truncated:{reasons:Nk([...o]),maxFiles:Ml,maxDepth:Bl,maxTotalBytes:jl}}:{}}}function Pk(e){let t=new Set(yk);for(let n of e.routeEntryFiles??[]){let r=Bs.safeParse(n);r.success&&(r.data.startsWith("app/")||r.data.startsWith("src/app/"))&&t.add(r.data)}return[...t]}function Ak(e,t,n){return Kl(e)?{composition:n,path:e,kind:"binary",language:null,sizeBytes:t,mimeType:Hm(e),readonly:!0}:{composition:n,path:e,kind:"text",language:Wm(e),sizeBytes:t,readonly:!1}}function Tk(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 zm(t)}function zm(e){return e.map(t=>t.kind==="directory"?{...t,children:zm(t.children)}:t).sort((t,n)=>t.kind!==n.kind?t.kind==="directory"?-1:1:t.name.localeCompare(n.name))}function wk(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 Kl(e){return!hk(e)}function Hm(e){let t=$l.posix.extname(e).toLowerCase();return!t&&$l.posix.basename(e).toLowerCase()==="favicon"?"image/x-icon":bk[t]??"application/octet-stream"}function Wm(e){let t=$l.posix.extname(e).toLowerCase();return Ek[t]??"plaintext"}import*as Br from"@babel/types";import Jl from"@babel/traverse";import*as En from"@babel/types";function ze(e){if(e.isJSXFragment())return!0;if(!e.isJSXElement())return!1;let t=e.node.openingElement.name;if(En.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(En.isIdentifier(s)&&s.name==="Fragment"||En.isStringLiteral(s)&&s.value==="Fragment")&&Gm(i.parentPath)}if(!En.isJSXMemberExpression(t)||!En.isJSXIdentifier(t.property)||t.property.name!=="Fragment"||!En.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())&&Gm(r.parentPath)}function Gm(e){return e?.isImportDeclaration()===!0&&e.node.source.value==="react"}var tr=typeof Jl=="function"?Jl:Jl.default,Us=new WeakMap,Ks=new WeakMap;function Sn(e,t){let n=Al(e,t);if(!n.ok)return Pl(e,n.diagnostic.code,n.diagnostic.message,t.kind);let r=Ee(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}}:Pl(e,r.diagnostic.code,r.diagnostic.message,t.kind,r.diagnostic.details)}function Ee(e,t){return t.kind==="jsx-node"?Qm(e,t):t.kind==="jsx-attribute"?Bk(e,t):t.kind==="value"?jk(e,t):t.kind==="expression"?$k(e,t):t.kind==="directive"?Vk(e,t):t.kind==="export"?Uk(e,t):{ok:!1,diagnostic:wr("unsupported-syntax",`Unsupported locator kind: ${t.kind}`)}}function Qm(e,t){return t.strategy==="source-range"?Ok(e,t):Fk(e,t)}function Ok(e,t){let n=null;if(tr(e,{JSXElement(o){if(!Mr(o.node,t.sourceRange))return;let i=Qe("jsx-node",o);if(i){if(!n){n=i;return}i.end-i.start<n.end-n.start&&(n=i)}},JSXFragment(o){if(!Mr(o.node,t.sourceRange))return;let i=Qe("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXExpressionContainer(o){if(!Mr(o.node,t.sourceRange))return;let i=Qe("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXText(o){if(!Mr(o.node,t.sourceRange))return;let i=Qe("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)}}),!n)return ot("jsx-node","locator-miss","JSX node not found for source-range locator");let r=n;return t.expectedIdentity&&!eR(r.path,t.expectedIdentity)?ot("jsx-node","locator-miss","JSX node failed expected identity validation"):{ok:!0,match:r}}function Fk(e,t){if(t.structuralPath===""){let r=Dk(e,t.component);if(r){let o=Mk(r);if(o)return o}}let n=null;return tr(e,{JSXElement(r){if(si(r)!==t.component||zl(r)!==t.structuralPath)return;let i=Qe("jsx-node",r);i&&(n=i,r.stop())},JSXFragment(r){if(si(r)!==t.component||zl(r)!==t.structuralPath)return;let i=Qe("jsx-node",r);i&&(n=i,r.stop())}}),!n&&t.expectedRange&&(n=Lk(e,t.component,t.expectedRange)),n?{ok:!0,match:n}:ot("jsx-node","locator-miss","JSX node not found for structural-path locator")}function Lk(e,t,n){let r=null;return tr(e,{JSXElement(o){if(si(o)!==t||!Mr(o.node,n))return;let i=Qe("jsx-node",o);i&&(r=i,o.stop())},JSXFragment(o){if(si(o)!==t||!Mr(o.node,n))return;let i=Qe("jsx-node",o);i&&(r=i,o.stop())}}),r}function Dk(e,t){let n=null;return tr(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 Mk(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 ot("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}return null}return(t.isParenthesizedExpression()?t.get("expression"):t).isJSXFragment()?ot("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 ot("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}}}return null}function Bk(e,t){let n=Qm(e,t.element);if(!n.ok)return n;let s=n.match.path.get("openingElement").get("attributes").find(c=>tR(c,t.name));if(!s||!s.isJSXAttribute())return ot("jsx-attribute","locator-miss",`JSX attribute '${t.name}' not found`);let a=Qe("jsx-attribute",s);return a?{ok:!0,match:a}:ot("jsx-attribute","locator-miss",`JSX attribute '${t.name}' has no source range`)}function jk(e,t){let n=Kk(e,t);if(!n.ok)return n;let r=Jk(n.match.path,t.path??[]);return r.ok?t.expectedRange&&!jn(r.match.path.node.loc,t.expectedRange)?ot("value","locator-miss","Resolved value does not match expected range"):{ok:!0,match:r.match}:r}function $k(e,t){let n=null;return tr(e,{Identifier(r){if(!Yk(r))return;let o=Zm(r);if(!o||!qm(o,t))return;let i=Qe("expression",r);i&&(t.expectedRange&&!jn(r.node.loc,t.expectedRange)||(n=i,r.stop()))},MemberExpression(r){let o=Zm(r);if(!o||!qm(o,t))return;let i=Qe("expression",r);i&&(t.expectedRange&&!jn(r.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:ot("expression","locator-miss","Expression not found")}function Vk(e,t){let n=null;return tr(e,{Program(r){let i=r.get("directives").find(a=>a.node.value.value===t.value);if(!i||t.expectedRange&&!jn(i.node.loc,t.expectedRange))return;let s=Qe("directive",i);s&&(n=s,r.stop())}}),n?{ok:!0,match:n}:ot("directive","locator-miss",`Directive '${t.value}' not found`)}function Uk(e,t){let n=null;return tr(e,{ExportNamedDeclaration(r){if(t.exportKind==="generate-metadata"){let c=r.get("declaration");if(c.isFunctionDeclaration()&&c.node.id?.name==="generateMetadata"){let p=Qe("export",c);if(!p||t.expectedRange&&!jn(c.node.loc,t.expectedRange))return;n=p,r.stop();return}if(!c.isVariableDeclaration())return;let l=Hl(c,"generateMetadata");if(!l||!l.isVariableDeclarator())return;let u=l.get("init");if(!u.node)return;let d=Qe("export",u);if(!d||t.expectedRange&&!jn(u.node.loc,t.expectedRange))return;n=d,r.stop();return}let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=Hl(o,t.exportKind==="named"?t.name:"metadata");if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node||t.expectedRange&&!jn(s.node.loc,t.expectedRange))return;let a=Qe("export",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(t.exportKind!=="default")return;let o=r.get("declaration"),i=Qe("export",o);i&&(t.expectedRange&&!jn(o.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:ot("export","export-not-found",`Export '${Qk(t)}' not found`)}function Kk(e,t){let n=null;return tr(e,{Expression(r){if(n||t.root.kind!=="expression"||!Mr(r.node,t.root.sourceRange))return;let o=Qe("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 m=r.get("init");if(!m.node)return;let f=Qe("value",m);if(!f)return;n=f,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(m=>m?.type==="Identifier"&&m.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 p=Qe("value",d);p&&(n=p,r.stop())},ExportNamedDeclaration(r){if(n||t.root.kind!=="named-export")return;let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=Hl(o,t.root.name);if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node)return;let a=Qe("value",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(n||t.root.kind!=="default-export")return;let o=r.get("declaration"),i=Qe("value",o);i&&(n=i,r.stop())}}),n?{ok:!0,match:n}:ot("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 Jk(e,t){let n=Xl(e);for(let o of t){if(n=Xl(n),o.kind==="property"){if(!n.isObjectExpression())return ot("value","unsupported-syntax","Property path requires object expression");let a=n.get("properties");if(a.some(l=>!l.isObjectProperty()))return ot("value","unsupported-syntax","Spread properties are not supported");let c=a.find(l=>nR(l,o.name));if(!c||!c.isObjectProperty())return ot("value","property-not-found",`Property '${o.name}' not found`);n=c.get("value");continue}if(!n.isArrayExpression())return ot("value","unsupported-syntax","Array index path requires array expression");let i=n.get("elements");if(i.some(a=>a.node?.type==="SpreadElement"))return ot("value","unsupported-syntax","Spread array elements are not supported");let s=i[o.index];if(!s?.node)return ot("value","array-index-out-of-range",`Array index ${o.index} is out of range`);n=s}n=Xl(n);let r=Qe("value",n);return r?{ok:!0,match:r}:ot("value","locator-miss","Resolved value has no source range")}function Xl(e){let t=e;for(;t.isTSAsExpression()||t.isTSSatisfiesExpression()||t.isTSNonNullExpression();)t=t.get("expression");return t}function Qe(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 Mr(e,t){return jn(e.loc,t)}function jn(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 zl(e){let t=[],n=e,r=e.node;for(;n;){if(n.isJSXElement()){if(!ze(n)){let o=tg(n.node.openingElement);o&&(/^[A-Z]/.test(o)?t.unshift(`component:${o}#${Ym(n,o)}`):t.unshift(`${o}#${Ym(n,o)}`))}}else n.isJSXFragment()&&n.node===r&&t.unshift("fragment");if(!n.parentPath||Wk(n.parentPath)&&!Gk(n.parentPath))break;n=n.parentPath}return t.join("/")}function Ym(e,t){let n=eg(e)??e.getFunctionParent();if(!n)return 0;let r=Us.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=0,i=Us.get(n.node)?.get(t);if(!i){let a=Us.get(n.node);a||(a=new Map,Us.set(n.node,a)),i=new WeakMap,a.set(t,i)}let s=n.isJSXElement()||n.isJSXFragment()?ii(n):Xk(n);for(let a of s)if(tg(a.node.openingElement)===t){if(i.set(a.node,o),a.node===e.node)return o;o++}return i.get(e.node)??0}function Xk(e){let t=Ks.get(e.node);if(t)return t;let n=[];return e.traverse({JSXElement(r){r.getFunctionParent()?.node===e.node&&!eg(r)&&n.push(r)}}),Ks.set(e.node,n),n}function eg(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(ze(t)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function ii(e){let t=Ks.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(ze(o)){n.push(...ii(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...ii(o));continue}o.isJSXExpressionContainer()&&n.push(...Bn(o.get("expression")))}return Ks.set(e.node,n),n}function Bn(e){if(e.isJSXElement())return ze(e)?ii(e):[e];if(e.isJSXFragment())return ii(e);if(e.isParenthesizedExpression())return Bn(e.get("expression"));if(e.isLogicalExpression()&&zk(e.node.operator))return Bn(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(...Bn(c))}if(s.isReturnStatement()){let a=s.get("argument");a.isExpression()&&i.push(...Bn(a));break}}return i}else if(o.node&&o.isExpression())return Bn(o)}}}}return e.isConditionalExpression()?[...Bn(e.get("consequent")),...Bn(e.get("alternate"))]:e.isArrayExpression()?e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:Bn(t)):[]}function zk(e){return e==="&&"||e==="||"||e==="??"}function tg(e){return e.name.type==="JSXIdentifier"?e.name.name:e.name.type==="JSXMemberExpression"?Hk(e.name):null}function Hk(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 si(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 Wk(e){return!!(e.isFunctionDeclaration()||e.isFunctionExpression()||e.isArrowFunctionExpression())}function Gk(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 Yk(e){return!(!e.isExpression()||e.parentPath?.isMemberExpression({property:e.node}))}function Zm(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 qm(e,t){return e.base===t.base&&Zk(e.path,t.path??[])}function Zk(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 qk(e){return e.key.type==="Identifier"?e.key.name:e.key.type==="StringLiteral"?e.key.value:null}function Qk(e){return e.exportKind==="named"?e.name:e.exportKind}function ot(e,t,n,r){return{ok:!1,diagnostic:wr(t,n,e,r)}}function eR(e,t){return si(e)!==t.component?!1:zl(e)===t.structuralPath}function tR(e,t){return!e.isJSXAttribute()||e.node.name.type!=="JSXIdentifier"?!1:e.node.name.name===t}function Hl(e,t){return e.get("declarations").find(n=>!n.isVariableDeclarator()||n.node.id.type!=="Identifier"?!1:n.node.id.name===t)}function nR(e,t){return e.isObjectProperty()?qk(e.node)===t:!1}import*as rg from"@babel/parser";import{arrayExpression as aR,booleanLiteral as cR,identifier as lR,jsxAttribute as uR,jsxExpressionContainer as dR,jsxIdentifier as fR,nullLiteral as pR,numericLiteral as mR,objectExpression as gR,objectProperty as hR,stringLiteral as Gl}from"@babel/types";import Wl from"@babel/generator";var rR=typeof Wl=="function"?Wl:Wl.default;function oR(e){let t=e.split(`
|
|
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
|
|
3
|
-
`).map(r=>
|
|
4
|
-
`)}function Js(e){let{ast:t,source:n}=e;try{let r=oR(n),i=rR(t,{comments:!0,jsescOption:{minimal:!0,quotes:"single"}},n).code;return r!=="2"&&(i=sR(i,r)),{ok:!0,source:i}}catch(r){return q(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 ai(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 we(e,t,n){let r=Js({ast:e,source:t});return r.ok?ai(t,r.source,n):r}function Je(e,t){let n=ni(e,t);return n.ok?{ok:!0,ast:n.ast}:{ok:!1,result:{ok:!1,source:e,diagnostic:n.diagnostic}}}function Xs(e,t){return Js({ast:e,source:t})}function yR(e,t,n){let r=Ee(e,t);return r.ok?{ok:!0,match:r.match}:{ok:!1,result:{ok:!1,source:n,diagnostic:r.diagnostic}}}function co(e,t,n){let r=yR(e,t,n);return r.ok?r.match.path.isJSXElement()?r:{ok:!1,result:q(n,"unsupported-syntax","JSX locator must resolve to JSXElement","jsx-node")}:r}function nr(e){return typeof e=="string"?Gl(e):typeof e=="number"?mR(e):typeof e=="boolean"?cR(e):e===null?pR():Array.isArray(e)?aR(e.map(t=>nr(t))):gR(Object.entries(e).map(([t,n])=>{let r=hR(Yl(t),nr(n));return t==="__proto__"&&(r.computed=!0),r}))}function xR(e){return typeof e=="string"?Gl(e):dR(nr(e))}function ci(e,t){return uR(fR(e),xR(t))}function zs(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:q(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:q(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function Yl(e){return/^[$A-Z_][0-9A-Z_$]*$/i.test(e)?lR(e):Gl(e)}function Hs(e){let{source:t,locator:n,segmentIndex:r,newText:o}=e,i=Je(t,"jsx-node");if(!i.ok)return i.result;let s=Ee(i.ast,n);if(!s.ok)return{ok:!1,source:t,diagnostic:s.diagnostic};let c=bR(s.match.path)[r];if(!c)return q(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]??"",p=l.match(/\s*$/)?.[0]??"";c.path.replaceWithMultiple([...d?[Br.jsxText(d)]:[],Br.jsxExpressionContainer(Br.stringLiteral("")),...p?[Br.jsxText(p)]:[]]);break}let u=ER(l,o);c.path.node.value=u,c.path.node.extra={rawValue:u,raw:u.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/{/g,"{").replace(/}/g,"}")};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 we(i.ast,t,{kind:"update-text",target:"jsx-node",inverse:"restore-text"})}function bR(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=SR(r.get("expression"));o.length>0&&t.push(...o)}}return t}function ER(e,t){let n=e.match(/^\s*/)?.[0]??"",r=e.match(/\s*$/)?.[0]??"";return`${n}${t.trim()}${r}`}function SR(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 Zl}from"@babel/types";function jr(e){let{source:t,locator:n}=e,r=Je(t,"jsx-node");if(!r.ok)return r.result;let o=Ee(r.ast,n);return o.ok?(vR(o.match.path),we(r.ast,t,{kind:"remove-node",target:"jsx-node",inverse:"insert-child"})):{ok:!1,source:t,diagnostic:o.diagnostic}}function vR(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(Zl());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(Zl());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(Zl());return}e.remove()}import{cloneNode as IR}from"@babel/types";function lo(e){let t=Je(e.source,"jsx-node");if(!t.ok)return t.result;let n=Ee(t.ast,e.locator);if(!n.ok)return{ok:!1,source:e.source,diagnostic:n.diagnostic};let r=zs(e.source,e.node.jsx);return r.ok?(n.match.path.replaceWith(IR(r.node,!0)),we(t.ast,e.source,{kind:"replace-node",target:"jsx-node",inverse:"replace-node"})):r.result}import{cloneNode as FR}from"@babel/types";import ql from"@babel/traverse";import*as de from"@babel/types";function li(e,t,n){return`${e}::${t}::${n}`}var B={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 kR=typeof ql=="function"?ql:ql.default;function Gt(e,t,n,r){if(!e.ok)return e;let o=Wt(n,t);if(!o)return e;let i=RR(t,o,r);return i?{...e,selectionRef:i}:e}function RR(e,t,n){let r=CR(e,t);if(!r)return;let o=n.sourceLocator?og(n.sourceLocator):void 0,i=n.targetParentLocator?og(n.targetParentLocator):void 0,s=n.file??i?.file??o?.file,a=n.component??_R(r)??i?.component??o?.component;if(!(!s||!a))return{key:li(s,a,PR(r))}}function og(e){return e.strategy==="structural-path"?{file:e.file,component:e.component,structuralPath:e.structuralPath}:e.expectedIdentity}function CR(e,t){let n=ug(e,t);return!n||n.node.type!=="JSXElement"?null:n}function ug(e,t){let n=null;return kR(e,{JSXElement(r){r.node===t&&(n=r,r.stop())},JSXFragment(r){r.node===t&&(n=r,r.stop())}}),n}function Wt(e,t){if(!e)return null;if(de.isJSXElement(e))return OR(t,e)?ig(e.children,t):e;if(de.isJSXFragment(e))return ig(e.children,t);if(de.isJSXExpressionContainer(e)||de.isParenthesizedExpression(e)||de.isTSAsExpression(e)||de.isTSSatisfiesExpression(e)||de.isTSTypeAssertion(e)||de.isTSNonNullExpression(e))return Wt(e.expression,t);if(de.isLogicalExpression(e))return Wt(e.right,t);if(de.isConditionalExpression(e))return Wt(e.consequent,t)??Wt(e.alternate,t);if(de.isCallExpression(e)||de.isOptionalCallExpression(e))return dg(e)?NR(e.arguments[0],t):null;if(de.isArrayExpression(e))for(let n of e.elements){if(!n)continue;let r=Wt(n,t);if(r)return r}return null}function ig(e,t){for(let n of e){let r=Wt(n,t);if(r)return r}return null}function NR(e,t){return!e||!de.isArrowFunctionExpression(e)&&!de.isFunctionExpression(e)?null:de.isBlockStatement(e.body)?ui(e.body.body,t):Wt(e.body,t)}function ui(e,t){for(let n of e){if(de.isReturnStatement(n)){let r=Wt(n.argument,t);if(r)return r;continue}if(de.isBlockStatement(n)){let r=ui(n.body,t);if(r)return r;continue}if(de.isIfStatement(n)){let r=sg(n.consequent,t);if(r)return r;let o=n.alternate?sg(n.alternate,t):null;if(o)return o;continue}if(de.isSwitchStatement(n))for(let r of n.cases){let o=ui(r.consequent,t);if(o)return o}}return null}function sg(e,t){return de.isBlockStatement(e)?ui(e.body,t):ui([e],t)}function _R(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(de.isFunctionDeclaration(n))return n.id?.name??"default"}if(t.isVariableDeclarator()&&de.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 ag=new WeakMap,cg=new WeakMap,Ql=new WeakMap;function PR(e){let t=ag.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=AR(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return ag.set(e.node,o),o}function AR(e){let t=fg(e.node.openingElement.name);return!t||ze(e)?null:/^[A-Z]/.test(t)?`component:${t}#${lg(e,t)}`:`${t}#${lg(e,t)}`}function lg(e,t){let n=TR(e);if(!n)return 0;let r=Ql.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=Ql.get(n.node);o||(o=new Map,Ql.set(n.node,o));let i=o.get(t);i||(i=new WeakMap,o.set(t,i));let s=0;for(let a of $r(n))if(fg(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 TR(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(ze(t)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function $r(e){let t=cg.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(ze(o)){n.push(...$r(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...$r(o));continue}o.isJSXExpressionContainer()&&n.push(...vn(o.get("expression")))}return cg.set(e.node,n),n}function vn(e){if(e.isJSXElement())return ze(e)?$r(e):[e];if(e.isJSXFragment())return $r(e);if(e.isParenthesizedExpression())return vn(e.get("expression"));if(e.isLogicalExpression())return vn(e.get("right"));if(e.isConditionalExpression())return[...vn(e.get("consequent")),...vn(e.get("alternate"))];if(e.isArrayExpression())return e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:vn(t));if((e.isCallExpression()||e.isOptionalCallExpression())&&dg(e.node)){let t=e.get("arguments"),n=Array.isArray(t)?t[0]:void 0;return n?wR(n):[]}return[]}function wR(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return ze(t)?$r(t):[t];if(t.isJSXFragment())return $r(t);if(t.isParenthesizedExpression())return vn(t.get("expression"));if(t.isLogicalExpression()||t.isConditionalExpression())return vn(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(...vn(s))}if(!r.isReturnStatement())continue;let o=r.get("argument");return o.node&&n.push(...vn(o)),n}return n}function dg(e){let t=e.callee;return(de.isMemberExpression(t)||de.isOptionalMemberExpression(t))&&de.isIdentifier(t.property)&&t.property.name==="map"&&!t.computed}function OR(e,t){let n=ug(e,t);return n?ze(n):!1}function fg(e){return de.isJSXIdentifier(e)?e.name:de.isJSXMemberExpression(e)?pg(e):de.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function pg(e){return`${de.isJSXIdentifier(e.object)?e.object.name:pg(e.object)}.${e.property.name}`}function rr(e,t){if(t.parentPath===e&&t.listKey==="children"&&eu(e))return e;if(!t.parentPath||t.listKey!=="children")return null;let n=t.parentPath;if(!eu(n))return null;let r=n;for(;r&&r!==e;){if(!eu(r)||!ze(r)||r.listKey!=="children")return null;r=r.parentPath}return r===e?n:null}function eu(e){return e.isJSXElement()||e.isJSXFragment()}function Yt(e){let{source:t,locator:n,node:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=Je(t,"jsx-node");if(!a.ok)return a.result;let c=Ee(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};if(!c.match.path.isJSXElement()&&!c.match.path.isJSXFragment())return q(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 q(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=zs(t,r.jsx);if(!u.ok)return u.result;let d=FR(u.node,!0),p=l.node.children,m={...s,targetParentLocator:n},f=b=>s?Gt(b,a.ast,d,m):b;if(o==="append")return p.push(d),f(we(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return p.unshift(d),f(we(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(!i)return q(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let h=Ee(a.ast,i);if(!h.ok)return{ok:!1,source:t,diagnostic:h.diagnostic};let y=rr(c.match.path,h.match.path);if(!y)return q(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,E=x.findIndex(b=>b===h.match.path.node);return E===-1?q(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(x.splice(o==="before"?E:E+1,0,d),f(we(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"})))}import*as mg from"@babel/parser";import{cloneNode as LR}from"@babel/types";function Ws(e){let{source:t,locator:n,expression:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=Je(t,"jsx-node");if(!a.ok)return a.result;let c=DR(t,r);if(!c.ok)return c.result;let l=Ee(a.ast,n);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return q(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 q(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=l.match.path,d=null;if(i){let x=Ee(a.ast,i);if(!x.ok)return{ok:!1,source:t,diagnostic:x.diagnostic};let E=rr(l.match.path,x.match.path);if(!E)return q(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=E,d=x.match.path.node}else if(o==="before"||o==="after")return q(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let p=LR(c.node,!0),m=u.node.children,f={...s,targetParentLocator:n},h=x=>s?Gt(x,a.ast,p,f):x;if(o==="append")return m.push(p),h(we(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return m.unshift(p),h(we(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));let y=m.findIndex(x=>x===d);return y===-1?q(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(m.splice(o==="before"?y:y+1,0,p),h(we(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"})))}function DR(e,t){try{let r=mg.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:q(e,"unsupported-syntax","Expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:q(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}import{cloneNode as MR,nullLiteral as tu}from"@babel/types";import*as or from"@babel/types";import*as gg from"@babel/types";function di(e,t){let n=e.parentPath;if(!n?.isConditionalExpression()||e.key!=="consequent"||!gg.isNullLiteral(n.node.alternate))return e;let r=n.parentPath;return!r?.isJSXExpressionContainer()||r.parentPath?.node!==t.node||r.listKey!=="children"?e:r}function Vr(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=Je(t,"jsx-node");if(!a.ok)return a.result;let c=Ee(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};let l=Ee(a.ast,r);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return q(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 q(t,"self-closing-element","Cannot move child into self-closing element","jsx-node")}let d=null;if(i){let b=Ee(a.ast,i);if(!b.ok)return{ok:!1,source:t,diagnostic:b.diagnostic};let S=b.match.path.isJSXElement()?di(b.match.path,l.match.path):b.match.path,N=rr(l.match.path,S);if(!N)return q(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=N,d=S}else if(o==="before"||o==="after")return q(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let p=d&&typeof d.key=="number"?d.key:-1;if(d&&p===-1)return q(t,"locator-miss","Anchor node does not exist in target parent","jsx-node");let m=c.match.path.isJSXElement()?di(c.match.path,l.match.path):c.match.path,f=MR(m.node,!0);if(!or.isJSXElement(f)&&!or.isJSXExpressionContainer(f)&&!or.isJSXFragment(f)&&!or.isJSXText(f))return q(t,"unsupported-syntax","move-node source must resolve to a JSX child","jsx-node");let h=m.parentPath?.node===u.node&&typeof m.key=="number"?m.key:-1;if(d&&m.parentPath?.node===d.parentPath?.node&&m.key===d.key)return q(t,"invalid-parent-child-relation","Cannot move a node relative to itself","jsx-node");BR(m);let y=u.node.children,x={...s,sourceLocator:n,targetParentLocator:r};if(o==="append")return y.push(f),Gt(Xs(a.ast,t),a.ast,f,x);if(o==="prepend")return y.unshift(f),Gt(Xs(a.ast,t),a.ast,f,x);let E=p-(h!==-1&&h<p?1:0);return y.splice(o==="before"?E:E+1,0,f),Gt(Xs(a.ast,t),a.ast,f,x)}function BR(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(tu());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(tu());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(tu());return}e.remove()}import*as hg from"@babel/parser";import{cloneNode as jR,nullLiteral as nu}from"@babel/types";function Gs(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,repeatExpression:s,selectionContext:a}=e,c=Je(t,"jsx-node");if(!c.ok)return c.result;let l=$R(t,s);if(!l.ok)return l.result;let u=Ee(c.ast,n);if(!u.ok)return{ok:!1,source:t,diagnostic:u.diagnostic};let d=Ee(c.ast,r);if(!d.ok)return{ok:!1,source:t,diagnostic:d.diagnostic};if(!d.match.path.isJSXElement()&&!d.match.path.isJSXFragment())return q(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 q(t,"self-closing-element","Cannot move repeat child into self-closing element","jsx-node")}let p=d.match.path,m=null;if(i){let b=Ee(c.ast,i);if(!b.ok)return{ok:!1,source:t,diagnostic:b.diagnostic};let S=rr(d.match.path,b.match.path);if(!S)return q(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");p=S,m=b.match.path.node}else if(o==="before"||o==="after")return q(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");if(!u.match.path.isJSXElement())return q(t,"unsupported-syntax","move-repeat-template-child source must be a JSXElement","jsx-node");let f=p.node,h=jR(l.node,!0);VR(u.match.path);let y={...a,sourceLocator:n,targetParentLocator:r},x=f.children;if(o==="append")return x.push(h),Gt(we(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,h,y);if(o==="prepend")return x.unshift(h),Gt(we(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,h,y);let E=x.findIndex(b=>b===m);return E===-1?q(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(x.splice(o==="before"?E:E+1,0,h),Gt(we(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,h,y))}function $R(e,t){try{let r=hg.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:q(e,"unsupported-syntax","Repeat expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:q(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function VR(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(nu());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(nu());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(nu());return}e.remove()}import{SiteEditSetPropsParamsSchema as UR,classifySiteEditPropertyName as KR}from"@vcp-dev/contracts";import*as uo from"@babel/types";function Ys(e){let t=UR.safeParse({kind:"set-props",scope:"selection",changes:e.changes});if(!t.success)return q(e.source,"unsupported-syntax","Invalid typed JSX property changes","jsx-node",{issues:t.error.issues});let n=Je(e.source,"jsx-node");if(!n.ok)return n.result;let r=co(n.ast,e.locator,e.source);if(!r.ok)return r.result;for(let a of t.data.changes){let c=KR(a.name);if(c.owner!=="generic")return q(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(uo.isJSXAttribute),s=new Map;for(let a of i){let c=JR(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 q(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=ci(a.name,a.value).value;c?c.value=l:o.attributes.push(ci(a.name,a.value))}return we(n.ast,e.source,{kind:"set-props",target:"jsx-node",inverse:"set-props"})}function JR(e){return uo.isJSXIdentifier(e.name)?e.name.name:uo.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:null}import{SiteEditOperationParamsSchema as XR}from"@vcp-dev/contracts";import*as ne from"@babel/types";var yg=["prefetch","replace","scroll","locale","onNavigate"],zR=/^on(?:Click|DoubleClick|AuxClick|MouseDown|MouseUp|PointerDown|PointerUp|TouchStart|TouchEnd|KeyDown|KeyUp|ContextMenu)(?:Capture)?$/;function HR(e){let t=e;for(;t;){if(t.isJSXElement()&&t.node.openingElement.attributes.some(n=>ne.isJSXAttribute(n)&&ne.isJSXIdentifier(n.name)&&zR.test(n.name.name)))return!0;t=t.parentPath}return!1}function Zs(e){let t=Je(e.source,"jsx-node");if(!t.ok)return t.result;let n=co(t.ast,e.locator,e.source);if(!n.ok)return n.result;let r=XR.safeParse({kind:"set-link-target",scope:"selection",link:e.link,changes:e.changes});if(!r.success||r.data.kind!=="set-link-target")return $n(e.source,"Invalid typed link-target changes");let o=n.match.path,i=o.node,s=i.openingElement,a=eC(s.name);if(!a)return $n(e.source,"Unsupported JSX link tag");if(s.attributes.some(ne.isJSXSpreadAttribute))return $n(e.source,"Link elements with spread props cannot be transformed safely");let c=new Map;for(let f of s.attributes){if(!ne.isJSXAttribute(f))continue;let h=ou(f);if(!h)return $n(e.source,"Unsupported JSX attribute name");let y=c.get(h)??[];y.push(f),c.set(h,y)}if([...c.values()].some(f=>f.length>1))return $n(e.source,"Duplicate JSX attributes cannot be transformed safely");let l=c.get("href")?.[0];if(l&&!QR(l))return $n(e.source,"Dynamic link href cannot be transformed safely");let u=a==="a",d=u?null:YR(o,s.name);if(!u&&!d)return $n(e.source,"Only native anchors and imported next/link components are supported");if(e.link.kind==="none"&&HR(o))return $n(e.source,"A link with an active event handler in its JSX ancestry cannot become an inert anchor");let p=null;if(e.link.kind==="internal-route")if(d)p=a;else{let f=ZR(t.ast,o);if(!f.ok)return $n(e.source,f.reason);p=f.localName}if(d&&e.link.kind!=="internal-route"){let f=ne.jsxIdentifier("a");s.name=f,i.closingElement&&(i.closingElement.name=ne.jsxIdentifier("a")),qR(t.ast,d,o)}else p&&u&&(s.name=ne.jsxIdentifier(p),i.closingElement&&(i.closingElement.name=ne.jsxIdentifier(p)));let m=new Set;return e.link.kind==="none"?(m.add("href"),m.add("target"),m.add("rel"),yg.forEach(f=>m.add(f))):(m.add("href"),e.link.kind==="native-link"&&yg.forEach(f=>m.add(f))),s.attributes=s.attributes.filter(f=>{if(!ne.isJSXAttribute(f))return!0;let h=ou(f);return!h||!m.has(h)}),e.link.kind!=="none"&&s.attributes.push(ne.jsxAttribute(ne.jsxIdentifier("href"),ne.stringLiteral(e.link.href))),WR(s,e.changes),we(t.ast,e.source,{kind:"set-link-target",target:"jsx-node",inverse:"set-link-target"})}function WR(e,t){for(let n of t){let r=e.attributes.find(s=>ne.isJSXAttribute(s)&&ou(s)===n.name);if(n.operation==="remove"){e.attributes=e.attributes.filter(s=>s!==r);continue}let o=typeof n.value=="string"?ne.stringLiteral(n.value):ne.jsxExpressionContainer(ru(n.value)),i=ne.jsxAttribute(ne.jsxIdentifier(n.name),o);r&&ne.isJSXAttribute(r)?r.value=i.value:e.attributes.push(i)}}function ru(e){return e===null?ne.nullLiteral():typeof e=="string"?ne.stringLiteral(e):typeof e=="number"?ne.numericLiteral(e):typeof e=="boolean"?ne.booleanLiteral(e):Array.isArray(e)?ne.arrayExpression(e.map(t=>ru(t))):typeof e=="object"?ne.objectExpression(Object.entries(e).map(([t,n])=>ne.objectProperty(ne.isValidIdentifier(t)?ne.identifier(t):ne.stringLiteral(t),ru(n)))):ne.nullLiteral()}function GR(e){return ne.isImportDefaultSpecifier(e)||ne.isImportSpecifier(e)&&e.importKind!=="type"&&(ne.isIdentifier(e.imported,{name:"default"})||ne.isStringLiteral(e.imported,{value:"default"}))}function xg(e){return!e.parentPath?.isImportDeclaration()||e.parentPath.node.importKind==="type"?!1:e.isImportDefaultSpecifier()||e.isImportSpecifier()&&e.node.importKind!=="type"&&(ne.isIdentifier(e.node.imported,{name:"default"})||ne.isStringLiteral(e.node.imported,{value:"default"}))}function YR(e,t){if(!ne.isJSXIdentifier(t))return null;let n=e.scope.getBinding(t.name);if(!n||!xg(n.path))return null;let r=n.path.parentPath;return!r?.isImportDeclaration()||r.node.source.value!=="next/link"?null:t.name}function ZR(e,t){let n=e.program.body.filter(c=>ne.isImportDeclaration(c)&&c.source.value==="next/link"&&c.importKind!=="type"),r=n[0],o=n.flatMap(c=>c.specifiers).find(GR);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=ne.importDefaultSpecifier(ne.identifier(s));if(r)r.specifiers.unshift(a);else{let c=ne.importDeclaration([a],ne.stringLiteral("next/link")),l=0;for(;l<e.program.body.length&&ne.isImportDeclaration(e.program.body[l]);)l+=1;e.program.body.splice(l,0,c)}return{ok:!0,localName:s}}function qR(e,t,n){let r=n.scope.getProgramParent();r.crawl();let o=r.getBinding(t);if(!o||!xg(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 QR(e){return!e.value||ne.isStringLiteral(e.value)}function eC(e){return ne.isJSXIdentifier(e)?e.name:null}function ou(e){return ne.isJSXIdentifier(e.name)?e.name.name:null}function $n(e,t){return q(e,"unsupported-syntax",t,"jsx-node")}import*as ut from"@babel/types";import{classifySiteEditPropertyName as bg}from"@vcp-dev/contracts";function qs(e){let t=bg(e.name),n=bg(e.property);if(t.owner!=="generic"||n.owner!=="generic")return q(e.source,"unsupported-syntax","Property binding is only available for generic properties","jsx-node");if(!Eg(e.object))return q(e.source,"unsupported-syntax","Property binding object must be a single identifier","jsx-node");if(e.property.length===0)return q(e.source,"unsupported-syntax","Property binding requires a non-empty property name","jsx-node");let r=Je(e.source,"jsx-node");if(!r.ok)return r.result;let o=co(r.ast,e.locator,e.source);if(!o.ok)return o.result;let i=o.match.path.node.openingElement,s=i.attributes.filter(l=>ut.isJSXAttribute(l)&&nC(l)===e.name);if(s.length>1)return q(e.source,"unsupported-syntax",`JSX attribute '${e.name}' has multiple sources`,"jsx-node");let a=tC(e.object,e.property),c=s[0];if(c)c.value=ut.jsxExpressionContainer(a);else{let l=ci(e.name,"");l.value=ut.jsxExpressionContainer(a),i.attributes.push(l)}return we(r.ast,e.source,{kind:"set-property-binding",target:"jsx-node",inverse:"restore-property-binding"})}function tC(e,t){return Eg(t)?ut.memberExpression(ut.identifier(e),ut.identifier(t)):ut.memberExpression(ut.identifier(e),ut.stringLiteral(t),!0)}function Eg(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(e)}function nC(e){return ut.isJSXIdentifier(e.name)?e.name.name:ut.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:null}import{getBindingIdentifiers as oC,identifier as fi,importDeclaration as iC,importDefaultSpecifier as sC,importNamespaceSpecifier as aC,importSpecifier as cC,isImportDefaultSpecifier as Sg,isImportNamespaceSpecifier as vg,isImportSpecifier as Ig,stringLiteral as lC}from"@babel/types";function Zt(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(y=>!xC(y));if(o!==-1){let y=r[o],x=y&&typeof y=="object"&&"kind"in y?y.kind:void 0;return q(t,"unsupported-syntax",`Unsupported import spec kind: ${String(x)}`)}let i=gC(r);if(!i.ok)return q(t,"unsupported-syntax",i.message);let s=Je(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 E=bC(y,x);return E?[E]:[]}))),d=i.imports.filter(y=>!u.has(Pg(y)));if(d.length===0)return ai(t,t,{kind:"add-import",target:"import",inverse:"remove-import"});let p=hC(c.body),m=d.find(y=>p.has(iu(y)));if(m)return q(t,"unsupported-syntax",`Import local binding already exists: ${iu(m)}`);let f=mC(d);if(f.reduce((y,x)=>y+x.length,0)!==d.length)return q(t,"unsupported-syntax","Unsupported import specifier grouping");for(let y of f){if(!Ng(Rg(y)))return q(t,"unsupported-syntax","Unsupported import specifier combination");let x=l.find(E=>uC(E,y));if(x)dC(x,y);else{let E=iC(kg(y),lC(n));yC(c.body,E),l.push(E)}}return we(a,t,{kind:"add-import",target:"import",inverse:"remove-import"})}function uC(e,t){return e.importKind==="type"?!1:Ng(pC(fC(e),Rg(t)))}function dC(e,t){let n=!1,r=new Set(e.specifiers.map(o=>su(o)));for(let o of kg(t)){let i=su(o);r.has(i)||(e.specifiers.push(o),r.add(i),n=!0)}return _g(e.specifiers),{changed:n}}function kg(e){let t=e.map(n=>{switch(n.kind){case"named":return cC(n.local?fi(n.local):fi(n.imported),fi(n.imported));case"default":return sC(fi(n.local));case"namespace":return aC(fi(n.local));default:return n}});return _g(t),t}function Rg(e){let t=Cg();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 fC(e){let t=Cg();for(let n of e.specifiers)Sg(n)?t.defaultLocals.add(n.local.name):vg(n)?t.namespaceLocals.add(n.local.name):t.hasNamed=!0;return t}function Cg(){return{defaultLocals:new Set,hasNamed:!1,namespaceLocals:new Set}}function pC(e,t){return{defaultLocals:new Set([...e.defaultLocals,...t.defaultLocals]),hasNamed:e.hasNamed||t.hasNamed,namespaceLocals:new Set([...e.namespaceLocals,...t.namespaceLocals])}}function Ng(e){return e.defaultLocals.size>1||e.namespaceLocals.size>1?!1:!(e.hasNamed&&e.namespaceLocals.size>0)}function _g(e){let t=[...e.filter(n=>Sg(n)),...e.filter(n=>vg(n)),...e.filter(n=>Ig(n))];e.splice(0,e.length,...t)}function mC(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 gC(e){let t=new Map,n=new Map;for(let r of e){let o=Pg(r);if(t.has(o))continue;let i=iu(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 hC(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(oC(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 yC(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 xC(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 Pg(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 iu(e){return e.kind==="named"?e.local??e.imported:e.local}function bC(e,t){return e.importKind==="type"||Ig(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 fo(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(u=>!SC(u));if(o!==-1){let u=r[o],d=u&&typeof u=="object"&&"kind"in u?u.kind:void 0;return q(t,"unsupported-syntax",`Unsupported remove import spec kind: ${String(d)}`)}let i=Je(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 ai(t,t,{kind:"remove-import",target:"import",inverse:"add-import"});let l=a.body[c];return r.length===0?(a.body.splice(c,1),we(s,t,{kind:"remove-import",target:"import",inverse:"add-import"})):(l.specifiers=l.specifiers.filter(u=>!r.some(d=>EC(u,d))),l.specifiers.length===0&&a.body.splice(c,1),we(s,t,{kind:"remove-import",target:"import",inverse:"add-import"}))}function EC(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 SC(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 pi(e){let{source:t,locator:n,next:r}=e,o=na(t,n);return o.ok?(o.path.replaceWith(nr(r)),we(o.ast,t,{kind:"update-value",target:"value",inverse:"restore-value"})):o.result}function Qs(e){let{source:t,locator:n,index:r,value:o}=e,i=na(t,n);return i.ok?i.path.isArrayExpression()?i.path.node.elements.some(s=>s?.type==="SpreadElement")?q(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>i.path.node.elements.length?q(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(i.path.node.elements.splice(r,0,nr(o)),we(i.ast,t,{kind:"insert-array-element",target:"value",inverse:"remove-array-element"})):q(t,"unsupported-syntax","Array operations require array expression target","value"):i.result}function ea(e){let{source:t,locator:n,index:r}=e,o=na(t,n);return o.ok?o.path.isArrayExpression()?o.path.node.elements.some(i=>i?.type==="SpreadElement")?q(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>=o.path.node.elements.length?q(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(o.path.node.elements.splice(r,1),we(o.ast,t,{kind:"remove-array-element",target:"value",inverse:"insert-array-element"})):q(t,"unsupported-syntax","Array operations require array expression target","value"):o.result}function ta(e){let{source:t,locator:n,fromIndex:r,toIndex:o}=e,i=na(t,n);if(!i.ok)return i.result;if(!i.path.isArrayExpression())return q(t,"unsupported-syntax","Array operations require array expression target","value");if(i.path.node.elements.some(c=>c?.type==="SpreadElement"))return q(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 q(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),we(i.ast,t,{kind:"move-array-element",target:"value",inverse:"move-array-element-back"})}function na(e,t){let n=Je(e,"value");if(!n.ok)return{ok:!1,result:n.result};let r=Ee(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 gt from"@babel/types";function ra(e){let t=Je(e.source,"value");if(!t.ok)return t.result;let n=Ee(t.ast,e.objectLocator);if(!n.ok)return{ok:!1,source:e.source,diagnostic:n.diagnostic};if(!n.match.path.isObjectExpression())return q(e.source,"unsupported-syntax","Object property upsert requires an ObjectExpression parent","value");let r=n.match.path.node;if(r.properties.some(a=>gt.isSpreadElement(a)||gt.isObjectProperty(a)&&a.computed))return q(e.source,"unsupported-syntax","Object property upsert does not support spreads or computed keys","value");let o=r.properties.filter(a=>gt.isObjectProperty(a)&&vC(a.key)===e.name);if(o.length>1)return q(e.source,"unsupported-syntax",`Object property '${e.name}' has multiple sources`,"value");let i=e.value.kind==="undefined"?gt.unaryExpression("void",gt.numericLiteral(0)):nr(e.value.value),s=o[0];if(s)s.value=i,s.shorthand=!1;else{let a=gt.objectProperty(Yl(e.name),i);e.name==="__proto__"&&(a.computed=!0),r.properties.push(a)}return we(t.ast,e.source,{kind:"upsert-object-property",target:"value",inverse:"restore-object-property"})}function vC(e){return gt.isIdentifier(e)?e.name:gt.isStringLiteral(e)?e.value:gt.isNumericLiteral(e)?String(e.value):null}import{isSiteEditRuntimeContainerTag as IC,isSiteEditRuntimeVoidElementTag as kC}from"@vcp-dev/contracts/site-edit-runtime-capability";function po(e){if(!e.composition)throw new Error("Composition unavailable for render source graph.");return e.composition}function RC(e,t,n){let r=po(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(S=>({kind:S.kind,message:S.reason})),a=i.isOpaque,l=o.parentKey===null&&i.componentName==="Page",u=i.tag.toLowerCase(),d=i.tag!==u,p=!d&&kC(u),m=d||IC(u),f=d&&i.childKeys.length>0&&!i.isPublicUiComponent,h=i.textSegments.length>0&&i.textSegments.some(S=>S.editable);p&&!s.some(S=>S.kind==="void-element")&&s.push({kind:"void-element",message:`Element '${i.tag}' is void: children cannot be inserted`}),!p&&!m&&!s.some(S=>S.kind==="void-element")&&s.push({kind:"void-element",message:`Element '${i.tag}' cannot contain structured children`});let y=h&&(!a||i.importedFrom==="next/link"),x=!i.isPublicUiComponent&&!p&&m&&(!a||f);return{composition:r,key:e,canUpdateText:y,canInsertChild:x,canMove:!l,canRemove:!l,constraints:s}}function oa(e,t){let n=new Map;for(let r of e.nodes.keys())n.set(r,RC(r,e,t));return n}function au(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:ve(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Key not found: ${e.key}`}]};let n=CC(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:ve(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Unable to locate JSX element for key ${t.identity.key}`}]};let r=n.openingElement,o=r.attributes.find(c=>c.type==="JSXAttribute"&&c.name.type==="JSXIdentifier"&&c.name.name==="className"),i={key:e.key,composition:e.route.composition,filePath:t.sourceFile,componentName:t.componentName,openingElementRange:Tg(r),version:{documentVersion:e.route.graph.version,contentHash:ve(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";return{...i,sourceKind:a,attrRaw:Ag(e.route.source,o),valueRaw:s?Ag(e.route.source,s):null,attrRange:Tg(o),diagnostics:[]}}function wg(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 CC(e,t){let n=bn({source:e,profile:Or({filePath:t.sourceFile,source:e})});if(!n.ok)return null;let r=Ee(n.ast,{kind:"jsx-node",strategy:"structural-path",file:t.identity.file,component:t.identity.component,structuralPath:t.identity.structuralPath,expectedRange:NC(t.sourceRange)});return!r.ok||r.match.node.type!=="JSXElement"?null:r.match.node}function Og(e){let t=bn({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 Ag(e,t){return t.start==null||t.end==null?"":e.slice(t.start,t.end)}function Tg(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 NC(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function Fg(){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 _C}from"node:crypto";import ia from"node:fs/promises";import cu from"node:path";import{setTimeout as PC}from"node:timers/promises";var AC={async mkdir(e,t){await ia.mkdir(e,t)},async writeFile(e,t,n){await ia.writeFile(e,t,n)},async rename(e,t){await ia.rename(e,t)},async rm(e,t){await ia.rm(e,t)}},TC=new Set(["EACCES","EBUSY","EPERM"]),wC=[10,20,40,80,160];async function OC(e,t,n){for(let r of wC)try{await e.rename(t,n);return}catch(o){if(!FC(o))throw o;await PC(r)}await e.rename(t,n)}function FC(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&TC.has(e.code)}async function sa(e,t,n=AC){let r=cu.dirname(e),o=cu.basename(e),i=cu.join(r,`.${o}.${process.pid}.${_C()}.tmp`),s=!1;try{await n.mkdir(r,{recursive:!0}),await n.writeFile(i,t,"utf8"),await OC(n,i,e),s=!0}finally{if(!s)try{await n.rm(i,{force:!0})}catch{}}}import lu from"@babel/traverse";import*as C from"@babel/types";import*as Pe from"@babel/types";function In(e,t={}){if(Pe.isTSAsExpression(e)||Pe.isTSSatisfiesExpression(e)||Pe.isTSNonNullExpression(e)||Pe.isTypeCastExpression(e)||Pe.isParenthesizedExpression(e))return In(e.expression,t);if(Pe.isStringLiteral(e))return{status:"resolved",value:e.value};if(Pe.isNumericLiteral(e))return Number.isFinite(e.value)?{status:"resolved",value:e.value}:{status:"unresolved"};if(Pe.isBooleanLiteral(e))return{status:"resolved",value:e.value};if(Pe.isNullLiteral(e))return{status:"resolved",value:null};if(Pe.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(Pe.isIdentifier(e))return e.name==="undefined"&&!t.resolveIdentifier?{status:"undefined"}:t.resolveIdentifier?.(e.name)??{status:"unresolved"};if(Pe.isUnaryExpression(e)&&e.operator==="void"&&Pe.isNumericLiteral(e.argument)&&e.argument.value===0)return{status:"undefined"};if(Pe.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||Pe.isSpreadElement(r))return{status:"unresolved"};let o=In(r,t);if(o.status!=="resolved")return{status:"unresolved"};n.push(o.value)}return{status:"resolved",value:n}}if(Pe.isObjectExpression(e)){let n=Object.create(null);for(let r of e.properties){if(!Pe.isObjectProperty(r)||r.computed||!Pe.isExpression(r.value))return{status:"unresolved"};let o=LC(r.key);if(o===null)return{status:"unresolved"};let i=In(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 Pe.isMemberExpression(e)||Pe.isOptionalMemberExpression(e)?t.resolveMember?.(e)??{status:"unresolved"}:{status:"unresolved"}}function LC(e){return Pe.isIdentifier(e)?e.name:Pe.isStringLiteral(e)?e.value:Pe.isNumericLiteral(e)?String(e.value):null}var DC=typeof lu=="function"?lu:lu.default;function vt(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 MC(e){return/^[A-Z]/.test(e)}function mu(e){let t=e.openingElement;return C.isJSXIdentifier(t.name)?t.name.name==="Fragment":C.isJSXMemberExpression(t.name)?t.name.property.name==="Fragment":!1}function go(e){return C.isJSXFragment(e)}function Dg(e){return C.isJSXIdentifier(e.name)?e.name.name:C.isJSXMemberExpression(e.name)?Mg(e.name):C.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:"unknown"}function Mg(e){return C.isJSXIdentifier(e.object)?`${e.object.name}.${e.property.name}`:C.isJSXMemberExpression(e.object)?`${Mg(e.object)}.${e.property.name}`:e.property.name}function BC(e){return e.split(".")[0]??e}function jC(e){let t=e;for(;t;){let n=t.node;if(C.isFunctionDeclaration(n)&&n.id||C.isVariableDeclarator(n)&&C.isIdentifier(n.id))return n.id.name;if(C.isExportDefaultDeclaration(n)){let r=n.declaration;if(C.isFunctionDeclaration(r)&&r.id)return r.id.name;if(C.isFunctionDeclaration(r)&&!r.id)return"default"}t=t.parentPath}return null}function $C(){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 VC(e){let t=new Map;for(let n of e.program.body){if(!C.isImportDeclaration(n))continue;let r=n.source.value;for(let o of n.specifiers)if(C.isImportDefaultSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"default"});else if(C.isImportNamespaceSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"*"});else if(C.isImportSpecifier(o)){let i=C.isIdentifier(o.imported)?o.imported.name:o.imported.value;t.set(o.local.name,{specifier:r,exportName:i})}}return t}function Vn(e,t=[]){if(C.isIdentifier(e))return t.push(e.name),t;if(C.isObjectPattern(e)){for(let n of e.properties)C.isObjectProperty(n)?Vn(n.value,t):C.isRestElement(n)&&Vn(n.argument,t);return t}if(C.isArrayPattern(e)){for(let n of e.elements)n&&(C.isRestElement(n)?Vn(n.argument,t):Vn(n,t));return t}return C.isAssignmentPattern(e)?(Vn(e.left,t),t):(C.isRestElement(e)&&Vn(e.argument,t),t)}function an(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function mi(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 UC(e,t,n){e.set(t,{resolved:!0,value:n})}function gu(e,t){e.set(t,{resolved:!1})}function Bg(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 at(e,t,n){if(C.isTSAsExpression(e)||C.isTSSatisfiesExpression(e)||C.isTSNonNullExpression(e)||C.isTypeCastExpression(e)||C.isParenthesizedExpression(e))return at(e.expression,t,n);if(C.isLogicalExpression(e))return aa([at(e.left,t,n),at(e.right,t,n)]);if(C.isBinaryExpression(e))return aa([C.isExpression(e.left)?at(e.left,t,n):null,C.isExpression(e.right)?at(e.right,t,n):null]);if(C.isConditionalExpression(e))return aa([at(e.consequent,t,n),at(e.alternate,t,n)]);if(C.isTemplateLiteral(e))return aa(e.expressions.filter(C.isExpression).map(i=>at(i,t,n)));if(C.isIdentifier(e))return{kind:"identifier",expression:e.name,base:e.name,path:[]};if(!C.isMemberExpression(e)&&!C.isOptionalMemberExpression(e))return null;let r=[],o=e;for(;C.isMemberExpression(o)||C.isOptionalMemberExpression(o);){if(o.computed)if(C.isNumericLiteral(o.property))r.unshift({kind:"index",index:o.property.value});else if(C.isStringLiteral(o.property))r.unshift({kind:"property",name:o.property.value});else if(n&&C.isExpression(o.property)){let i=ir(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(!C.isIdentifier(o.property))return null;r.unshift({kind:"property",name:o.property.name})}o=o.object}return C.isIdentifier(o)?{kind:r.some(i=>i.kind==="index")?"index-expression":"member-expression",expression:an(e,t),base:o.name,path:r}:null}function aa(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 hu(e,t,n){if(C.isArrayExpression(e)){let r=e.elements[0];return e.elements.length===1&&C.isExpression(r)?at(r,t,n):null}return C.isCallExpression(e)&&C.isMemberExpression(e.callee)&&!e.callee.computed&&C.isIdentifier(e.callee.property)&&["filter","slice","sort","toSorted","reverse","toReversed"].includes(e.callee.property.name)&&C.isExpression(e.callee.object)?hu(e.callee.object,t,n):at(e,t,n)}function ir(e,t){if(C.isStringLiteral(e)||C.isNumericLiteral(e)||C.isBooleanLiteral(e))return e.value;if(C.isNullLiteral(e))return null;if(C.isTemplateLiteral(e))return e.expressions.length===0&&e.quasis.length===1?e.quasis[0].value.cooked??e.quasis[0].value.raw:void 0;if(C.isIdentifier(e)){let n=mi(e.name,t.valueScopes);return n.kind==="resolved"?n.value:void 0}if(C.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||C.isSpreadElement(r))return;let o=ir(r,t);if(o===void 0)return;n.push(o)}return n}if(C.isObjectExpression(e)){let n={};for(let r of e.properties){if(!C.isObjectProperty(r)||r.computed||!C.isExpression(r.value))return;let o=null;if(C.isIdentifier(r.key)?o=r.key.name:C.isStringLiteral(r.key)&&(o=r.key.value),!o)return;let i;if(r.shorthand){if(!C.isIdentifier(r.value))return;let s=mi(r.value.name,t.valueScopes);if(s.kind!=="resolved")return;i=s.value}else i=ir(r.value,t);if(i===void 0)return;n[o]=i}return n}if(C.isMemberExpression(e)){let n=at(e,"",t);if(!n)return;let r=mi(n.base,t.valueScopes);if(r.kind!=="resolved")return;let o=Bg(r.value,n.path);return o.kind==="resolved"?o.value:void 0}if(C.isCallExpression(e))return $g(e,t)??void 0}function jg(e,t,n){let r=at(e,n,t);if(!r)return C.isMemberExpression(e)||C.isBinaryExpression(e)||C.isLogicalExpression(e)||C.isConditionalExpression(e)||C.isCallExpression(e)?{value:an(e,n),source:null}:null;let o=mi(r.base,t.valueScopes),i=r.kind==="identifier"?o:o.kind==="resolved"?Bg(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 uu(e,t,n,r,o,i){return{file:e,componentName:t,elements:n,regions:r,ordinalTracker:$C(),parentStack:[],valueScopes:i,importMap:o}}function fu(e,t,n){for(let r of e)for(let o of r.declarations){for(let s of Vn(o.id))gu(n,s);if(!C.isIdentifier(o.id)||!o.init||!C.isExpression(o.init))continue;let i=ir(o.init,t);i!==void 0&&UC(n,o.id.name,i)}}function KC(e){let t=[];for(let n of e){if(C.isVariableDeclaration(n)){t.push(n);continue}C.isExportNamedDeclaration(n)&&n.declaration&&C.isVariableDeclaration(n.declaration)&&t.push(n.declaration)}return t}function JC(e,t,n){let r=[],o=0;for(let i of e)if(C.isJSXText(i)){let s=i.value.trim();s&&r.push({index:o++,value:s,sourceRange:vt(i),editable:!0,source:null})}else if(C.isJSXExpressionContainer(i)&&C.isStringLiteral(i.expression))r.push({index:o++,value:i.expression.value,sourceRange:vt(i),editable:!0,source:null});else if(C.isJSXExpressionContainer(i)&&C.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:vt(i),editable:!0,source:null}):r.push({index:o++,value:an(s,n),sourceRange:vt(i),editable:!0,source:at(s,n,t)})}else if(C.isJSXExpressionContainer(i)&&C.isExpression(i.expression)){let s=jg(i.expression,t,n);s&&r.push({index:o++,value:s.value,sourceRange:vt(i),editable:!0,source:s.source})}return r}function XC(e,t,n){let r=[];for(let[o,i]of e.attributes.entries()){if(!C.isJSXAttribute(i))continue;let s=HC(i.name);if(!s)continue;let a=an(i,n);if(C.isStringLiteral(i.value)){r.push({name:s,value:i.value.value,sourceRange:vt(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:vt(i),source:null,syntaxKind:"boolean-shorthand",raw:a,order:o,resolution:{status:"resolved",value:!0},resolvedValue:!0});continue}if(C.isJSXExpressionContainer(i.value)&&C.isExpression(i.value.expression)){let c=ir(i.value.expression,t);if(s==="className"){let m=typeof c=="string"?c:c===void 0?$g(i.value.expression,t):null;if(m){r.push({name:s,value:m,sourceRange:vt(i),source:null,resolvedValue:m,syntaxKind:"expression",raw:a,order:o,resolution:{status:"resolved",value:m}});continue}}let l=jg(i.value.expression,t,n);if(c!==void 0){r.push({name:s,value:eN(c),sourceRange:vt(i),source:at(i.value.expression,n,t),resolvedValue:c,syntaxKind:"expression",raw:a,order:o,resolution:{status:"resolved",value:c}});continue}let u=WC(i.value.expression,t),d=at(i.value.expression,n,t),p=l?.value??an(i.value.expression,n);r.push({name:s,value:u.status==="undefined"?"undefined":p,sourceRange:vt(i),source:l?.source??d,syntaxKind:"expression",raw:a,order:o,resolution:u})}}return r}function zC(e,t,n){return e.attributes.flatMap((r,o)=>!C.isJSXSpreadAttribute(r)||!C.isExpression(r.argument)?[]:[{raw:an(r.argument,n),sourceRange:vt(r),order:o,source:at(r.argument,n,t)}])}function HC(e){return C.isJSXIdentifier(e)?e.name:C.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function WC(e,t){return In(e,{resolveIdentifier(n){let r=mi(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=ir(n,t);return r===void 0?{status:"unresolved"}:{status:"resolved",value:r}}})}function $g(e,t){let n=mo(e,t);return n&&n.map(o=>o.trim()).filter(Boolean).join(" ")||null}function mo(e,t){if(C.isStringLiteral(e))return[e.value];if(C.isTemplateLiteral(e))return e.expressions.length>0?null:[e.quasis.map(n=>n.value.cooked??"").join("")];if(C.isNullLiteral(e))return[];if(C.isBooleanLiteral(e))return e.value?null:[];if(C.isIdentifier(e)||C.isMemberExpression(e)){if(C.isIdentifier(e)&&e.name==="undefined")return[];let n=ir(e,t);return typeof n=="string"?[n]:null}if(C.isConditionalExpression(e)){let n=mo(e.consequent,t),r=mo(e.alternate,t);return!n||!r?null:[...n,...r]}if(C.isLogicalExpression(e)){if(e.operator!=="&&")return null;let n=ir(e.left,t);return n===!1||n===null?[]:mo(e.right,t)}if(C.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||C.isSpreadElement(r))return null;let o=mo(r,t);if(!o)return null;n.push(...o)}return n}if(C.isObjectExpression(e)){let n=[];for(let r of e.properties){if(!C.isObjectProperty(r))return null;let o=YC(r.key);if(!o)return null;n.push(o)}return n}if(C.isCallExpression(e)){let n=GC(e.callee);if(!n||!["cn","clsx","twMerge"].includes(n))return null;let r=[];for(let o of e.arguments){if(!C.isExpression(o))return null;let i=mo(o,t);if(!i)return null;r.push(...i)}return r}return null}function GC(e){return C.isIdentifier(e)?e.name:C.isMemberExpression(e)&&C.isIdentifier(e.property)?e.property.name:null}function YC(e){return C.isIdentifier(e)?e.name:C.isStringLiteral(e)?e.value:null}function ZC(e,t){let n=e.attributes.find(r=>C.isJSXAttribute(r)&&C.isJSXIdentifier(r.name)&&r.name.name===t);return!n||!C.isJSXAttribute(n)||!C.isJSXExpressionContainer(n.value)?null:n.value.expression}function qC(e,t){for(let n of t){let r=ZC(e,n);if(r)return r}return null}function QC(e){return C.isJSXIdentifier(e.name)?e.name.name:null}function eN(e){return e===null?"null":typeof e=="boolean"?e?"true":"false":JSON.stringify(e)}function tN(e){if(!C.isCallExpression(e)&&!C.isOptionalCallExpression(e))return null;let t=e.callee;return!C.isMemberExpression(t)&&!C.isOptionalMemberExpression(t)||!C.isIdentifier(t.property)||t.property.name!=="map"||t.computed||!C.isExpression(t.object)?null:{call:e,collection:t.object,callback:e.arguments[0]}}function du(e){return C.isArrowFunctionExpression(e)||C.isFunctionExpression(e)}function nN(e){return e==="render"||e==="itemRender"||e==="rowRender"||e==="children"}function rN(e){return e==="empty"||e==="emptyRender"||e==="loading"||e==="loadingRender"||e==="error"||e==="errorRender"||e==="fallback"||e==="headerRender"||e==="footerRender"}function Lg(e,t,n,r){if(!e||!C.isExpression(e))return null;let o={kind:"repeat-template",collectionExpression:an(e,n),collectionSource:hu(e,n,r)};if(t){let i=t.params[0],s=t.params[1];C.isIdentifier(i)&&(o.itemParamName=i.name),C.isIdentifier(s)&&(o.indexParamName=s.name)}return o}function Un(e,t,n){if(!e)return[];if(C.isJSXElement(e)){if(mu(e))return fa(e.children,t,n);let r=ua(e,t,n);return r?[r]:[]}return go(e)?da(e,t,n):C.isParenthesizedExpression(e)?Un(e.expression,t,n):C.isExpression(e)?pa(e,t,n):[]}function ca(e,t,n){let r=new Map;for(let o of e.params)for(let i of Vn(o))gu(r,i);t.valueScopes.push(r);try{if(!C.isBlockStatement(e.body))return Un(e.body,t,n);let o=new Map;t.valueScopes.push(o);try{return Vg(e.body.body,t,n)}finally{t.valueScopes.pop()}}finally{t.valueScopes.pop()}}function Vg(e,t,n){let r=[];for(let o of e){if(C.isVariableDeclaration(o)){let i=t.valueScopes[t.valueScopes.length-1];if(i){fu([o],t,i);for(let s of o.declarations)C.isIdentifier(s.id)&&(C.isJSXElement(s.init)||C.isJSXFragment(s.init))&&r.push(...Un(s.init,t,n))}continue}r.push(...pu(o,t,n))}return r}function pu(e,t,n){if(C.isReturnStatement(e))return e.argument?Un(e.argument,t,n):[];if(C.isBlockStatement(e))return Ur(e.body,t,n);if(C.isIfStatement(e)){let r=C.isBlockStatement(e.consequent)?Ur(e.consequent.body,t,n):pu(e.consequent,t,n),o=e.alternate?C.isBlockStatement(e.alternate)?Ur(e.alternate.body,t,n):pu(e.alternate,t,n):[];return[...r,...o]}if(C.isSwitchStatement(e))return Ur(e.cases.flatMap(r=>r.consequent),t,n);if(C.isTryStatement(e)){let r=Ur(e.block.body,t,n);return e.handler&&r.push(...Ur(e.handler.body.body,t,n)),e.finalizer&&r.push(...Ur(e.finalizer.body,t,n)),r}return[]}function Ur(e,t,n){let r=new Map;t.valueScopes.push(r);try{return Vg(e,t,n)}finally{t.valueScopes.pop()}}function la(e,t,n,r,o,i){o.length!==0&&e.regions.push({kind:t,ownerKey:n,childKeys:o,sourceRange:vt(r),sourceCandidates:i&&i.length>0?i:void 0})}function oN(e,t,n,r){let o=qC(e.openingElement,["items","dataSource","data"]),i={key:t,tag:Dg(e.openingElement)};n.parentStack.push(i);try{for(let s of e.openingElement.attributes){if(!C.isJSXAttribute(s))continue;let a=QC(s);if(!a||!C.isJSXExpressionContainer(s.value))continue;let c=s.value.expression;if(!C.isJSXEmptyExpression(c)){if(nN(a)&&du(c)){let l=ca(c,n,r),u=Lg(o,c,r,n);la(n,"repeat-region",t,s,l,u?[u]:void 0);continue}if(rN(a)){let l=du(c)?ca(c,n,r):Un(c,n,r);la(n,"conditional-region",t,s,l)}}}if(o)for(let s of e.children){if(!C.isJSXExpressionContainer(s)||!du(s.expression))continue;let a=ca(s.expression,n,r),c=Lg(o,s.expression,r,n);la(n,"repeat-region",t,s,a,c?[c]:void 0)}}finally{n.parentStack.pop()}}function ua(e,t,n){let r=Dg(e.openingElement);if(r==="Fragment"||mu(e))return fa(e.children,t,n),null;let o=t.parentStack[t.parentStack.length-1]??null,i=o?.key??null,s=MC(r),a;if(s){let S=t.ordinalTracker.getOrdinal(i,r);a=`component:${r}#${S}`}else{let S=t.ordinalTracker.getOrdinal(i,r);a=`${r}#${S}`}let c=o?t.elements.get(o.key)?.identity.structuralPath:void 0,l=c?`${c}/${a}`:a,u=li(t.file,t.componentName,l),d={file:t.file,component:t.componentName,structuralPath:l,key:u},p=s?"component-boundary":null,m=JC(e.children,t,n),f=XC(e.openingElement,t,n),h=zC(e.openingElement,t,n),y,x,E=!1;if(s){let S=t.importMap.get(r)??t.importMap.get(BC(r));S&&(y=S.specifier,x=S.exportName,E=Fr(S.specifier,t.file))}let b={identity:d,tag:r,componentName:t.componentName,sourceFile:t.file,sourceRange:vt(e),parentKey:i,childKeys:[],textSegments:m,attributes:f.length>0?f:void 0,attributeSpreads:h.length>0?h:void 0,boundaryKind:p,isOpaque:s,...E?{isPublicUiComponent:!0}:{},importedFrom:y,exportName:x};return t.elements.set(u,b),i&&t.elements.has(i)&&t.elements.get(i).childKeys.push(u),oN(e,u,t,n),(!s||e.children.length>0)&&(t.parentStack.push({key:u,tag:r}),iN(e.children,t,n),t.parentStack.pop()),u}function da(e,t,n){return fa(e.children,t,n)}function fa(e,t,n){let r=[];for(let o of e)if(C.isJSXElement(o))if(mu(o))r.push(...fa(o.children,t,n));else{let i=ua(o,t,n);i&&r.push(i)}else go(o)?r.push(...da(o,t,n)):C.isJSXExpressionContainer(o)&&r.push(...pa(o.expression,t,n));return r}function iN(e,t,n){for(let r of e)C.isJSXElement(r)?ua(r,t,n):go(r)?da(r,t,n):C.isJSXExpressionContainer(r)&&pa(r.expression,t,n)}function sN(e){return e==="&&"||e==="||"||e==="??"}function pa(e,t,n){if(C.isJSXEmptyExpression(e))return[];let r=tN(e);if(r){let o=r.call,i=t.parentStack[t.parentStack.length-1]??null,s=[],a=r.callback,c={kind:"repeat-template",collectionExpression:an(r.collection,n),collectionSource:hu(r.collection,n,t)};if(C.isArrowFunctionExpression(a)||C.isFunctionExpression(a)){let u=a.params[0],d=a.params[1];C.isIdentifier(u)&&(c.itemParamName=u.name),C.isIdentifier(d)&&(c.indexParamName=d.name)}s.push(c);let l={kind:"repeat-region",ownerKey:i?.key??"",childKeys:[],sourceRange:vt(o),sourceCandidates:s.length>0?s:void 0};return t.regions.push(l),(C.isArrowFunctionExpression(a)||C.isFunctionExpression(a))&&l.childKeys.push(...ca(a,t,n)),l.childKeys}if(C.isConditionalExpression(e)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:an(e.test,n),conditionSource:at(e.test,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:vt(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...Un(e.consequent,t,n)),s.childKeys.push(...Un(e.alternate,t,n)),s.childKeys}if(C.isLogicalExpression(e)&&sN(e.operator)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:an(e.left,n),conditionSource:at(e.left,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:vt(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...Un(e.right,t,n)),s.childKeys}if(C.isParenthesizedExpression(e))return pa(e.expression,t,n);if(C.isJSXElement(e)){let o=ua(e,t,n);return o?[o]:[]}return go(e)?da(e,t,n):[]}function aN(e){let t=e.argument;return t&&(C.isExpression(t)||go(t))?t:null}function gi(e,t){let n=[];for(let r of e){if(C.isReturnStatement(r)){let o=aN(r);o&&n.push({argument:o,statement:r,condition:t});continue}if(C.isIfStatement(r)){let o=C.isBlockStatement(r.consequent)?r.consequent.body:[r.consequent];if(n.push(...gi(o,r.test)),r.alternate){let i=C.isBlockStatement(r.alternate)?r.alternate.body:[r.alternate];n.push(...gi(i,r.test))}continue}if(C.isSwitchStatement(r))for(let o of r.cases){let i=o.test?C.binaryExpression("===",r.discriminant,o.test):r.discriminant;n.push(...gi(o.consequent,i))}}return n}function ma(e){return{routeId:e,rootKeys:[],elements:new Map,regions:[],fileIndex:new Map,version:1,diagnostics:[]}}function Ug(e){let{file:t,source:n,ast:r}=e,o=e.imports.map(p=>p.specifier);if(!C.traverseFast(r,p=>{if(C.isJSXElement(p)||C.isJSXFragment(p))return C.traverseFast.stop}))return{graph:ma(t),localImports:o};let s=new Map,a=[],c=[],l=new Map,u=VC(r);DC(r,{"FunctionDeclaration|FunctionExpression|ArrowFunctionExpression"(p){let m=jC(p);if(!m)return;let f=p.node,h=[];if(C.isArrowFunctionExpression(f))C.isExpression(f.body)||go(f.body)?h=[{argument:f.body,statement:C.returnStatement(C.isExpression(f.body)?f.body:null)}]:C.isBlockStatement(f.body)&&(h=gi(f.body.body));else{let N=f.body;C.isBlockStatement(N)&&(h=gi(N.body))}if(h.length===0){p.skip();return}let y=new Map;fu(KC(r.program.body),uu(t,m,s,a,u,[y]),y);let x=new Map;for(let N of f.params)for(let P of Vn(N))gu(x,P);let E=C.isBlockStatement(f.body)?f.body.body:[],b=h[0]?.statement??null;for(let N of E){if(b&&N===b)break;C.isVariableDeclaration(N)&&fu([N],uu(t,m,s,a,u,[y,x]),x)}let S=uu(t,m,s,a,u,[y,x]);for(let N of h){let P=Un(N.argument,S,n);for(let R of P)c.includes(R)||c.push(R);if(N.condition){let R={kind:"conditional-branch",conditionExpression:an(N.condition,n),conditionSource:at(N.condition,n,S)};la(S,"conditional-region","",N.statement,P,[R])}}p.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 yu(e,t,n,r){return[...e.map(o=>({...o})),{fromFile:t,specifier:n,targetPath:r}]}function ga(e,t,n){return{...e,details:{...e.details??{},entryFile:t,importStack:n.map(r=>({...r}))}}}async function Kg(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 ha(e,t,n,r,o={}){let i=o.maxDepth??10,s=o.version??1,a=o.parseModule??Ue,c=new Map,l=new Map,u=new Map,d=[],p=new Set,m=x=>{let E=`${x.path}\0${x.code}\0${x.message}\0${JSON.stringify(x.details??{})}`;p.has(E)||(p.add(E),d.push(x))},f=[{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:[]}))],h=new Set;for(;f.length>0;){let x=f.shift(),{file:E,source:b,depth:S,diagnosticEntryFile:N,importStack:P}=x;if(h.has(E))continue;h.add(E),c.set(E,b);let R=o.validationOnly&&S<i?o.validatedImports?.(E,b):void 0,A,T;if(R)A=ma(E),T=R;else{let U=a(E,b);if(!U.ok){m(ga(U.diagnostic,N,P));continue}u.set(E,U.module);let H=o.validationOnly&&S<i?{graph:ma(E),localImports:U.module.imports.map(ye=>ye.specifier)}:Ug(U.module);A=H.graph,T=H.localImports}let O=[...new Set([...A.elements.values()].map(U=>U.importedFrom).filter(U=>typeof U=="string"&&mt(U)))],D=O.length?await Kg(O,U=>Ps(E,U,r)):[],V=new Map(O.map((U,H)=>[U,D[H]]));for(let U of A.elements.values())if(U.importedFrom&&mt(U.importedFrom)){let H=U.importedFrom,ye=V.get(H);ye.ok?(U.importedFrom=ye.path,Mn(ye.path)&&(U.isPublicUiComponent=!0)):Fr(H,E)||m(ga(ye.diagnostic,N,yu(P,E,H,ye.diagnostic.path)))}if(l.set(E,A),S>=i)continue;let Q=await Kg(T,async U=>{if(Im(U))return null;let H=V.get(U)??await Ps(E,U,r);if(!H.ok)return Fr(U,E)?null:{diagnostic:ga(H.diagnostic,N,yu(P,E,U,H.diagnostic.path))};let ye=H.path;if(h.has(ye)||Mn(ye))return null;let st=yu(P,E,U,ye);try{let pt=await n(ye);return{entry:{file:ye,source:pt,depth:S+1,diagnosticEntryFile:N,importStack:st}}}catch(pt){return{diagnostic:ga({path:ye,code:"import-read-failed",message:`Failed to read imported file: ${ye}`,details:{fromFile:E,specifier:U,reason:pt instanceof Error?pt.message:String(pt)}},N,st)}}});for(let U of Q)U&&"entry"in U?f.push(U.entry):U&&m(U.diagnostic)}let y=cN(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 cN(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 p=s.get(u)??[];s.set(u,[...p,...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 Jg(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 MN}from"@vcp-dev/contracts";import{createHash as lN,randomUUID as Nu}from"node:crypto";import Ze from"node:fs/promises";import qe from"node:path";var eh=new WeakMap;function ho(e){return eh.get(e)?.()??e.readIndex()}var qt=1,bu=1,uN=2,dN="index.json",fN="recovery.json",pN="transaction-journal.json",mN="document-version.json",ba={maxEntries:100,maxSessionBytes:512*1024*1024,maxEntryBytes:128*1024*1024},pe={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"},ge=class extends Error{constructor(t,n,r){super(n),this.name="FileHistoryStoreError",this.code=t,r?.cause!==void 0&&(this.cause=r.cause)}};function Kn(){return{entries:new Map,blobSizes:new Map}}function ya(e,t){let n={entries:new Map,blobs:new Map,objectBytes:0};for(let r of e)th(n,r,t);return n}function th(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 rh(e,t={}){let n=TN(e),r=LN(t.limits),o=xu(n),i=wN(n),s=await Tt(i),a=await Tt(o)||s;a||(await IN(n),await kN(n)),a||await DN(n);let c=Kn(),l=await Sa(n,c),u=new Set(a?(await Ca(n)).map(E=>E.stageId):[]);a||await Gg(n,l.entryIds,c);let d=l.digest,p=ya(l.entryIds,c),m=async E=>{let{index:b,sizeBytes:S}=await Ei(n);if(uh(b,E),b.digest!==d){let N=Kn();await ah(n,b.entryIds,N,S),p=ya(b.entryIds,N),d=b.digest}return{...Na(b),totalBytes:p.objectBytes+S}},f=async E=>{_u(E),await m(),await Hg(n,p,[E.entryId],E.blobIds,E.stageId),await Ea(n,E.stageId)},h=async(E,b)=>{let S=await m(b);ih(E,S.entryIds.length);let N=Kn();for(let P of S.entryIds.slice(Math.min(S.cursor,E)+1,Math.max(S.cursor,E)+1))await yi(n,P,N);return S},y=async()=>{if(await Tt(o)||s)throw new ge(pe.RECOVERY_PENDING,"history store requires explicit recovery before accepting writes")},x={rootDir:n,recoveryRequired:a,async readDocumentVersion(){return qg(n)},async writeDocumentVersion(E){if(await y(),!Number.isInteger(E)||E<0)throw new ge(pe.INVALID_SCHEMA,"document version must be a non-negative integer");let b=await qg(n);E<=b||await hi(mh(n),{schemaVersion:1,version:Math.max(b,E)})},async stageAppend(E,b={}){await y();let S=await yN(E,r),N={schemaVersion:bu,stageId:Nu(),entryId:S.entryId,blobIds:S.blobs.map(P=>P.digest)};try{await xN(n,S),await EN(n,N,b.durableManifest!==!1)}catch(P){try{await f(N)}catch(R){throw new ge(pe.INDEX_CORRUPT,"staged history cleanup failed after preparation error",{cause:R})}throw P}return{stageId:N.stageId,entryId:N.entryId,blobIds:N.blobIds}},async discardStage(E){await y(),vu(E);let b=await Eu(n,E);b&&await f(b)},async previewStagedAppend(E,b){await y();let S=await m(b);return(await Xg(n,r,E,S,p)).transition},async previewCursor(E,b){await y();let S=await h(E,b);return oh(S,S.entryIds,E)},async publishStagedAppend(E,b,S){if(await y(),Ia(E,"entryId"),S){vu(S);let T=await Eu(n,S);if(!T||T.entryId!==E)throw new ge(pe.INVALID_SCHEMA,"history stage does not match the published entry")}let N=await m(b),P=p,R=await Xg(n,r,E,N,P),A=await Zg({rootDir:n,previousDigest:R.current.digest,entryIds:R.entryIds,cursor:R.cursor,readback:async()=>Yg(n,R.usage),afterWrite:async()=>{S?await Ea(n,S):await vN(n,E),await Hg(n,R.usage,[...P.entries.keys()].filter(T=>!R.usage.entries.has(T)),[...P.blobs.keys()].filter(T=>!R.usage.blobs.has(T)))}});return p=R.usage,d=A.digest,A},async append(E){await y();let b=await m(),S=await x.stageAppend(E);try{return await x.publishStagedAppend(S.entryId,b.digest,S.stageId)}catch(N){throw await x.discardStage(S.stageId),N}},async readEntry(E){return Ia(E,"entryId"),yi(n,E)},async readBlob(E){Ia(E,"blobId");let b=await hh(n,E),S=await xi(b,pe.NOT_FOUND,"blob");return ph(S,E,b),S},async readIndex(){let E=Kn(),b=await Sa(n,E);return p=ya(b.entryIds,E),d=b.digest,b},async readStatus(){let E=await va(n);return{canUndo:E.undoIds.length>0,canRedo:E.redoIds.length>0,undoDepth:E.undoIds.length,redoDepth:E.redoIds.length,cursor:E.cursor,recoveryRequired:await Tt(o)||await Tt(i)}},async readUndoRedoIds(){let E=await va(n);return{undoIds:E.undoIds,redoIds:E.redoIds,currentId:E.currentId}},async setCursor(E,b){await y();let S=await h(E,b),N=await Zg({rootDir:n,previousDigest:S.digest,entryIds:S.entryIds,cursor:E,readback:async()=>Yg(n,p)});return d=N.digest,N},async markRecoveryRequired(E){await Tt(o)||await hi(xu(n),{schemaVersion:qt,reason:ON(E),createdAt:new Date().toISOString()})},async clearRecoveryRequired(){await Ze.rm(xu(n),{force:!0})},async readTransactionJournal(){return await Tt(i)?xa(i):null},async writeTransactionJournal(E){await y(),gh(E);try{await hi(i,E)}catch(S){let N=await xa(i).catch(()=>null);if(N&&Buffer.from(wt(N)).equals(Buffer.from(wt(E))))return;throw N?new ge(pe.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous",{cause:S}):S}let b=await xa(i);if(!Buffer.from(wt(b)).equals(Buffer.from(wt(E))))throw new ge(pe.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous")},async clearTransactionJournal(E){let b=await Tt(i)?await xa(i):null;if(b&&b.transactionId!==E)throw new ge(pe.INVALID_SCHEMA,"transaction journal changed concurrently");try{await Ze.rm(i,{force:!0})}catch(S){if(!await Tt(i))return;throw S}if(await Tt(i))throw new ge(pe.INDEX_CORRUPT,"transaction journal clear outcome is ambiguous");s=!1},async cleanupTmp(){await y();for(let S of u)await Ea(n,S),u.delete(S);await RN(n);let E=Kn(),b=await Sa(n,E);await Gg(n,b.entryIds,E),p=ya(b.entryIds,E),d=b.digest}};return eh.set(x,()=>va(n)),x}async function Xg(e,t,n,r,o){Ia(n,"entryId");let i=Kn(),s=await yi(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);th(a,s.id,i),c.push(s.id);let l=bN(c,t,a);return{current:r,entryIds:l.entryIds,cursor:l.cursor,usage:a,transition:oh(r,l.entryIds,l.cursor)}}function oh(e,t,n){return ih(n,t.length),{expectedIndexDigest:e.digest,publishedIndexDigest:gN(t,n),publishedCursor:n,publishedCurrentId:t[n]??null}}function gN(e,t){return sr(wt({schemaVersion:qt,entryIds:e,cursor:t}))}function ih(e,t){if(!Number.isInteger(e)||e<-1||e>=t)throw new ge(pe.INVALID_SCHEMA,`history cursor is out of bounds: ${e}`)}function hN(e){if(!cn(e))return!1;let t=e.publishedCursor,n=e.publishedCurrentId;return!Mt(e.expectedIndexDigest)||!Mt(e.publishedIndexDigest)||!Number.isInteger(t)||t<-1||n!==null&&!Mt(n)?!1:t===-1?n===null:Mt(n)}async function yN(e,t){if(!e.kind.trim())throw new ge(pe.INVALID_JSON,"history entry kind must not be empty");let n=[],r=[];for(let c of e.blobs??[]){if(!c.name.trim())throw new ge(pe.INVALID_JSON,"history blob name must not be empty");let l=AN(c.data),u=sr(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:qt,kind:e.kind,manifest:e.manifest,blobs:r},i=wt({...o}),s=sr(i),a=i.byteLength+n.reduce((c,l)=>c+l.sizeBytes,0);if(a>t.maxEntryBytes)throw new ge(pe.CAPACITY_EXCEEDED,`history entry exceeds maxEntryBytes (${a} > ${t.maxEntryBytes})`);return{entryBody:o,entryId:s,blobs:n}}async function xN(e,t){let n=wu(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=>zg(Ou(e,c.digest),c.bytes,{kind:"blob",digest:c.digest},Lu(e,c.digest))),zg(n,wt(r),{kind:"entry",digest:t.entryId},Fu(e,t.entryId))],a=(await Promise.allSettled(i)).find(c=>c.status==="rejected");if(a)throw a.reason}async function zg(e,t,n,r){let o=await Ru(e)??(r?await Ru(r):null);if(o!==null){if(Buffer.compare(o,t)!==0)throw new ge(n.kind==="blob"?pe.BLOB_CORRUPT:pe.ENTRY_CORRUPT,`${n.kind} content mismatch for ${n.digest}`);return}await dh(e,t)}function bN(e,t,n){let r=[...e],o=r.length-1;for(;;){if(n.objectBytes+wt(lh(r,o)).byteLength<=t.maxSessionBytes&&r.length<=t.maxEntries)return{entryIds:r,cursor:o};if(o<=0||r.length===0)throw new ge(pe.CAPACITY_EXCEEDED,"history store exceeds capacity limits and the current entry cannot be trimmed");nh(n,r.shift()),o-=1}}async function EN(e,t,n){_u(t);let r=Tu(e,t.stageId);if(n){await hi(r,t);return}await PN(r,t)}async function Eu(e,t){let n=await Ru(Tu(e,t));if(n===null)return null;let r=Si(Buffer.from(n).toString("utf8"),`history stage ${t}`),o=_u(r);if(o.stageId!==t)throw new ge(pe.INVALID_SCHEMA,`history stage id mismatch: ${t}`);return o}async function Ca(e){let t=[];for(let n of await Ra(Au(e))){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);vu(r);let o=await Eu(e,r);o&&t.push(o)}return t}async function Hg(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 Ca(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 Wg(wu(e,a),Fu(e,a));for(let a of new Set(r))!t.blobs.has(a)&&!s.has(a)&&await Wg(Ou(e,a),Lu(e,a));await Cu(vi(e)),await Cu(Ii(e))}async function Ea(e,t){await Su(Tu(e,t)),await SN(e)}async function SN(e){try{await Ze.rmdir(Au(e))}catch(t){if(ki(t)||cn(t)&&t.code==="ENOTEMPTY")return;throw t}}async function vN(e,t){for(let n of await Ca(e))n.entryId===t&&await Ea(e,n.stageId)}async function Su(e){if(await Ze.rm(e,{force:!0}),await Tt(e))throw new ge(pe.INDEX_CORRUPT,`unable to remove staged history object: ${e}`)}async function Wg(e,t){await Su(e),await Su(t)}function _u(e){if(!cn(e)||e.schemaVersion!==bu||typeof e.stageId!="string"||!sh(e.stageId)||!Mt(e.entryId))throw new ge(pe.INVALID_SCHEMA,"history stage schema is invalid");let t=fh(e.blobIds,"history stage blobIds");return{schemaVersion:bu,stageId:e.stageId,entryId:e.entryId,blobIds:t}}function vu(e){if(!sh(e))throw new ge(pe.INVALID_PATH,"history stageId must be a UUID")}function sh(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 Gg(e,t,n=Kn()){let r=new Set(t),o=new Set;for(let l of t){let u=await yi(e,l,n);for(let d of u.blobs)o.add(d.digest)}for(let l of await Ca(e)){r.add(l.entryId);for(let u of l.blobIds)o.add(u)}let i=vi(e),s=await Ra(i);for(let l of s){if(!l.endsWith(".json"))continue;let u=Qg(l.slice(0,-5));u&&!r.has(u)&&await ka(qe.join(i,l))}let a=Ii(e),c=await Ra(a);for(let l of c){let u=Qg(l);u&&!o.has(u)&&await ka(qe.join(a,l))}}async function Sa(e,t=Kn()){let{index:n,sizeBytes:r}=await Ei(e),{totalBytes:o}=await ah(e,n.entryIds,t,r);return{...Na(n),totalBytes:o}}async function Yg(e,t){let{index:n,sizeBytes:r}=await Ei(e);return{...Na(n),totalBytes:t.objectBytes+r}}async function Ei(e){let t=Pu(e),n=await xi(t,pe.NOT_FOUND,"index"),r=Si(Buffer.from(n).toString("utf8"),"index");return{index:CN(r),sizeBytes:n.byteLength}}async function va(e){return Na((await Ei(e)).index)}function Na(e){let t=[...e.entryIds],n=t.slice(0,e.cursor+1).reverse(),r=t.slice(e.cursor+1);return{schemaVersion:qt,digest:e.digest,entryIds:t,cursor:e.cursor,currentId:t[e.cursor]??null,undoIds:n,redoIds:r}}async function ah(e,t,n,r){let o=0,i=new Set;o+=r??(await Ei(e)).sizeBytes;for(let s of new Set(t)){let a=await yi(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 yi(e,t,n=Kn()){let r=n.entries.get(t);if(r)return r.entry;let o=await FN(e,t),i=await xi(o,pe.NOT_FOUND,"entry"),s=Si(Buffer.from(i).toString("utf8"),`entry ${t}`),a=NN(s);if(a.id!==t)throw new ge(pe.ENTRY_CORRUPT,`entry id mismatch for ${t}`);if(sr(wt({schemaVersion:a.schemaVersion,kind:a.kind,manifest:a.manifest,blobs:a.blobs}))!==t)throw new ge(pe.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 p=await hh(e,d),m=await xi(p,pe.NOT_FOUND,"blob");return ph(m,d,p),m.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),p=[],m=0,f=Array.from({length:Math.min(4,l.length)},async()=>{for(;m<l.length&&p.length===0;){let x=m++;try{d[x]=await u(l[x])}catch(E){p.push({index:x,error:E})}}}),h=await Promise.allSettled(f),y=p.sort((x,E)=>x.index-E.index)[0];if(y)throw y.error;for(let x of h)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 ch(e,t,n){await hi(Pu(e),lh(t,n))}function lh(e,t){return{schemaVersion:qt,digest:sr(wt({schemaVersion:qt,entryIds:e,cursor:t})),entryIds:e,cursor:t}}function uh(e,t){if(t!==void 0&&e.digest!==t)throw new ge(pe.INVALID_SCHEMA,`history index changed concurrently (expected ${t}, current ${e.digest})`)}async function Zg(e){uh(await va(e.rootDir),e.previousDigest);let t=sr(wt({schemaVersion:qt,entryIds:e.entryIds,cursor:e.cursor}));try{await ch(e.rootDir,e.entryIds,e.cursor),await e.afterWrite?.();let n=await e.readback();if(n.digest!==t)throw new ge(pe.INDEX_CORRUPT,"history index readback did not match the published transition");return n}catch(n){let r=await Sa(e.rootDir).catch(()=>null);if(r?.digest===t)return r;throw r?.digest===e.previousDigest?n:new ge(pe.INDEX_CORRUPT,"history index publish outcome is ambiguous",{cause:n})}}async function IN(e){await Ze.mkdir(e,{recursive:!0}),await Ze.mkdir(vi(e),{recursive:!0}),await Ze.mkdir(Ii(e),{recursive:!0}),await Ze.mkdir(bi(e),{recursive:!0})}async function kN(e){await Ze.rm(bi(e),{recursive:!0,force:!0}),await Ze.mkdir(bi(e),{recursive:!0})}async function RN(e){let t=bi(e);await Ze.mkdir(t,{recursive:!0});for(let n of await Ra(t))n!=="stages"&&await Ze.rm(qe.join(t,n),{recursive:!0,force:!0})}function CN(e){if(!cn(e))throw new ge(pe.INDEX_CORRUPT,"index.json must be an object");if(e.schemaVersion!==qt)throw new ge(pe.INVALID_SCHEMA,`unsupported index schemaVersion: ${String(e.schemaVersion)}`);let t=fh(e.entryIds,"index.entryIds"),n=e.cursor;if(!Number.isInteger(n)||n<-1||n>=t.length)throw new ge(pe.INDEX_CORRUPT,"index cursor is out of bounds");let r=n,o=e.digest;if(!Mt(o))throw new ge(pe.INDEX_CORRUPT,"index digest is invalid");let i=sr(wt({schemaVersion:qt,entryIds:t,cursor:r}));if(o!==i)throw new ge(pe.INDEX_CORRUPT,"index digest mismatch");return{schemaVersion:qt,digest:o,entryIds:t,cursor:r}}function NN(e){if(!cn(e))throw new ge(pe.ENTRY_CORRUPT,"entry must be an object");if(e.schemaVersion!==qt)throw new ge(pe.INVALID_SCHEMA,`unsupported entry schemaVersion: ${String(e.schemaVersion)}`);let t=e.id;if(!Mt(t))throw new ge(pe.ENTRY_CORRUPT,"entry id is invalid");let n=e.kind;if(typeof n!="string"||n.trim().length===0)throw new ge(pe.ENTRY_CORRUPT,"entry kind is invalid");let r=ku(e.manifest,"entry.manifest"),o=_N(e.blobs);return{id:t,schemaVersion:qt,kind:n,manifest:r,blobs:o}}function _N(e){if(!Array.isArray(e))throw new ge(pe.ENTRY_CORRUPT,"entry blobs must be an array");return e.map((t,n)=>{if(!cn(t))throw new ge(pe.ENTRY_CORRUPT,`entry blob ref ${n} must be an object`);let r=t.name;if(typeof r!="string"||r.trim().length===0)throw new ge(pe.ENTRY_CORRUPT,`entry blob ref ${n} name is invalid`);let o=t.digest;if(!Mt(o))throw new ge(pe.ENTRY_CORRUPT,`entry blob ref ${n} digest is invalid`);let i=t.sizeBytes;if(!Number.isInteger(i)||i<0)throw new ge(pe.ENTRY_CORRUPT,`entry blob ref ${n} sizeBytes is invalid`);return{name:r,digest:o,sizeBytes:i}})}async function hi(e,t){await dh(e,wt(t))}async function PN(e,t){let n=qe.dirname(e),r=qe.basename(e),o=qe.join(n,`.${r}.${process.pid}.${Nu()}.tmp`);await Ze.mkdir(n,{recursive:!0});try{await Ze.writeFile(o,wt(t),{flag:"wx"}),await Ze.rename(o,e)}finally{await ka(o)}}async function dh(e,t){let n=qe.dirname(e),r=qe.basename(e),o=qe.join(n,`.${r}.${process.pid}.${Nu()}.tmp`);await Ze.mkdir(n,{recursive:!0});try{let i=await Ze.open(o,"wx");try{await i.writeFile(t),await i.sync()}finally{await i.close()}await Ze.rename(o,e),await Cu(n)}finally{await ka(o)}}function wt(e){return Buffer.from(JSON.stringify(Iu(e)),"utf8")}function Iu(e){if(Array.isArray(e))return e.map(t=>Iu(t));if(cn(e)){let t={};for(let n of Object.keys(e).sort())t[n]=Iu(e[n]);return t}return e}function Si(e,t){try{return JSON.parse(e)}catch(n){throw new ge(pe.INVALID_JSON,`${t} is not valid JSON`,{cause:n})}}function ku(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=>ku(n,t));if(cn(e)){let n={};for(let[r,o]of Object.entries(e))n[r]=ku(o,t);return n}break}throw new ge(pe.INVALID_JSON,`${t} must be JSON-serializable`)}function fh(e,t){if(!Array.isArray(e))throw new ge(pe.INDEX_CORRUPT,`${t} must be an array`);return e.map((n,r)=>{if(!Mt(n))throw new ge(pe.INDEX_CORRUPT,`${t}[${r}] is invalid`);return n})}function Ia(e,t){if(!Mt(e))throw new ge(pe.INVALID_PATH,`${t} must be a sha256 digest`)}function Mt(e){return typeof e=="string"&&/^sha256:[a-f0-9]{64}$/u.test(e)}function sr(e){return`sha256:${lN("sha256").update(e).digest("hex")}`}function AN(e){return typeof e=="string"?Buffer.from(e,"utf8"):Buffer.from(e)}async function xi(e,t,n){try{return await Ze.readFile(e)}catch(r){throw new ge(t,`${n} not found: ${e}`,{cause:r})}}async function Ru(e){try{return await Ze.readFile(e)}catch(t){if(ki(t))return null;throw t}}function ph(e,t,n){if(sr(e)!==t)throw new ge(pe.BLOB_CORRUPT,`blob hash mismatch for ${n}`)}async function Tt(e){try{return await Ze.access(e),!0}catch(t){if(ki(t))return!1;throw t}}async function ka(e){try{await Ze.rm(e,{force:!0,recursive:!0})}catch{}}async function Cu(e){try{let t=await Ze.open(e,"r");try{await t.sync()}finally{await t.close()}}catch{}}async function Ra(e){try{return await Ze.readdir(e)}catch(t){if(ki(t))return[];throw t}}function TN(e){if(typeof e!="string"||e.trim().length===0)throw new ge(pe.INVALID_ROOT,"history store rootDir must be a non-empty string");return qe.resolve(e)}function Pu(e){return qe.join(e,dN)}function xu(e){return qe.join(e,fN)}function wN(e){return qe.join(e,pN)}function mh(e){return qe.join(e,mN)}async function qg(e){try{let t=await Ze.readFile(mh(e),"utf8"),n=Si(t,"document version");if(!cn(n)||n.schemaVersion!==1||!Number.isInteger(n.version)||n.version<0)throw new ge(pe.INVALID_SCHEMA,"document version schema is invalid");return n.version}catch(t){if(ki(t))return 0;throw t}}async function xa(e){let t=await xi(e,pe.RECOVERY_PENDING,"transaction journal"),n=Si(Buffer.from(t).toString("utf8"),"transaction journal");return gh(n),n}function gh(e){if(!cn(e)||e.schemaVersion!==uN||typeof e.transactionId!="string"||e.transactionId.length===0||typeof e.operationId!="string"||e.operationId.length===0||!["prepared","files-written","history-published"].includes(e.phase)||!hN(e.historyTransition)||!Array.isArray(e.files))throw new ge(pe.INVALID_SCHEMA,"transaction journal schema is invalid");for(let t of e.files)if(!cn(t)||typeof t.path!="string"||t.path.length===0||t.preDigest!==null&&!Mt(t.preDigest)||t.postDigest!==null&&!Mt(t.postDigest))throw new ge(pe.INVALID_SCHEMA,"transaction journal file digest is invalid")}function ON(e){return e.replace(/[\r\n]+/g," ").slice(0,512)}function vi(e){return qe.join(e,"entries")}function Ii(e){return qe.join(e,"blobs")}function bi(e){return qe.join(e,"tmp")}function Au(e){return qe.join(bi(e),"stages")}function Tu(e,t){return qe.join(Au(e),`${t}.json`)}function wu(e,t){return qe.join(vi(e),`${xh(t)}.json`)}function Ou(e,t){return qe.join(Ii(e),xh(t))}function Fu(e,t){return qe.join(vi(e),`${t}.json`)}function Lu(e,t){return qe.join(Ii(e),t)}async function FN(e,t){return yh(wu(e,t),Fu(e,t))}async function hh(e,t){return yh(Ou(e,t),Lu(e,t))}async function yh(e,t){return await Tt(e)?e:await Tt(t)?t:e}function xh(e){return e.slice(7)}function Qg(e){let t=e.startsWith("sha256:")?e:`sha256:${e}`;return Mt(t)?t:null}function cn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ki(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function LN(e){return{maxEntries:e?.maxEntries??ba.maxEntries,maxSessionBytes:e?.maxSessionBytes??ba.maxSessionBytes,maxEntryBytes:e?.maxEntryBytes??ba.maxEntryBytes}}async function DN(e){let t=Pu(e);await Tt(t)||await ch(e,[],-1)}var BN={affectedCompositions:[]};function Ih(e){let t=null,n=new WeakMap;async function r(){return t??=jN(e),t}async function o(i){if(!i)return null;let s=Du(i);return s?$N(e,s):i}return{async prepareAppend(i){let s=await ho(e),a=await e.stageAppend(Sh(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 ho(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 ho(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);bh(c,i.historyTransition),i.entry.historyId=s.entryId,Object.assign(a,yo(c))}else{if(s.cursor===void 0)throw new Error("prepared cursor is missing");let c=i.kind==="undo"?a.undo:a.redo;if(Du(c.at(-1))!==Du(i.entry))throw new Error("history state changed before publish");let l=await e.setCursor(s.cursor,s.expectedDigest);bh(l,i.historyTransition),Object.assign(a,yo(l))}n.delete(i)},async discardPrepared(i){let s=n.get(i);if(!s)return;let a=i.historyTransition;if(a){let c=await ho(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,yo(d));return}catch(d){throw s.redo.push(i),d}}let c=await e.append(Sh(i)),l=c.currentId;if(!l)throw new Error("history store did not publish an entry");i.historyId=l,Object.assign(s,yo(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,yo(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 bh(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 Du(e){return typeof e=="string"?e:e?.historyId}async function jN(e){let t=await ho(e);return yo(t)}function yo(e){return{undo:[...e.undoIds].reverse(),redo:[...e.redoIds].reverse(),entryIds:[...e.entryIds],cursor:e.cursor}}async function $N(e,t){let n=await e.readEntry(t),r=VN(n),o=r.provenance??BN;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 Eh(e,n,r.preSnapshots),postSnapshots:await Eh(e,n,r.postSnapshots)}}async function Eh(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(JN(r,o.blobName))).toString("utf8"):"";return{file:o.file,content:i,version:o.version,exists:o.exists,...o.sha256?{sha256:o.sha256}:{}}}))}function Sh(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=UN(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 VN(e){if(!Rh(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:kh(t.provenance)}:{},preSnapshots:vh(t.preSnapshots,"preSnapshots"),postSnapshots:vh(t.postSnapshots,"postSnapshots")}}function UN(e){if(e.provenance!==void 0)return kh(e.provenance);if(e.composition)return{initiatingComposition:e.composition,affectedCompositions:[]}}function kh(e){let t=MN.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 vh(e,t){return e.map((n,r)=>{if(!Rh(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&&!KN(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 KN(e){return/^sha256:[0-9a-f]{64}$/.test(e)}function JN(e,t){let n=e.get(t);if(!n)throw new Error(`durable history blob is missing: ${t}`);return n}function Rh(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{GeneratedSiteCapabilitiesSchema as XN}from"@vcp-dev/contracts";var Ch={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 Mu(){let e=XN.safeParse(Ch);return e.success?e.data:null}import{randomBytes as s_}from"node:crypto";import Pa from"node:path";import{parse as Mh}from"@babel/parser";import a_ from"@babel/traverse";import*as Bh from"@babel/types";import{COMPONENT_I18N_FILE_SUFFIX as ju,PageResourceArtifactSchema as c_,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as l_,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as u_,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as d_,parseComponentI18nResourcesJson as f_}from"@vcp-dev/contracts";var _h={colorMixPolicy:"always",includeExtendedColorFunctions:!0},Ph=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\(/i,Ah=/\b(?:bg-black|bg-white|text-white|text-black)(?:\b|\/)/g,zN=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke)-\[#(?:[0-9a-fA-F]{3,8})\](?:\/\d+)?/g,HN=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*#[0-9a-fA-F]{3,8}[^'"]*['"]/g,WN=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*rgba?\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,GN=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,YN=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,ZN=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*(?:oklch|lab|lch|hsla?)\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,qN=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*(?:oklch|lab|lch|hsla?)\([^)]+\)[^'"]*['"]/gi,QN=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*color-mix\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,e_=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*color-mix\([^'"]*['"]/gi,t_=/\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,n_=/var\(\s*--(?:_|private-|vcp-)[^)]+\)/gi,r_=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\([^)]*\)/gi;function Ri(e,t){let n=_a([...Qt(e,zN),...Qt(e,HN),...Qt(e,WN),...Qt(e,t.includeRgbBackgroundImage?GN:YN),...t.includeExtendedColorFunctions?[...Qt(e,ZN),...Qt(e,qN)]:[]]),r=_a([...Qt(e,QN),...Qt(e,e_)]).filter(o=>t.colorMixPolicy==="always"||Ph.test(o));return n.push(...r.filter(o=>!n.includes(o))),t.rejectTailwindPalette&&n.push(...Qt(e,t_).filter(o=>!n.includes(o))),t.rejectAnyRawColorLiteral&&n.push(...Qt(e,r_).filter(o=>!n.includes(o))),{hardCodedSurfaceHits:_a(Qt(e,Ah)),hardCodedSurfaceOccurrences:i_(e),rawColorHits:n,privateTokenHits:t.rejectPrivateTokens?_a(Qt(e,n_)):[]}}function Qt(e,t){return e.match(new RegExp(t.source,t.flags))??[]}var Nh=160,o_=/((?:[a-z][a-z0-9-]*(?:\[[^\]]*\])?:)+)$/;function i_(e){let t=new RegExp(Ah.source,"g"),n=[0];for(let s=0;s<e.length;s+=1)e[s]===`
|
|
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=
|
|
6
|
-
`,i.index),m=e.slice(n[d]??0,p===-1?void 0:p).trim();o.push({token:a,variant:u?.[1]??"",alpha:c?Number(c[1]):null,line:d+1,snippet:m.length>Nh?`${m.slice(0,Nh-1)}\u2026`:m})}return o}function _a(e){return[...new Set(e)]}var $u="{{$INSTANCE}}",p_=/\{\{\$PAGE_ROUTE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,m_=/\{\{\$PAGE_TITLE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,Vu="components/site/generated",g_=/\.(?:tsx?|json)$/,h_=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,y_=["react","react/","next","next/","lucide-react","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],x_=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),Bu=a_,b_=typeof Bu=="function"?Bu:Bu.default;async function Uu(e){let t=c_.safeParse(e.artifact);if(!t.success)return We("Page resource artifact failed contract validation.");let n=t.data,r=e.randomHex??(()=>s_(4).toString("hex")),o=Math.max(1,Math.min(e.maxAttempts??5,5)),i=__(r());if(!i)return We("Random instance suffix must be 8 lowercase hex chars.");let s=`${P_(n.resource_id)}-${i}`,a=new Map,c=new Map,l=[];for(let b of n.pages){let S=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/${S}/page.tsx`})}let u=[],d=new Set,p=new Set,m=new Map,f=new Map,h=[],y=new Set(n.pages.flatMap(b=>b.components.map(S=>S.component_id)));for(let b of n.components){if(!y.has(b.component_id))continue;let S=Th({materialization:b.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c});if(!S.ok)return S;for(let N of S.files){let P=Oh(N,d,u);if(P)return P}p.add(S.entry),f.set(S.entry,S.entryExport),m.set(b.component_id,S.entry)}for(let[b,S]of n.pages.entries()){let N=l[b],P=Th({materialization:S.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c,pageEntryTarget:N.route_file_path,pageTitle:N.title});if(!P.ok)return P;for(let R of P.files){let A=Oh(R,d,u);if(A)return A}p.add(P.entry),f.set(P.entry,P.entryExport),h.push({entry:P.entry,declaredComponentIds:new Set(S.components.map(R=>R.component_id))})}let x=S_(u,p,s,m,h,f);if(!x.ok)return x;for(let b of u)if(await e.exists(b.file))return!b.file.startsWith("app/")&&o>1?Uu({...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 E=v_(u);return E||(u.sort((b,S)=>b.file.localeCompare(S.file)),{ok:!0,packageInstanceId:s,pages:l,files:u})}function Th(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:wh(o.pathTemplate,e.packageInstanceId);if(!s)return We("Materialization path cannot be mapped into the package namespace.",o.pathTemplate);let a=E_(o.content,e.packageInstanceId,e.routeByPage,e.titleByPage);if(!a.ok)return a;let c=i&&e.pageTitle!==void 0?k_(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??wh(t,e.packageInstanceId);return!r||!n.some(o=>o.file===r)?We("Materialization entry must match one controlled source file.",t):{ok:!0,files:n,entry:r,entryExport:e.materialization.entry.export}}function E_(e,t,n,r){let o,i=e.replace(p_,(c,l)=>{let u=n.get(l);return u||(o=l,c)});if(o)return We(`Page route placeholder references unknown template page: ${o}`);let s=i.replace(m_,(c,l)=>{let u=r.get(l);return u?JSON.stringify(u):(o=l,c)});if(o)return We(`Page title placeholder references unknown template page: ${o}`);let a=s.replaceAll($u,t);return a.includes("{{$PAGE_ROUTE:")||a.includes("{{$PAGE_TITLE:")||a.includes("{{$INSTANCE}}")?We("Materialization contains an unresolved placeholder."):{ok:!0,data:a}}function wh(e,t){let n=`${Vu}/${t}`;if(e.split($u).length>2)return null;let o=e.replace($u,t),i=`${Vu}/${t}/`,s=o.startsWith(i)?o:`${n}/${o}`,a=Pa.posix.normalize(s);return a!==s||!a.startsWith(`${n}/`)||!g_.test(a)||h_.test(a)?null:a}function Oh(e,t,n){return t.has(e.file)?We(`Page resource materializations resolve duplicate target: ${e.file}`,e.file):(t.add(e.file),n.push(e),null)}function S_(e,t,n,r,o,i){let s=new Set(e.map(m=>m.file)),a=`${Vu}/${n}`,c=new Map(e.map(m=>[m.file,new Set])),l=new Map;for(let m of e){if(m.file.endsWith(".json")){try{JSON.parse(m.content)}catch{return We("Materialization JSON file must contain valid JSON.",m.file)}if(m.file.endsWith(ju)&&!f_(m.content).success)return We("Materialization component i18n resources are invalid.",m.file);continue}try{let h=Mh(m.content,{sourceType:"module",plugins:["jsx","typescript"]});l.set(m.file,h);for(let x of h.program.body)if((x.type==="ImportDeclaration"||x.type==="ExportAllDeclaration"||x.type==="ExportNamedDeclaration"&&x.source)&&x.source){let E=x.source.value,b=C_(m.file,E,s,a);if(!b.allowed)return We(`Materialization import is outside the controlled package: ${E}`,m.file);b.internalPath&&c.get(m.file).add(b.internalPath)}let y;if(b_(h,{Identifier(x){x.isReferencedIdentifier()&&x_.has(x.node.name)&&(y??=x.node.name,x.stop())},JSXAttribute(x){x.node.name.type==="JSXIdentifier"&&x.node.name.name==="style"&&(y??="inline style",x.stop())},JSXOpeningElement(x){x.node.name.type==="JSXIdentifier"&&x.node.name.name.toLowerCase()==="style"&&(y??="style element",x.stop())}}),y)return We(`Materialization source uses forbidden capability: ${y}`,m.file)}catch{return We("Materialization source must parse as TS/TSX.",m.file)}let f=Ri(m.content,{colorMixPolicy:"always",includeExtendedColorFunctions:!0,includeRgbBackgroundImage:!0,rejectAnyRawColorLiteral:!0,rejectPrivateTokens:!0,rejectTailwindPalette:!0});if(f.hardCodedSurfaceHits.length>0||f.rawColorHits.length>0||f.privateTokenHits.length>0)return We("Materialization source violates the public theme token policy.",m.file)}if([...t].some(m=>!s.has(m)))return We("Materialization entry is outside the controlled package.");for(let m of t)if(m.endsWith(".json"))return We("Materialization JSON files cannot be package entries.");for(let[m,f]of i){let h=l.get(m);if(!h||!I_(h,f))return We("Materialization entry does not declare its contracted export.",m)}let u=new Map([...r].map(([m,f])=>[f,m]));for(let m of o){let f=Dh(m.entry,c);for(let h of m.declaredComponentIds){let y=r.get(h);if(!y||!f.has(y))return We(`Page entry does not reach declared component: ${h}`,m.entry)}for(let h of f){let y=u.get(h);if(y&&!m.declaredComponentIds.has(y))return We(`Page entry imports undeclared component: ${y}`,m.entry)}}let d=new Set;for(let m of t)for(let f of Dh(m,c))d.add(f);if(d.size!==e.length)return We("Every materialization file must be reachable from a package entry.");let p=N_(e,l,c);return p||{ok:!0}}function v_(e){if(e.length>l_)return We("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>u_)return We("Page resource file exceeds the content byte limit.",n.file);t+=r}return t>d_?We("Page resource exceeds the aggregate content byte limit."):null}function I_(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 k_(e,t,n){let r;try{r=Mh(e,{sourceType:"module",sourceFilename:n,plugins:["jsx","typescript"]})}catch{return We("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=Fh(s.init);if(a?.type!=="ObjectExpression")return{ok:!0,data:e};let c=a.properties.find(u=>u.type==="ObjectProperty"&&!u.computed&&R_(u.key));if(!c||c.type!=="ObjectProperty")return{ok:!0,data:e};let l=Fh(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 Fh(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression"||t?.type==="TSNonNullExpression";)t=t.expression;return t&&Bh.isExpression(t)?t:null}function R_(e){return e.type==="Identifier"&&e.name==="title"||e.type==="StringLiteral"&&e.value==="title"}function C_(e,t,n,r){if(t.startsWith(`@/${r}/`)){let s=t.slice(2),a=Lh(s,n);return a?{allowed:!0,internalPath:a}:{allowed:!1}}if(!t.startsWith("."))return{allowed:y_.some(s=>s.endsWith("/")?t.startsWith(s):t===s)};if(t.includes("\\")||t.includes("\0"))return{allowed:!1};let o=Pa.posix.normalize(Pa.posix.join(Pa.posix.dirname(e),t)),i=Lh(o,n);return i&&(i.startsWith(`${r}/`)||i.startsWith("app/"))?{allowed:!0,internalPath:i}:{allowed:!1}}function Lh(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 N_(e,t,n){let r=new Set(e.map(o=>o.file));for(let o of e){if(!o.file.endsWith(ju))continue;let i=o.file.slice(0,-ju.length),s=[`${i}.tsx`,`${i}.ts`].find(u=>r.has(u));if(!s)return We("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 We("Component i18n resources must have exactly one same-name Client Component static importer.",s)}return null}function Dh(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 __(e){return/^[a-f0-9]{8}$/.test(e)?e:null}function P_(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"page-resource"}function We(e,t){return{ok:!1,code:"MATERIALIZATION_REJECTED",message:e,...t?{path:t}:{}}}import{randomBytes as $_}from"node:crypto";import Xn from"node:path";import{parse as V_}from"@babel/parser";import U_ from"@babel/traverse";import{COMPONENT_I18N_FILE_SUFFIX as Aa,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as Vh,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as K_,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as J_,SiteEditMaterializationSchema as X_,parseComponentI18nResourcesJson as z_}from"@vcp-dev/contracts";import{parse as A_}from"@babel/parser";import T_ from"@babel/traverse";import{GeneratedSiteCapabilitiesSchema as w_,FormDefinitionIdSchema as O_}from"@vcp-dev/contracts";var F_=["@/components/site/","@/lib/generated/","@/lib/cms","@/lib/cms/"],L_=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),jh=new Set(["require","module","exports","__dirname","__filename"]),Ku=T_,D_=typeof Ku=="function"?Ku:Ku.default;function Xu(e,t={}){let n=[],r=M_(t.hostCapabilities),o=Ri(e,t.style??_h),i;try{i=A_(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"&&j_(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(p=>p.code===u.code&&p.name===u.name&&p.source===u.source)||n.push(u)};return D_(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(Ju(u.node))},OptionalMemberExpression(u){l(Ju(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)&&O_.safeParse(/^@\/components\/site\/generated\/forms\/form-([^/]+)$/u.exec(u)?.[1]).success)&&!(u.startsWith("./")||u.startsWith("../"))){if(t.allowSiteOwnedImports&&F_.some(d=>d.endsWith("/")?u.startsWith(d):u===d)){c(u);return}r?B_(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||!L_.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:jh.has(u)?"commonjs-forbidden":"browser-global-forbidden",message:jh.has(u)?`Generated source cannot depend on the CommonJS global ${u}.`:`Generated source cannot depend on the restricted global ${u}.`,name:u})}}}function M_(e){if(e==null)return null;let t=w_.safeParse(e);return t.success?t.data:null}function B_(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)):$h(n)===$h(o)})}function $h(e){return e.replace(/\.(?:jsx?|tsx?|json)$/i,"")}function j_(e){return e.hardCodedSurfaceHits.length>0||e.rawColorHits.length>0||e.privateTokenHits.length>0}function Ju(e){return e.type==="Identifier"?e.name:e.type==="MemberExpression"||e.type==="OptionalMemberExpression"?Ju(e.object):null}var Hh="components/site/generated",Uh="{{$INSTANCE}}",Ta=5,H_=/^[a-z][a-z0-9-]{0,48}$/,W_=/^[a-f0-9]{8}$/,Kh=/\.tsx?$/,G_=/\.json$/,Y_=/\.(?:tsx?|json)$/,Z_=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,zu=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),Hu=U_,q_=typeof Hu=="function"?Hu:Hu.default;function Q_(e){let t=Array.isArray(e.manifest.files)?e.manifest.files:[];if(t.length>Vh)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file count exceeds the reusable limit."}};let n=mP(t);if(n)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Static prefab resolves duplicate target path: ${n}`,path:n}};let r=X_.safeParse(e.manifest);if(!r.success)return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab manifest failed schema validation."}};let o=dP(e.generatedRoot);if(!o)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Generated root must be ${Hh}.`,path:e.generatedRoot}};if(!Wh(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=Xh(r.data.files),s=Xh(e.controlledFiles);if(!gP(i,s))return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Controlled file list must exactly match the manifest file templates."}};if(i.size>Vh)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>K_)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>J_?{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 eP(e){let t=Q_(e);if(!t.ok)return t;let n=t.data.generatedRoot,r=Wh(e.manifest.instanceBaseName),o=Math.max(1,Math.min(Ta,e.maxAttempts??Ta));for(let i=0;i<o;i+=1){let s=fP(e.instanceNameGenerator?.()??$_(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=Yh(n,a),l=tP({manifest:e.manifest,generatedRoot:n,instanceName:a,instanceRoot:c,hostCapabilities:e.hostCapabilities??null,availableHostDependencies:e.availableHostDependencies});if(!l.ok)return l;if(!await rP(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 Wu(e){let t=Math.max(1,Math.min(Ta,e.maxAttempts??Ta));for(let n=0;n<t;n+=1){let r=await eP({...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 tP(e){let t=nP(e);if(t)return{ok:!1,error:t};let n=[],r=new Set;for(let s of e.manifest.files){let a=Ci({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=Ci({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=Gu({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 nP(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 rP(e,t,n){if(await e(t))return!0;for(let r of n)if(await e(r.path))return!0;return!1}function Ci(e){if(e.pathTemplate.split(Uh).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(Uh,e.instanceName),n=pP(t);return n?Yh(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||!Y_.test(n)||Z_.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 Gu(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(m=>m.path)),c=new Map,l=new Map(t.map(m=>[m.path,new Set])),u=new Map;for(let m of t){if(G_.test(m.path)){if(m.path.endsWith(Aa)){let x=z_(m.content);if(!x.success)return Jn("MATERIALIZATION_DATA_UNSUPPORTED",x.error.message,m.path);u.set(m.path,new Set)}else try{JSON.parse(m.content)}catch{return Jn("MATERIALIZATION_DATA_UNSUPPORTED","Static prefab JSON file must contain valid JSON.",m.path)}continue}let f;try{f=V_(m.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:m.path}}}let h=Xu(m.content,{hostCapabilities:o,protectedImportPrefixes:["@/components/site/generated/"],trustedManagedImports:e.trustedManagedImports,rejectInlineStyles:!e.preserveCapturedStyles,rejectStyleElements:!0,themeStyleMode:e.preserveCapturedStyles?"report":"reject",style:{colorMixPolicy:"always",includeExtendedColorFunctions:!0,includeRgbBackgroundImage:!0,rejectAnyRawColorLiteral:!0,rejectPrivateTokens:!0,rejectTailwindPalette:!0}}),y=iP(h.violations,m.path);if(y)return{ok:!1,error:y};c.set(m.path,f)}for(let m of t){if(!Kh.test(m.path))continue;let f=c.get(m.path),h=null;if(q_(f,{ImportDeclaration(y){let x=Jh({importer:m.path,source:y.node.source.value,instanceRoot:n,filePaths:a});if(!x.allowed)h??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab imports must resolve within the controlled instance or match the starter allowlist.",file:m.path},y.stop();else if(!x.internalPath&&!sP(y.node.source.value,i,s))h??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"External prefab imports must be declared and available in the target host.",file:m.path},y.stop();else if(x.internalPath&&(l.get(m.path).add(x.internalPath),x.internalPath.endsWith(Aa))){let E=cP({importer:m.path,imported:x.internalPath,source:y.node.source.value,ast:f});E.ok?u.get(x.internalPath).add(m.path):(h??=E.error,y.stop())}},ExportAllDeclaration(y){h??={code:"MATERIALIZATION_ENTRY_INVALID",message:"Static prefab files cannot use export-star declarations.",file:m.path},y.stop()},ExportNamedDeclaration(y){if(y.node.source){let x=Jh({importer:m.path,source:y.node.source.value,instanceRoot:n,filePaths:a});!x.allowed||!x.internalPath&&!e.trustedManagedImports?.includes(y.node.source.value)?(h??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab re-exports must resolve within the controlled instance.",file:m.path},y.stop()):x.internalPath&&l.get(m.path).add(x.internalPath)}},CallExpression(y){if(y.node.callee.type==="Import"){h??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab files cannot use dynamic import().",file:m.path},y.stop();return}y.node.callee.type==="Identifier"&&y.node.callee.name==="require"&&(h??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab files cannot use require().",file:m.path},y.stop())},NewExpression(y){y.node.callee.type==="Identifier"&&y.node.callee.name==="Function"&&(h??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot construct functions dynamically.",file:m.path},y.stop())},MetaProperty(y){y.node.meta.type==="Identifier"&&y.node.meta.name==="import"&&(h??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot use import.meta.",file:m.path},y.stop())},MemberExpression(y){let x=zh(y.node);x&&zu.has(x)&&(h??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${x}.`,file:m.path},y.stop())},OptionalMemberExpression(y){let x=zh(y.node);x&&zu.has(x)&&(h??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${x}.`,file:m.path},y.stop())},Identifier(y){y.isReferencedIdentifier()&&zu.has(y.node.name)&&(h??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${y.node.name}.`,file:m.path},y.stop())},JSXAttribute(y){if(y.node.name.type==="JSXIdentifier"&&y.node.name.name==="style"){if(e.preserveCapturedStyles&&oP(y.node.value))return;h??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot use inline style attributes.",file:m.path},y.stop()}},JSXOpeningElement(y){y.node.name.type==="JSXIdentifier"&&y.node.name.name.toLowerCase()==="style"&&(h??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot declare style elements.",file:m.path},y.stop())},StringLiteral(y){e.preserveCapturedStyles&&wa(y.node.value)&&(h??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Captured styles cannot load URLs or execute CSS expressions.",file:m.path},y.stop())},TemplateElement(y){e.preserveCapturedStyles&&wa(y.node.value.cooked??y.node.value.raw)&&(h??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Captured styles cannot load URLs or execute CSS expressions.",file:m.path},y.stop())},JSXElement(y){let x=y.node.openingElement.name;e.preserveCapturedStyles&&x.type==="JSXIdentifier"&&["script","iframe","object","embed"].includes(x.name.toLowerCase())&&(h??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Captured components cannot embed executable external documents.",file:m.path},y.stop())}}),h)return{ok:!1,error:h}}if(r.length===0)return Jn("MATERIALIZATION_ENTRY_INVALID","Static prefab requires at least one source entry.");let d=new Set;for(let m of r){if(d.has(m.path))return Jn("MATERIALIZATION_PATH_INVALID",`Static prefab contains duplicate source entries: ${m.path}`,m.path);if(d.add(m.path),!Kh.test(m.path))return Jn("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must be a .ts/.tsx source module.",m.path);let f=c.get(m.path);if(!f)return Jn("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must resolve to a controlled source file.",m.path);if(!lP(f,m.export))return Jn("MATERIALIZATION_EXPORT_MISSING","Static prefab entry does not declare the manifest export.",m.path)}for(let[m,f]of u)if(f.size!==1)return Jn("MATERIALIZATION_IMPORT_FORBIDDEN","Each component .i18n.json file must have exactly one same-name Client Component static importer.",m);let p=new Set;for(let m of r)for(let f of uP(m.path,l))p.add(f);return p.size!==t.length?Jn("MATERIALIZATION_ENTRY_INVALID","Every controlled source file must be reachable from the entry module.",r[0]?.path):{ok:!0}}function wa(e){return/(?:url|expression)\s*\(|@import|javascript:|-moz-binding|\\/iu.test(e)}function oP(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"||wa(n))return!1;let r=t.value;return r.type==="StringLiteral"&&!wa(r.value)||r.type==="NumericLiteral"||r.type==="NullLiteral"||r.type==="UnaryExpression"&&["-","+"].includes(r.operator)&&r.argument.type==="NumericLiteral"})}function iP(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 Jh(e){if(!e.source.startsWith("./")&&!e.source.startsWith("../"))return{allowed:!0};if(e.source.includes("\\")||e.source.includes("\0"))return{allowed:!1};let t=Xn.posix.normalize(Xn.posix.join(Xn.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 sP(e,t,n){if(n===null)return!0;let r=aP(e);return r===null||t.has(r)&&n.has(r)}function aP(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 cP(e){let t=Xn.posix.dirname(e.importer),n=Xn.posix.dirname(e.imported),r=Xn.posix.basename(e.importer).replace(/\.tsx?$/,""),o=Xn.posix.basename(e.imported).slice(0,-Aa.length),i=`./${r}${Aa}`;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 lP(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 uP(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 Jn(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{file:n}:{}}}}function dP(e){let t=Gh(e);return t===Hh?t:null}function fP(e){let t=e.trim().toLowerCase();return W_.test(t)?t:null}function Wh(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 H_.test(t)?t:null}function Gh(e){if(!e||e.startsWith("/")||e.includes("\\"))return null;let t=Xn.posix.normalize(e);return t==="."||t.startsWith("../")||t.includes("/../")||t.includes("//")?null:t}function pP(e){let t=Gh(e);return!t||t!==e?null:t}function Yh(...e){return Xn.posix.join(...e)}function Xh(e){return new Set(e.map(t=>t.pathTemplate))}function mP(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 gP(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function zh(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 vd}from"node:crypto";import gd from"@babel/traverse";function Yu(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 Oa(e){if(e.node.alternate||!hP(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 hP(e){let t=Zh(e);return e.traverse({enter(n){Zh(n)||(t=!1,n.stop())}}),t}function Zh(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 jP}from"node:crypto";import cy from"node:path";import*as Eo from"@babel/parser";import id from"@babel/traverse";import sd from"@babel/generator";import*as ce from"@babel/types";import td from"@babel/generator";import{parse as CP}from"@babel/parser";import nd from"@babel/traverse";import*as Re from"@babel/types";import{PortableInvocationBindingSchema as NP}from"@vcp-dev/contracts";import Zu from"@babel/traverse";import*as Ce from"@babel/types";var qh=typeof Zu=="function"?Zu:Zu.default;function ln(e){let t=ey(e.module,e.exportName,e.parsedModules??new Map([[e.module.file,e.module]]),new Set);return t?Qh(t,e.allowNonRenderingGuards):ar("component-export-unresolved","The requested local component export is not a statically resolvable function.",e.module.file)}function cr(e){let t=yP(e.module,e.componentName,e.callSourceRange);return t.kind==="local"?Qh(t.definition):t.kind==="imported"?!e.imported?.module&&!mt(t.specifier)?ar("component-external-module-opaque","External package components are opaque to the local source graph.",t.specifier):e.imported?e.imported.module?ln({module:e.imported.module,exportName:e.imported.exportName,parsedModules:e.imported.parsedModules}):ar("component-module-unavailable","The component source module is unavailable in the parsed graph.",e.imported.file):ar("component-local-binding-unresolved","The JSX call does not resolve to a statically declared local component function.",e.module.file):ar("component-local-binding-unresolved","The JSX call does not resolve to a statically declared local component function.",e.module.file)}function Qh(e,t=!1){let n=vP(e.module.ast,e.node);if(!n)return ar("component-function-unresolved","The component function has no source AST path.",e.module.file);let r=ty(n,t);if(!r){let s=IP(n);return s?{ok:!0,componentName:e.name,sourceFile:e.module.file,metadataOnly:!1,roots:[s[0]],returnAlternatives:s}:ar("component-control-flow-unsupported","Component roots require an expression body or one direct return.",e.module.file)}let o=[],i=ny(r);return La(r,o)?{ok:!0,componentName:e.name,sourceFile:e.module.file,metadataOnly:i,roots:o}:ar("component-root-dynamic","Component return contains an unsupported dynamic or spread root.",e.module.file)}function yP(e,t,n){let r={kind:"unresolved"};return qh(e.ast,{JSXElement(o){if(!EP(o.node.loc,n))return;let i=o.node.openingElement.name;if(!Ce.isJSXIdentifier(i)||i.name!==t)return;let s=o.scope.getBinding(t);if(!s||s.constantViolations.length>0){o.stop();return}if(xP(s.path)){let c=s.path.parentPath;c?.isImportDeclaration()&&(r={kind:"imported",specifier:c.node.source.value}),o.stop();return}let a=bP(s.path);a&&(r={kind:"local",definition:{node:a,name:t,module:e}}),o.stop()}}),r}function xP(e){return e.isImportSpecifier()||e.isImportDefaultSpecifier()||e.isImportNamespaceSpecifier()}function bP(e){if(e.isFunctionDeclaration())return e.node;if(!e.isVariableDeclarator())return null;let t=e.get("init");return!Array.isArray(t)&&ed(t.node)?t.node:null}function EP(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 ey(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 p=Qn(e.file,u,n),m=p?n.get(p):void 0;return m?ey(m,d,n,i):null},a=u=>{let d=SP(e,u);if(d)return{...d,module:e};for(let p of e.ast.program.body)if(!(!Ce.isImportDeclaration(p)||p.importKind==="type")){for(let m of p.specifiers)if(m.local.name===u){if(Ce.isImportDefaultSpecifier(m))return s(p.source.value,"default");if(Ce.isImportSpecifier(m)&&m.importKind!=="type")return s(p.source.value,Fa(m.imported))}}return null};for(let u of e.ast.program.body){if(Ce.isExportDefaultDeclaration(u)&&t==="default"){let d=u.declaration;if(ed(d))return{node:d,name:RP(d)??"default",module:e};if(Ce.isIdentifier(d))return a(d.name)}if(!(!Ce.isExportNamedDeclaration(u)||u.exportKind==="type")){if(u.declaration){let d=kP(u.declaration,t);if(d)return a(d)}for(let d of u.specifiers)if(Ce.isExportSpecifier(d)&&d.exportKind!=="type"&&Fa(d.exported)===t)return u.source?s(u.source.value,Fa(d.local)):a(Fa(d.local))}}let c=e.ast.program.body.flatMap(u=>{if(!Ce.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(p=>p.node===u.node&&p.module.file===u.module.file)===d);return l.length===1?l[0]:null}function SP(e,t){for(let n of e.ast.program.body){let r=Ce.isExportNamedDeclaration(n)?n.declaration:n;if(Ce.isFunctionDeclaration(r)&&r.id?.name===t)return{node:r,name:t};if(Ce.isVariableDeclaration(r)){for(let o of r.declarations)if(Ce.isIdentifier(o.id)&&o.id.name===t&&ed(o.init))return{node:o.init,name:t}}}return null}function vP(e,t){let n=null;return qh(e,{Function(r){r.node===t&&(n=r,r.stop())}}),n}function ty(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()||t&&i.isIfStatement()&&Oa(i))?null:o.get("argument")}function IP(e){let t=e.get("body");if(!t.isBlockStatement())return null;let n=qu(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(!Ce.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=>!Ce.isJSXText(c)||c.value.trim()!=="")||i.node.openingElement.attributes.some(c=>Ce.isJSXSpreadAttribute(c)||Ce.isJSXAttribute(c)&&Ce.isJSXIdentifier(c.name,{name:"children"}))))return null;r.push(i)}return r}function qu(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=>qu(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:qu(e.slice(t+1));return o&&s?[...o,...s]:null}return null}function La(e,t){if(ny(e))return!0;if(e.isJSXFragment()||e.isJSXElement()&&ze(e)){let n=e.get("children");for(let r of Array.isArray(n)?n:[n])if(!r.isJSXText()&&(r.isJSXSpreadChild()||!La(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()||La(n,t)}return e.isParenthesizedExpression()||e.isTSAsExpression()||e.isTSTypeAssertion()||e.isTSNonNullExpression()||e.isTypeCastExpression()?La(e.get("expression"),t):e.isNullLiteral()||e.isStringLiteral()||e.isNumericLiteral()||e.isBooleanLiteral()}function Qu(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 Ce.isJSXIdentifier(o)&&Qu(o.name)?(t=!0,!0):ze(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||!Ce.isIdentifier(o.node.property,{name:"map"})||i.length!==1)return!1;let s=i[0];if(!s.isArrowFunctionExpression()&&!s.isFunctionExpression())return!1;let a=ty(s);return a!==null&&n(a)}return!1};return n(e)&&t}function kP(e,t){return Ce.isFunctionDeclaration(e)?e.id?.name===t?t:null:Ce.isVariableDeclaration(e)&&e.declarations.some(n=>Ce.isIdentifier(n.id)&&n.id.name===t)?t:null}function ed(e){return Ce.isFunctionDeclaration(e)||Ce.isFunctionExpression(e)||Ce.isArrowFunctionExpression(e)}function RP(e){return"id"in e&&e.id&&Ce.isIdentifier(e.id)?e.id.name:null}function Fa(e){return Ce.isIdentifier(e)?e.name:e.value}function ar(e,t,n){return{ok:!1,diagnostic:{code:e,message:t,file:n}}}var rd=typeof td=="function"?td:td.default,ry=typeof nd=="function"?nd:nd.default,iy=new Set(["sourceBlockId","source_block_id","originalBlockId","original_block_id"]),_P=new Set(["sourceOrder","source_order","originalOrder","original_order"]),PP=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"]),AP=/^[A-Za-z_$][A-Za-z0-9_$]*$/u,TP=/^[A-Za-z_$][A-Za-z0-9_$]*(?:\.[A-Za-z_$][A-Za-z0-9_$]*)*$/u;function ur(e){if(!ay(e)||!Array.isArray(e.bindings))return lr("INVOCATION_INPUT_INVALID","bindings must be an array in a portable invocation.","bindings");let t=LP(e);if(!t||!TP.test(t))return lr("INVOCATION_COMPONENT_INVALID","Portable invocation requires a safe JSX component local name.","component");let n=sy(e.targetBlockId);if(!n.ok)return n;let r=DP(e.targetOrder);if(!r.ok)return r;let o=e.searchParamsIdentifier??"searchParams";if(!AP.test(o))return lr("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,p]of e.bindings.entries()){let m=NP.safeParse(p);if(!m.success)return lr("INVOCATION_VALUE_UNRESOLVED","Portable invocation values must use the closed JSON/server/identity contract.",`bindings.${d}`);let f=m.data;if(a.has(f.propName))return lr("INVOCATION_DUPLICATE_PROP",`Portable invocation contains duplicate prop ${f.propName}.`,`bindings.${d}.propName`);if(a.add(f.propName),_P.has(f.propName))return lr("INVOCATION_SOURCE_METADATA","Source block order cannot be copied or rebound as a component prop.",`bindings.${d}`);if(iy.has(f.propName)&&f.value.kind!=="target-block-id")return lr("INVOCATION_SOURCE_METADATA","Source block identity/order cannot be copied as a business prop.",`bindings.${d}`);if(f.value.kind==="target-block-id"&&(l+=1,l>1))return lr("INVOCATION_DUPLICATE_PROP","A portable invocation may bind the target block identity only once.",`bindings.${d}`);f.value.kind==="route-search-params"&&(c=!0),s.push(f),i.push(Re.jsxAttribute(Re.jsxIdentifier(f.propName),Re.jsxExpressionContainer(OP(f.value,n.value,o))))}let u=Re.jsxElement(Re.jsxOpeningElement(FP(t),i,!0),null,[],!0);return{ok:!0,plan:{kind:"portable-invocation",component:t,jsx:rd(u,{jsescOption:{minimal:!0}}).code,bindings:s,targetBlockId:n.value,targetOrder:r.value,requiresRouteSearchParams:c,searchParamsIdentifier:c?o:null}}}function wP(e){if(!ay(e)||e.jsx===void 0==(e.source===void 0))return xo("BLOCK_METADATA_INPUT_INVALID","Provide exactly one JSX expression or full source module.","input");let t=sy(e.targetBlockId);if(!t.ok)return xo("BLOCK_METADATA_TARGET_INVALID",t.error.message,"targetBlockId");if(!Number.isSafeInteger(e.targetOrder)||e.targetOrder<0)return xo("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 m=Ue("portable-entry.tsx",e.source);if(!m.ok)throw new Error(m.diagnostic.message);o=m.module,r=o.ast}else r=CP(n?e.jsx:e.source,{sourceType:"module",plugins:["jsx","typescript"]})}catch(m){return xo("BLOCK_METADATA_PARSE_FAILED",m instanceof Error?m.message:String(m),n?"jsx":"source")}let i=[],s;if(o&&e.entryExport){let m=ln({module:o,exportName:e.entryExport.kind==="default"?"default":e.entryExport.name});m.ok&&m.roots.length===1&&(s=m.roots[0],i.push(s.node))}else ry(r,{JSXElement(m){oy(m)||i.push(m.node)},JSXFragment(m){oy(m)||i.push(m.node)}});if(i.length!==1)return xo("BLOCK_METADATA_ROOT_AMBIGUOUS","Portable block metadata requires exactly one JSX root.",n?"jsx":"source");let a=i[0],c=MP(a);if(!c)return xo("BLOCK_METADATA_ROOT_AMBIGUOUS","Portable block metadata requires exactly one direct JSX element root.",n?"jsx":"source");let l=0,u=0,d=m=>{let f=BP(m.node.name);!f||!PP.has(f)||(f==="data-site-block-id"||f==="data-vcp-block-id"||iy.has(f)?l+=1:u+=1,m.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 p=n?rd(a,{jsescOption:{minimal:!0}}).code:rd(r,{jsescOption:{minimal:!0}}).code;return{ok:!0,plan:{kind:"portable-block-metadata",source:p,jsx:p,targetBlockId:t.value,targetOrder:e.targetOrder,removedSourceBlockIdCount:l,removedSourceOrderCount:u}}}function OP(e,t,n){return e.kind==="route-search-params"?Re.identifier(n):e.kind==="target-block-id"?Re.stringLiteral(t):od(e.value)}function od(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=>od(t))):Re.objectExpression(Object.entries(e).map(([t,n])=>Re.objectProperty(Re.stringLiteral(t),od(n))))}function FP(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 LP(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 sy(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 DP(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 MP(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 oy(e){let t=e.parentPath;for(;t;){if(t.isJSXElement()||t.isJSXFragment())return!0;t=t.parentPath}return!1}function BP(e){return Re.isJSXIdentifier(e)?e.name:null}function ay(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function lr(e,t,n){return{ok:!1,error:{code:e,path:n,message:t}}}function xo(e,t,n){return{ok:!1,error:{code:e,path:n,message:t}}}var cd=typeof sd=="function"?sd:sd.default,$P=typeof id=="function"?id:id.default;function Ai(e){let t=my(e);if(t)return{ok:!1,error:t};let n=e.projection,r=md(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=KP(n,o),s=QP(e);if(!s.ok)return s;let a={jsx:s.invocation?.jsx??`<${e.component.localName} />`},c=VP(e);if(i){let f=ld(e);return f.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:f.locator,sourceHash:f.sourceHash,node:a,placement:o.relation,replaceOriginal:n.container.kind==="starter-placeholder"}}}:f.result}let l=o.containerSourceRange??n.container.sourceRange,u=o.containerSourceHash??(Da(l,n.container.sourceRange)?n.container.sourceHash:null);if(!l||!u)return Ni("Route page composition does not expose a verifiable container boundary.");let d=Pi(l),p=uy(e.source,d,u,"Route page composition container");if(!p.ok)return p.result;let m=o.anchorSourceRange?Pi(o.anchorSourceRange):void 0;if(m){if(!o.anchorSourceHash)return Ni("Route page composition placement does not expose a verifiable anchor boundary.");let f=uy(e.source,m,o.anchorSourceHash,"Route page composition anchor");if(!f.ok)return f.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,...m?{anchorLocator:m}:{}},rewriteStep:{kind:"insert-child",parentLocator:d,node:a,placement:o.relation,...m?{anchorLocator:m}:{}}}}}function fd(e){let t=Ue(e.entryFile,e.source);if(!t.ok)return dr("PORTABLE_ROUTE_SOURCE_INVALID",t.diagnostic.message);let n=un({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 dr("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&&Da(l.anchorSourceRange,e.anchor.sourceRange)?[{placement:l,matchCount:1}]:[];let u=l.members.reduce((d,p)=>d+fy(p,e.anchor.componentName),0);return u===0?[]:[{placement:l,matchCount:u}]}),o=r.reduce((l,u)=>l+u.matchCount,0);if(o===0)return dr("PORTABLE_ROUTE_ANCHOR_MISSING","Portable route anchor was not found in the canonical page composition.");if(o!==1||r.length!==1)return dr("PORTABLE_ROUTE_ANCHOR_AMBIGUOUS","Portable route anchor does not identify exactly one page-composition gap.");let i=Ai({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=Ti({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 dr("PORTABLE_ROUTE_PATCH_FAILED",l.diagnostic.message);s=l.source}else{let l=Yt({source:s,locator:a.parentLocator,node:a.node,placement:a.placement,...a.anchorLocator?{anchorLocator:a.anchorLocator}:{}});if(!l.ok)return dr("PORTABLE_ROUTE_PATCH_FAILED",l.diagnostic.message);s=l.source}if(i.plan.serverParamsStep){let l=gy({source:s,step:i.plan.serverParamsStep});if(!l.ok)return dr("PORTABLE_ROUTE_PATCH_FAILED",l.diagnostic.message);s=l.source}let c=Zt({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}}:dr("PORTABLE_ROUTE_PATCH_FAILED",c.diagnostic.message)}function fy(e,t){return(e.label===t?1:0)+e.children.reduce((n,r)=>n+fy(r,t),0)}function dr(e,t,n=[]){return{ok:!1,error:{code:e,message:t,diagnostics:n}}}function VP(e){let t=HP(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 Ti(e){if(e.locator.root.kind!=="expression"||e.locator.path?.length)return Kr(e.source,"Root expression rewrite requires an exact expression locator.");let t=ni(e.source,"value");if(!t.ok)return Kr(e.source,t.diagnostic.message);let n=Ee(t.ast,e.locator);if(!n.ok)return Kr(e.source,n.diagnostic.message);let r=n.match.path;if(!r.isExpression())return Kr(e.source,"Resolved value locator does not point to an expression.");let o=bo(e.source,r.node.start??null,r.node.end??null);if(!o||o!==e.expectedSourceHash)return Kr(e.source,"Root expression hash no longer matches the current source.");if(e.action.kind==="remove")return r.replaceWith(ce.nullLiteral()),{ok:!0,source:cd(t.ast,{}).code};let i;try{i=Eo.parseExpression(e.action.jsx,{plugins:["jsx","typescript"]})}catch(s){return Kr(e.source,s instanceof Error?s.message:String(s))}return!ce.isJSXElement(i)&&!ce.isJSXFragment(i)?Kr(e.source,"Root expression rewrite requires a JSX insertion expression."):(e.action.kind==="replace"?r.replaceWith(i):r.replaceWith(UP(r.node,i,e.action.placement,e.action.replaceOriginal)),{ok:!0,source:cd(t.ast,{}).code})}function UP(e,t,n,r){if(ce.isNullLiteral(e)||r)return t;let o=ce.isJSXFragment(e)?[...e.children]:[ce.isJSXElement(e)?e:ce.jsxExpressionContainer(e)],s=n==="before"||n==="prepend"?[t,...o]:[...o,t];return ce.jsxFragment(ce.jsxOpeningFragment(),ce.jsxClosingFragment(),s)}function Kr(e,t){return{ok:!1,source:e,diagnostic:{message:t}}}function pd(e){let t=my(e);if(t)return{ok:!1,error:t};let n=e.projection,r=Sy(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(JP(n,o)){let h=ld(e);return h.ok?e.operation==="remove-node"&&!ly(n,o.placementUnitKey)?Ni("The last editable page unit cannot be deleted."):e.operation==="move-node"?Ni("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:h.sourceHash,rewriteStep:{kind:e.operation==="remove-node"?"remove-root-expression":"replace-root-expression",locator:h.locator,sourceHash:h.sourceHash}}}:h.result}let s=Pi(o.sourceRange),a=Sn(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?[]:[_i(a.diagnostic)]}};if(bo(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 h=ld(e);return h.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}}}:Ni("The last editable page unit cannot be deleted."):h.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||!zP(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=md(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 p=Pi(d),m=Sn(e.source,p);if(!m.ok||!m.match.node)return{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:m.ok===!1?m.diagnostic.message:"Route page composition target container could not be resolved.",diagnostics:m.ok?[]:[_i(m.diagnostic)]}};if(bo(e.source,m.match.node.start??null,m.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 h=u.anchorSourceRange,y=u.anchorSourceHash;if(!h||!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=Pi(h),E=Sn(e.source,x);return!E.ok||!E.match.node?{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:E.ok===!1?E.diagnostic.message:"Route page composition target anchor could not be resolved.",diagnostics:E.ok?[]:[_i(E.diagnostic)]}}:bo(e.source,E.match.node.start??null,E.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:p,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:p,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 KP(e,t){let n=e.placementUnitByKey.get(t.placementUnitKey);return n&&e.container.kind!=="jsx-container"&&Da(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 JP(e,t){return e.container.kind!=="jsx-container"&&Da(t.sourceRange,e.mutationTarget.sourceRange)&&t.sourceHash===e.mutationTarget.sourceHash}function ld(e){let t=e.projection.mutationTarget,n={kind:"value",root:{kind:"expression",sourceRange:t.sourceRange}},r=Sn(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?[]:[_i(r.diagnostic)]}}}:bo(e.source,r.match.node.start??null,r.match.node.end??null)!==t.sourceHash?{ok:!1,result:py("Route mutation target hash no longer matches the current source.")}:{ok:!0,locator:n,sourceHash:t.sourceHash}}function uy(e,t,n,r){let o=Sn(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?[]:[_i(o.diagnostic)]}}}:bo(e,o.match.node.start??null,o.match.node.end??null)!==n?{ok:!1,result:py(`${r} hash no longer matches the current source.`)}:{ok:!0}}function py(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function Ni(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 _i(e){return{code:"UNSUPPORTED_PAGE_SHAPE",message:e.message,details:{astCode:e.code}}}function my(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&&!XP(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 XP(e,t){return e.routeId===t.routeId&&e.effectiveTemplateId===t.effectiveTemplateId}function zP(e,t){return e.routeId===t.routeId&&e.templateId===t.effectiveTemplateId}function HP(e,t){let n=cy.posix.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=cy.posix.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function Pi(e){return{kind:"jsx-node",strategy:"source-range",sourceRange:e}}function bo(e,t,n){return t==null||n==null?null:`sha256:${jP("sha256").update(e.slice(t,n)).digest("hex")}`}function Da(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 gy(e){let t;try{t=Eo.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=WP(t,e.step);return n.ok?{ok:!0,source:cd(t,{}).code}:{ok:!1,source:e.source,diagnostic:{message:n.message}}}function WP(e,t){let n=by(e);if(!n)return{ok:!1,message:"Route default function could not be resolved for searchParams wiring."};let r=dd(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."}:yy(r)!==t.identifier?{ok:!1,message:"Existing route searchParams binding no longer matches the plan."}:{ok:!0};let o=hy(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?ud():GP()),{ok:!0};let i=n.node.params[0],s=dd(i);return s?(YP(s,t.typescript),{ok:!0}):{ok:!1,message:"Route page parameter is not a supported object pattern."}}function GP(){return ce.objectPattern([ce.objectProperty(ce.identifier("searchParams"),ce.identifier("searchParams"),!1,!0)])}function ud(){let t=Eo.parse("function __PortablePage({ searchParams }: { searchParams?: Promise<Record<string, string | string[] | undefined>> }) {}",{sourceType:"module",plugins:["typescript"]}).program.body[0];if(!ce.isFunctionDeclaration(t))throw new Error("Failed to construct the canonical searchParams type.");let n=t.params[0];if(!ce.isObjectPattern(n))throw new Error("Failed to construct the canonical searchParams pattern.");return ce.cloneNode(n,!0)}function YP(e,t){let n=ce.objectProperty(ce.identifier("searchParams"),ce.identifier("searchParams"),!1,!0),r=e.properties.findIndex(ce.isRestElement);if(r<0?e.properties.push(n):e.properties.splice(r,0,n),!t)return;let o=xy(e);if(!o){e.typeAnnotation=ud().typeAnnotation;return}if(!ce.isTSTypeLiteral(o.typeAnnotation))return;let i=ud().typeAnnotation;if(!i||!ce.isTSTypeAnnotation(i)||!ce.isTSTypeLiteral(i.typeAnnotation))return;let s=i.typeAnnotation.members[0];s&&!ZP(o.typeAnnotation)&&o.typeAnnotation.members.push(ce.cloneNode(s,!0))}function ZP(e){return e.members.some(t=>!("key"in t)||!t.key?!1:Ey(t.key)==="searchParams")}function qP(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 QP(e){if(!e.invocation)return{ok:!0};let t=ur({component:e.component.localName,bindings:e.invocation.bindings,targetBlockId:e.invocation.targetBlockId,targetOrder:e.invocation.targetOrder});if(!t.ok)return ad(t.error.message);let n;if(t.plan.requiresRouteSearchParams){let r=eA(e.source,e.entryFile);if(!r.ok)return ad(r.message,"UNSUPPORTED_ROUTE_PARAMS");if(n=r.step,r.step.identifier!==t.plan.searchParamsIdentifier&&(t=ur({component:e.component.localName,bindings:e.invocation.bindings,targetBlockId:e.invocation.targetBlockId,targetOrder:e.invocation.targetOrder,searchParamsIdentifier:r.step.identifier}),!t.ok))return ad(t.error.message)}return{ok:!0,invocation:t.plan,...n?{serverParamsStep:n}:{}}}function ad(e,t="PORTABLE_INVOCATION_INVALID"){return{ok:!1,error:{code:t,message:e,diagnostics:[]}}}function eA(e,t){let n;try{n=Eo.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=by(n);if(!r)return{ok:!1,message:"Portable route searchParams wiring requires a default server function."};let o=/\.(?:ts|tsx)$/iu.test(t),i=hy(r.node.params,o);return i.ok?{ok:!0,step:{kind:"ensure-search-params",action:i.action,identifier:i.identifier,typescript:o}}:i}function hy(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=dd(e[0]);if(!n)return{ok:!1,message:"Portable route searchParams wiring requires an object page parameter or an empty signature."};let r=yy(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&&!tA(n)?{ok:!1,message:"Portable route searchParams wiring cannot safely extend this typed page signature."}:{ok:!0,action:"add",identifier:"searchParams"}}function dd(e){return!e||ce.isTSParameterProperty(e)?null:ce.isObjectPattern(e)?e:ce.isAssignmentPattern(e)&&ce.isObjectPattern(e.left)?e.left:null}function yy(e){for(let t of e.properties)if(!(!ce.isObjectProperty(t)||t.computed||Ey(t.key)!=="searchParams"))return ce.isIdentifier(t.value)?t.value.name:ce.isAssignmentPattern(t.value)&&ce.isIdentifier(t.value.left)?t.value.left.name:"unsupported";return null}function tA(e){let t=xy(e);return t?ce.isTSTypeLiteral(t.typeAnnotation):e.properties.length===0}function xy(e){return e.typeAnnotation&&ce.isTSTypeAnnotation(e.typeAnnotation)?e.typeAnnotation:null}function by(e){let t=null;return $P(e,{ExportDefaultDeclaration(n){if(t)return;let r=qP(n,n.get("declaration"));r&&(t=r)}}),t}function Ey(e){return ce.isIdentifier(e)?e.name:ce.isStringLiteral(e)?e.value:null}var nA=typeof gd=="function"?gd:gd.default;function un(e){if(!e.ast)return dn(e,[ct("UNSUPPORTED_PAGE_SHAPE","SourceGraph entry AST is required",{reason:"parsed-ast-required"})]);let t=uA(e.ast);if(!t)return dn(e,[ct("UNSUPPORTED_PAGE_SHAPE","Route default export must resolve to a local function component",{reason:"default-export-unresolved"})]);let n=fA(t);if(!n.ok)return dn(e,[n.diagnostic]);let r=n.expression;if(r.isIdentifier()){let o=mA(r,t);if(o.status==="resolved")r=o.expression;else if(o.status==="invalid")return dn(e,[ct("UNSUPPORTED_PAGE_SHAPE","Route default export local binding is not a supported JSX root")])}if(hA(r,t))return dn(e,[ct("INDIRECT_RETURN_ONLY","Route default export only returns through an indirect function boundary")]);if(r.isNullLiteral())return yd(e,t,"virtual-route-root",r);if(gA(r)){let o=EA({input:e,source:e.source,expression:r});return hd(e,t,o,{kind:"virtual-route-root",sourceKind:"atomic-expression"},r)}if(r.isConditionalExpression())return dn(e,[ct("UNSUPPORTED_PAGE_SHAPE","Route conditional root contains an unsupported branch shape",{reason:"ambiguous-placement"})]);if(r.isJSXElement()&&!ze(r)&&!Oi(r)){let o=Ed(r),i=ky({input:e,containerKind:"virtual-route-root",sourceKind:"jsx-element",source:e.source,containerPath:r,members:[o]});return hd(e,t,i,{kind:"virtual-route-root",sourceKind:"jsx-element"},r)}if(r.isJSXElement()||r.isJSXFragment()){let o=xA(r);if(!o.ok)return dn(e,[o.diagnostic]);let i=So(o.path);if(i.unsupported)return dn(e,[ct("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);if(yA(e.source,r,i.members))return yd(e,t,"starter-placeholder",r);let s=r.isJSXFragment()||ze(r);if(i.members.length===0&&s)return yd(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=ky({input:e,containerKind:a,sourceKind:c,source:e.source,containerPath:o.path,members:i.members});return hd(e,t,l,{kind:a,sourceKind:c},r)}return dn(e,[ct("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")])}function md(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:ct("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:ct("PLACEMENT_KEY_NOT_FOUND","Placement key was not found in the projected page composition",{placementKey:t})}}function Sy(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:ct("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:ct("PLACEMENT_KEY_NOT_FOUND","Placement unit key was not found in the projected page composition",{placementUnitKey:t})}}function Ry(e){return e.ok?rA(e.projection):oA(e.projection)}function rA(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((h,y)=>Cy(e,u,h,y,e.container.placementKey)),p=d.filter(({member:h})=>h.isBusinessMember).map(({sourceMember:h})=>sA(l,h,u.independent)),m=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,m.map(({sourceMember:h})=>h)),o.set(l,p);let f=m[0]?.sourceMember.key??l;n.push({key:l,containerKey:f,businessMemberKeys:p.map(h=>h.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:iA(e,a),sourceMembers:i,businessMembers:s,placementUnits:n,placements:c}}function oA(e){let t=e.diagnostics.map(aA);return{status:"unsupported",version:e.version,composition:e.composition,reason:cA(e.diagnostics),diagnostics:t}}function iA(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 Cy(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)=>Cy(e,t,a,c,i))]}function sA(e,t,n){return{key:`business:${e}:${t.key}`,sourceMemberKey:t.key,containerKey:e,label:t.label,isIndependent:n}}function aA(e){return{code:lA(e),message:e.message}}function cA(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 lA(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 uA(e){let t=null;return nA(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=dA(o.path);i&&(t=i,n.stop())}}),t}function dA(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 fA(e){let t=e.get("body");if(!t.isBlockStatement()){let s=wi(t);return s?{ok:!0,expression:s}:{ok:!1,diagnostic:ct("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:ct("ROUTE_RETURN_NOT_FOUND","Route default export does not contain a proven return boundary")};if(!r.isReturnStatement())return{ok:!1,diagnostic:ct("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(!pA(s)&&!Oa(s))return{ok:!1,diagnostic:ct("UNSUPPORTED_PAGE_SHAPE","Route guard return shape is not statically safe",{reason:"guard-shape"})};continue}if(Ny(s)||_y(s))return{ok:!1,diagnostic:ct("UNSUPPORTED_PAGE_SHAPE","Route default export contains unsupported control flow before the terminal return",{reason:"control-flow-return"})}}let o=r.get("argument"),i=wi(o);return i?{ok:!0,expression:i}:{ok:!1,diagnostic:ct("ROUTE_RETURN_NOT_FOUND","Route default export returns without a boundary expression",{reason:"bare-return"})}}function pA(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(Ny(o)||_y(o))return null;return r}function Ny(e){return e.isForStatement()||e.isForInStatement()||e.isForOfStatement()||e.isWhileStatement()||e.isDoWhileStatement()||e.isSwitchStatement()||e.isTryStatement()||e.isWithStatement()}function _y(e){let t=!1;return e.traverse({Function(n){n.skip()},ReturnStatement(){t=!0}}),t}function mA(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=wi(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 gA(e){return e.isConditionalExpression()?vy(wi(e.get("consequent")))&&vy(wi(e.get("alternate"))):!1}function vy(e){return!!(e&&(e.isJSXElement()||e.isJSXFragment()||e.isNullLiteral()))}function wi(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 hA(e,t){if(e.isIdentifier())return Iy(e.node.name,t);if(e.isCallExpression()){let n=e.get("callee");if(n.isIdentifier())return Iy(n.node.name,t)}return!1}function Iy(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 yA(e,t,n){return e.includes("DESIGN_PLAN_REPLACE_ME")&&t.isJSXElement()&&n.length>0&&bd(t)}function bd(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(!bd(t))return!1;continue}if(t.isJSXElement()&&!bd(t))return!1}return!0}function xA(e){return{ok:!0,path:e}}function So(e){let t=[],n=!1;for(let r of e.get("children")){if(r.isJSXText()){if(!r.node.value.trim())continue;t.push({memberKey:Sd(r.node.type,r.node.start,r.node.end),kind:"text",nodeType:r.node.type,sourceRange:en(r.node.loc),businessMemberCount:0,parentSourceRange:en(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=So(o);n||=i.unsupported,t.push(...i.members);continue}if(o.isJSXElement()){let i=Oi(o)?So(o):null;n||=i?.unsupported??!1,t.push({...Ed(o,i?.members),sourceRange:en(r.node.loc),parentSourceRange:en(e.node.loc)});continue}if(o.isJSXSpreadChild()){n=!0;continue}t.push({memberKey:Sd(o.node.type,o.node.start,o.node.end),kind:"atomic-expression",nodeType:o.node.type,sourceRange:en(r.node.loc),businessMemberCount:1,parentSourceRange:en(e.node.loc),children:[],isBusinessMember:!0,label:"atomic-expression"});continue}if(r.isJSXFragment()||r.isJSXElement()&&ze(r)){let o=So(r);n||=o.unsupported,t.push(...o.members);continue}if(r.isJSXElement()){let o=Oi(r)?So(r):null;n||=o?.unsupported??!1,t.push({...Ed(r,o?.members),parentSourceRange:en(e.node.loc)})}}return{members:t,unsupported:n}}function Ed(e,t){let n=e.isJSXElement()&&Oi(e)?t??So(e).members:[],r=e.isJSXElement()&&!Oi(e)&&!ze(e);return{memberKey:Sd(e.node.type,e.node.start,e.node.end),kind:"jsx-element",nodeType:e.node.type,sourceRange:en(e.node.loc),businessMemberCount:r?1:Py(n),parentSourceRange:en(e.parentPath?.node.loc),children:n,isBusinessMember:r,label:bA(e)}}function Oi(e){let t=e.node.openingElement.name;return t.type==="JSXIdentifier"&&t.name[0]===t.name[0]?.toLowerCase()}function bA(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 Py(e){return e.reduce((t,n)=>t+n.businessMemberCount,0)}function Ma(e){return e.length===0?0:Math.max(1,Py(e))}function ky(e){let t=en(e.containerPath.node.loc),n=Id(e.source,e.containerPath.node.start,e.containerPath.node.end),r=tn(e.input,e.containerKind,e.sourceKind,t),o=tn(e.input,e.containerKind,"placement-unit",t);return{placementKey:r,placementUnitKey:o,version:e.input.version,containerKey:r,independent:Ma(e.members)<=1,memberCount:Ma(e.members),sourceRange:t,sourceHash:n,relation:"append",containerSourceRange:t,containerSourceHash:n,anchorSourceRange:null,anchorSourceHash:null,members:e.members}}function EA(e){let t=en(e.expression.node.loc),n=Id(e.source,e.expression.node.start,e.expression.node.end),r=tn(e.input,"virtual-route-root","atomic-expression",t),o=tn(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:tn(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 Ay(e,t){let n=en(t.node.loc),r=Id(e.source,t.node.start,t.node.end);return!n||!r?null:{kind:"expression",documentVersion:e.version,sourceRange:n,sourceHash:r}}function hd(e,t,n,r,o){let i=Ay(e,o);if(!i)return dn(e,[ct("UNSUPPORTED_PAGE_SHAPE","Route default export does not provide an exact mutation target",{reason:"mutation-target-unavailable"})]);let s=n.containerSourceRange??n.sourceRange,a=SA(e,n,s),c=Yu(a),l={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:wy(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 SA(e,t,n){if(t.members.length===0)return[t];let r=[],o=(l,u,d,p,m,f,h=n)=>({...t,placementKey:u,placementUnitKey:d,containerKey:t.placementKey,independent:Ma(f)<=1,memberCount:Ma(f),sourceRange:p,sourceHash:p?xd(e.source,p):null,relation:l,containerSourceRange:h,containerSourceHash:h?xd(e.source,h):null,anchorSourceRange:m,anchorSourceHash:m?xd(e.source,m):null,members:f}),i=t.placementKey,s=t.members.map(l=>tn(e,i,"placement-unit",l.sourceRange)),a=s[0]??t.placementUnitKey,c=s.at(-1)??t.placementUnitKey;r.push(o("prepend",tn(e,i,"prepend",n),a,n,null,[]));for(let l of t.members){let u=l.parentSourceRange??n,d=tn(e,i,"placement-unit",l.sourceRange);r.push(o("before",tn(e,d,"before",l.sourceRange),d,l.sourceRange,l.sourceRange,[l],u)),r.push(o("after",tn(e,d,"after",l.sourceRange),d,l.sourceRange,l.sourceRange,[l],u))}return r.push(o("append",i,c,n,null,[])),r}function yd(e,t,n,r){let o=Ay(e,r);if(!o)return dn(e,[ct("UNSUPPORTED_PAGE_SHAPE","Route default export does not provide an exact mutation target",{reason:"mutation-target-unavailable"})]);let i=tn(e,n,"empty-container",void 0),s=tn(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=Yu([a]),l={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:wy(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 dn(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 ct(e,t,n){return n===void 0?{code:e,message:t}:{code:e,message:t,details:n}}function tn(e,t,n,r){return Ty([e.route,e.entryFile,String(e.version),t,n,r?`${r.startLine}:${r.startColumn}-${r.endLine}:${r.endColumn}`:"no-range"])}function Sd(e,t,n){return Ty(["member",e,String(t??-1),String(n??-1)])}function Ty(e){return`pc_${vd("sha256").update(e.join("\0")).digest("hex").slice(0,24)}`}function Id(e,t,n){return t==null||n==null?null:`sha256:${vd("sha256").update(e.slice(t,n)).digest("hex")}`}function xd(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:${vd("sha256").update(e.slice(r+t.startColumn,o+t.endColumn)).digest("hex")}`}function en(e){return e?{startLine:e.start.line,startColumn:e.start.column,endLine:e.end.line,endColumn:e.end.column}:null}function wy(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 OA}from"node:crypto";import*as fn from"@babel/types";function Oy(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 kd from"@babel/traverse";import*as vo from"@babel/types";var IA=typeof kd=="function"?kd:kd.default,kA=32;function Fi(e,t,n,r=new Set){if(r.has(e.ast)||r.size>=kA)return null;let o=new Set(r).add(e.ast),i;if(IA(e.ast,{Program(d){i=d,d.stop()}}),!i)return null;let s=(d,p)=>{let m=Qn(e.file,d,n),f=m?n.get(m):void 0;return f?Fi(f,p,n,o):null},a=d=>{let p=i.scope.getBinding(d);if(!p||p.constantViolations.length)return null;let m=p.path.parentPath;return m?.isImportDeclaration()?m.node.importKind==="type"?null:p.path.isImportDefaultSpecifier()?s(m.node.source.value,"default"):p.path.isImportSpecifier()&&p.path.node.importKind!=="type"?s(m.node.source.value,Ba(p.path.node.imported)):null:p.path.isVariableDeclarator()?p.path.get("init"):p.path},c=[],l=[];for(let d of i.get("body"))if(d.isExportDefaultDeclaration()&&t==="default"){let p=d.get("declaration");c.push(p.isIdentifier()?a(p.node.name):p)}else if(d.isExportNamedDeclaration()&&d.node.exportKind!=="type"){let p=d.get("declaration");p.node&&Object.hasOwn(vo.getBindingIdentifiers(p.node),t)&&c.push(a(t));for(let m of d.node.specifiers)vo.isExportSpecifier(m)&&m.exportKind!=="type"&&Ba(m.exported)===t&&c.push(d.node.source?s(d.node.source.value,Ba(m.local)):a(Ba(m.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 Ba(e){return vo.isIdentifier(e)?e.name:e.value}import*as he from"@babel/types";var RA=32;function Bt(e,t=new Map,n=new Set){if(n.has(e.node)||n.size>=RA)return null;let r=new Set(n).add(e.node),o=t.get(e.node);if(o)return Li(o,t,r);if(e.isTSAsExpression()||e.isTSTypeAssertion()||e.isTSNonNullExpression()||e.isTSSatisfiesExpression()||e.isParenthesizedExpression())return Bt(e.get("expression"),t,r);if(e.isIdentifier()){let i=e.scope.getBinding(e.node.name);return!i||i.constantViolations.length?null:Cd(i,t,r)}if(e.isMemberExpression()||e.isOptionalMemberExpression()){let i=jt(e.node.property,e.node.computed),s=e.get("object"),a=Bt(s,t,r);return i!==null&&a?Va(a,i,t,r):null}if(e.isConditionalExpression())return Li([e.get("consequent"),e.get("alternate")],t,r);if(e.isLogicalExpression())return Li([e.get("left"),e.get("right")],t,r);if(e.isSequenceExpression()){let i=e.get("expressions").at(-1);return i?Bt(i,t,r):null}if(e.isCallExpression()&&he.isIdentifier(e.node.callee)){let i=e.scope.getBinding(e.node.callee.name);if(!i||!Io(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[m,f]of a.get("params").entries()){if(!f.isIdentifier())return null;let h=l[m];if(!h?.isExpression())return null;let y=Bt(h,t,r);if(!y)return null;let x=f.scope.getBinding(f.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 p=d.isReturnStatement()?d.get("argument"):d;return p.node?Bt(p,c,r):null}return[e]}function Cd(e,t=new Map,n=new Set){if(e.constantViolations.length)return null;let r=t.get(e.identifier);if(r)return Li(r,t,n);if(!e.path.isVariableDeclarator())return null;let o=e.path.get("init");if(!o.node)return null;let i=Bt(o,t,n);if(!i)return null;let s=Rd(e.path.node.id,e.identifier.name);return s?s.reduce((a,c)=>a&&Va(a,c,t,n),i):null}function ja(e){if(!e.params.every(n=>he.isIdentifier(n)||he.isAssignmentPattern(n)&&he.isIdentifier(n.left)&&Jr(n.right)))return!1;if(!he.isBlockStatement(e.body))return Jr(e.body);if(e.body.body.length!==1)return!1;let t=e.body.body[0];return he.isReturnStatement(t)&&!!t.argument&&Jr(t.argument)}function Io(e){if(e.constantViolations.length>0)return!1;if(e.path.isFunctionDeclaration())return ja(e.path.node);let t=e.path.isVariableDeclarator()?e.path:e.path.findParent(r=>r.isVariableDeclarator()),n=t?.isVariableDeclarator()?t.node.init:null;return he.isArrowFunctionExpression(n)||he.isFunctionExpression(n)?ja(n):!1}function Jr(e){let t=!0;return he.traverseFast(e,n=>{(he.isCallExpression(n)&&!$a(n)||he.isOptionalCallExpression(n)||he.isNewExpression(n)||he.isAwaitExpression(n)||he.isAssignmentExpression(n)||he.isUpdateExpression(n)||he.isUnaryExpression(n,{operator:"delete"})||he.isYieldExpression(n)||he.isTaggedTemplateExpression(n))&&(t=!1)}),t}function $a(e){return he.isIdentifier(e.callee,{name:"useTranslations"})&&e.arguments.length===1&&he.isStringLiteral(e.arguments[0])}function Li(e,t,n){let r=[];for(let o of e){let i=Bt(o,t,n);if(!i)return null;r.push(...i)}return r.length?r:null}function Va(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=>he.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 Li(o,n,r)}function Nd(e,t){let n=Bt(e,t);return!!(n?.length&&n.every(r=>he.isLiteral(r.node)&&!r.isRegExpLiteral()||r.isTemplateLiteral()||r.isBinaryExpression()||r.isUnaryExpression()))}function jt(e,t){return!t&&he.isIdentifier(e)?e.name:he.isStringLiteral(e)||he.isNumericLiteral(e)?String(e.value):null}function Rd(e,t){if(he.isIdentifier(e))return e.name===t?[]:null;if(he.isObjectPattern(e))for(let n of e.properties){if(!he.isObjectProperty(n)||n.computed)continue;let r=jt(n.key,!1),o=Rd(n.value,t);if(r!==null&&o)return[r,...o]}if(he.isArrayPattern(e))for(let[n,r]of e.elements.entries()){if(!r)continue;let o=Rd(r,t);if(o)return[String(n),...o]}return null}function Fy(e,t=new Set,n){return Ly(e.get("callee"),t,n)}function Ly(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),p=d&&Qn(d.file,l,n),m=p?n.get(p):void 0,f=r.path.isImportDefaultSpecifier()?"default":r.path.isImportSpecifier()&&r.path.node.importKind!=="type"?jt(r.path.node.imported,!1):null,h=m&&f&&i.node.importKind!=="type"?Fi(m,f,n):null;return h?ko(h,o,n):{kind:"guard"}}let s=r.path.isVariableDeclarator()?r.path.get("init"):r.path;if(!s.node)return{kind:"unknown"};let a=ko(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=ko(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=Bt(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=ko(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 ko(e,new Set(t).add(e.node),n)}function ko(e,t,n){if(e.isIdentifier())return Ly(e,t,n);if(e.isTSAsExpression()||e.isTSTypeAssertion()||e.isTSNonNullExpression()||e.isParenthesizedExpression())return ko(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 Ka(e,t){return JSON.stringify([t,e])}var NA=new Set;function $y(e,t){let n=new Map,r=[],o=new Map,i=(f,h)=>JSON.stringify([f,h.loc?.start.line,h.loc?.start.column,h.loc?.end.line,h.loc?.end.column]);for(let f of e.graph.elements.values()){let h=f.sourceRange;o.set(JSON.stringify([f.sourceFile,h.startLine,h.startColumn,h.endLine,h.endColumn]),f)}let s=f=>r.push({code:"render-occurrence-unproven",message:"A block render occurrence cannot be proven statically.",file:f}),a=(f,h)=>!jy(h)&&[...t].some(y=>e.graph.elements.get(y)?.sourceFile===f);function c(f,h,y,x,E,b=NA){if(f.isIdentifier())return x&&Ua(f,x)?x.children.some(N=>c(N.path,N.file,y,N.substitution,E,b)):u({path:f,file:h,active:y,substitution:x,unknownIsRelevant:E,aliases:b});if(f.isCallExpression()||f.isOptionalCallExpression()){let N=f,P=Fy(N,b,e.parsedModules);return P.kind==="guard"||P.kind==="sources"&&P.sources.some(R=>c(R,[...e.parsedModules.values()].find(A=>A.ast.program===R.scope.getProgramParent().path.node)?.file??h,y,x,E,P.aliases))?!0:N.get("arguments").some(R=>c(R,h,y,x,E,b))||P.kind==="unknown"&&E}if(f.isJSXElement()){if(ze(f))return f.get("children").some(D=>c(D,h,y,x,E,b));let N=o.get(i(h,f.node));if(N){if(t.has(N.identity.key))return!0;if(N.boundaryKind==="component-boundary"&&!N.isPublicUiComponent){let D=e.parsedModules.get(N.sourceFile);if(!D)return!1;let V=cr({module:D,componentName:N.tag,callSourceRange:N.sourceRange,...N.importedFrom?{imported:{file:N.importedFrom,module:e.parsedModules.get(N.importedFrom),exportName:N.exportName??N.tag,parsedModules:e.parsedModules}}:{}});return V.ok?V.metadataOnly?!1:l(V,f,N.sourceFile,y,x,b):V.diagnostic.code==="component-external-module-opaque"?Di(f).some(Q=>c(Q,h,y,x,!1,b)):a(D.file,V.diagnostic.code)}return f.get("children").some(D=>c(D,h,y,x,E,b))}let P=f.node.openingElement.name;if(!fn.isJSXIdentifier(P))return!1;if(/^[a-z]/.test(P.name))return f.get("children").some(D=>c(D,h,y,x,E,b));let R=e.parsedModules.get(h),A=f.node.loc;if(!R||!A)return!1;let T=wA({path:f,file:h,componentName:P.name,parsedModules:e.parsedModules}),O=cr({module:R,componentName:P.name,callSourceRange:{startLine:A.start.line,startColumn:A.start.column,endLine:A.end.line,endColumn:A.end.column},...T?{imported:T}:{}});return O.ok?O.metadataOnly?!1:l(O,f,h,y,x,b):O.diagnostic.code==="component-external-module-opaque"?Di(f).some(D=>c(D,h,y,x,!1,b)):a(R.file,O.diagnostic.code)}if(f.isJSXFragment())return f.get("children").some(N=>c(N,h,y,x,E,b));if(f.isJSXExpressionContainer()||f.isParenthesizedExpression()||f.isTSAsExpression()||f.isTSNonNullExpression()||f.isTSTypeAssertion())return c(f.get("expression"),h,y,x,E,b);let S=!1;return f.traverse({"CallExpression|OptionalCallExpression"(N){c(N,h,y,x,E,b)&&(S=!0),N.skip(),S&&N.stop()},ReferencedIdentifier(N){c(N,h,y,x,E,b)&&(S=!0),S&&N.stop()},JSXElement(N){c(N,h,y,x,E,b)&&(S=!0),N.skip(),S&&N.stop()},JSXFragment(N){c(N,h,y,x,E,b)&&(S=!0),N.skip(),S&&N.stop()}}),S?!0:E&&!Xr(f)}function l(f,h,y,x,E,b){let S=`${f.sourceFile}#${f.componentName}`;if(x.has(S))return!1;let N=new Set(x).add(S);return f.returnAlternatives?.some(P=>Di(P).some(R=>c(R,f.sourceFile,N,null,!1,b)))||f.roots.some(P=>c(P,f.sourceFile,N,null,!1,b))?!0:Dy(f.roots).kind==="none"?!1:By(h).some(P=>c(P,y,N,E,!0,b))}function u(f){if(!f.path.isIdentifier())return f.unknownIsRelevant;let h=Oy({path:f.path,aliases:f.aliases});return h.kind==="unbound"?f.unknownIsRelevant&&f.path.node.name!=="undefined":h.kind==="guard"||h.kind==="reassigned"?!0:h.kind==="not-alias"?f.unknownIsRelevant:c(h.initializer,f.file,f.active,f.substitution,f.unknownIsRelevant,h.aliases)?!0:_d(h.initializer).isIdentifier()?!1:f.unknownIsRelevant&&!Xr(h.initializer)}let d=(f,h,y,x,E,b)=>{if(f.isIdentifier()){c(f,h,x,b,!1)&&s(h);return}if(f.isJSXElement()){if(ze(f)){for(let P of f.get("children"))d(P,h,y,x,E,b);return}let S=o.get(i(h,f.node));if(!S)return;let N=S.identity.key;if(t.has(N)){E||s(h);let P=n.get(N)??[];P.push(Ka(N,y)),n.set(N,P)}if(S.boundaryKind==="component-boundary"&&!S.isPublicUiComponent){let P=e.parsedModules.get(S.sourceFile);if(!P)return;let R=cr({module:P,componentName:S.tag,callSourceRange:S.sourceRange,...S.importedFrom?{imported:{file:S.importedFrom,module:e.parsedModules.get(S.importedFrom),exportName:S.exportName??S.tag,parsedModules:e.parsedModules}}:{}});if(!R.ok){if(R.diagnostic.code==="component-external-module-opaque"){Di(f).some(Q=>c(Q,h,x,b,!1))&&s(h);return}[...t].some(Q=>e.graph.elements.get(Q)?.sourceFile===P.file)&&!jy(R.diagnostic.code)&&s(P.file);return}if(R.metadataOnly)return;let A=`${R.sourceFile}#${R.componentName}`;if(x.has(A)){s(P.file);return}let T=new Set(x).add(A);R.returnAlternatives?.some(Q=>Di(Q).some(U=>c(U,R.sourceFile,T,b,!1)))&&s(R.sourceFile);let O=Dy(R.roots),D=TA(f);if(O.kind==="unproven"||O.kind==="supported"&&D){for(let Q of By(f))if(c(Q,h,T,b,!0)){s(h);break}}let V=O.kind==="supported"&&!D?{bindingNode:O.bindingNode,children:f.get("children").map(Q=>({path:Q,file:h,substitution:b}))}:null;for(let Q of R.roots)d(Q,R.sourceFile,[...y,N],T,E,V);return}for(let P of f.get("children"))d(P,h,y,x,E,b);return}if(f.isJSXFragment()){for(let S of f.get("children"))d(S,h,y,x,E,b);return}if(f.isJSXExpressionContainer()){let S=f.get("expression");if(b&&!S.isJSXEmptyExpression()){let N=_d(S);if(Ua(N,b)){for(let P of b.children)d(P.path,P.file,y,x,E,P.substitution);return}if(_A(S,b))for(let P of b.children)d(P.path,P.file,y,x,!1,P.substitution)}d(S,h,y,x,E,b);return}if(f.isParenthesizedExpression()||f.isTSAsExpression()||f.isTSNonNullExpression()||f.isTSTypeAssertion()){d(f.get("expression"),h,y,x,E,b);return}c(f,h,x,b,!1)&&s(h),f.traverse({JSXElement(S){d(S,h,y,x,!1,b),S.skip()}})},p=e.parsedModules.get(e.entryFile);if(!p)return{occurrences:n,diagnostics:r};let m=ln({module:p,exportName:"default",allowNonRenderingGuards:!0});if(!m.ok)return s(e.entryFile),{occurrences:n,diagnostics:r};for(let f of m.roots)d(f,p.file,[],new Set,!0,null);return{occurrences:n,diagnostics:r}}function _d(e){let t=e;for(;t.isParenthesizedExpression()||t.isTSAsExpression()||t.isTSNonNullExpression()||t.isTSTypeAssertion();)t=t.get("expression");return t}function Xr(e){let t=_d(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||Xr(n)):t.isConditionalExpression()?Xr(t.get("consequent"))&&Xr(t.get("alternate")):t.isLogicalExpression()?Xr(t.get("left"))&&Xr(t.get("right")):!1}function Ua(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 _A(e,t){if(Ua(e,t))return!0;let n=!1;return e.traverse({Identifier(r){Ua(r,t)&&(n=!0,r.stop())}}),n}function Dy(e){let t=e[0]?.getFunctionParent();if(!t)return{kind:"none"};let n=t.get("params")[0];return n?n.isAssignmentPattern()?My(n.get("left"),!0):My(n,!1):{kind:"none"}}function My(e,t){if(e.isObjectPattern()){let n=[],r=!1;for(let i of e.get("properties")){if(i.isObjectProperty()){if(i.node.computed){kn(i.get("value"))&&(r=!0);continue}let s=i.node.key;(fn.isIdentifier(s)?s.name:fn.isStringLiteral(s)?s.value:null)==="children"&&n.push(i);continue}i.isRestElement()&&kn(i.get("argument"))&&(r=!0)}if(n.length>1)return r||n.some(i=>kn(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=>PA(s))?t?{kind:"unproven"}:{kind:"supported",bindingNode:o.node}:{kind:"unproven"}}return kn(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=>AA(r))?{kind:"none"}:{kind:"unproven"}}return kn(e)?{kind:"unproven"}:{kind:"none"}}function kn(e){if(e.isIdentifier()){let t=e.scope.getBinding(e.node.name);return!!(t&&t.referencePaths.length>0)}return e.isAssignmentPattern()?kn(e.get("left")):e.isRestElement()?kn(e.get("argument")):e.isObjectPattern()?e.get("properties").some(t=>t.isObjectProperty()?kn(t.get("value")):t.isRestElement()?kn(t.get("argument")):!0):e.isArrayPattern()?e.get("elements").some(t=>t.node?kn(t):!1):!0}function PA(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 AA(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?fn.isStringLiteral(n)&&n.value!=="children":fn.isIdentifier(n)&&n.name!=="children"}function TA(e){for(let t of e.get("openingElement").get("attributes")){if(t.isJSXAttribute()){let n=t.node.name;if(fn.isJSXIdentifier(n)&&n.name==="children")return!0;continue}if(t.isJSXSpreadAttribute()&&Vy(t.get("argument")))return!0}return!1}function By(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(!fn.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");Vy(r)&&t.push(r)}}return t}function Di(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 Vy(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 wA(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=Qn(e.file,r.node.source.value,e.parsedModules);if(!o)return;let i=n.isImportDefaultSpecifier()?"default":fn.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 jy(e){return e==="component-export-unresolved"||e==="component-local-binding-unresolved"}function Jy(e){let t=[],n=[];return Xy(e.element,e,[],e.ownerNode,e.element,[],new Set,t,n),{roots:t,diagnostics:n}}function Xy(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(Qu(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=cr({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 p=d.sourceFile,m=`${p}#${d.componentName}`;if(s.has(m)){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:p,structuralPath:e.identity.structuralPath});return}let f=[...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(E=>({key:E.identity.key,structuralPath:E.identity.structuralPath,sourceRange:E.sourceRange}))}:{}}],h=d.roots.length>1?{kind:"component-definition",key:m}:r,y=new Set(s);y.add(m);let x=[];for(let E of d.returnAlternatives??[]){let b=Ky(E),S=b?Uy(t.graph,p,b):[];if(S.length!==1){c.push({code:"conditional-component-root-unproven",message:"A conditional call site is absent or ambiguous in the source graph.",file:p});return}x.push(S[0])}for(let E of d.roots){let b=Ky(E),S=b?Uy(t.graph,p,b):[];if(S.length!==1){c.push({code:S.length?"component-root-ambiguous":"component-root-unresolved",message:"The component root could not be matched to one source graph node.",file:p,structuralPath:e.identity.structuralPath});continue}Xy(S[0],t,f,h,d.roots.length>1?S[0]:o,d.roots.length>1?f:i,y,a,c,x)}}function Uy(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 Ky(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 Ja(e){let t=[],n=[];if(e.projection.entryFile!==e.entryFile||!Hy(e.projection.composition,e.composition)||e.graph.composition&&!Hy(e.graph.composition,e.composition))return{roots:[],diagnostics:[Mi("composition-mismatch",e.entryFile)]};if(!e.parsedModules.has(e.entryFile))return{roots:[],diagnostics:[Mi("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(Mi("route-member-not-addressable",e.entryFile));continue}let s=LA(e.graph,e.entryFile,i.sourceRange);if(s.length!==1){t.push(Mi(s.length?"route-root-ambiguous":"route-root-unresolved",e.entryFile));continue}let a=s[0],c=Jy({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=$y(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=Ka(s,i.callChain.map(c=>c.callLocator.key));o.occurrences.get(s)?.filter(c=>c===a).length!==1&&t.push(Mi("render-occurrence-unproven",i.element.sourceFile))}return{roots:FA(n,e.composition,o.occurrences),diagnostics:t}}function FA(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:OA("sha256").update(JSON.stringify([t,c,s.identity.key])).digest("hex"),rootRef:{key:s.identity.key,...a.length>1?{instanceIndex:a.indexOf(Ka(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=zy(i);o.set(s,[...o.get(s)??[],i])}return r.map(i=>{let s=o.get(zy(i))??[i];return{...i,siblingIndex:s.indexOf(i),siblingRootKeys:s.filter(a=>a!==i).map(a=>a.rootKey)}})}function zy(e){return JSON.stringify([e.ownerNode.kind,e.ownerNode.key,e.parentStructuralPath,e.ownerCallKeys])}function LA(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 Hy(e,t){return e.routeId===t.routeId&&e.effectiveTemplateId===t.effectiveTemplateId}function Mi(e,t){return{code:e,message:"Page block roots could not be proven from the current source graph.",file:t}}import{SiteEditPageBlockDirectorySchema as DA,SiteEditPageBlockDescriptorSchema as MA,SiteEditSourcePathSchema as Gy}from"@vcp-dev/contracts";function Xa(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}),Wy(i,r,o,t,e)}}return{nodes:t,rootKeys:[...e.rootKeys]}}function Wy(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}),Wy(s,t,n,r,o))}}function Bi(e){let t=[],n={...e.graph,composition:e.composition},r=oa(Xa(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=$A(a,e.graph),p=d?e.parsedModules.get(d):void 0;if(!c||!l||l.sourceFile!==d||!u||!Gy.safeParse(a.sourceFile).success||!d||!p||!Gy.safeParse(d).success){t.push(Pd("root-source-unavailable",a.sourceFile));continue}if(i.has(a.rootKey)){t.push(Pd("block-key-ambiguous",a.sourceFile));continue}let m=ve(u.source),f=MA.safeParse({blockKey:a.rootKey,rootRef:a.rootRef,definitionKey:a.rootRef.key,source:{file:a.sourceFile,structuralPath:a.structuralPath,contentHash:m},owner:a.ownerNode,siblingBlockKeys:a.siblingRootKeys,placementUnitKey:VA(a,e),capabilities:BA(c,r),...jA(c,r)});if(!f.success){t.push(Pd("page-block-descriptor-invalid",a.sourceFile));continue}let h=f.data;o.push(h),i.set(a.rootKey,{blockKey:a.rootKey,composition:e.composition,documentVersion:e.documentVersion,descriptor:h,root:a,ownerFile:d,ownerSourceHash:ve(p.source),ownerSourceContent:p.source,sourceHash:m,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=DA.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 BA(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 jA(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 $A(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 VA(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 Pd(e,t){return{code:e,message:"The page block source binding could not be proven.",file:t}}import Ad from"@babel/traverse";import{BlockRenderRefSchema as UA,SiteEditPageBlockPositionSchema as KA,SiteEditPageBlockTargetSchema as JA}from"@vcp-dev/contracts";var XA=typeof Ad=="function"?Ad:Ad.default;function Ro(e,t,n,r){if(!JA.safeParse(t).success)return Ot("INVALID_PARAMS","Invalid page block target.");if(n!==e.documentVersion)return Ot("VERSION_STALE","The page block index is stale.");if(t.composition.routeId!==e.composition.routeId||t.composition.templateId!==e.composition.effectiveTemplateId)return Ot("INVALID_TARGET","The target belongs to another composition.");let o=e.bindings.get(t.blockKey);return o?r&&(!UA.safeParse(r).success||r.key!==o.descriptor.rootRef.key||r.instanceIndex!==o.descriptor.rootRef.instanceIndex||r.instanceCount!==o.descriptor.rootRef.instanceCount)?Ot("INVALID_TARGET","The render occurrence does not match the target."):{ok:!0,binding:o}:Ot("INVALID_TARGET","The page block target was not found.")}function za(e,t){if(!KA.safeParse(t).success)return Ot("INVALID_PARAMS","Invalid page block boundary.");if(t.documentVersion!==e.documentVersion)return Ot("VERSION_STALE","The page block boundary is stale.");if(t.composition.routeId!==e.composition.routeId||t.composition.templateId!==e.composition.effectiveTemplateId)return Ot("INVALID_TARGET","The boundary belongs to another composition.");let n=e.bindings.get(t.anchorBlockKey);if(!n)return Ot("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 Ot("INVALID_TARGET","A verified sibling binding is unavailable.");let o=r.sort((u,d)=>u.root.siblingIndex-d.root.siblingIndex),i=Yy(n);if(!i)return Ot("INVALID_TARGET","The operation owner call site is unavailable.");let s=Zy(n,i);if(s===void 0)return Ot("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||!zA(Zy(u,Yy(u)),s))return Ot("INVALID_TARGET","Siblings do not share one proven source boundary.");let a=o.findIndex(u=>u.blockKey===n.blockKey);if(a<0)return Ot("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 Yy(e){return e.ownerLocator.file===e.ownerFile?e.ownerLocator:null}function Zy(e,t){if(!t)return;let n=Ue(t.file,e.ownerSourceContent);if(!n.ok)return;let r=[];if(XA(n.module.ast,{JSXElement(i){let s=Td(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=Td(o.node);return i?{kind:"jsx-fragment",file:t.file,sourceRange:i}:void 0}if(o.isJSXElement()){let i=Td(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 zA(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 Td(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 Ot(e,t){return{ok:!1,code:e,message:t}}import ex from"node:path";import{SiteEditSourcePathSchema as rT}from"@vcp-dev/contracts";import Ha from"node:path";import wd from"@babel/traverse";import*as fr from"@babel/types";import{SiteEditSourcePathSchema as qy,SiteEditPageBlockTargetSchema as HA}from"@vcp-dev/contracts";var WA=typeof wd=="function"?wd:wd.default;function Qy(e){if(!e.operationId)return et("INVALID_PARAMS","An operationId is required.");if(!HA.safeParse(e.target).success)return et("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 et("INVALID_TARGET","The request target does not match its resolved block binding.");if(e.documentVersion!==e.binding.documentVersion)return et("VERSION_STALE","The resolved block belongs to a stale document version.");if(e.operation==="move-node"||e.operation==="remove-node")return et("UNSUPPORTED_OPERATION","Move and remove are planned by the structural operation task.");if(!e.node)return et("INVALID_PARAMS","An insert/replacement node is required.");let t=e.operation==="insert-child"?e.boundary?.ownerFile:e.binding.ownerFile;if(!t||!qy.safeParse(t).success)return et("INVALID_TARGET","The exact owner source file is unavailable.");let n=e.files.get(t);if(n===void 0)return et("INVALID_TARGET","The exact owner source is absent from the fixed file map.");if(ve(n)!==e.binding.ownerSourceHash)return et("VERSION_STALE","The owner source hash changed after target resolution.");let r=e.files.get(e.binding.descriptor.source.file);if(r===void 0||ve(r)!==e.binding.descriptor.source.contentHash)return et("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 et("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 et("INVALID_TARGET","The boundary anchor is not a verified same-owner sibling.");if(!o.parentLocator)return et("UNSUPPORTED_OPERATION","A root without a source parent has no safe sibling insertion boundary.")}let i=YA(e.node,t,n,e.files);if(!i.ok)return i;let s=e.operation==="replace-node"?lo({source:n,locator:GA(e.binding),node:{jsx:i.value.jsx}}):Yt({source:n,locator:Od(o.parentLocator),anchorLocator:Od(o.anchorLocator),placement:o.placement,node:{jsx:i.value.jsx}});if(!s.ok)return et("UNSUPPORTED_OPERATION",s.diagnostic.message);let a=s.source;if(i.value.import){let l=Zt({source:a,moduleSpecifier:i.value.import.moduleSpecifier,imports:i.value.import.specifiers});if(!l.ok)return et("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 GA(e){return Od(e.ownerLocator)}function Od(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 YA(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}>`}}:et("INVALID_PARAMS","The native JSX tag is invalid.");if(!e.component)return et("UNSUPPORTED_OPERATION","A materialized component entry is resolved by the materialization task.");let o=ZA(t,e.component.source,r);if(!o)return et("INVALID_TARGET","The component source is not in the safe fixed file map.");let i=Ue(t,n);if(!i.ok)return et("UNSUPPORTED_OPERATION",i.diagnostic.message);let s=qA(i.module.ast.program.body,e.component.source,e.component.exportName),a=s??eT(tT(e.component.exportName,o),QA(i.module.ast)),c=nT(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 ZA(e,t,n){let r=t.startsWith("@/")?t.slice(2):t.startsWith("./")||t.startsWith("../")?Ha.posix.normalize(Ha.posix.join(Ha.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=>qy.safeParse(i).success&&n.has(i))??null:null}function qA(e,t,n){for(let r of e)if(!(!fr.isImportDeclaration(r)||r.source.value!==t)){for(let o of r.specifiers)if(n==="default"&&fr.isImportDefaultSpecifier(o)||n!=="default"&&fr.isImportSpecifier(o)&&(fr.isIdentifier(o.imported)?o.imported.name:o.imported.value)===n)return o.local.name}return null}function QA(e){let t=new Set;return WA(e,{Program(n){n.scope.crawl(),t=new Set(Object.keys(n.scope.bindings)),n.stop()}}),t}function eT(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n+=1;return`${e}${n}`}function tT(e,t){let r=(e==="default"?Ha.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 nT(e){let t=[];for(let[n,r]of Object.entries(e)){if(!/^[A-Za-z_][A-Za-z0-9_:.-]*$/.test(n))return et("INVALID_PARAMS","A component prop name is invalid.");let o;try{o=JSON.stringify(r)}catch{return et("INVALID_PARAMS","Component props must be JSON serializable.")}if(o===void 0)return et("INVALID_PARAMS","Component props must be JSON serializable.");t.push(`${n}={${o}}`)}return{ok:!0,value:t.join(" ")}}function et(e,t){return{ok:!1,code:e,message:t}}function tx(e){if(e.materialization.kind!=="static-prefab-materialization"||!e.materialization.files.some(i=>i.path===e.materialization.entry.path))return Wa("MATERIALIZATION_ENTRY_INVALID","The materialization entry must identify one controlled create-only file.");if(!e.materialization.files.every(i=>i.kind==="create-only"&&rT.safeParse(i.path).success))return Wa("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 Wa("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 Wa("INVALID_TARGET","The exact page-block owner source is missing from the fixed file map.");let n=iT(t,e.materialization.entry.path),r=Qy({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:oT(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 oT(e,t){let n=new Map(e);for(let r of t.files)n.set(r.path,r.content);return n}function iT(e,t){let n=ex.posix.relative(ex.posix.dirname(e),t);return n.startsWith(".")?n:`./${n}`}function Wa(e,t){return{ok:!1,code:e,message:t}}import{PageTemplateIdSchema as hT}from"@vcp-dev/contracts";import vJ from"node:fs";import kJ from"node:path";var sT=/^page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function ji(e){let t=e.map(r=>gT(r.path)),n=aT(t);return n?t.filter(r=>lT(n,r)).map(r=>({routeId:uT(n,r),entryFile:r})).sort((r,o)=>r.routeId.localeCompare(o.routeId)):[]}function Fd(e,t=""){let r=((e??"/").trim()||"/").split(/[?#]/,1)[0]||"/",o=r.startsWith("/")?r:`/${r}`,i=mT(t),s=i&&(o===i||o.startsWith(`${i}/`))?o.slice(i.length)||"/":o,a=s.startsWith("/")?s:`/${s}`;return a==="/"?"/":a.replace(/\/+$/,"")}function aT(e){return e.some(r=>r.startsWith("app/")&&!cT(r))?"app":e.some(r=>r.startsWith("src/app/"))?"src/app":null}function cT(e){return/^(?:src\/)?app\/(?:_vcp|\.vcp)/.test(e)}function lT(e,t){if(!t.startsWith(`${e}/`))return!1;let n=t.slice(t.lastIndexOf("/")+1);return sT.test(n)?t.slice(e.length+1,-n.length-1).split("/").filter(Boolean).every(r=>!r.startsWith("_")&&!r.startsWith(".")):!1}function uT(e,t){let n=t.slice(e.length+1).split("/").slice(0,-1).map(fT).filter(r=>!!r);return n.length===0?"/":`/${n.join("/")}`}function dT(e){return e.startsWith("(")&&e.endsWith(")")}function fT(e){return!e||e.startsWith("@")||e.startsWith("_")||dT(e)?null:pT(e)}function pT(e){return e.replace(/^\((?:\.|\.\.|\.\.\.)\)/,"")}function mT(e){let t=e.trim();return!t||t==="/"?"":(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"")}function gT(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}var $i=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="PageTemplateManagedSourceError"}};function Ft(e,t={}){throw new $i("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Invalid page-template source (${e}): ${t.path??t.routeId??t.templateId??""}`,{reason:e,...t})}function Ld(e){return hT.safeParse(e).success||Ft("invalid-template-id",{templateId:e}),Buffer.from(e,"utf8").toString("base64url")}function nx(e){/^[A-Za-z0-9_-]{1,255}$/.test(e)||Ft("invalid-template-key",{path:e});let t;try{t=new TextDecoder("utf-8",{fatal:!0}).decode(Buffer.from(e,"base64url"))}catch{return Ft("invalid-template-key",{path:e})}return Ld(t)!==e&&Ft("noncanonical-template-key",{path:e}),t}function yT(e){let t=Fd(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("(")||xT(r)&&!rx(r)))&&Ft("invalid-public-route",{routeId:e}),t}function xT(e){return e.includes("[")||e.includes("]")}function rx(e){return/^\[\[\.\.\.[^\[\]]+\]\]$|^\[[^\[\]]+\]$/.test(e)}function ox(e){return e.some(rx)}function ix(e,t,n="app"){n!=="app"&&n!=="src/app"&&Ft("invalid-app-root");let r=yT(e),o=Ld(t),i=ox(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))&&Ft("path-too-long",{path:a}),{appRoot:n,routeRoot:s,templateKey:o,templateEntryFile:a}}function sx(e){return/^(?:src\/)?app\/\.vcp\/page-templates\//.test(e)}function ax(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===".")&&Ft("invalid-file-path",{path:i}),n.has(i)&&Ft("duplicate-file-path",{path:i}),n.set(i,o)}return n}function Ya(e){let t=ax(e.files),n=ji([...t.keys()].map(i=>({path:i}))),r=new Map;for(let i of n){if(r.has(i.routeId))throw new $i("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(!sx(i))continue;let s=/^(app|src\/app)\/\.vcp\/page-templates\/(.+)\/page\.tsx$/.exec(i);s||Ft("candidate-must-be-single-page",{path:i});let a=s[1],c=s[2].split("/"),l=ox(c),u=l?c[0]:c.pop(),d=l?c.slice(1):c,p=nx(u),m=d.length?`/${d.join("/")}`:"/";ix(m,p,a).templateEntryFile!==i&&Ft("candidate-path-mismatch",{path:i,routeId:m});let h=r.get(m);(!h||!h.startsWith(`${a}/`))&&Ft("canonical-entry-missing",{path:i,routeId:m}),o.push({routeId:m,templateId:p,entryFile:i,canonicalEntryFile:h,appRoot:a})}return o.sort((i,s)=>Ga(i.routeId,s.routeId)||Ga(i.templateId,s.templateId))}function Za(e){let t=ax(e.files),n=Ya({files:t}),r=ji([...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)=>Ga(o.context.routeId,i.context.routeId)||(o.context.effectiveTemplateId===void 0?-1:i.context.effectiveTemplateId===void 0?1:Ga(o.context.effectiveTemplateId,i.context.effectiveTemplateId)))}function bT(e){let t=Fd(e.selector.routeId),n=Za({files:e.files}),r=n.find(i=>i.context.routeId===t&&i.context.effectiveTemplateId===void 0);(!r||r.entryFile!==e.canonicalEntryFile)&&Ft("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||Ft("template-selection-not-found",{routeId:t,templateId:e.selector.templateId}),{...o,mode:e.selector.templateId===void 0?"direct":"candidate",effectiveEntryFile:o.entryFile}}function Ga(e,t){return e<t?-1:e>t?1:0}import{HOME_PAGE_URL_PATH as $T}from"@vcp-dev/contracts";import{parse as wT}from"@babel/parser";import{parse as OJ}from"@babel/parser";import{FormBlockIdSchema as LJ,FormSpecV1Schema as DJ}from"@vcp-dev/contracts";var Vi="components/site/generated/forms",MJ=`${Vi}/vcp-form-runtime.tsx`,qa="[A-Za-z0-9][A-Za-z0-9_-]{0,127}",BJ=new RegExp(`^${Vi}/form-(${qa})\\.spec\\.ts$`),jJ=new RegExp(`^${Vi}/form-(${qa})\\.tsx$`),$J=new RegExp(`^@/${Vi}/form-(${qa})$`),VJ=new RegExp(`(?:^|/)${Vi}/form-(${qa})(?:\\.tsx?)?$`);var UJ=Symbol("invalid-literal");import{createHash as XJ}from"node:crypto";import{posix as HJ}from"node:path";import{parse as GJ}from"@babel/parser";import{FormSpecV1Schema as ZJ}from"@vcp-dev/contracts";var qJ=Symbol("dynamic");import{parse as ET}from"@babel/parser";function Qa(e){return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&typeof t.type=="string"):[]}var ST=/^(?:src\/)?app\/(.*)page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function cx(e){let t=ST.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 vT(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 IT(e){let t=e;for(;t&&(t.type==="TSAsExpression"||t.type==="TSSatisfiesExpression"||t.type==="ParenthesizedExpression");)t=t.expression??null;return t}function Dd(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(Dd);if(t?.type==="ObjectExpression"){let n={};for(let r of Qa(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]=Dd(r.value)}return n}throw new Error(`unsupported static value: ${t?.type??"unknown"}`)}function Md(e,t){let n=[],r=cx(t);if(r===null)return{found:!1,seo:null,diagnostics:n};let o;try{o=ET(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 Qa(o.program.body)){let u=l.type==="ExportNamedDeclaration"?l.declaration:l;if(u?.type==="VariableDeclaration")for(let d of Qa(u.declarations)){let p=d.id;p?.type==="Identifier"&&p.name==="PAGE_SEO"&&(i=d.init)}}if(i==null)return{found:!1,seo:null,diagnostics:n};let s=IT(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 Qa(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=vT(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=Dd(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 kT}from"@babel/parser";var ux=["page","anchor","external","email","phone","group","file"],RT=["link","cta"],fx=["description","badge","iconKey"],Bd=["label","targetType","href","role","openInNewTab","nofollow","children",...fx],CT=new Set(Bd);function Ki(e){return Array.isArray(e)?e:[]}function Ui(e){let t=e;return t?.type==="StringLiteral"&&typeof t.value=="string"?t.value:void 0}function NT(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 jd(e){let t=[],n;try{n=kT(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 Ki(n.program.body)){let s=i.type==="ExportNamedDeclaration"?i.declaration:i;if(s?.type==="VariableDeclaration")for(let a of Ki(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 Ki(r.elements).forEach((i,s)=>{let a=px(i,`NAV_ITEMS[${s}]`,t);a&&o.push(a)}),{items:o,diagnostics:t}}function px(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 Ki(e.properties)){if(l.type!=="ObjectProperty"||l.computed)continue;let u=NT(l.key);u&&(r[u]=l.value)}let o=Ui(r.label),i=Ui(r.targetType);if(!o)return n.push({severity:"fatal",path:`${t}.label`,message:"label must be a static string"}),null;if(!i||!ux.includes(i))return n.push({severity:"fatal",path:`${t}.targetType`,message:`targetType must be one of ${ux.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 fx){if(r[l]===void 0)continue;let u=Ui(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))CT.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 ${Bd.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=[];Ki(r.children.elements).forEach((u,d)=>{let p=px(u,`${t}.children[${d}]`,n);p&&l.push(p)}),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=Ui(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=Ui(r.role);if(c!==void 0&&(RT.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 _T}from"@babel/parser";function Ji(e){return Array.isArray(e)?e:[]}function mx(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression";)t=t.expression;return t?.type==="ArrayExpression"?t:void 0}function PT(e){let t;try{t=_T(e,{sourceType:"module",plugins:["typescript","jsx"],tokens:!0})}catch{return{status:"unsupported"}}let n=[];for(let o of Ji(t.program.body)){let i=o.type==="ExportNamedDeclaration"?o.declaration:o;if(i?.type==="VariableDeclaration")for(let s of Ji(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=mx(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 $d(e,t){let n=gx(t);if(!n)return{status:"unsupported",source:e};let r=PT(e);if(r.status!=="ok")return{status:r.status,source:e};let o=r.array;if(jd(e).diagnostics.some(({severity:l})=>l==="fatal"))return{status:"unsupported",source:e};let s=[],a=l=>{let u=Ji(l.elements);for(let[d,p]of u.entries()){if(TT(p,n)){let f=u[d+1],h=u[d-1],y=p.start,x=p.end;if(typeof y!="number"||typeof x!="number")continue;if(f&&typeof f.start=="number")s.push({start:y,end:f.start});else if(h&&typeof h.end=="number")s.push({start:h.end,end:x});else{let E=/^\s*,/.exec(e.slice(x));s.push({start:y,end:E?x+E[0].length:x})}continue}let m=AT(p);m&&a(m)}};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 AT(e){if(e.type==="ObjectExpression")for(let t of Ji(e.properties)){if(t.type!=="ObjectProperty")continue;let n=t.key;if((n?.name??n?.value)==="children")return mx(t.value)}}function gx(e){let t=e.trim();return t.startsWith("/")?t==="/"?t:t.replace(/\/+$/,""):null}function TT(e,t){if(e.type!=="ObjectExpression")return!1;let n,r;for(let o of Ji(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"&&gx(n??"")===t}import{estimateNavLabelWidth as c1}from"@vcp-dev/contracts";import{parse as d1}from"@babel/parser";function zn(e,t){let n;try{n=wT(e,{sourceType:"module",sourceFilename:t.filePath,plugins:["jsx","typescript"]})}catch(A){let T=A.loc;return{form_codes:[],components:[],uncertain_components:[],rendered_component_openings:[],renders_native_form:!1,diagnostics:[{code:"rendered-module.parse-failed",message:A instanceof Error?A.message:"Rendered module failed Babel parsing.",file_path:t.filePath??"",line:T?.line??1}]}}let r=n.program,o=$t(r?.body),i=new Map,s=new Map,a=new Map,c=new Map,l=A=>{if(A?.type==="FunctionDeclaration"){let T=A.id;T?.type==="Identifier"&&typeof T.name=="string"&&s.set(T.name,A);return}if(A?.type==="VariableDeclaration")for(let T of $t(A.declarations)){let O=T.id,D=T.init;O?.type==="Identifier"&&typeof O.name=="string"&&D&&(pr(D)?s.set(O.name,D):D.type==="Identifier"&&typeof D.name=="string"&&a.set(O.name,D.name))}};for(let A of o){if(A.type==="ImportDeclaration"){let T=A.source?.value;if(typeof T!="string")continue;for(let O of $t(A.specifiers)){let D=O.local;if(!(D?.type!=="Identifier"||typeof D.name!="string")){if(O.type==="ImportDefaultSpecifier")i.set(D.name,{source:T,exportName:"default"});else if(O.type==="ImportNamespaceSpecifier")i.set(D.name,{source:T,exportName:"*"});else if(O.type==="ImportSpecifier"){let V=O.imported,Q=V?.type==="Identifier"&&typeof V.name=="string"?V.name:V?.type==="StringLiteral"&&typeof V.value=="string"?V.value:"";Q&&i.set(D.name,{source:T,exportName:Q})}}}continue}A.type==="ExportNamedDeclaration"?l(A.declaration):l(A)}for(let A of o){if(A.type==="ExportDefaultDeclaration"){let D=A.declaration;D&&pr(D)?c.set("default",D):D?.type==="Identifier"&&typeof D.name=="string"&&c.set("default",D.name);continue}if(A.type!=="ExportNamedDeclaration")continue;let T=A.declaration;if(T?.type==="FunctionDeclaration"){let D=T.id;D?.type==="Identifier"&&typeof D.name=="string"&&c.set(D.name,D.name)}else if(T?.type==="VariableDeclaration")for(let D of $t(T.declarations)){let V=D.id;V?.type==="Identifier"&&typeof V.name=="string"&&c.set(V.name,V.name)}let O=A.source?.value;for(let D of $t(A.specifiers)){let V=xx(D.local),Q=xx(D.exported);if(!(!V||!Q))if(typeof O=="string"){let U=`#re-export:${Q}`;i.set(U,{source:O,exportName:V}),c.set(Q,U)}else c.set(Q,V)}}let u=new Set,d=[],p=new Set,m=[],f=new Set,h=[],y=new Map,x=!1,E=[],b=new Map,S=new Map,N=(A,T="rendered")=>{let O=yx(A,i);if(!O)return!1;let D=`${O.source}\0${O.exportName}`;if(T==="uncertain")return!p.has(D)&&!f.has(D)&&(f.add(D),m.push({source:O.source,export_name:O.exportName})),!0;if(!p.has(D)&&(p.add(D),d.push({source:O.source,export_name:O.exportName}),f.delete(D))){let V=m.findIndex(Q=>Q.source===O.source&&Q.export_name===O.exportName);V>=0&&m.splice(V,1)}return!0},P=(A,T="rendered",O=[])=>{let D=`${T}\0${Ud(O)}`,V=b.get(A)??new Set,Q=S.get(A)??new Set;if(V.has(D)||Q.has(T))return;V.add(D),b.set(A,V),Q.add(T),S.set(A,Q);let U=new Map(s),H=new Map,ye=[],st=(xe,rt=!1)=>{if(ec(xe)){if(!rt&&pr(xe)){if(xe.type==="FunctionDeclaration"){let Te=xe.id;Te?.type==="Identifier"&&typeof Te.name=="string"&&U.set(Te.name,xe)}return}if(xe.type==="VariableDeclarator"){let Te=xe.id,ue=xe.init;Te?.type==="Identifier"&&typeof Te.name=="string"&&ue&&(pr(ue)?U.set(Te.name,ue):H.set(Te.name,ue))}else if(xe.type==="ReturnStatement"){let Te=xe.argument;Te&&ye.push(Te)}if(xe.type==="CallExpression"){let Te=xe.callee;if(Te?.type==="Import"&&E.push({code:"rendered-module.dynamic-import",message:"Rendered component graph must use static imports.",file_path:t.filePath??"",line:xe.loc?.start.line??1}),Xi(Te)==="cms.forms.getConfig"){let ue=$t(xe.arguments)[0];ue?.type==="StringLiteral"&&typeof ue.value=="string"&&ue.value.trim()?T==="rendered"?u.add(ue.value.trim()):E.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:xe.loc?.start.line??1}):E.push({code:"rendered-module.dynamic-form-code",message:"Rendered cms.forms.getConfig() requires a non-empty string literal.",file_path:t.filePath??"",line:xe.loc?.start.line??1})}}for(let[Te,ue]of Object.entries(xe))if(Te!=="loc")if(Array.isArray(ue))for(let Le of ue)st(Le);else st(ue)}};st(A,!0);let pt=new Set,Qo=new Set,on=(xe,rt=T,Te=O)=>{if(!(!ec(xe)||pr(xe))){if(xe.type==="Identifier"&&typeof xe.name=="string"){let ue=H.get(xe.name),Le=`${rt}\0${xe.name}\0${Ud(Te)}`;ue&&!pt.has(Le)&&!Qo.has(xe.name)?(pt.add(Le),Qo.add(xe.name),on(ue,rt,Te),Qo.delete(xe.name)):N(xe.name,rt);return}if(xe.type==="CallExpression"){let ue=xe.callee,Le=$t(xe.arguments),bt=Xi(ue),sn=ue?.type==="Identifier"&&typeof ue.name=="string"?i.get(ue.name):void 0;if(rt==="rendered"&&(bt==="createElement"||bt.endsWith(".createElement")||sn?.source==="react"&&sn.exportName==="createElement")&&Le[0]?.type==="StringLiteral"&&Le[0].value==="form"&&(x=!0),ue?.type==="Identifier"&&typeof ue.name=="string"){let Et=U.get(ue.name);if(Et){P(Et,rt,Te);return}}if(ue&&pr(ue)){P(ue,rt,Te);return}if(LT(ue)){for(let Et of Le)if(pr(Et))P(Et,rt,Te);else if(Et.type==="Identifier"&&typeof Et.name=="string"){let ks=U.get(Et.name);ks&&P(ks,rt,Te)}return}for(let Et of Le)DT(Et)&&E.push({code:"rendered-module.unresolved-export",message:"Unable to prove whether a JSX-producing call argument is rendered.",file_path:t.filePath??"",line:Et.loc?.start.line??1});return}if(xe.type==="JSXElement"){let ue=xe.openingElement,Le=ue?hx(Te,OT(ue)):Te;on(ue,rt,Le);for(let bt of $t(xe.children))on(bt,rt,Le);return}if(xe.type==="JSXOpeningElement"){let ue=tc(xe.name);rt==="rendered"&&ue==="form"&&(x=!0);let Le=ue?yx(ue,i):void 0;if(rt==="rendered"&&Le&&typeof xe.start=="number"){let bt=`${Le.source}\0${Le.exportName}\0${xe.start}`,sn=y.get(bt);if(!sn){let Et=MT(xe).get("formBlockId");sn={source:Le.source,export_name:Le.exportName,start_offset:xe.start,...typeof Et=="string"?{static_form_block_id:Et}:{}},y.set(bt,sn),h.push(sn)}Te.length>0&&(sn.static_render_blockers=hx(sn.static_render_blockers??[],Te))}if(ue&&!N(ue,rt)){let bt=U.get(ue);bt?P(bt,rt,Te):H.has(ue)?on(H.get(ue),rt,Te):FT(ue)||/^[A-Z]/.test(ue)&&E.push({code:"rendered-module.dynamic-import",message:`Unable to resolve rendered component ${ue} from a static import.`,file_path:t.filePath??"",line:xe.loc?.start.line??1})}for(let bt of $t(xe.attributes))on(bt,"uncertain",Te);return}if(xe.type==="JSXAttribute"){let ue=xe.value,Le=ue?.type==="JSXExpressionContainer"?ue.expression:ue;Le&&pr(Le)?P(Le,"uncertain",Te):on(Le,"uncertain",Te);return}for(let[ue,Le]of Object.entries(xe))if(!(ue==="loc"||ue==="closingElement"))if(Array.isArray(Le))for(let bt of Le)on(bt,rt,Te);else on(Le,rt,Te)}},ei=A.body;ei&&ei.type!=="BlockStatement"&&ye.push(ei);for(let xe of ye)on(xe);Q.delete(T)},R=c.get(t.exportName);if(typeof R=="string"){let A=R,T=new Set;for(;a.has(A)&&!T.has(A);)T.add(A),A=a.get(A);if(!N(A)){let O=s.get(A);O?P(O):E.push(bx(t))}}else R?P(R):E.push(bx(t));return{form_codes:[...u],components:d,uncertain_components:m,rendered_component_openings:h,renders_native_form:x,diagnostics:E}}function Ud(e){return e.map(t=>`${t.start_offset}:${t.reason}`).join("|")}function hx(e,t){return[...new Map([...e,...t].map(r=>[Ud([r]),r])).values()]}function OT(e){let t=new Map;for(let a of $t(e.attributes)){if(a.type==="JSXSpreadAttribute"){t.clear();continue}let c=Ex(a.name);if(!c)continue;let l=a.value;t.set(c,l?.type==="JSXExpressionContainer"?l.expression:l)}let n=tc(e.name)??"unknown",r=[],o=a=>{r.push({element_name:n,line:e.loc?.start.line??1,start_offset:jT(e.start),reason:a})};for(let a of["hidden","inert","aria-hidden","disabled"]){if(!t.has(a)||a==="disabled"&&n!=="fieldset")continue;let c=Vd(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 $t(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,Vd(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=Vd(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(p=>d.has(p.split(":").at(-1)))&&o(`className=${u}`)}return r}function Vd(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"&&$t(e.expressions).length===0)return $t(e.quasis)[0]?.value?.cooked}}function yx(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 FT(e){return e.endsWith(".Provider")||e.endsWith(".Consumer")}function pr(e){return e?.type==="FunctionDeclaration"||e?.type==="FunctionExpression"||e?.type==="ArrowFunctionExpression"}function LT(e){let t=Xi(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 DT(e){let t=!1;return Kd(e,n=>{if(!t){if(n.type==="JSXOpeningElement"){t=!0;return}n.type==="CallExpression"&&Xi(n.callee)==="cms.forms.getConfig"&&(t=!0)}}),t}function xx(e){return e?.type==="Identifier"&&typeof e.name=="string"?e.name:e?.type==="StringLiteral"&&typeof e.value=="string"?e.value:""}function bx(e){return{code:"rendered-module.unresolved-export",message:`Unable to resolve rendered export ${e.exportName}.`,file_path:e.filePath??"",line:1}}function Xi(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=Xi(e.object),n=e.property;return!t||n?.type!=="Identifier"||typeof n.name!="string"?"":`${t}.${n.name}`}function MT(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=Ex(o.name);i&&t.set(i,BT(o.value))}return t}function BT(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 Ex(e){let t=e;if(t?.type==="JSXIdentifier")return typeof t.name=="string"?t.name:void 0}function jT(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function Kd(e,t){if(ec(e)){t(e);for(let[n,r]of Object.entries(e))if(n!=="loc"){if(Array.isArray(r)){for(let o of r)Kd(o,t);continue}Kd(r,t)}}}function ec(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}function tc(e){let t=e;if(!t)return"";if(t.type==="JSXIdentifier")return typeof t.name=="string"?t.name:"";if(t.type==="JSXMemberExpression"){let n=tc(t.object),r=tc(t.property);return n&&r?`${n}.${r}`:r||n}return""}function $t(e){return Array.isArray(e)?e.filter(t=>ec(t)):[]}var VT="components/site/generated/",zi=[".tsx",".ts",".jsx",".js"];function Sx(e){if(e.expectedUrlPath===$T)return{ok:!1,code:"HOME_PAGE_LOCKED",message:"The homepage source is protected from deletion."};let t=new Set(ji(Object.keys(e.files).map(h=>({path:h}))).map(h=>h.entryFile)),n=Object.entries(e.files).filter(([h,y])=>{let x=h.replace(/\\/g,"/");if(!t.has(x))return!1;let E=Md(y,x);return E.found&&E.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 h=Ya({files:new Map(Object.entries(e.files))});for(let y of h)y.canonicalEntryFile===r&&o.add(y.entryFile)}catch(h){return{ok:!1,code:"SOURCE_DEPENDENCY_UNSAFE",message:h instanceof Error?h.message:"Invalid page template source."}}let i=UT(e.files);if(!i.ok)return i.error;let s=i.graph,a=zT(o,s),c=HT(o,a,s),l=[...a].filter(h=>!c.has(h)).sort((h,y)=>h.localeCompare(y)),u=[...o,...[...c].sort((h,y)=>h.localeCompare(y))],d=new Set(u),p=u.map(h=>({operation:"delete",file:h})),m=[],f=[];for(let[h,y]of Object.entries(e.files))if(!d.has(h)){if(y.includes("NAV_ITEMS")){let x=$d(y,e.expectedUrlPath);x.status==="removed"?(p.push({operation:"upsert",file:h,content:x.source}),m.push(h)):x.status==="unsupported"&&f.push(`unsupported_navigation:${h}`)}y.includes(e.expectedUrlPath)&&!y.includes("NAV_ITEMS")&&f.push(`preserved_link:${h}`)}return{ok:!0,edits:p,deletedFiles:u,updatedFiles:m,preservedSharedFiles:l,warnings:f}}function UT(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")||!KT(r))continue;let s=Ue(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(JT(c))continue;let l=xn(r,c),u=XT(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 KT(e){let t=e.toLowerCase();return zi.some(n=>t.endsWith(n))}function JT(e){return!!(/\.([a-z0-9]+)$/i.exec(e)&&!zi.some(n=>e.endsWith(n)))}function XT(e,t){let n=e.replace(/\\/g,"/");return(zi.some(o=>n.endsWith(o))?[n]:[...zi.map(o=>`${n}${o}`),...zi.map(o=>`${n}/index${o}`)]).find(o=>t.has(o))??null}function zT(e,t){let n=new Set,r=[...e].flatMap(o=>[...t.get(o)??[]]);for(;r.length>0;){let o=r.pop();!o.startsWith(VT)||n.has(o)||(n.add(o),r.push(...t.get(o)??[]))}return n}function HT(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 vb from"@babel/parser";import*as Ae from"@babel/types";import*as bc from"node:path";import*as Me from"@babel/types";function vx(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 Rn(e){if(e.path.isObjectPattern()||e.path.isArrayPattern())return zr(e.path.node,e.identifier.name);if(e.path.isVariableDeclarator()){let n=e.path.node.id;if(Me.isObjectPattern(n)||Me.isArrayPattern(n))return zr(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(GT(e.path,n))return!0}if(t.isFunction()||t.isVariableDeclarator())return!1;t=t.parentPath}return!1}function zr(e,t,n=!1){return Me.isIdentifier(e)?e.name===t&&n:Me.isObjectPattern(e)?e.properties.some(r=>Me.isObjectProperty(r)?zr(r.value,t,n):zr(r.argument,t,n)):Me.isArrayPattern(e)?e.elements.some(r=>{if(!r)return!1;let o=Me.isRestElement(r)?r.argument:r;return zr(o,t,n)}):Me.isAssignmentPattern(e)?zr(e.left,t,!0):Me.isRestElement(e)?zr(e.argument,t,n):!1}function Co(e,t){if(e.path.isObjectPattern()){if(t){let r=pn(e.path.node,t.base),[o,...i]=r??[];if(o?.kind==="property")return{propName:o.name,remainingPath:[...i,...t.path],hasDefault:Rn(e)}}return t?{propName:t.base,remainingPath:t.path,hasDefault:Rn(e)}:null}if(e.path.isVariableDeclarator()){let r=e.path.get("init");if(r?.isExpression()){let o=Ix(r),i=!1,s=o?o.initBinding&&Jd(o.initBinding)?(i=Rn(o.initBinding),[...o.initPathPrefix]):o.initBinding?(()=>{let c=Co(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=pn(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||Rn(e)}}}}let n=qT(e);if(n){let r=WT(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||Rn(e)}}if(n.findParent(s=>s.isVariableDeclarator()))return null;let o=YT(e);if(o){let[s,...a]=o;return!s||s.kind!=="property"?null:{propName:s.name,remainingPath:[...a,...t?.path??[]],hasDefault:Rn(e)}}let i=Hi(n.node);return i?{propName:i,remainingPath:t?.path??[],hasDefault:Rn(e)}:null}if(Jd(e)){let[r,...o]=t?.path??[];return!r||r.kind!=="property"?null:{propName:r.name,remainingPath:o,hasDefault:Rn(e)}}return null}function WT(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=Ix(r);if(!o)return null;let{initBinding:i,initPathPrefix:s}=o;if(!i)return null;let a=!1,c=Jd(i)?(a=Rn(i),[...s]):(()=>{let u=Co(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=pn(n.node.id,t.identifier.name);return l?{path:[...c,...l],hasDefault:a||Rn(t)}:null}function Ix(e){if(e.isIdentifier())return{initBinding:e.scope.getBinding(e.node.name),initPathPrefix:[]};if(!e.isMemberExpression())return null;let t=QT(e.node);return t?{initBinding:e.scope.getBinding(t.base),initPathPrefix:t.path}:null}function Jd(e){return e.path.isIdentifier()&&e.path.key===0&&Array.isArray(e.path.container)&&e.path.parentPath?.isFunction()===!0}function GT(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function YT(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=pn(i.node,t);if(a)return a}return null}function kx(e,t,n){if(e.path.isVariableDeclarator()){let a=e.path.get("id");if(!Array.isArray(a)&&(a.isObjectPattern()||a.isArrayPattern())){let c=nc(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=Hi(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=ZT(e);if(!r)return null;let o=r.parentPath;if(!o?.isObjectProperty())return null;let i=Hi(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 nc(e,t){if(e.isObjectPattern()){for(let n of e.get("properties"))if(n.isObjectProperty()){let r=Hi(n.node),o=n.get("value");if(o.isAssignmentPattern()){let i=o.get("left"),s=o.get("right");if(r&&!Array.isArray(i)&&pn(i.node,t)&&!Array.isArray(s)&&s.isExpression())return{propName:r,expressionPath:s}}if(!Array.isArray(o)&&(o.isObjectPattern()||o.isArrayPattern())){let i=nc(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=nc(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=nc(r,t);if(o)return o}}return null}function pn(e,t,n=[]){if(Me.isIdentifier(e))return e.name===t?n:null;if(Me.isObjectPattern(e)){for(let r of e.properties)if(Me.isObjectProperty(r)){let o=Hi(r);if(!o)continue;let i=pn(r.value,t,[...n,{kind:"property",name:o}]);if(i)return i}else if(Me.isRestElement(r)){let o=pn(r.argument,t,n);if(o)return o}}if(Me.isArrayPattern(e))for(let r=0;r<e.elements.length;r+=1){let o=e.elements[r];if(!o)continue;let i=Me.isRestElement(o)?o.argument:o,s=pn(i,t,[...n,{kind:"index",index:r}]);if(s)return s}return Me.isAssignmentPattern(e)?pn(e.left,t,n):null}function ZT(e){if(!e.path.isIdentifier())return null;let t=e.path.parentPath;return t?.isAssignmentPattern()&&t.node.left===e.path.node?t:null}function qT(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 Hi(e){return e.computed?null:Me.isIdentifier(e.key)?e.key.name:Me.isStringLiteral(e.key)?e.key.value:null}function QT(e){let t=[],n=e;for(;Me.isMemberExpression(n);){if(n.computed)if(Me.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(Me.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(Me.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return Me.isIdentifier(n)?{base:n.name,path:t}:null}import*as Ax from"@babel/parser";import Hd from"@babel/traverse";import*as No from"@babel/types";import*as Ie from"@babel/types";var Rx=new WeakMap;function ic(e,t=[]){if(e.isIdentifier()){let n=e.scope.getBinding(e.node.name);return n?rc(n,t):null}if(e.isMemberExpression()){let n=iw(e.node),r=ew(e.node);if(!n||r===null)return null;let o=e.scope.getBinding(n);return o?rc(o,[...r,...t]):null}return e.isAwaitExpression()||zd(e.node)?mr(aw(e.node),t,"awaited or fetched expression"):null}function ew(e){let t=[],n=e;for(;Ie.isMemberExpression(n);){if(n.computed)if(Ie.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(Ie.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(Ie.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return Ie.isIdentifier(n)?t:null}function rc(e,t=[],n){let r=tw(e,t);if(r)return r;let o=nw(e,t,n);if(o)return o;let i=rw(e,t,n);return i||null}function Gi(e){return e?.kind==="api-source"}function tw(e,t){if(e.path.isVariableDeclarator()&&Ie.isIdentifier(e.path.node.id)){let s=e.path.get("init");if(s?.isCallExpression()&&Xd(s.node)&&t[0]?.kind==="property"&&t[0].name==="data")return mr(e.identifier.name,t,"query hook result.data binding")}if(e.path.isVariableDeclarator()&&Ie.isObjectPattern(e.path.node.id)){let s=e.path.node.id.properties.find(c=>Ie.isObjectProperty(c)&&_x(c)==="data"&&Wi(c.value,e.identifier.name)),a=e.path.get("init");if(s&&a?.isCallExpression()&&Xd(a.node))return mr(e.identifier.name,t,"query hook data binding")}let n=ow(e);if(!n||_x(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()||!Xd(i.node)?null:mr(e.identifier.name,t,"query hook data binding")}function nw(e,t,n){if(e.path.isVariableDeclarator()&&Ie.isArrayPattern(e.path.node.id)){let c=e.path.get("init");if(!c?.isCallExpression()||!Nx(c.node))return null;let[l,u]=e.path.node.id.elements;return!Ie.isIdentifier(l)||l.name!==e.identifier.name||!Ie.isIdentifier(u)?null:Cx(e,u.name,n)?mr(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()||!Nx(i.node)||r.node.elements.findIndex(c=>c===e.path.node)!==0)return null;let a=r.node.elements[1];return Ie.isIdentifier(a)&&Cx(e,a.name,n)?mr(e.identifier.name,t,"state setter is updated by API data"):null}function rw(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()?mr(e.identifier.name,t,"awaited binding result"):zd(o.node,n)?mr(e.identifier.name,t,"fetch-backed binding result"):null:null}function ow(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 Wi(e,t){return Ie.isIdentifier(e)?e.name===t:Ie.isAssignmentPattern(e)?Wi(e.left,t):Ie.isObjectPattern(e)?e.properties.some(n=>Ie.isObjectProperty(n)?Wi(n.value,t):Wi(n.argument,t)):Ie.isArrayPattern(e)?e.elements.some(n=>!!n&&Wi(Ie.isRestElement(n)?n.argument:n,t)):!1}function Cx(e,t,n){let r=!1,o=!1,i=e.scope.path,s;if(n){let c=Rx.get(n);c||(c=new WeakMap,Rx.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){zd(c.node)&&(r=!0),(sw(c.node.callee,t)||c.node.arguments.some(l=>Ie.isIdentifier(l)&&l.name===t))&&(o=!0)}});let a=r&&o;return s?.set(t,a),a}function Xd(e){let t=sc(e.callee);return t==="useQuery"||t==="useSWR"||t==="useSuspenseQuery"}function Nx(e){return sc(e.callee)==="useState"}function zd(e,t){let n=t?.get(e);if(n!==void 0)return n;let r=oc(e,o=>Ie.isCallExpression(o)&&sc(o.callee)==="fetch");return t?.set(e,r),r}function iw(e){let t=e;for(;Ie.isMemberExpression(t);)t=t.object;return Ie.isIdentifier(t)?t.name:null}function _x(e){return e.computed?null:Ie.isIdentifier(e.key)?e.key.name:Ie.isStringLiteral(e.key)?e.key.value:null}function sc(e){return Ie.isIdentifier(e)?e.name:Ie.isMemberExpression(e)&&Ie.isIdentifier(e.property)?e.property.name:null}function sw(e,t){return oc(e,n=>Ie.isIdentifier(n)&&n.name===t)}function oc(e,t){if(t(e))return!0;let n=Ie.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(Ie.isNode(i)&&oc(i,t))return!0;continue}if(Ie.isNode(o)&&oc(o,t))return!0}return!1}function aw(e){return Ie.isIdentifier(e)?e.name:Ie.isCallExpression(e)?sc(e.callee)??"api":Ie.isAwaitExpression(e)?"awaited-api":"api"}function mr(e,t,n){return{kind:"api-source",readonly:!0,sourceId:e,displayPath:cw(e,t),reason:n}}function cw(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}var Tx=typeof Hd=="function"?Hd:Hd.default;function wx(e,t){let n=Fx(e);if(!n)return{allowed:!0};let r=!1;return Tx(n,{CallExpression(o){if(!Lx(o.node,t.sourceRange)||!lw(o.node))return;let i=o.get("callee");if(!i.isMemberExpression())return;let s=i.get("object");Array.isArray(s)||!s.isExpression()||Gi(ic(s))&&(r=!0,o.stop())}}),r?{allowed:!1,reason:"Cannot add data-backed items to a dynamic API list"}:{allowed:!0}}function Ox(e,t){let n=Fx(e);if(!n)return{allowed:!0};let r=!1;return Tx(n,{JSXExpressionContainer(o){Lx(o.node,t.sourceRange)&&(No.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 Fx(e){try{return Ax.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function lw(e){let t=e.callee;return No.isMemberExpression(t)&&No.isIdentifier(t.property)&&t.property.name==="map"}function Lx(e,t){let n=e.loc;return n?Px({line:n.start.line,column:n.start.column},{line:t.startLine,column:t.startColumn})>=0&&Px({line:n.end.line,column:n.end.column},{line:t.endLine,column:t.endColumn})<=0:!1}function Px(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 ee from"@babel/types";import*as Dx from"@babel/parser";import Wd from"@babel/traverse";import*as Ge from"@babel/types";import*as _o from"node:path";var mn=typeof Wd=="function"?Wd:Wd.default;function dt(e){try{return Dx.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function Gd(e){return e.computed?Ge.isStringLiteral(e.key)||Ge.isNumericLiteral(e.key)?String(e.key.value):null:uw(e.key)}function uw(e){return Ge.isIdentifier(e)?e.name:Ge.isStringLiteral(e)||Ge.isNumericLiteral(e)?String(e.value):null}function Hr(e){return Ge.isParenthesizedExpression(e)||Ge.isTSAsExpression(e)||Ge.isTSSatisfiesExpression(e)||Ge.isTSNonNullExpression(e)||Ge.isTSTypeAssertion(e)?Hr(e.expression):Ge.isExpression(e)?e:null}function Yd(e){if(Ge.isIdentifier(e))return[e.name];if((Ge.isMemberExpression(e)||Ge.isOptionalMemberExpression(e))&&!e.computed&&Ge.isIdentifier(e.property)){let t=Hr(e.object),n=t?Yd(t):null;return n?[...n,e.property.name]:null}return null}function Wr(e,t){return t.startsWith("@/")?t.slice(2).replace(/\\/g,"/"):t.startsWith(".")?_o.normalize(_o.join(_o.dirname(e),t)).replace(/\\/g,"/"):t}function Vt(e,t){return ac(e)===ac(t)}function ac(e){let t=Po(e);return t.endsWith("/index")?t.slice(0,-6):t}function Po(e){return e.replace(/\.(tsx|ts|jsx|js)$/,"")}function jx(e,t,n){let r=Kx(e,t);if(Jx(e,r),Xx(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 mn(e,{JSXElement(s){Gx(s,r)&&o.push(s)}}),o.length!==1?{ok:!1,reason:"Cannot move prop-backed repeat child without a single unambiguous component call site"}:cc(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 $x(e,t){let n=new Map,r=i=>{let s=Ao(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 dw(i,n))o=r(s)||o}return[...n.values()]}function dw(e,t){let n=[],r=fw(e,t);for(let o of e.ast.program.body){if(ee.isExportDefaultDeclaration(o)&&ee.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=Yi(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(ee.isExportNamedDeclaration(o)&&o.source&&typeof o.source.value=="string"){let i=Wr(e.file,o.source.value);for(let s of o.specifiers){if(ee.isExportNamespaceSpecifier(s)){let l=gr(s.exported);for(let u of t.values())Vt(u.file,i)&&n.push({file:e.file,namespace:Zd(l,u.namespace),exportName:u.exportName});continue}if(!ee.isExportSpecifier(s))continue;let a=gr(s.local),c=[...t.values()].filter(l=>Vt(l.file,i)&&Gr(l.namespace,a));if(c.length>0){let l=gr(s.exported);for(let u of c){let d=Yi(u.namespace,a,l);d&&n.push({file:e.file,namespace:d,exportName:u.exportName})}continue}t.has(Ao({file:i,exportName:a}))&&n.push({file:e.file,exportName:gr(s.exported)})}continue}if(ee.isExportNamedDeclaration(o)&&!o.source){for(let i of o.specifiers){if(!ee.isExportSpecifier(i))continue;let s=gr(i.local),a=r.get(s)??[];if(a.length>0){let c=gr(i.exported);n.push({file:e.file,exportName:c});for(let l of a){let u=Yi(l.namespace,s,c);u&&n.push({file:e.file,namespace:u,exportName:l.exportName})}}}continue}if(ee.isExportAllDeclaration(o)&&typeof o.source.value=="string"){let i=Wr(e.file,o.source.value),s=o.exported;if(s){let a=gr(s);for(let c of t.values())Vt(c.file,i)&&n.push({file:e.file,namespace:Zd(a,c.namespace),exportName:c.exportName});continue}for(let a of t.values())Vt(a.file,i)&&(a.namespace||a.exportName!=="default")&&n.push({file:e.file,namespace:a.namespace,exportName:a.exportName})}}return n}function Zd(e,t){return t?`${e}.${t}`:e}function Gr(e,t){return e===t||e?.startsWith(`${t}.`)===!0}function Yi(e,t,n){return!Gr(e,t)||!e?null:e===t?n:`${n}${e.slice(t.length)}`}function fw(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(!ee.isImportDeclaration(i)||typeof i.source.value!="string")continue;let s=Wr(e.file,i.source.value);for(let a of i.specifiers){if(ee.isImportDefaultSpecifier(a)){let c=t.get(Ao({file:s,exportName:"default"}));c&&r(a.local.name,c);let l=[...t.values()].filter(u=>Vt(u.file,s)&&Gr(u.namespace,"default"));for(let u of l){let d=Yi(u.namespace,"default",a.local.name);d&&r(a.local.name,{...u,namespace:d})}continue}if(ee.isImportSpecifier(a)){let c=gr(a.imported),l=[...t.values()].filter(d=>Vt(d.file,s)&&Gr(d.namespace,c));for(let d of l)r(a.local.name,d);let u=t.get(Ao({file:s,exportName:c}));u&&r(a.local.name,u);continue}if(ee.isImportNamespaceSpecifier(a))for(let c of t.values())Vt(c.file,s)&&r(a.local.name,{...c,namespace:Zd(a.local.name,c.namespace)})}}let o=!0;for(;o;){o=!1;for(let i of e.ast.program.body)if(ee.isVariableDeclaration(i))for(let s of i.declarations){if(!ee.isIdentifier(s.id)||!s.init)continue;let a=Hr(s.init);if(!a||!ee.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(Ao));for(let d of c){let p=Yi(d.namespace,a.name,s.id.name),m=p?{...d,namespace:p}:d,f=Ao(m);u.has(f)||(r(s.id.name,m),u.add(f),o=!0)}}}return n}function Ao(e){let t=e.namespace?`${e.namespace}.${e.exportName}`:e.exportName;return`${ac(e.file)}#${t}`}function gr(e){return ee.isIdentifier(e)?e.name:e.value}function Vx(e,t){for(let n of e.program.body){if(ee.isExportDefaultDeclaration(n)){let o=n.declaration;if((ee.isFunctionDeclaration(o)||ee.isClassDeclaration(o))&&o.id?.name===t)return{exportName:"default"};if(ee.isIdentifier(o)&&o.name===t)return{exportName:"default"}}if(!ee.isExportNamedDeclaration(n))continue;let r=n.declaration;if((ee.isFunctionDeclaration(r)||ee.isClassDeclaration(r))&&r.id?.name===t)return{exportName:t};if(ee.isVariableDeclaration(r)){for(let o of r.declarations)if(ee.isIdentifier(o.id,{name:t}))return{exportName:t}}for(let o of n.specifiers){if(!ee.isExportSpecifier(o)||o.local.name!==t)continue;return{exportName:ee.isIdentifier(o.exported)?o.exported.name:o.exported.value}}}return null}function Qd(e){let t=pw(e),n=[],r=Xx(e.ast,t);return mn(e.ast,{JSXElement(o){Vt(e.file,e.sourceFile)&&cc(o)===e.sourceComponent||Gx(o,t)&&n.push({file:e.file,path:o})}}),{callSites:n,hasUnsafeReference:r}}function Ux(){return{localBindings:new Set,namespaceMembers:new Map,hasUnsupportedAlias:!1}}function Kx(e,t){let n=Ux();return mn(e,{Program(r){let o=r.scope.getBinding(t);o&&n.localBindings.add(o),r.stop()}}),n}function pw(e){let t=Ux();return Vt(e.file,e.sourceFile)&&mw(t,Kx(e.ast,e.sourceComponent)),mn(e.ast,{ImportDeclaration(n){let r=n.node,o=r.source.value;if(typeof o!="string")return;let i=Wr(e.file,o),s=e.componentIdentities.filter(a=>Vt(a.file,i));if(s.length!==0)for(let a of r.specifiers){let c=n.scope.getBinding(a.local.name);if(c){if(ee.isImportDefaultSpecifier(a)&&s.some(l=>l.exportName==="default")&&t.localBindings.add(c),ee.isImportDefaultSpecifier(a)){let l=s.filter(u=>Gr(u.namespace,"default"));if(l.length>0){let u=t.namespaceMembers.get(c)??new Set;for(let d of l){let p=Bx(d,"default");p&&u.add(p)}t.namespaceMembers.set(c,u)}continue}if(ee.isImportSpecifier(a)){let l=ee.isIdentifier(a.imported)?a.imported.name:a.imported.value,u=s.filter(d=>Gr(d.namespace,l));if(u.length>0){let d=t.namespaceMembers.get(c)??new Set;for(let p of u){let m=Bx(p,l);m&&d.add(m)}t.namespaceMembers.set(c,d);continue}s.some(d=>!d.namespace&&d.exportName===l)&&t.localBindings.add(c);continue}if(ee.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)}}}}}),Jx(e.ast,t),t}function mw(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 Jx(e,t){mn(e,{VariableDeclarator(n){if(!n.node.init)return;let r=Hr(n.node.init);if(r){if(ee.isIdentifier(n.node.id)){let o=Yr(r,t,n),i=n.scope.getBinding(n.node.id.name);o&&i&&qd(t,i,o);return}if(ee.isObjectPattern(n.node.id)){let o=Yr(r,t,n);o?.unsupported||o?.local?t.hasUnsupportedAlias=!0:o&&o.namespaceMembers.size>0&&Wx(n.node.id,o.namespaceMembers,t,n)}}}})}function Xx(e,t){if(t.hasUnsupportedAlias)return!0;let n=!1;return mn(e,{ReferencedIdentifier(r){if(n){r.stop();return}gw(r)||!r.isIdentifier()||!zx(r,t)||hw(r,t)||yw(r)||(n=!0,r.stop())}}),n}function gw(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 zx(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)&&Yr(r.node,t,r)?r:null}function hw(e,t){let n=e.findParent(c=>c.isVariableDeclarator());if(!n?.isVariableDeclarator())return!1;let r=n.get("init");if(!r?.isExpression()||!Mx(e,r))return!1;let o=zx(e,t);if(!o)return!1;if(Hr(r.node)===o.node)return!!Yr(r.node,t,r);let s=e.findParent(c=>c.isObjectProperty());if(!s?.isObjectProperty())return!1;let a=s.get("value");return a.isExpression()&&Mx(e,a)&&!!Yr(a.node,t,a)}function yw(e){let t=e.parentPath;return t?.isExportDefaultDeclaration()&&t.node.declaration===e.node?!0:!!(t?.isExportSpecifier()&&t.node.local===e.node)}function Mx(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function Yr(e,t,n){let r=Hr(e);if(!r)return null;if(ee.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(ee.isObjectExpression(r))return xw(r,t,n);let o=Yd(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?Hx(s,o.slice(1).join(".")):null}function xw(e,t,n){let r=new Set,o=!1;for(let i of e.properties){if(!ee.isObjectProperty(i))continue;let s=Gd(i);if(!s||!ee.isExpression(i.value)){ee.isExpression(i.value)&&(o||=Yr(i.value,t,n)!==null);continue}let a=Yr(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 Hx(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 qd(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 Wx(e,t,n,r){for(let o of e.properties){if(ee.isRestElement(o)){if(ee.isIdentifier(o.argument)){let c=r.scope.getBinding(o.argument.name);c&&qd(n,c,{local:!1,namespaceMembers:new Set(t),unsupported:!1})}else n.hasUnsupportedAlias=!0;continue}if(!ee.isObjectProperty(o))continue;let i=Gd(o);if(!i){n.hasUnsupportedAlias=!0;continue}let s=Hx(t,i);if(!s)continue;n.hasUnsupportedAlias||=s.unsupported;let a=ee.isAssignmentPattern(o.value)?o.value.left:o.value;if(ee.isIdentifier(a)){let c=r.scope.getBinding(a.name);c&&qd(n,c,s);continue}if(ee.isObjectPattern(a)&&s.namespaceMembers.size>0){Wx(a,s.namespaceMembers,n,r);continue}n.hasUnsupportedAlias=!0}}function Bx(e,t){if(!Gr(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 Gx(e,t){let n=e.node.openingElement.name;if(ee.isJSXIdentifier(n)){let o=e.scope.getBinding(n.name);return!!(o&&t.localBindings.has(o))}let r=Yx(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 Yx(e){if(ee.isJSXIdentifier(e))return[e.name];if(ee.isJSXMemberExpression(e)){let t=Yx(e.object);return t?[...t,e.property.name]:null}return null}function cc(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()&&ee.isIdentifier(n.node.id))return n.node.id.name}return null}function Zx(e,t){let n=dt(e);if(!n||!t.tag||!t.importedFrom||!t.exportName)return Number.POSITIVE_INFINITY;let r=Qd({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 De(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 Oe(e){return typeof e.start=="number"&&typeof e.end=="number"?{start:e.start,end:e.end}:null}function Cn(e,t){let n=Oe(e);return!!(n&&Ut(t,n))}function Ut(e,t){return t.start>=e.start&&t.end<=e.end}function nn(e,t){let n=Ee(e,De(t));return n.ok&&n.match.path.isJSXElement()?n.match.path:lc(e,t)}function To(e,t){let n=Oe(t);return n?e.slice(n.start,n.end):""}function qx(e,t){return e.start===t.start&&e.end===t.end}function lc(e,t){let n=null;return mn(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 uc(e,t){return ef(e,t).length>0}function dc(e,t){let n=Oe(e.node),r=Oe(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()&&!bw(o,n,r)))return!0;o=o.parentPath}return!1}function bw(e,t,n){let r=Oe(e.node.consequent);if(r&&Ut(r,t)&&!Ut(r,n))return!1;let o=e.node.alternate?Oe(e.node.alternate):null;return!(o&&Ut(o,t)&&!Ut(o,n))}function ef(e,t){let n=Oe(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=Oe(o.node.consequent),a=Oe(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()&&tf(o.node.operator)){let s=Oe(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 tf(e){return e==="&&"||e==="||"||e==="??"}function Qx(e,t){let n=Oe(e.consequent);if(n&&Ut(n,t))return n;let r=Oe(e.alternate);return r&&Ut(r,t)?r:null}function eb(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=>Po(a.file)));if(!t.has(Po(e.sourceFile))||!t.has(Po(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(Po(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=Vx(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=dt(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=$x(r,{file:e.sourceFile,exportName:n.exportName}),i=[];for(let a of r){let c=Qd({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!Vt(s.file,e.targetFile)||cc(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 Rw}from"@vcp-dev/contracts";function fc(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 Zi();let a=s.target,c=a.locator;if(a.sourceKind==="repeat-template"){let l=o?.instanceIndex;if(l===void 0)return Zi();let u=Ew(a,l,o?.instanceCount);if(!u)return Zi();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"?Zi():{ok:!0,target:{kind:"jsx-attribute"}}}function Zi(){return{ok:!1,code:"unsupported-binding",reason:"Property does not have a safe typed binding write target for this scope and operation"}}function Ew(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 Nn from"@babel/types";import{SiteEditSetPropsParamsSchema as Sw}from"@vcp-dev/contracts";function tb(e){let t=e.changes??(e.change?[e.change]:[]);if(!Sw.safeParse({kind:"set-props",scope:"selection",changes:t}).success)return qi("invalid-change","Repeat property changes are invalid");if(t.length!==1||t[0].name!==e.target.propertyName)return qi("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=Je(e.source,"value");if(!o.ok)return qi("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=Ee(o.ast,a);if(!c.ok||!c.match.path.isObjectExpression())return qi("unsupported-object",`Repeat item ${s} is not a writable object expression`);let l=s===e.target.sourceItemIndex?vw(r):Iw(c.match.path.node,r.name);if(!l)return qi("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 vw(e){return e.operation==="set"?{kind:"value",value:e.value}:{kind:"undefined"}}function Iw(e,t){let n=e.properties.filter(i=>Nn.isObjectProperty(i)&&kw(i.key)===t);if(n.length>1)return null;let r=n[0];if(!r)return{kind:"undefined"};if(!Nn.isExpression(r.value))return null;let o=In(r.value);return o.status==="undefined"?{kind:"undefined"}:o.status!=="resolved"?null:{kind:"value",value:o.value}}function kw(e){return Nn.isIdentifier(e)?e.name:Nn.isStringLiteral(e)?e.value:Nn.isNumericLiteral(e)?String(e.value):null}function qi(e,t){return{ok:!1,errorCode:e,reason:t}}function nb(e){if(e.change.name!=="className"&&e.change.name!=="class")return Qi("unsupported-owner",`No specialized property owner is available for '${e.change.name}'`);let t=e.classNameSource;if(!t||t.filePath!==e.node.file)return Qi("owner-source-unavailable","className source details are unavailable for the selected node");if(e.change.name==="class"&&t.sourceKind==="missing")return Qi("owner-source-unavailable","The class alias requires an existing className source");if(t.sourceKind==="expression")return Qi("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 Qi("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 Qi(e,t){return{ok:!1,errorCode:e,reason:t}}async function ob(e){let t=Rw.safeParse({kind:"set-props",scope:e.scope,changes:e.changes});if(!t.success)return hr("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 hr("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 Cw(e,r);if(o){if(!o.ok)return hr("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 hr("missing-property-state",`No authoritative property state is available for '${r.name}'`);if(i.status==="blocked")return hr("readonly-property",i.diagnostic?.message??`Property '${r.name}' is not writable`);if(Pw(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=fc({state:i,scope:e.scope,operation:r.operation,selectionRef:e.selectionRef,repeatTarget:s});if(!a.ok)return hr(a.code,a.reason);let c=a.target;if(c.kind==="value-binding"&&r.operation==="set"){nf(n,{type:"update-value",order:n.length,file:c.file,locator:c.locator,value:r.value});continue}if(c.kind==="repeat-property"){let l=tb({source:e.getFileContent(c.target.sourceFile),target:c.target,changes:[r]});if(!l.ok)return hr("repeat-target-failed",l.reason);rb(n,l.steps);continue}nf(n,{type:"set-property-changes",order:n.length,file:e.node.file,locator:Nw(e.node),scope:e.scope,changes:[r]})}return n.forEach((r,o)=>{r.order=o}),_w(n)?hr("step-conflict","Property changes resolve to conflicting write steps"):{ok:!0,steps:n}}async function Cw(e,t){return t.name!=="className"&&t.name!=="class"?null:nb({node:e.node,change:t,classNameSource:e.classNameSource})}function Nw(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 _w(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)nf(e,{...n,order:e.length})}function nf(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 Pw(e,t){if(t.operation!=="set"||e.status!=="direct")return!1;let n=e.attribute?.resolution;return n?.status==="resolved"?rf(n.value,t.value):e.attribute?.source===null&&e.attribute.value===t.value}function rf(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)=>rf(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=>rf(n[i],r[i]))}return!1}function hr(e,t){return{ok:!1,errorCode:e,reason:t}}import*as Oo from"@babel/types";import*as ie from"@babel/types";function of(e,t,n){let r=nn(t,n);return r?_n(e,r):null}function _n(e,t){let n=t.findParent(h=>h.isArrowFunctionExpression()||h.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(h=>h===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(!ie.isIdentifier(l)||l.name!=="map"||c.computed)return null;let u=a.get("object"),d=To(e,u.node),p=r.node.params.map(h=>To(e,h)),m=Oe(i.node),f=Oe(r.node);return!d||p.some(h=>h.length===0)||!m||!f?null:{callStart:m.start,callEnd:m.end,callbackStart:f.start,callbackEnd:f.end,collectionExpression:d,callbackParams:p,mapOperator:ie.isOptionalMemberExpression(c)&&c.optional?"?.map":".map",collectionNeedsParens:pc(u.node),callbackPath:r,collectionPath:u}}function es(e,t){return!!(e&&t&&e.callStart===t.callStart&&e.callEnd===t.callEnd&&e.callbackStart===t.callbackStart&&e.callbackEnd===t.callbackEnd)}function Aw(e,t){let n=Oe(e.node);return n?Tw(t).some(r=>{let o=Oe(r);return r===e.node||!!(o&&o.start===n.start&&o.end===n.end)}):!1}function Tw(e){let t=e.callbackPath.node.body;return ie.isBlockStatement(t)?yr(t.body):xr(t)}function yr(e){let t=[];for(let n of e){if(ie.isReturnStatement(n)){n.argument&&t.push(...xr(n.argument));continue}if(ie.isBlockStatement(n)){t.push(...yr(n.body));continue}if(ie.isIfStatement(n)){let r=ie.isBlockStatement(n.consequent)?n.consequent.body:[n.consequent];if(t.push(...yr(r)),n.alternate){let o=ie.isBlockStatement(n.alternate)?n.alternate.body:[n.alternate];t.push(...yr(o))}continue}if(ie.isSwitchStatement(n)){for(let r of n.cases)t.push(...yr(r.consequent));continue}ie.isTryStatement(n)&&(t.push(...yr(n.block.body)),n.handler&&t.push(...yr(n.handler.body.body)),n.finalizer&&t.push(...yr(n.finalizer.body)))}return t}function xr(e){return ie.isJSXElement(e)?ww(e)?ib(e.children):[e]:ie.isJSXFragment(e)?ib(e.children):ie.isParenthesizedExpression(e)||ie.isTSAsExpression(e)||ie.isTSSatisfiesExpression(e)||ie.isTSNonNullExpression(e)||ie.isTSTypeAssertion(e)?xr(e.expression):ie.isConditionalExpression(e)?[...xr(e.consequent),...xr(e.alternate)]:ie.isLogicalExpression(e)&&tf(e.operator)?xr(e.right):[]}function ib(e){return e.flatMap(t=>ie.isJSXElement(t)||ie.isJSXFragment(t)?xr(t):ie.isJSXExpressionContainer(t)&&(ie.isJSXElement(t.expression)||ie.isJSXFragment(t.expression)||ie.isConditionalExpression(t.expression)||ie.isLogicalExpression(t.expression))?xr(t.expression):[])}function ww(e){let t=e.openingElement.name;return ie.isJSXIdentifier(t)?t.name==="Fragment":ie.isJSXMemberExpression(t)&&t.property.name==="Fragment"}function sb(e,t){return!!(e&&t&&e.callbackStart<t.callbackStart&&e.callbackEnd>t.callbackEnd)}function pc(e){return!(ie.isIdentifier(e)||ie.isThisExpression(e)||ie.isMemberExpression(e)||ie.isOptionalMemberExpression(e)||ie.isCallExpression(e)||ie.isOptionalCallExpression(e))}function ab(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(ie.isMemberExpression(n)||ie.isOptionalMemberExpression(n))&&ie.isIdentifier(n.property)&&n.property.name==="map"&&!n.computed}function wo(e,t){let n=dt(e);if(!n)return t.isRepeatItemRoot===!0;let r=Ee(n,De(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:lc(n,t);if(!o)return t.isRepeatItemRoot===!0;let i=_n(e,o);return i?Aw(o,i):t.isRepeatItemRoot===!0}function cb(e,t){let n=dt(e);if(!n)return!1;let r=Ee(n,De(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:lc(n,t);return o?!!o.findParent(i=>{if(!i.isCallExpression()&&!i.isOptionalCallExpression())return!1;let s=i.node.callee;return(ie.isMemberExpression(s)||ie.isOptionalMemberExpression(s))&&ie.isIdentifier(s.property)&&s.property.name==="map"}):!1}import*as $e from"@babel/types";function sf(e){if($e.isJSXIdentifier(e))return/^[A-Z]/.test(e.name)?e.name:null;if($e.isJSXMemberExpression(e)){let t=e;for(;$e.isJSXMemberExpression(t);)t=t.object;return t.name}return null}function Ow(e,t){let n=Oe(e.node);if(!n)return[];let r=new Set,o=(i,s)=>{let a=s.scope.getBinding(i);!a||Cn(a.path.node,n)||br(a,i,t)||r.add(i)};return e.traverse({ReferencedIdentifier(i){o(i.node.name,i)},JSXOpeningElement(i){let s=sf(i.node.name);s&&o(s,i)}}),[...r].sort()}function af(e,t,n){let r=dt(e);if(!r)return{ok:!0};let o=Ee(r,De(t));if(!o.ok||!o.match.path.isJSXElement())return{ok:!0};let i=Ee(r,De(n));if(!i.ok||!i.match.path.isJSXElement())return{ok:!0};let s=di(o.match.path,i.match.path);if(uc(s,i.match.path))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let a=Ow(s,i.match.path);return a.length>0?{ok:!1,bindingNames:a}:{ok:!0}}function ub(e){let t=e;for(;$e.isTSQualifiedName(t);)t=t.left;return $e.isIdentifier(t)?t.name:null}function ts(e,t){e.isIdentifier()&&e.isReferencedIdentifier()&&t(e),e.traverse({ReferencedIdentifier(n){n.isIdentifier()&&t(n)}})}function mc(e){let t=[],n=r=>{if(r){if($e.isIdentifier(r)){t.push(r.name);return}if($e.isObjectPattern(r)){for(let o of r.properties){if($e.isRestElement(o)){n(o.argument);continue}$e.isObjectProperty(o)&&n(o.value)}return}if($e.isArrayPattern(r)){for(let o of r.elements)n(o);return}if($e.isAssignmentPattern(r)){n(r.left);return}if($e.isRestElement(r)){n(r.argument);return}$e.isTSParameterProperty(r)&&n(r.parameter)}};return n(e),t}function cf(e,t){let n=Oe(e.node),r=Oe(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||!qx(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=Qx(s.node,n);if(a&&!Ut(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=Oe(s.node.right);if(a&&Ut(a,n)&&!Ut(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())&&ab(s)){let a=Oe(s.node.body)??Oe(s.node);if(a&&!Ut(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?Oe(t.node.argument):null;if(t.isArrowFunctionExpression()&&($e.isJSXElement(t.node.body)||$e.isJSXFragment(t.node.body)||$e.isConditionalExpression(t.node.body)||$e.isLogicalExpression(t.node.body)))return Oe(t.node.body);t=t.parentPath}return null}function br(e,t,n){return n.scope.getBinding(t)===e}function lf(e,t,n,r={}){if(!r.preserveConditionalBoundary&&uc(e,t))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let o=Oe(e.node);if(!o)return{ok:!0};let i=new Set(n.callbackPath.node.params.flatMap(c=>mc(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||Cn(u.path.node,o)||i.has(u.path.node)||br(u,c,t)||s.add(c)};return e.traverse({ReferencedIdentifier(c){a(c.node.name,c)},JSXOpeningElement(c){let l=sf(c.node.name);l&&a(l,c)}}),s.size>0?{ok:!1,bindingNames:[...s].sort()}:{ok:!0}}function uf(e,t,n){let r=Oe(e.node);if(!r)return{ok:!0};let o=new Set(n.callbackPath.node.params.flatMap(s=>mc(s)).map(s=>n.callbackPath.scope.getBinding(s)?.path.node).filter(Boolean)),i=new Set;return ts(e,s=>{let a=s.scope.getBinding(s.node.name);!a||Cn(a.path.node,r)||o.has(a.path.node)||br(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=>mc(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)||br(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(Oo.isIdentifier(l))o(l.name,c);else{let u=ub(l);u&&o(u,c)}}});return r.size>0?{ok:!1,bindingNames:[...r].sort()}:{ok:!0}}function df(e,t){let n=Oe(e.node),r=new Set;return ts(e,o=>{let i=o.scope.getBinding(o.node.name);i&&(n&&Cn(i.path.node,n)||br(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 fb(e){let t=[];for(let n of e.callbackPath.node.params){if(Oo.isIdentifier(n)){t.push(n.name);continue}if(Oo.isRestElement(n)&&Oo.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 pb(e,t){return{...e,callbackParams:t}}function ff(e,t){return`${e.collectionNeedsParens?`(${e.collectionExpression})`:e.collectionExpression}${e.mapOperator}((${e.callbackParams.join(", ")}) => ${t})`}function ns(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 mb(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 Zr(e){return{file:e.file,component:e.component}}function Fw(e){return e.target.kind==="node"?e.target.key:null}function Lw(e){return"kind"in e&&e.kind==="page-composition"}function yc(e){return typeof e=="object"&&e!==null&&"kind"in e&&e.kind==="block-boundary"}function gc(e){return!Lw(e)&&!yc(e)}function yf(e,t){let n=bc.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=bc.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function pf(e,t){let n=e.getFileContent(t.file);if(!n)return;let r=Sn(n,De(t));if(r.ok)return n.slice(r.match.start,r.match.end)}function bf(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 Dw(e){if(e.isNumericLiteral())return!0;if(!e.isUnaryExpression({operator:"-"}))return!1;let t=e.get("argument");return!Array.isArray(t)&&t.isNumericLiteral()}function Mw(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 mf(e){return e==="Cannot edit repeat-backed child node structure with a generic node operation"}function Bw(e){let t=jx(e.ast,e.sourceNode.component,e.targetParent.component);if(!t.ok)return{ok:!1,reason:t.reason};let n=cf(t.path,e.targetParentPath);if(!n.ok)return{ok:!1,reason:n.reason};let r=jw({source:e.source,sourceContext:e.sourceContext,callSitePath:t.path,targetParentPath:e.targetParentPath});if(!r.ok)return r;let o=Ib(r.collectionExpression);return{ok:!0,context:{...e.sourceContext,collectionExpression:r.collectionExpression,collectionNeedsParens:o?pc(o):!0}}}function jw(e){let t=Oe(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||Cn(a.path.node,t))return;let c=Uw(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=Jw(e.callSitePath,c.propName,e.source);if(!l.ok){o=l.reason;return}let u=$w(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=df(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}br(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:Xw(e.source,t,[...n.values()])}}function $w(e,t){if(t.length===0)return e;let n=Ib(e);if(!n)return null;let r=pc(n)?`(${e})`:e;for(let o of t){if(o.kind==="property"){r=Vw(o.name)?`${r}.${o.name}`:`${r}[${JSON.stringify(o.name)}]`;continue}r=`${r}[${o.index}]`}return r}function Vw(e){return/^[$A-Z_a-z][$\w]*$/.test(e)}function Uw(e,t,n){let r=Kw(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=Co(t,o);if(!i)return null;let s=r?.range??Oe(e.node);return s?{propName:i.propName,remainingPath:i.remainingPath,hasDefault:i.hasDefault,range:s}:null}function Kw(e,t){let n=e.parentPath;if(!n||!n.isMemberExpression()&&!n.isOptionalMemberExpression()||n.node.object!==e.node||!Cn(n.node,t)||n.node.computed||!Ae.isIdentifier(n.node.property))return null;let r=Oe(n.node);return r?{propertyName:n.node.property.name,range:r}:null}function Jw(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()&&Ae.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=To(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 Xw(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 Ib(e){try{let n=vb.parse(`const __VD_EXPR__ = (${e});`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0],r=Ae.isVariableDeclaration(n)?n.declarations[0]?.init:null;return r&&Ae.isExpression(r)?r:null}catch{return null}}function zw(e){let t=Oe(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||Cn(s.path.node,t))return;let a=gb(s,e.sourceFile,e.targetFile);if(a){let c=e.targetParentPath.scope.getBinding(a.localName);if(c){let u=gb(c,e.targetFile,e.targetFile);(!u||u.moduleFile!==a.moduleFile||!Hw(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 ts(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 Hw(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 gb(e,t,n){let r=Ww(e),o=r?.parentPath;if(!r||!o?.isImportDeclaration())return null;let i=o.node.source.value;if(typeof i!="string")return null;let s=Wr(t,i),a=i.startsWith(".")?yf(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=Ae.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 Ww(e){let t=e.path;for(;t&&!t.isImportDeclaration();){if(t.isImportSpecifier()||t.isImportDefaultSpecifier()||t.isImportNamespaceSpecifier())return t;t=t.parentPath}return null}function hb(e,t,n,r){let o=ef(t,n);if(o.length===0)return{sourceJsx:r,conditionPaths:[]};let i=r,s=[];for(let a of o){let c=To(e,a.conditionPath.node);if(!c)return{sourceJsx:r,conditionPaths:[]};let l=Gw(a.conditionPath,c);if(s.push(a.conditionPath),a.kind==="logical"){i=`${l} ${a.operator} ${Zw(i)}`;continue}i=a.branch==="consequent"?`${l} ? ${i} : null`:`${l} ? null : ${i}`}return{sourceJsx:i,conditionPaths:s}}function Gw(e,t){return Yw(e.node)?t:`(${t})`}function Yw(e){return Ae.isIdentifier(e)||Ae.isThisExpression(e)||Ae.isSuper(e)||Ae.isMemberExpression(e)||Ae.isOptionalMemberExpression(e)||Ae.isCallExpression(e)||Ae.isOptionalCallExpression(e)||Ae.isBooleanLiteral(e)||Ae.isNumericLiteral(e)||Ae.isStringLiteral(e)||Ae.isNullLiteral(e)||Ae.isUnaryExpression(e)}function Zw(e){return e.trim().startsWith("<")?e:`(${e})`}var qw={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 hc(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=qw[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 Qw(e,t){for(let n of e.program.body){if(!Ae.isImportDeclaration(n)||n.source.value!==t)continue;let r=n.specifiers.find(o=>Ae.isImportDefaultSpecifier(o));if(r&&Ae.isImportDefaultSpecifier(r))return r.local.name}return null}function eO(e,t,n){for(let r of e.program.body){if(!Ae.isImportDeclaration(r)||r.source.value!==t)continue;let o=r.specifiers.find(i=>Ae.isImportSpecifier(i)&&(Ae.isIdentifier(i.imported)?i.imported.name:i.imported.value)===n);if(o&&Ae.isImportSpecifier(o))return o.local.name}return null}function yb(e){let t=new Set;return mn(e,{Program(n){for(let r of Object.keys(n.scope.bindings))t.add(r);n.stop()}}),t}function xb(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n+=1;return`${e}${n}`}function tO(e,t){if(!e.component)return{localName:"Component"};let n=e.component,r=bf(e),o=dt(t);if(n.exportName!=="default"){let a=o?eO(o,n.source,n.exportName):null;if(a)return{localName:a};let c=o?xb(r,yb(o)):r;return{localName:c,importStep:gf(e,c)}}if(!o)return{localName:r,importStep:gf(e,r)};let i=Qw(o,n.source);if(i)return{localName:i};let s=xb(r,yb(o));return{localName:s,importStep:gf(e,s)}}function nO(e,t){if(e.kind==="native-tag")return e.text?`<${e.tag}>${e.text}</${e.tag}>`:`<${e.tag} />`;let n=t??bf(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 rO(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?oO(e.props):void 0;return{kind:e.kind,component:{source:e.component.source,exportName:e.component.exportName},...t?{props:t}:{}}}function oO(e){return Object.fromEntries(Object.entries(e).filter(t=>xf(t[1])))}function xf(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(xf):typeof e=="object"?Object.values(e).every(xf):!1}function gf(e,t=bf(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 bb(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 iO(e,t,n){let r=e;for(;r;){if(r===t)return!0;r=n.getNode(r)?.parentKey}return!1}function Fo(e,t){return`Operation kind '${e}' does not match params.kind '${t}'`}function Ef(e,t=e.path){return{kind:"value",root:e.root,path:t&&t.length>0?t:void 0,expectedRange:e.expectedRange}}function rs(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:Ef(e,t.slice(0,n)),index:r.index}}return null}function hf(e,t){return e.locator?e.collectionPathMap?.[t]?Ef(e.locator,e.collectionPathMap[t]):rs(e.locator)?aO(e.locator,cO(t,e.collectionIndexMap)):null:null}function sO(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:kb(o,t)}function kb(e,t){let[n,...r]=e;if(!n)return t;if(n.kind!=="property")return;let o=kb(r,t);return o===void 0?void 0:{[n.name]:o}}function aO(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},Ef(e,i)}return null}function cO(e,t){return t?.[e]??e}function Eb(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 lO(e,t){return uO(e.root,t.root)&&fO(e.path??[],t.path??[])}function uO(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&&dO(e.sourceRange,t.sourceRange)}}function dO(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function fO(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 xc=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:Fo(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:Fo(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:Fo(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:Fo(t.kind,t.params.kind)};let r=t;if(yc(r.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page-block boundaries require the page-block resolver"};if(!gc(r.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};let o=bb(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:Fo(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:Fo(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=Fw(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):Sb(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 Sb(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:De(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?ob({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(m=>m.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 m=u.locator;if(u.sourceKind==="repeat-template"&&typeof i?.instanceIndex=="number"){let f=hf(u,i.instanceIndex);if(!f)return{ok:!1,errorCode:"invalid-params",reason:"apply-style-draft could not resolve the selected repeat item"};m=f}s.push({order:n+s.length,file:u.file,type:"update-value",locator:m,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:De(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=hf(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:De(t),segmentIndex:n,newText:r}]}}coerceTextValueForValueTarget(t,n,r,o="update-text"){let i=this.graph.getFileContent(t),s=dt(i);if(!s)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not inspect the value source`};let a=Ee(s,n);if(!a.ok)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not resolve the value source`};if(!Dw(a.match.path))return{ok:!0,value:r};let c=Mw(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=hf(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=dt(this.graph.getFileContent(t));if(!o)return!1;let i=Ee(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 p=rs(d.locator);if(p)return this.buildPlan(t,n,[{order:0,file:d.file,type:"remove-bound-array-item",locator:p.locator,index:p.index}],o)}return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed node removal requires a writable array target"}}let s=ns(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:De(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||Zx(n,t)>1)return null;let r=yf(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(!gc(n.params.position))return yc(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=ns(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 p=this.getRepeatBackedTemplateStructureReason(r);if(p)return{ok:!1,errorCode:"unsupported-operation",reason:p};let m=wx(this.graph.getFileContent(r.file),r);if(!m.allowed)return{ok:!1,errorCode:"unsupported-operation",reason:m.reason??"Cannot insert child into this node"};let f=hc(r,n.params.node);if(f)return{ok:!1,errorCode:"unsupported-operation",reason:f};let h=[],y=0,x=n.params.node.kind==="component-call"?tO(n.params.node,this.graph.getFileContent(r.file)):void 0,E=x?.importStep;return E&&h.push({order:y++,file:r.file,type:"add-import",moduleSpecifier:E.moduleSpecifier,imports:E.imports}),h.push({order:y++,file:r.file,type:"insert-child",parentLocator:De(r),node:{jsx:nO(n.params.node,x?.localName)},placement:n.params.position.relation,anchorLocator:i?De(i):void 0}),this.buildPlan(t,n,h,o)}async planExternalBackedInsertChild(t,n,r,o,i,s){if(!gc(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:rO(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(!gc(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=rs(a.locator);if(!c)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child requires an array-backed target"};let l=sO(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"?Eb(0,a.collectionIndexMap):Eb(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=ns(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 wo(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:")||cb(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&&wo(this.graph.getFileContent(r.file),r)||r.file!==o.file)return null;let c=this.graph.getFileContent(r.file),l=dt(c);if(!l)return null;let u=nn(l,r),d=nn(l,o);if(!u||!d)return null;let p=_n(c,u),m=_n(c,d);if(!es(p,m))return null;if(a&&(s==="before"||s==="after")){let h=nn(l,a),y=h?_n(c,h):null;if(!es(p,y))return null}if(dc(u,d))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child across statement-level conditional branches"};let f=af(c,r,o);return f.ok?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:De(r),targetParentLocator:De(o),placement:s,anchorLocator:a?De(a):void 0,selectionContext:Zr(o)}],i):{ok:!1,errorCode:"unsupported-operation",reason:f.reason??`Cannot move node because it depends on bindings outside the target scope: ${f.bindingNames.join(", ")}`}}planRepeatTemplateHoistMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&wo(this.graph.getFileContent(r.file),r)||r.file!==o.file)return null;let c=this.graph.getFileContent(r.file),l=dt(c);if(!l)return null;let u=nn(l,r),d=nn(l,o);if(!u||!d)return null;let p=_n(c,u);if(!p)return null;let m=_n(c,d);if(es(p,m))return null;if(m&&!sb(m,p))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=of(c,l,a);if(m&&!es(m,b)||!m&&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=hc(o,{kind:"native-tag",tag:r.tag});if(b)return{ok:!1,errorCode:"unsupported-operation",reason:b}}let f=pf(this.graph,r);if(!f)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(dc(u,d))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let h=hb(c,u,d,f);for(let b of h.conditionPaths){let S=uf(b,d,p);if(!S.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its condition depends on bindings outside the target scope: ${S.bindingNames.join(", ")}`}}let y=lf(u,d,p,{preserveConditionalBoundary:h.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(p,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 E=p;if(r.component!==o.component){let b=Bw({source:c,ast:l,sourceContext:p,sourceNode:r,targetParent:o,targetParentPath:d});if(!b.ok)return{ok:!1,errorCode:"unsupported-operation",reason:b.reason};E=b.context}else{let b=df(p.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:De(r),targetParentLocator:De(o),placement:s,anchorLocator:a?De(a):void 0,repeatExpression:ff(E,h.sourceJsx),selectionContext:Zr(o)}],i)}planCrossFileRepeatTemplateHoistMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&wo(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=dt(c),d=dt(l);if(!u||!d)return null;let p=eb({knownSourceFiles:this.graph.getKnownSourceFiles?.(),routeEntryFiles:this.graph.getRouteEntryFiles?.(),sourceAst:u,sourceFile:r.file,targetFile:o.file,sourceComponent:r.component,targetComponent:o.component});if(!p.ok)return{ok:!1,errorCode:"unsupported-operation",reason:p.reason};let m=nn(u,r),f=nn(d,o);if(!m||!f)return null;let h=cf(p.callSitePath,f);if(!h.ok)return{ok:!1,errorCode:"unsupported-operation",reason:h.reason};let y=_n(c,m);if(!y)return null;if(_n(l,f))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child into a different repeat template"};if(a&&(s==="before"||s==="after")&&of(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 T=hc(o,{kind:"native-tag",tag:r.tag});if(T)return{ok:!1,errorCode:"unsupported-operation",reason:T}}let E=pf(this.graph,r);if(!E)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(dc(m,f))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let b=hb(c,m,f,E);for(let T of b.conditionPaths){let O=uf(T,f,y);if(!O.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its condition depends on bindings outside the target scope: ${O.bindingNames.join(", ")}`}}let S=lf(m,f,y,{preserveConditionalBoundary:b.conditionPaths.length>0});if(!S.ok)return{ok:!1,errorCode:"unsupported-operation",reason:S.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${S.bindingNames.join(", ")}`};let N=zw({sourceFile:r.file,targetFile:o.file,sourceContext:y,targetParentPath:f});if(!N.ok)return{ok:!1,errorCode:"unsupported-operation",reason:N.reason};let P=fb(y);if(!P.ok)return{ok:!1,errorCode:"unsupported-operation",reason:P.reason};let R=pb(y,P.callbackParams),A=[{order:0,file:r.file,type:"remove-node",locator:De(r),removeWhitespace:!0}];for(let T of N.imports)A.push({order:A.length,file:o.file,type:"add-import",moduleSpecifier:T.moduleSpecifier,imports:T.imports});return A.push({order:A.length,file:o.file,type:"insert-jsx-expression-child",parentLocator:De(o),expression:ff(R,b.sourceJsx),placement:s,anchorLocator:a?De(a):void 0,selectionContext:Zr(o)}),this.buildPlan(t,n,A,i)}async planMoveNode(t,n,r,o){if(!o.canMove)return{ok:!1,errorCode:"capability-denied",reason:"Cannot move this node"};if(yc(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,S=this.graph.getNode(b.anchorKey);if(!S||r.file!==S.file||r.component!==S.component)return{ok:!1,errorCode:"locator-miss",reason:"Source sibling move requires a sibling in the same component file"};let N=this.graph.getFileVersion(r.file);if(n.documentVersion!==N)return{ok:!1,errorCode:"stale-version",reason:`Document version ${n.documentVersion} is stale or otherwise does not match source sibling file version (current: ${N})`};let P=this.graph.getFileContent(r.file),R=dt(P),A=R?nn(R,r):null,T=R?nn(R,S):null,O=A?.parentPath,D=T?.parentPath;if(!A||!T||!O||!D||O.node!==D.node||!O.isJSXFragment()&&!(O.isJSXElement()&&ze(O)))return{ok:!1,errorCode:"unsupported-operation",reason:"Source sibling move requires two direct children of the same transparent Fragment"};let V=O.node.loc;return V?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:De(r),targetParentLocator:{kind:"jsx-node",strategy:"source-range",sourceRange:{startLine:V.start.line,startColumn:V.start.column,endLine:V.end.line,endColumn:V.end.column}},placement:b.relation,anchorLocator:De(S),selectionContext:Zr(r)}],o):{ok:!1,errorCode:"locator-miss",reason:"Source Fragment has no stable source range"}}let i=bb(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(iO(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,S=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:S?.kind==="external-entry"?S.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,p=this.graph.getTextProvenance?.(r.key,0)??null,m=ns(r,c,p);if(m&&!mf(m)&&!mb(r,s,c,p))return{ok:!1,errorCode:"unsupported-operation",reason:m};if(r.isRepeatItemRoot&&d?.isRepeatItemRoot&&r.repeatOwnerKey&&r.repeatOwnerKey===d.repeatOwnerKey&&(u==="before"||u==="after")){let b=c,S=await this.graph.getTextWriteTarget(d.key,0);if(b?.kind==="value-binding"&&S?.kind==="value-binding"&&b.locator&&S.locator){let N=rs(b.locator),P=rs(S.locator);if(N&&P&&b.file===S.file&&lO(N.locator,P.locator)){let R=N.index,A=P.index,T=u==="before"?A-(R<A?1:0):A+(R<A?0:1);return this.buildPlan(t,n,[{order:0,file:b.file,type:"move-array-item",locator:N.locator,fromIndex:R,toIndex:T}],o)}}}if(r.isRepeatItemRoot&&wo(this.graph.getFileContent(r.file),r))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed item outside its collection"};let f=this.getRepeatBackedTemplateStructureReason(r),h=mf(m)?m:f;if(h&&mf(h)){let b=this.planRepeatTemplateInternalMove(t,n,r,s,o,u,d);if(b)return b;let S=this.planRepeatTemplateHoistMove(t,n,r,s,o,u,d);if(S)return S;let N=this.planCrossFileRepeatTemplateHoistMove(t,n,r,s,o,u,d);return N||{ok:!1,errorCode:"unsupported-operation",reason:h}}if(f)return{ok:!1,errorCode:"unsupported-operation",reason:f};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=hc(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=af(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 E=[{order:0,file:r.file,type:"move-node",locator:De(r),targetParentLocator:De(s),placement:u,anchorLocator:d?De(d):void 0,selectionContext:Zr(s)}];return this.buildPlan(t,n,E,o)}planCrossFileMove(t,n,r,o,i,s,a){let c=[],l=0,u=this.graph.getFileContent(r.file),d=pf(this.graph,r)??`<${r.component} />`,p=Ox(u,r);if(!p.allowed)return{ok:!1,errorCode:"unsupported-operation",reason:p.reason??"Cannot move subtree across files"};if(c.push({order:l++,file:r.file,type:"remove-node",locator:De(r),removeWhitespace:!0}),r.importedFrom&&r.exportName){let f=r.tag??r.component,y={moduleSpecifier:yf(o.file,r.importedFrom),imports:r.exportName==="default"?[{kind:"default",local:f}]:[{kind:"named",imported:r.exportName,local:f===r.exportName?void 0:f}]};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:De(o),node:{jsx:d},placement:s,anchorLocator:a?De(a):void 0,selectionContext:Zr(o)})}else c.push({order:l++,file:o.file,type:"insert-child",parentLocator:De(o),node:{jsx:d},placement:s,anchorLocator:a?De(a):void 0,selectionContext:Zr(o)});let m=this.buildRemoveComponentImportStep(r,u);return m&&c.push({...m,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:ve(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 Sb(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 Cf from"@babel/generator";import{parse as CO,parseExpression as NO}from"@babel/parser";import*as v from"@babel/types";import*as Pn from"@babel/types";import Sf from"@babel/generator";import*as Be from"@babel/types";var pO=typeof Sf=="function"?Sf:Sf.default,mO=/(?:token|secret|key|password|authorization|cookie|signature|credential)/i,gO=/^((?:https?:)?\/\/)[^/@\s]+@/i,hO=/(\/(?:token|secret|api[-_]?key|password|credential|signature)\/)[^/?#]+/gi;function Cb(e,t){let n=Kt(e.callee);if(!n)return null;if(n==="fetch")return vf(e.arguments[0],"GET",t,["fetch call"]);if(n.startsWith("axios.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(Rb(r))return vf(e.arguments[0],r,t,["axios client contract"])}if(n.startsWith("ky.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(Rb(r))return vf(e.arguments[0],r,t,["ky client contract"])}return null}function vf(e,t,n,r){if(!e||Be.isSpreadElement(e)||Be.isJSXNamespacedName(e))return EO(t,n,r,"missing url argument");let o=os(e);return{sourceKind:bO(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 os(e){if(Be.isStringLiteral(e))return qr(e.value);if(Be.isTemplateLiteral(e))return qr(yO(e));if(Be.isBinaryExpression(e)&&e.operator==="+"){let t=os(e.left),n=os(e.right);return!t&&!n?void 0:qr(`${t??If(e.left)}${n??If(e.right)}`)}if(Be.isMemberExpression(e)){let t=Nb(e);if(t)return`env:${t}`}if(!(Be.isCallExpression(e)&&Kt(e.callee)==="new URL")){if(Be.isNewExpression(e)&&Be.isIdentifier(e.callee,{name:"URL"})){let[t,n]=e.arguments,r=t&&!Be.isSpreadElement(t)?os(t):void 0,o=n&&!Be.isSpreadElement(n)?os(n):void 0;return o&&r?qr(`${o} + ${r}`):r??o}if(Be.isIdentifier(e))return`:${e.name}`}}function yO(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+=If(r))}return t}function If(e){if(Be.isIdentifier(e))return`:${e.name}`;if(Be.isMemberExpression(e)){let t=Nb(e);if(t)return`env:${t}`}return`:${xO(e)}`}function xO(e){return pO(e,{comments:!1}).code.replace(/[^a-zA-Z0-9_$]+/g,"_").replace(/^_+|_+$/g,"")||"param"}function qr(e){let[t]=e.split("#"),[n,r]=t.split("?"),o=n.replace(gO,"$1<redacted>@").replace(hO,"$1<redacted>");if(!r)return o;let i=r.split("&").map(s=>{let[a]=s.split("=");return a?mO.test(a)?`${a}=<redacted>`:`${a}=:${a}`:""}).filter(Boolean).join("&");return i?`${o}?${i}`:o}function bO(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 EO(e,t,n,r){return{sourceKind:"unknown-api",method:e,confidence:"partial",evidence:[{file:t.file,reason:[...n,r].join("; ")}]}}function Rb(e){return["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(e)}function Nb(e){return!Be.isMemberExpression(e.object)||!Be.isIdentifier(e.object.object,{name:"process"})||!SO(e.object.property,"env")?null:Be.isIdentifier(e.property)?e.property.name:Be.isStringLiteral(e.property)?e.property.value:null}function SO(e,t){return Be.isIdentifier(e)&&e.name===t}function Kt(e){if(Be.isIdentifier(e))return e.name;if(Be.isMemberExpression(e)){let t=Kt(e.object),n=Be.isIdentifier(e.property)?e.property.name:Be.isStringLiteral(e.property)?e.property.value:null;if(t&&n)return`${t}.${n}`}return null}var vO=new Set(["list","listStrict","get","getStrict","getByUrl","getByUrlStrict","schema","categories"]),IO=new Set(["getConfig","submit"]);function _b(e,t){let n=Pb(Kt(e.callee),t);if(!n)return null;let r="cms.collections.";if(n.startsWith(r)){let i=n.slice(r.length);if(!vO.has(i))return null;let s=kf(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(!IO.has(i))return null;let s=kf(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=kf(e,0)??kO(e,0,"path")??"/cms/:path",s=RO(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 Pb(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 Ab(e,t){let n=Kt(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 Ec(e,t){let n=Kt(e.callee),r=t?Pb(n,t):n;return typeof r=="string"&&r.startsWith("cms.field.")}function kf(e,t){let n=e.arguments[t];return Pn.isStringLiteral(n)?n.value:null}function kO(e,t,n){let r=e.arguments[t];if(!Pn.isObjectExpression(r))return null;for(let o of r.properties)if(Pn.isObjectProperty(o)&&!o.computed&&(Pn.isIdentifier(o.key)&&o.key.name===n||Pn.isStringLiteral(o.key)&&o.key.value===n)&&Pn.isStringLiteral(o.value))return o.value.value;return null}function RO(e){let t=/^\/collections\/([^/]+)(?:\/|$)/.exec(e)?.[1];return t&&/^[a-z0-9][a-z0-9_-]*$/i.test(t)?t:null}function Tb(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 p={fromFile:s,exportName:a,targetFile:c,maxImportDepth:l,pending:d},m=t.get(s)??new Map,f=m.get(a)??new Map,h=f.get(c)??new Map;return h.set(l,p),f.set(c,h),m.set(a,f),t.set(s,m),n.add(p),d.catch(()=>{r(p)}),d}}}import*as It from"@babel/types";import{posix as Rf}from"node:path";function Lo(e,t,n=new Set){if(n.has(e))return;let r=new Set(n).add(e);if(It.isBooleanLiteral(e))return e.value;if(It.isUnaryExpression(e,{operator:"!"})){let l=Lo(e.argument,t,r);return l===void 0?void 0:!l}if(It.isLogicalExpression(e)){let l=Lo(e.left,t,r),u=Lo(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(!It.isCallExpression(e)||!It.isIdentifier(e.callee))return;let o=t.imports.get(e.callee.name),i=o?.source.startsWith(".")&&t.file?Rf.normalize(Rf.join(Rf.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=It.isExpression(s.body)?s.body:s.body.body.length===1&&It.isReturnStatement(s.body.body[0])?s.body.body[0].argument:null;if(!a||!It.isExpression(a))return;let c=s.params.flatMap(l=>It.isIdentifier(l)?[l.name]:[]);return Lo(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 mz=typeof Cf=="function"?Cf:Cf.default,Vb=new WeakMap;function Ub(e){let t=new Map;return Vb.set(t,new Map([...e].map(n=>[n.file,n]))),t}var _O={maxFunctionDepth:8,maxImportDepth:6},PO=new Set(["src","href","alt","poster","content","title","aria-label"]),wb=new WeakMap;function AO(e,t,n){let r=wb.get(t.fileCache);r||(r=new WeakMap,wb.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 p={element:d,order:u++};d.importedFrom&&d.exportName&&o.imported.push(p);let m=o.local.get(d.sourceFile);m||(m=new Map,o.local.set(d.sourceFile,m));let f=m.get(d.tag)??[];f.push(p),m.set(d.tag,f)}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 Kb(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")&&Fb(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=Ff(e.file,e.source,t),r={file:e.file,analysis:n,readFile:e.readFile,exists:e.exists,fileCache:t,options:{..._O,...e.options},variableCache:new Map,functionDepth:0,importDepth:0,paramSources:new Map,paramArguments:new Map,resolvingVariables:new Set,resolvingComponentProps:new Set,scopeVariables:oE(n,e.element.componentName),scopeFunction:Lf(n,e.element.componentName)};await Jb(e.element.componentName,e.graph,r);let o=[];o.push(...await FO(e.element,e.graph,r),...await LO(e.element,e.graph,r));for(let s of e.element.textSegments){let a=await DO(s,e.element,e.graph,r);a&&o.push(_c(a,"text","children"))}for(let s of e.element.attributes??[]){let a=Fb(s,e.element);if(!a)continue;let c=await Hb(s.source,e.element,e.graph,r);if(!c&&s.syntaxKind==="expression"&&!(s.source&&eo(s.source.base,e.element,e.graph))){let u=n.jsxElementsByRange.get(Ac(e.element.sourceRange))?.openingElement.attributes.find(d=>v.isJSXAttribute(d)&&v.isJSXIdentifier(d.name,{name:s.name}));v.isJSXExpressionContainer(u?.value)&&v.isExpression(u.value.expression)&&!Gb(u.value.expression,e.element,e.graph)&&(c=await He(u.value.expression,r))}c&&o.push(_c(c,a,s.name))}let i=WO(o).sort(nE);return{hasDynamicData:i.length>0,bindings:i}}async function Jb(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 AO(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 TO(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 zb(l.sourceFile,n);if(!d)continue;let p=Ir(d,n,{importDepth:n.importDepth+1});p.paramSources.clear(),p.scopeVariables=oE(d,l.componentName),p.scopeFunction=Lf(d,l.componentName),p.lexicalContext=void 0,await Jb(l.componentName,t,p);let m=await wO(l,t,p);for(let[f,h]of m){if(!h)continue;let y=a.get(f)??[];y.push(h),a.set(f,y)}}finally{n.resolvingComponentProps.delete(u)}}}let c=new Map;for(let[l,u]of a){let d=Of(u);d.length===1&&c.set(l,d[0])}OO(o,c,n)}var Ob=new WeakMap;function TO(e,t,n,r){let o=Ob.get(r.fileCache);return o||(o=Tb(),Ob.set(r.fileCache,o)),o.resolve({fromFile:e,exportName:t,targetFile:n,maxImportDepth:r.options.maxImportDepth},()=>Xb(e,t,n,r))}async function Xb(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 zb(e,r))?.imports.get(t);if(!s||!mt(s.source))return!1;let a=await Mf(e,s.source,r.exists);return a?a===n?!0:Xb(a,s.importedName,n,r,o):!1}async function wO(e,t,n){let r=new Map,o=n.analysis.jsxElementsByRange.get(Ac(e.sourceRange));if(o)for(let s of o.openingElement.attributes)!v.isJSXAttribute(s)||!v.isJSXIdentifier(s.name)||!v.isJSXExpressionContainer(s.value)||!v.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?eo(c.base,e,t):null)?await Tc(c,e,t,n):Gb(a,e,t)?null:await He(a,n);u&&i.set(s,u)}return i}function Ac(e){return`${e.startLine}:${e.startColumn}:${e.endLine}:${e.endColumn}`}async function zb(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 Ff(e,r,t.fileCache)}function OO(e,t,n){if(v.isIdentifier(e)){t.size>0&&n.paramSources.set(e.name,Nc(Object.fromEntries(t),n.file));return}if(v.isObjectPattern(e))for(let r of e.properties){if(!v.isObjectProperty(r)||r.computed||!v.isIdentifier(r.key))continue;let o=t.get(r.key.name);if(!o)continue;let i=v.isAssignmentPattern(r.value)?r.value.left:r.value;v.isIdentifier(i)&&n.paramSources.set(i.name,ht(o))}}function Fb(e,t){return e.name==="dangerouslySetInnerHTML"?"richtext":PO.has(e.name)?"attribute":t.importedFrom||/^[A-Z]/.test(t.tag)?"component-prop":null}async function FO(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 wc(i.collectionSource,n);s&&r.push(_c(Er(s),"repeat-region",i.collectionExpression))}return r}async function LO(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 wc(i.conditionSource,n);s&&r.push(_c(Er(s),"conditional-region",i.conditionExpression))}return r}async function DO(e,t,n,r){if(!e.source){let i=r.analysis.jsxElementsByRange.get(Ac(t.sourceRange))?.children.find(s=>v.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 v.isJSXExpressionContainer(i)&&v.isCallExpression(i.expression)&&Ec(i.expression)?Wb(i.expression,t,n,r):null}return Hb(e.source,t,n,r)}async function Hb(e,t,n,r){return e&&eo(e.base,t,n)?Tc(e,t,n,r):wc(e,r)}async function Tc(e,t,n,r,o){if(!e)return null;let i=eo(e.base,t,n,o);if(!i||i.candidate.itemParamName!==e.base)return null;let s=i.candidate.collectionSource,c=(s?eo(s.base,t,n,i.region):null)?await Tc(s,t,n,r,i.region):s?await wc(s,r):await MO(i.candidate.collectionExpression,t,n,r,i.region);return c?is(c,e.path,!0):null}async function MO(e,t,n,r,o){let i;try{i=NO(e,{plugins:["typescript","jsx"]})}catch{return null}return Wb(i,t,n,r,o)}async function Wb(e,t,n,r,o){let i=Ir(r.analysis,r),s=new Set;v.traverseFast(e,a=>{v.isIdentifier(a)&&s.add(a.name)});for(let a of s){let c=eo(a,t,n,o);if(!c)continue;if(c.candidate.itemParamName!==a)return null;let l=await Tc({kind:"identifier",expression:a,base:a,path:[]},t,n,r,o);if(!l)return null;i.paramSources.set(a,l)}return He(e,i)}function eo(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&&!Lb(s.sourceRange,r.sourceRange))continue;let a=s.sourceCandidates?.find(c=>c.kind==="repeat-template"&&(c.itemParamName===e||c.indexParamName===e));a&&(!i||Lb(i.region.sourceRange,s.sourceRange))&&(i={candidate:a,region:s})}o=n.elements.get(o)?.parentKey??null}return i}function Lb(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 Gb(e,t,n){let r=!1;return v.traverseFast(e,o=>{!r&&v.isIdentifier(o)&&eo(o.name,t,n)&&(r=!0)}),r}async function wc(e,t){if(!e)return null;let n=await Tf(e.base,t);return n?is(n,e.path,!1):null}async function Tf(e,t){let n=t.paramSources.get(e);if(n)return ht(n);if(t.variableCache.has(e))return GO(t.variableCache.get(e)??null);let r=vr(e,t);if(r&&r!==t)return Tf(e,r);if(t.resolvingVariables.has(e))return null;t.resolvingVariables.add(e);let o=await jO(e,t);if(o)return t.variableCache.set(e,ht(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=v.isArrayExpression(s)&&s.elements.length===0?await BO(e,t):await He(s,t);return t.variableCache.set(e,c?ht(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 Df(a,t);if(c){let l=Ir(c,t,{importDepth:t.importDepth+1}),u=iE(a,c);if(u){let m=(await Qr(u,[],l)).returnSource;return t.variableCache.set(e,m?ht(m):null),t.resolvingVariables.delete(e),m}let d=c.variables.get(a.importedName);if(d){let p=await He(d,l);return t.variableCache.set(e,p?ht(p):null),t.resolvingVariables.delete(e),p}}}return t.variableCache.set(e,null),t.resolvingVariables.delete(e),null}function vr(e,t){return t.scopeVariables?.has(e)||t.scopeFunction?.params.some(n=>Sr(n).includes(e))?t:t.lexicalContext?vr(e,t.lexicalContext):void 0}function Sc(e,t,n=new Set){if(v.isIdentifier(e)){let s=vr(e.name,t);if(s&&s!==t)return Sc(e,s,n)}if(n.has(e))return null;if(n.add(e),v.isStringLiteral(e))return e.value;if(!v.isIdentifier(e))return null;let r=vr(e.name,t),o=t.paramArguments.get(e.name);if(o)return Sc(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?Sc(i,t,n):null}function An(e,t,n=new Set){if(n.has(e))return null;let r=new Set(n).add(e);if(v.isStringLiteral(e))return e.value;if(v.isNumericLiteral(e))return String(e.value);if(v.isIdentifier(e)){if(/token|secret|password|authorization|cookie|credential/i.test(e.name))return":redacted";let o=vr(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?An(s.expression,s.context,r):a?An(a,i,r):null)??`:${e.name}`}if(v.isBinaryExpression(e,{operator:"+"})){let o=An(e.left,t,r),i=An(e.right,t,r);return o!==null&&i!==null?o+i:null}if(v.isTemplateLiteral(e)){let o=e.quasis[0]?.value.cooked??"";for(let[i,s]of e.expressions.entries()){if(!v.isExpression(s))return null;o+=(An(s,t,r)??":param")+(e.quasis[i+1]?.value.cooked??"")}return o}if(v.isCallExpression(e)&&v.isIdentifier(e.callee)&&["encodeURIComponent","decodeURIComponent"].includes(e.callee.name)&&v.isExpression(e.arguments[0])){let o=An(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 v.isTSAsExpression(e)||v.isTSNonNullExpression(e)||v.isParenthesizedExpression(e)?An(e.expression,t,r):null}async function BO(e,t){let n=t.scopeFunction;if(!n)return null;let r=[],o=!1,i=0,s=u=>{let d=!1;return v.traverseFast(u,p=>{v.isIdentifier(p,{name:e})&&(d=!0)}),d},a=u=>{let d=u;for(;v.isMemberExpression(d);)d=d.object;return v.isIdentifier(d,{name:e})},c=async(u,d)=>{if(!o){if(v.isFunction(u)){s(u)&&(o=!0);return}if(v.isVariableDeclarator(u)&&(Sr(u.id).includes(e)&&i++,u.init&&s(u.init)&&(o=!0)),(v.isAssignmentExpression(u)||v.isUpdateExpression(u))&&a(v.isAssignmentExpression(u)?u.left:u.argument)){o=!0;return}if(v.isUnaryExpression(u,{operator:"delete"})&&a(u.argument)){o=!0;return}if(v.isCallExpression(u)){if(v.isMemberExpression(u.callee)&&v.isIdentifier(u.callee.object,{name:e})){if(!v.isIdentifier(u.callee.property,{name:"push"})||u.callee.computed||!u.arguments.length){o=!0;return}for(let p of u.arguments){let m=v.isSpreadElement(p)?p.argument:p,f=v.isExpression(m)?await He(m,d):null;f?r.push(Af(f)):o=!0}return}if(u.arguments.some(p=>s(p))){o=!0;return}}if(v.isForOfStatement(u)){let p=await He(u.right,d),m=Ir(d.analysis,d),f=v.isVariableDeclaration(u.left)?u.left.declarations[0]?.id:u.left;p&&f&&Rc(f,Af(p),m),await c(u.body,m);return}for(let p of v.VISITOR_KEYS[u.type]??[]){let m=u[p];for(let f of Array.isArray(m)?m:[m])v.isNode(f)&&await c(f,d)}}};await c(n.body,t);let l=Of(r);return!o&&i===1&&l.length===1?Er(l[0]):null}async function jO(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 He(o,t);if(i)return i}return null}async function He(e,t){if(v.isIdentifier(e))return Tf(e.name,t);if(v.isMemberExpression(e)||v.isOptionalMemberExpression(e)){let n=v.isMemberExpression(e)?Ab(e,{file:t.file}):null;if(n)return eE(n);let r=await $O(e,t);if(!r)return null;let o=HO(e);return is(r,o,!1)}if(v.isAwaitExpression(e))return v.isExpression(e.argument)?He(e.argument,t):null;if((v.isCallExpression(e)||v.isOptionalCallExpression(e))&&(v.isMemberExpression(e.callee)||v.isOptionalMemberExpression(e.callee))&&!e.callee.computed&&v.isIdentifier(e.callee.property)&&["trim","trimStart","trimEnd"].includes(e.callee.property.name)&&e.arguments.length===0&&v.isExpression(e.callee.object))return Mo(await He(e.callee.object,t));if(v.isCallExpression(e))return Zb(e,t);if(v.isObjectExpression(e)){let n=await Qb(e,t);return Object.keys(n).length>0?Nc(n,t.file):null}if(v.isArrayExpression(e)){let n={};for(let[r,o]of e.elements.entries()){if(!v.isExpression(o))continue;let i=await He(o,t);i&&(n[String(r)]=i)}return Object.keys(n).length?Nc(n,t.file):null}if(v.isConditionalExpression(e)){let n=await He(e.consequent,t),r=await He(e.alternate,t);return Mo(Bb(n,r))}if(v.isLogicalExpression(e)){let n=await He(e.left,t),r=await He(e.right,t);return Mo(Bb(n,r))}return v.isTSAsExpression(e)||v.isTSSatisfiesExpression(e)||v.isTSNonNullExpression(e)||v.isTypeCastExpression(e)||v.isParenthesizedExpression(e)?He(e.expression,t):null}async function $O(e,t){let n=e;for(;v.isMemberExpression(n)||v.isOptionalMemberExpression(n);)n=n.object;return v.isExpression(n)?He(n,t):null}var Nf=new WeakMap;function Pf(e,t){let n=Nf.get(e)?.get(t);if(n!==void 0)return n;let r=new Set([t]),o=l=>{let u=l;for(;v.isMemberExpression(u)||v.isOptionalMemberExpression(u);)u=u.object;return v.isIdentifier(u)?u.name:null},i=!0;for(;i;)i=!1,v.traverseFast(e,l=>{if(!v.isVariableDeclarator(l)||!l.init)return;let u=o(l.init);if(!(!u||!r.has(u)))for(let d of Object.keys(v.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(v.getBindingIdentifiers(l)).some(d=>r.has(d))},a=!1;v.traverseFast(e,l=>{(v.isAssignmentExpression(l)&&s(l.left)||v.isUpdateExpression(l)&&s(l.argument)||v.isUnaryExpression(l,{operator:"delete"})&&s(l.argument))&&(a=!0)});let c=Nf.get(e)??new Map;return c.set(t,a),Nf.set(e,c),a}async function Yb(e,t,n=0){if(n>=t.options.maxFunctionDepth)return null;let r=vr(e,t);if(r){if(r.scopeFunction&&Pf(r.scopeFunction,e))return null;let s=r.paramArguments.get(e);return s&&v.isIdentifier(s.expression)?Yb(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)||Pf(t.analysis.ast,e))return null;let i=await Mf(t.file,o.source,t.exists);return i?{...o,source:i}:null}async function Zb(e,t){let n=e.arguments[0],r=v.isExpression(n)?Sc(n,t):null,i=Kt(e.callee)?.split(".")[0],s=i?await Yb(i,t):null,a=r!==null&&!v.isStringLiteral(n)?{...e,arguments:[v.stringLiteral(r),...e.arguments.slice(1)]}:e;if(s&&["cmsFetch","cmsFetchResult","cmsFetchEnvelope"].includes(s.importedName)&&v.isObjectExpression(n)){let x=qb(n,"path"),E=x&&An(x,t);E?.startsWith("/")&&(a={...e,arguments:[{...n,properties:n.properties.map(b=>v.isObjectProperty(b)&&jo(b)==="path"?{...b,value:v.stringLiteral(qr(E))}:b)},...e.arguments.slice(1)]})}let c=_b(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"&&v.isObjectExpression(n)){let x=Db(n,"query"),E=v.isObjectExpression(x)?Db(x,"path"):null,S=(E&&An(E,t))?.match(/^\/([a-z0-9][a-z0-9_-]*)\/[^/?#]+(?:[?#].*)?$/i)?.[1];S&&(c.collection=S,c.evidence.push({file:t.file,reason:"CMS collection namespace from the actual content request path"}))}if(v.isMemberExpression(e.callee)){let x=await Hn(e.callee,t);if(x&&!vc(x.node))return null;if(x&&vc(x.node)){let E=await _f(e,t,{node:x.node,context:x.context});return E&&{...E,...E.sourceKind===c.sourceKind?{operation:c.operation}:{}}}}if((c.operation==="getByUrl"||c.operation==="getByUrlStrict")&&v.isExpression(n)){let x=An(n,t);x?.startsWith("/")&&(c.endpointPattern=qr(x))}return eE(c)}if(Kt(e.callee)==="Promise.all"&&v.isArrayExpression(n))return He(n,t);if(Ec(e)){if(!Ec(e,{file:t.file,imports:i&&s?new Map([[i,s]]):new Map})||!v.isExpression(e.callee))return null;let x=await Hn(e.callee,t);if(x)return vc(x.node)?_f(e,t,{node:x.node,context:x.context}):null;let E=e.arguments[0];if(E&&v.isExpression(E))return Mo(await He(E,t))}let l=await VO(e,t);if(l)return l;let u=Cb(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 KO(e,t);if(d)return d;let p=await JO(e,t);if(p)return p;let m=await XO(e,t);if(m)return m;let f=await _f(e,t);if(f)return f;let h=[];for(let x of e.arguments)if(v.isExpression(x)){let E=await He(x,t);E&&h.push(E)}let y=Of(h);return y.length===1?Mo(y[0]):null}async function VO(e,t){let n=Kt(e.callee);if(n!=="useQuery"&&n!=="useSuspenseQuery"&&n!=="useInfiniteQuery"&&n!=="useSWR")return null;if(n==="useSWR"){let i=UO(e.arguments[0],t.file,"SWR key"),s=e.arguments[1];if(v.isIdentifier(s)){let a=await Bo(s.name,t);if(a)return(await Qr(a.node,i?[i]:[],a.context)).returnSource??i}return i}let r=e.arguments[0];if(!v.isObjectExpression(r))return Ic(t.file,`${n} without static options`);let o=qb(r,"queryFn");if(!o)return Ic(t.file,`${n} without queryFn`);if(v.isIdentifier(o)){let i=await Bo(o.name,t);return i?(await Qr(i.node,[],i.context)).returnSource:Ic(t.file,`${n} queryFn unresolved`)}return v.isArrowFunctionExpression(o)||v.isFunctionExpression(o)?(await Qr(o,[],t)).returnSource:v.isCallExpression(o)?Zb(o,t):null}function qb(e,t){for(let n of e.properties){if(!v.isObjectProperty(n)||!v.isExpression(n.value))continue;if(jo(n)===t)return n.value}return null}function Db(e,t){let n=new Set;for(let i of e.properties){if(!v.isObjectProperty(i)||i.computed)return null;let s=jo(i);if(!s||n.has(s))return null;n.add(s)}let r=e.properties.filter(i=>v.isObjectProperty(i)&&jo(i)===t);if(r.length!==1)return null;let o=r[0];return v.isObjectProperty(o)&&v.isExpression(o.value)?o.value:null}function UO(e,t,n){return v.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 KO(e,t){if(!v.isMemberExpression(e.callee)||!v.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=v.isExpression(e.callee.object)?await He(e.callee.object,t):null;if(!r)return null;if(n!=="map")return Er(r);let o=e.arguments[0];if(v.isIdentifier(o)){let i=await Bo(o.name,t);if(!i)return Er(r);let s=await Qr(i.node,[r],i.context);return{...Er(r),...s.objectReturnMap??s.returnSource?.fieldMap?{fieldMap:s.objectReturnMap??s.returnSource.fieldMap}:{}}}if(v.isArrowFunctionExpression(o)||v.isFunctionExpression(o)){let i=await Qr(o,[r],t);return{...Er(r),...i.objectReturnMap??i.returnSource?.fieldMap?{fieldMap:i.objectReturnMap??i.returnSource.fieldMap}:{}}}return Er(r)}async function JO(e,t){return!v.isMemberExpression(e.callee)||!v.isIdentifier(e.callee.property,{name:"json"})||!v.isExpression(e.callee.object)?null:He(e.callee.object,t)}async function XO(e,t){return!v.isMemberExpression(e.callee)||!v.isIdentifier(e.callee.property,{name:"then"})||!v.isExpression(e.callee.object)?null:Mo(await He(e.callee.object,t))}async function _f(e,t,n){let r=n;if(!r&&v.isIdentifier(e.callee))r=await Bo(e.callee.name,t)??void 0;else if(!r&&v.isMemberExpression(e.callee)){let s=await Hn(e.callee,t);s&&vc(s.node)&&(r={node:s.node,context:s.context})}if(!r)return null;let o=[];for(let s of e.arguments){if(!v.isExpression(s)){o.push(Ic(t.file,`unsupported argument for ${Kt(e.callee)??"call"}`));continue}let a=await He(s,t);o.push(a)}return(await Qr(r.node,o,r.context,{arguments:e.arguments,context:t})).returnSource}function vc(e){return v.isFunctionDeclaration(e)||Pc(e)||v.isObjectMethod(e)&&e.kind==="method"}async function Hn(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(v.isTSAsExpression(e)||v.isTSSatisfiesExpression(e)||v.isTSNonNullExpression(e))return Hn(e.expression,t,o);if(v.isIdentifier(e)){let i=vr(e.name,t),s=i??t;if(Pf(i?.scopeFunction??t.analysis.ast,e.name))return r;let a=s.paramArguments.get(e.name);if(a)return Hn(a.expression,a.context,o);let c=i?i.scopeVariables?.get(e.name):s.analysis.variables.get(e.name);if(c)return Hn(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 Df(u,s);return d?Hn(v.identifier(u.importedName),Ir(d,s,{importDepth:s.importDepth+1}),o):null}if(v.isMemberExpression(e)&&v.isExpression(e.object)){let i=e.computed?v.isStringLiteral(e.property)?e.property.value:null:v.isIdentifier(e.property)?e.property.name:null;if(!i)return null;let s=await Hn(e.object,t,o);if(!s)return null;if(!v.isObjectExpression(s.node))return{node:null,context:s.context};if(s.node.properties.some(l=>v.isSpreadElement(l)||l.computed))return{node:null,context:s.context};let a=s.node.properties.filter(l=>(v.isObjectMethod(l)||v.isObjectProperty(l))&&(v.isIdentifier(l.key)?l.key.name:v.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 v.isObjectMethod(c)?c.kind==="method"?{node:c,context:s.context}:null:v.isObjectProperty(c)&&v.isExpression(c.value)?Hn(c.value,s.context,o):null}return{node:e,context:t}}async function Bo(e,t,n=new Set){let r=t.paramArguments.get(e);if(r&&!n.has(r.expression)){if(n.add(r.expression),Pc(r.expression))return{node:r.expression,context:r.context};if(v.isIdentifier(r.expression))return Bo(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 Df(i,t);if(!s)return null;let a=Ir(s,t,{importDepth:t.importDepth+1}),c=iE(i,s);return c?{node:c,context:a}:Bo(i.importedName,a)}async function Qr(e,t,n,r){if(n.functionDepth>=n.options.maxFunctionDepth)return{returnSource:null};let o=Ir(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,p)=>{for(let y of Sr(d))o.paramSources.delete(y),o.paramArguments.delete(y);let m=v.isAssignmentPattern(d)?d.left:d,f=r?.arguments[p];v.isIdentifier(m)&&v.isExpression(f)&&r&&o.paramArguments.set(m.name,{expression:f,context:r.context});let h=t[p];h&&Rc(d,Af(h),o)});let a=zO(e,o),c=null,l,u=!1;for(let d of a){let p=Ir(n.analysis,o);if(v.isObjectExpression(d)){l={...l??{},...await Qb(d,p)},c=c??Nc(l,n.file);continue}let m=await He(d,p);if(m){if(!c){c=m;continue}let f=wf(c,m);if(!f){u=!0,c=null;continue}c=f}}return{returnSource:u?null:c,...l?{objectReturnMap:l}:{}}}function Rc(e,t,n){if(v.isIdentifier(e)){n.paramSources.set(e.name,ht(t));return}if(v.isAssignmentPattern(e)){Rc(e.left,t,n);return}if(v.isObjectPattern(e))for(let r of e.properties){if(!v.isObjectProperty(r)||r.computed||!v.isIdentifier(r.key))continue;let o=is(t,[{kind:"property",name:r.key.name}],!0),i=v.isAssignmentPattern(r.value)?r.value.left:r.value;o&&Rc(i,o,n)}}function zO(e,t){if(v.isArrowFunctionExpression(e)&&v.isExpression(e.body))return[e.body];let n=[],r=e.body;if(!v.isBlockStatement(r))return n;let o=i=>{if(v.isFunction(i)&&i!==e)return;if(v.isReturnStatement(i)){i.argument&&v.isExpression(i.argument)&&n.push(i.argument);return}if(v.isIfStatement(i)){let a=Lo(i.test,{file:t.file,imports:new Map([...t.analysis.imports].filter(([c])=>!vr(c,t))),functions:t.analysis.functions});if(a!==void 0){a?o(i.consequent):i.alternate&&o(i.alternate);return}}let s=v.VISITOR_KEYS[i.type];for(let a of s??[]){let c=i[a];if(Array.isArray(c))for(let l of c)v.isNode(l)&&o(l);else v.isNode(c)&&o(c)}};return o(r),n}async function Qb(e,t){let n={};for(let r of e.properties){if(!v.isObjectProperty(r))continue;let o=jo(r);if(!o||!v.isExpression(r.value))continue;let i=await He(r.value,t);i&&(n[o]=i)}return n}function jo(e){return v.isIdentifier(e.key)&&!e.computed?e.key.name:v.isStringLiteral(e.key)?e.key.value:null}function HO(e){let t=[],n=e;for(;v.isMemberExpression(n)||v.isOptionalMemberExpression(n);){let r=n.property;n.computed?v.isStringLiteral(r)?t.unshift({kind:"property",name:r.value}):v.isNumericLiteral(r)&&t.unshift({kind:"index",index:r.value}):v.isIdentifier(r)&&t.unshift({kind:"property",name:r.name}),n=n.object}return v.isIdentifier(n),t}function is(e,t,n){if(t.length===0)return ht(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?is(s,t.slice(1),n):null}let i=ht(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=Do(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=Do(i.valuePath,"data")),i.fieldPath=Do(i.fieldPath,s.slice(a+1).join(".")),i.cmsFieldRoot=!0,i):i.cmsFieldRoot||n||i.fieldMap?(i.fieldPath=Do(i.fieldPath,s.join(".")),i):(i.valuePath=Do(i.valuePath,Mb(t)),i)}return i.valuePath=Do(i.valuePath,Mb(t)),i}function Mb(e){return e.map(t=>t.kind==="property"?t.name:`[${t.index}]`).join(".").replace(/\.\[/g,"[")}function Do(e,t){return t?e?t.startsWith("[")?`${e}${t}`:`${e}.${t}`:t:e}function eE(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 Er(e){let t=ht(e);return t.sourceType==="cms-field"&&!t.valuePath&&(t.valuePath="items[]"),t}function Af(e){let t=ht(e);return t.valuePath=void 0,t.sourceType==="cms-field"&&!t.fieldPath&&(t.cmsFieldRoot=!1),t}function Mo(e){return e?{...ht(e),confidence:e.confidence==="unknown"?"unknown":"safe-derived",evidence:[...e.evidence,{file:e.evidence[0]?.file??"unknown",reason:"safe derived expression"}]}:null}function Bb(e,t){return e?t?wf(e,t):ht(e):t?ht(t):null}function wf(e,t){if(Cc(e)!==Cc(t))return null;let n=rE(e.confidence,t.confidence)<=0?e.confidence:t.confidence;return{...e,confidence:n,evidence:[...e.evidence,...t.evidence]}}function Of(e){let t=new Map;for(let n of e){let r=Cc(n),o=t.get(r);t.set(r,o?wf(o,n):ht(n))}return[...t.values()]}function Cc(e){let t=e.fieldMap?Object.fromEntries(Object.entries(e.fieldMap).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>[n,Cc(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 Nc(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 Ic(e,t){return{sourceKind:"unknown-api",sourceType:"api-field",confidence:"unknown",readonly:!0,evidence:[{file:e,reason:t}]}}function _c(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 tE(e){let t=[...e].sort(nE),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 WO(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 nE(e,t){return jb(e.targetKind)-jb(t.targetKind)||rE(e.confidence,t.confidence)||$b(e.sourceKind)-$b(t.sourceKind)||e.targetName.localeCompare(t.targetName)}function jb(e){return{"repeat-region":0,"conditional-region":1,text:2,richtext:3,attribute:4,"component-prop":5}[e]}function $b(e){return e.startsWith("vcp-cms-")?0:e==="site-api-route"?1:e==="external-api"?2:3}function rE(e,t){let n={exact:0,"safe-derived":1,partial:2,unknown:3};return n[e]-n[t]}function Ff(e,t,n){let r=n.get(e);if(r?.source===t)return r;let o=Vb.get(n)?.get(e),i=o?.source===t?o.ast:CO(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=[];v.traverse(i,{enter(d){switch(v.isFunction(d)&&(s.functionParents.set(d,a.at(-1)??null),a.push(d)),d.type){case"CallExpression":c.push(d);break;case"JSXElement":{let p=d.loc;if(!p)return;let m=Ac({startLine:p.start.line,startColumn:p.start.column,endLine:p.end.line,endColumn:p.end.column});s.jsxElementsByRange.has(m)||s.jsxElementsByRange.set(m,d);break}case"ImportDeclaration":{let p=d.source.value;for(let m of d.specifiers)v.isImportSpecifier(m)&&v.isIdentifier(m.local)?s.imports.set(m.local.name,{source:p,importedName:v.isIdentifier(m.imported)?m.imported.name:m.imported.value,localName:m.local.name,isDefault:!1}):v.isImportDefaultSpecifier(m)&&s.imports.set(m.local.name,{source:p,importedName:"default",localName:m.local.name,isDefault:!0});break}case"FunctionDeclaration":{d.id?.name&&s.functions.set(d.id.name,d);break}case"VariableDeclarator":{let p=a.at(-1),m=p&&(v.isFunctionDeclaration(p)||v.isFunctionExpression(p)||v.isArrowFunctionExpression(p)||v.isObjectMethod(p))?p:null,f=m?s.functionVariables.get(m)??new Map:s.variables;m&&!s.functionVariables.has(m)&&s.functionVariables.set(m,f);for(let[h,y]of kc(d.id,v.isExpression(d.init)?d.init:null))f.set(h,y);if(v.isArrayPattern(d.id)&&v.isCallExpression(d.init)&&Kt(d.init.callee)==="useState"){let[h,y]=d.id.elements;v.isIdentifier(h)&&v.isIdentifier(y)&&s.stateSetters.set(h.name,y.name)}v.isIdentifier(d.id)&&Pc(d.init)&&s.functions.set(d.id.name,d.init);break}case"ExportNamedDeclaration":{let p=d.declaration,m=d.source?.value;if(m)for(let f of d.specifiers){if(!v.isExportSpecifier(f))continue;let h=v.isIdentifier(f.exported)?f.exported.name:f.exported.value,y=f.local.name;s.imports.set(h,{source:m,importedName:y,localName:h,isDefault:y==="default"})}if(v.isFunctionDeclaration(p)&&p.id?.name&&s.functions.set(p.id.name,p),v.isVariableDeclaration(p))for(let f of p.declarations)v.isIdentifier(f.id)&&Pc(f.init)&&s.functions.set(f.id.name,f.init);break}case"ExportDefaultDeclaration":{let p=d.declaration;if((v.isFunctionDeclaration(p)||v.isFunctionExpression(p)||v.isArrowFunctionExpression(p))&&s.functions.set("default",p),v.isIdentifier(p)){let m=s.functions.get(p.name);m&&s.functions.set("default",m)}break}}},exit(d){v.isFunction(d)&&a.pop()}});let l=new Set(s.stateSetters.values()),u=(d,p)=>{let m=s.stateSetterCandidates.get(d)??[];m.push(p),s.stateSetterCandidates.set(d,m)};if(l.size>0)for(let d of c){let p=v.isIdentifier(d.callee)?d.callee.name:null;p&&l.has(p)&&v.isExpression(d.arguments[0])&&u(p,d.arguments[0]);let m=new Set;for(let f of d.arguments)v.isIdentifier(f)&&f.name!==p&&l.has(f.name)&&m.add(f.name);for(let f of m)u(f,d)}return n.set(e,s),s}function kc(e,t){return v.isIdentifier(e)?[[e.name,t]]:v.isAssignmentPattern(e)?kc(e.left,t):v.isArrayPattern(e)?e.elements.flatMap((n,r)=>n&&!v.isRestElement(n)?kc(n,t?v.memberExpression(t,v.numericLiteral(r),!0):null):[]):v.isObjectPattern(e)?e.properties.flatMap(n=>{if(!v.isObjectProperty(n)||n.computed)return[];let r=jo(n);return r?kc(n.value,t?v.memberExpression(t,v.stringLiteral(r),!0):null):[]}):[]}function Sr(e){return!e||v.isVoidPattern(e)?[]:v.isIdentifier(e)?[e.name]:v.isObjectPattern(e)?e.properties.flatMap(t=>v.isObjectProperty(t)?Sr(t.value):Sr(t.argument)):v.isArrayPattern(e)?e.elements.flatMap(t=>t?Sr(v.isRestElement(t)?t.argument:t):[]):v.isAssignmentPattern(e)?Sr(e.left):v.isRestElement(e)?Sr(e.argument):[]}function Pc(e){return v.isFunctionExpression(e)||v.isArrowFunctionExpression(e)}function oE(e,t){let n=Lf(e,t);return n?e.functionVariables.get(n):void 0}function Lf(e,t){return e.functions.get(t)??e.functions.get("default")}async function Df(e,t){let n=await Mf(t.file,e.source,t.exists);if(!n)return null;let r=await t.readFile(n);return Ff(n,r,t.fileCache)}function iE(e,t){return e.isDefault?t.functions.get("default")??t.functions.get(e.localName)??null:t.functions.get(e.importedName)??null}async function Mf(e,t,n){return mt(t)?Tr(e,t,n):null}function Ir(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 GO(e){return e?ht(e):null}function ht(e){return{...e,evidence:e.evidence.map(t=>({...t})),...e.fieldMap?{fieldMap:Object.fromEntries(Object.entries(e.fieldMap).map(([t,n])=>[t,ht(n)]))}:{}}}import*as jf from"@babel/parser";import Bf from"@babel/traverse";import*as se from"@babel/types";import{classifySiteEditPropertyName as YO}from"@vcp-dev/contracts";var $f=typeof Bf=="function"?Bf:Bf.default;function Vf(e){let t=YO(e.propertyName);if(t.owner!=="generic")return Jt("invalid-property",t.diagnostic?.message??`Property '${e.propertyName}' is not a generic property`);let n=e.selectionRef;if(!n)return Jt("missing-selection-ref","A repeat property target requires a complete selection reference");if(n.key!==e.element.identity.key)return Jt("selection-mismatch","Selection reference does not identify the requested element");if(n.instanceIndex===void 0)return Jt("missing-instance-index","A repeat property target requires an instance index");let r;try{r=jf.parse(e.source,{sourceType:"module",plugins:["typescript","jsx"]})}catch(y){return Jt("repeat-not-found",`Unable to parse repeat source: ${y instanceof Error?y.message:String(y)}`)}let o=ZO(r,e.element.sourceRange);if(!o)return Jt("repeat-not-found","The selected element is not inside a supported map repeat");if(!se.isIdentifier(o.callback.params[0]))return Jt("unsupported-callback","Repeat property materialization requires an identifier callback item");let i=qO(r,o.collection,e.file,e.sources);if(!i)return Jt("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||!se.isObjectExpression(x)||!dE(x))return Jt("unsafe-collection","Repeat materialization requires an array of local static objects without spreads");let E=[{kind:"index",index:y}];l.push(E),u.push({kind:"value",root:a.root,path:E})}let d=u.length;if(n.instanceCount!==void 0&&n.instanceCount!==d)return Jt("count-mismatch",`Selection reports ${n.instanceCount} instances but the source collection has ${d}`);let p=n.instanceIndex;if(p>=d)return Jt("index-out-of-range",`Selected repeat instance ${p} is outside the source collection`);let m=s.elements[p];if(!m||!se.isObjectExpression(m))return Jt("unsafe-collection","Selected repeat item is not an object");let f=oF(e.element,e.propertyName),h=nF(m,e.propertyName);return h?{ok:!0,sourceFile:c,templateFile:e.file,collectionLocator:a,parentObjectLocators:u,selectedParentObjectLocator:u[p],sourceItemIndex:p,sourceItemPath:l[p],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:h,selectedResolution:rF(m,e.propertyName),...f?{property:f}:{},selectionRef:n}:Jt("unsafe-property-source",`Property '${e.propertyName}' has a dynamic or unsupported source in the repeat item`)}function ZO(e,t){let n=[];return $f(e,{CallExpression(r){let o=sE(r.node);o&&cE(o.callback,t)&&n.push({...o,span:aE(r.node)})},OptionalCallExpression(r){let o=sE(r.node);o&&cE(o.callback,t)&&n.push({...o,span:aE(r.node)})}}),n.sort((r,o)=>r.span-o.span),n[0]??null}function sE(e){let t=e.callee;if(!se.isMemberExpression(t)&&!se.isOptionalMemberExpression(t)||t.computed||!se.isIdentifier(t.property)||t.property.name!=="map"||!se.isExpression(t.object))return null;let n=e.arguments[0];return!n||!se.isExpression(n)||!se.isArrowFunctionExpression(n)&&!se.isFunctionExpression(n)?null:{collection:t.object,callback:n}}function qO(e,t,n,r){let o=ss(t);if(o&&se.isArrayExpression(o))return{array:o,locator:{kind:"value",root:{kind:"expression",sourceRange:pE(o)}},sourceFile:n};if(!se.isIdentifier(t))return null;let i=[];if($f(e,{VariableDeclarator(s){se.isIdentifier(s.node.id)&&s.node.id.name===t.name&&s.node.init&&i.push(s.node)}}),i.length===1){let s=ss(i[0].init);return!s||!se.isArrayExpression(s)?null:{array:s,locator:{kind:"value",root:{kind:"binding",name:t.name}},sourceFile:n}}return QO(e,t.name,n,r)}function QO(e,t,n,r){if(!r)return null;for(let o of e.program.body){if(!se.isImportDeclaration(o))continue;let i=o.specifiers.find(p=>p.local.name===t);if(!i||!se.isStringLiteral(o.source)||!se.isImportSpecifier(i))continue;let s=tF(n,o.source.value,r);if(!s)return null;let a=se.isIdentifier(i.imported)?i.imported.name:i.imported.value,c=r.get(s);if(c===void 0)return null;let l;try{l=jf.parse(c,{sourceType:"module",plugins:["typescript","jsx"]})}catch{return null}let u=eF(l,a),d=u?ss(u):null;return!d||!se.isArrayExpression(d)?null:{array:d,locator:{kind:"value",root:{kind:"binding",name:a}},sourceFile:s}}return null}function eF(e,t){let n=null;return $f(e,{VariableDeclarator(r){n||!se.isIdentifier(r.node.id)||r.node.id.name!==t||!r.node.init||!se.isExpression(r.node.init)||(n=r.node.init)}}),n}function tF(e,t,n){let r=xn(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 ss(e){return se.isParenthesizedExpression(e)?ss(e.expression):se.isTSAsExpression(e)?uE(e.typeAnnotation)?ss(e.expression):null:se.isTSSatisfiesExpression(e)?null:e}function uE(e){return se.isTSTypeReference(e)&&se.isIdentifier(e.typeName)&&e.typeName.name==="const"}function dE(e){return e.properties.every(t=>!se.isObjectProperty(t)||t.computed||!se.isExpression(t.value)?!1:Oc(t.value))}function Oc(e){if(se.isTSAsExpression(e)&&uE(e.typeAnnotation))return Oc(e.expression);if(se.isTSSatisfiesExpression(e))return!1;if(se.isArrayExpression(e))return e.elements.every(n=>!n||se.isSpreadElement(n)||!se.isExpression(n)?!1:Oc(n));if(se.isObjectExpression(e))return dE(e);let t=In(e);return t.status==="resolved"||t.status==="undefined"}function nF(e,t){let n=e.properties.filter(o=>se.isObjectProperty(o)&&fE(o.key)===t);if(n.length>1)return null;let r=n[0];return r?se.isExpression(r.value)?Oc(r.value)?"static":se.isIdentifier(r.value)||se.isMemberExpression(r.value)?"binding":null:null:"missing"}function rF(e,t){let n=e.properties.filter(o=>se.isObjectProperty(o)&&fE(o.key)===t);if(n.length>1)return{status:"unresolved"};let r=n[0];return!r||!se.isExpression(r.value)?{status:"undefined"}:In(r.value)}function oF(e,t){let n=e.attributes?.filter(r=>r.name===t)??[];return n.length===1?n[0]:void 0}function fE(e){return se.isIdentifier(e)?e.name:se.isStringLiteral(e)?e.value:se.isNumericLiteral(e)?String(e.value):null}function pE(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 cE(e,t){let n=pE(e);return lE(n.startLine,n.startColumn,t.startLine,t.startColumn)<=0&&lE(n.endLine,n.endColumn,t.endLine,t.endColumn)>=0}function lE(e,t,n,r){return e===n?t-r:e-n}function Jt(e,t){return{ok:!1,errorCode:e,reason:t}}import{classifySiteEditPropertyName as UF}from"@vcp-dev/contracts";import*as le from"@babel/types";import ds from"node:path";import*as G from"@babel/types";import*as bE from"@babel/parser";import Uf from"@babel/traverse";import*as me from"@babel/types";function Lc(e,t){let n=[],r=e;for(;me.isMemberExpression(r);){if(r.computed)if(me.isNumericLiteral(r.property))n.unshift({kind:"index",index:r.property.value});else if(me.isStringLiteral(r.property))n.unshift({kind:"property",name:r.property.value});else return null;else{if(!me.isIdentifier(r.property))return null;n.unshift({kind:"property",name:r.property.name})}r=r.object}return!me.isIdentifier(r)||r.name!==t?null:n}function mE(e){if(me.isIdentifier(e))return{base:e.name,path:[]};if(!me.isMemberExpression(e))return null;let t=[],n=e;for(;me.isMemberExpression(n);){if(n.computed)if(me.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(me.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else{if(!me.isIdentifier(n.property))return null;t.unshift({kind:"property",name:n.property.name})}n=n.object}return me.isIdentifier(n)?{base:n.name,path:t}:null}function kt(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 Tn=Symbol("not-closed-literal");function Fc(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:Tn;case"TSAsExpression":case"TSSatisfiesExpression":case"TSNonNullExpression":return Fc(e.expression);case"ArrayExpression":{let t=[];for(let n of e.elements){if(!n||me.isSpreadElement(n))return Tn;let r=Fc(n);if(r===Tn)return Tn;t.push(r)}return t}case"ObjectExpression":{let t={};for(let n of e.properties){if(!me.isObjectProperty(n)||n.computed||n.shorthand||!me.isExpression(n.value))return Tn;let r=me.isIdentifier(n.key)?n.key.name:me.isStringLiteral(n.key)?n.key.value:null;if(!r)return Tn;let o=Fc(n.value);if(o===Tn)return Tn;t[r]=o}return t}default:return Tn}}function gE(e){let{resolveBindingTarget:t}=e;async function n(i,s,a,c,l,u,d){let p=Fc(i);if(p!==Tn)return p;if(!me.isTemplateLiteral(i)){if(me.isTSAsExpression(i)||me.isTSSatisfiesExpression(i)||me.isTSNonNullExpression(i))return await n(i.expression,s,a,c,l,u,d);if(me.isIdentifier(i)){let m=s.getBinding(i.name);if(!m)return;let f=await t({currentFile:a,binding:m,readFile:c,exists:l,fileCache:u,visited:d});return f?.kind==="static"?f.value:void 0}if(me.isArrayExpression(i)){let m=[];for(let f of i.elements){if(!f||me.isSpreadElement(f))return;let h=await r(f,s,a,c,l,u,d);if(h===void 0)return;m.push(h)}return m}if(me.isObjectExpression(i)){let m={};for(let f of i.properties){if(!me.isObjectProperty(f)||f.computed)return;let h=null;if(me.isIdentifier(f.key)?h=f.key.name:me.isStringLiteral(f.key)&&(h=f.key.value),!h)return;if(f.shorthand){if(!me.isIdentifier(f.value))return;let x=await r(f.value,s,a,c,l,u,d);if(x===void 0)return;m[h]=x;continue}if(!me.isExpression(f.value))return;let y=await r(f.value,s,a,c,l,u,d);y!==void 0&&(m[h]=y)}return m}if(me.isMemberExpression(i)){let m=await o(i,s,a,c,l,u,d);if(!m)return;let f=s.getBinding(m.base);if(!f)return;let h=await t({currentFile:a,binding:f,readFile:c,exists:l,fileCache:u,visited:d});return!h||h.kind!=="static"?void 0:kt(h.value,m.path)}}}async function r(i,s,a,c,l,u,d){if(!me.isSpreadElement(i))return await n(i,s,a,c,l,u,d)}async function o(i,s,a,c,l,u,d){if(me.isIdentifier(i))return{base:i.name,path:[]};if(!me.isMemberExpression(i))return null;let p=[],m=i;for(;me.isMemberExpression(m);){if(m.computed){let f=m.property;if(me.isNumericLiteral(f))p.unshift({kind:"index",index:f.value});else if(me.isStringLiteral(f))p.unshift({kind:"property",name:f.value});else{let h=me.isExpression(f)?await n(f,s,a,c,l,u,d):void 0;if(typeof h=="string")p.unshift({kind:"property",name:h});else if(Number.isInteger(h))p.unshift({kind:"index",index:h});else return null}}else{if(!me.isIdentifier(m.property))return null;p.unshift({kind:"property",name:m.property.name})}m=m.object}return me.isIdentifier(m)?{base:m.name,path:p}:null}return{normalizeExpressionWithScope:o,evaluateStaticExpression:n}}var EE=typeof Uf=="function"?Uf:Uf.default,hE=new WeakMap;function SE(e){try{return bE.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function Dc(e,t,n){let r=e.get(t);if(r?.source===n)return r.ast;let o=SE(n);return e.set(t,{source:n,ast:o}),o}function Mc(e,t){return Kf(as(e).expressionRanges,t,!1)}function vE(e,t){return as(e).exactExpressions.get(IE(t))??null}function Bc(e,t){return Kf(as(e).jsxRanges,t,!0)}function as(e){let t=hE.get(e);if(t)return t;let n={expressions:[],expressionRanges:[],jsxRanges:[],exactExpressions:new Map};return EE(e,{Expression(r){let o=r;n.expressions.push(o);let i=yE(o,n.expressions.length-1);if(!i)return;n.expressionRanges.push(i);let s=IE(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=yE(r,n.jsxRanges.length);o&&n.jsxRanges.push(o)}}),n.expressionRanges.sort(xE),n.jsxRanges.sort(xE),hE.set(e,n),n}function yE(e,t){let n=cs(e.node);return n?{path:e,range:n,traversalIndex:t,span:(e.node.end??0)-(e.node.start??0)}:null}function IE(e){return`${e.startLine}:${e.startColumn}:${e.endLine}:${e.endColumn}`}function xE(e,t){return e.range.startLine-t.range.startLine||e.range.startColumn-t.range.startColumn||e.traversalIndex-t.traversalIndex}function Kf(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 cs(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 $o(e,t){if(t)return Jf(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 Jf(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function ls(e,t,n){let r=null,o=Number.POSITIVE_INFINITY;for(let i of as(e).expressions){if(Jf(i.node,t)!==n)continue;let s=(i.node.end??0)-(i.node.start??0);s<=o&&(r=i,o=s)}return r}function kE(e,t,n,r){return Kf(as(e).expressionRanges,r,!0,o=>Jf(o.node,t)===n)}function Vo(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}function us(e){let t=null;if(EE(e,{Program(n){t=n.scope,n.stop()}}),!t)throw new Error("Unable to determine program scope");return t}async function gn(e,t,n){let r=n.get(e);if(r)return r;let o=await t(e),i=SE(o),s={source:o,ast:i};return n.set(e,s),s}function iF(e){return G.isIdentifier(e.callee)&&(e.callee.name==="useState"||e.callee.name==="useReducer")?e.callee.name:G.isMemberExpression(e.callee)&&G.isIdentifier(e.callee.property)&&(e.callee.property.name==="useState"||e.callee.property.name==="useReducer")?e.callee.property.name:null}function sF(e){if(!G.isNewExpression(e)||!G.isIdentifier(e.callee,{name:"Proxy"})||e.arguments.length!==2||!G.isIdentifier(e.arguments[0])||!G.isObjectExpression(e.arguments[1])||e.arguments[1].properties.length!==1)return null;let[t]=e.arguments[1].properties;if(!G.isObjectMethod(t)||t.kind!=="method"||t.computed||t.async||t.generator||!G.isIdentifier(t.key,{name:"get"})||t.params.length!==3||!t.params.every(G.isIdentifier)||t.body.body.length!==2)return null;let[n,r,o]=t.params,[i,s]=t.body.body;if(G.isIfStatement(i)&&G.isBlockStatement(i.consequent)&&i.consequent.body.length!==1)return null;let a=G.isIfStatement(i)?i.test:null,c=a&&G.isLogicalExpression(a,{operator:"&&"})?a.right:null,l=G.isIfStatement(i)?G.isBlockStatement(i.consequent)?i.consequent.body[0]:i.consequent:null,u=G.isReturnStatement(s)?s.argument:null;return!a||!G.isLogicalExpression(a,{operator:"&&"})||!G.isBinaryExpression(a.left,{operator:"==="})||!G.isUnaryExpression(a.left.left,{operator:"typeof"})||!G.isIdentifier(a.left.left.argument,{name:r.name})||!G.isStringLiteral(a.left.right,{value:"string"})||!G.isUnaryExpression(c,{operator:"!"})||!G.isBinaryExpression(c.argument,{operator:"in"})||!G.isIdentifier(c.argument.left,{name:r.name})||!G.isIdentifier(c.argument.right,{name:n.name})||!G.isReturnStatement(l)||!G.isIfStatement(i)||i.alternate||!G.isCallExpression(u)||!G.isMemberExpression(u.callee)||!G.isIdentifier(u.callee.object,{name:"Reflect"})||!G.isIdentifier(u.callee.property,{name:"get"})||u.arguments.length!==3||!G.isIdentifier(u.arguments[0],{name:n.name})||!G.isIdentifier(u.arguments[1],{name:r.name})||!G.isIdentifier(u.arguments[2],{name:o.name})?null:e.arguments[0].name}function aF(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()||!G.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 RE(e,t){let n=aF(e.path);if(!n)return null;let r=Co(e,t);return r?{...n,...r}:null}function CE(e,t,n,r){return e.importedFrom===t?r?e.exportName===r:!0:e.sourceFile===t&&e.tag===n}function Xf(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 zf(e,t){for(let n of e.program.body){if(t==="default"&&G.isExportDefaultDeclaration(n))return G.isExpression(n.declaration)?{kind:"default-expression",expression:n.declaration}:(G.isFunctionDeclaration(n.declaration)||G.isClassDeclaration(n.declaration))&&n.declaration.id?{kind:"default-binding",name:n.declaration.id.name}:null;if(G.isExportNamedDeclaration(n)){if(n.declaration){if(G.isVariableDeclaration(n.declaration)){for(let r of n.declaration.declarations)if(G.isIdentifier(r.id)&&r.id.name===t)return{kind:"local-binding",name:r.id.name}}if((G.isFunctionDeclaration(n.declaration)||G.isClassDeclaration(n.declaration))&&n.declaration.id&&n.declaration.id.name===t)return{kind:"local-binding",name:t}}for(let r of n.specifiers)if((G.isIdentifier(r.exported)?r.exported.name:r.exported.value)===t&&G.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 NE(e){let{resolveExternalExpression:t,resolveCollectionCallTarget:n,evaluateStaticExpression:r,resolveSourceInfoProvenance:o,buildExpressionSourceInfo:i}=e;async function s(f){let{currentFile:h,binding:y,readFile:x,exists:E,fileCache:b,visited:S}=f,N=`${h}::${y.kind}::${y.identifier.name}`;if(S.has(N))return null;S.add(N);try{let P=await a({currentFile:h,binding:y,readFile:x,exists:E,fileCache:b,visited:S});if(P)return P;if(y.path.isImportSpecifier()||y.path.isImportDefaultSpecifier())return await p({currentFile:h,binding:y,readFile:x,exists:E,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,fileCache:b,visited:S});if(y.kind==="param")return null;if(y.path.isVariableDeclarator()){let R=y.path.node.init;if(!R||!G.isExpression(R))return null;let A=sF(R);if(A&&!y.path.scope.getBinding("Proxy")&&!y.path.scope.getBinding("Reflect")){let D=y.path.scope.getBinding(A),V=D?await s({...f,binding:D}):null;if(V?.kind==="static"&&V.value!==null&&!Array.isArray(V.value)&&typeof V.value=="object")return V}let T=y.path.get("init");if(T&&!Array.isArray(T)&&T.isExpression()){let D=await t({currentFile:h,expressionPath:T,readFile:x,exists:E,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:b,visited:S});if(D)return D;if(T.isCallExpression()){let V=await n({currentFile:h,callPath:T,readFile:x,exists:E,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:b,visited:S});if(V)return V}}let O=await r(R,y.path.scope,h,x,E,b,S);return O===void 0?null:{kind:"static",file:h,root:{kind:"binding",name:y.identifier.name},value:O,sourceKind:"binding"}}if(y.path.isIdentifier()&&y.path.parentPath?.isExportDefaultDeclaration()){let R=y.path.parentPath.node.declaration;if(!G.isExpression(R))return null;let A=await r(R,y.path.scope,h,x,E,b,S);return A===void 0?null:{kind:"static",file:h,root:{kind:"binding",name:y.identifier.name},value:A,sourceKind:"binding"}}return null}finally{S.delete(N)}}async function a(f){let{currentFile:h,binding:y,readFile:x,exists:E,fileCache:b,visited:S}=f;if(!y.path.isVariableDeclarator()||!y.path.get("id").isArrayPattern())return null;let N=y.path,P=N.node.init;if(!P||!G.isCallExpression(P))return null;let R=iF(P);if(!R||!G.isArrayPattern(N.node.id)||N.node.id.elements.findIndex(V=>G.isIdentifier(V)&&V.name===y.identifier.name)!==0)return null;let T=R==="useReducer"?1:0,O=P.arguments[T];if(!O||!G.isExpression(O))return null;let D=await r(O,N.scope,h,x,E,b,S);return D===void 0?null:{kind:"static",file:h,root:{kind:"hook-state",name:y.identifier.name,hook:R},value:D,sourceKind:"binding"}}async function c(f){let h=f.expressionPath.scope.getBinding(f.sourceInfo.base);if(!h||!h.constant||h.kind!=="param"||!f.graph)return null;let y=RE(h,f.sourceInfo);if(!y)return null;let x=[...f.graph.elements.values()].filter(b=>CE(b,f.currentFile,y.componentName,y.exportName));if(!x.length)return null;let E=[];for(let b of x){if(b.sourceFile!==x[0].sourceFile||b.componentName!==x[0].componentName||b.attributeSpreads?.length)return null;let S=await gn(b.sourceFile,f.readFile,f.fileCache),N=S.ast?Bc(S.ast,b.sourceRange):null;if(!N)return null;let P=N.parentPath;for(;P&&!P.isFunction();){if(P.isJSXElement()){let Q=P.node.openingElement.name;if(!G.isJSXIdentifier(Q)||!/^[a-z]/.test(Q.name))return null}else if(!P.isJSXFragment()&&!P.isReturnStatement()&&!P.isBlockStatement())return null;P=P.parentPath}if(!P)return null;let R=N.get("openingElement").get("attributes").filter(Q=>Q.isJSXAttribute()&&G.isJSXIdentifier(Q.node.name,{name:y.propName}));if(R.length!==1)return null;let A=R[0];if(!A?.isJSXAttribute())return null;let T=A.get("value"),O=T.isJSXExpressionContainer()?T.get("expression"):T;if(!O.isExpression())return null;let D=await r(O.node,O.scope,b.sourceFile,f.readFile,f.exists,f.fileCache,f.visited),V=D===void 0?void 0:kt(D,y.remainingPath);if(V===void 0)return null;E.push(V)}return E}async function l(f){let h=RE(f.binding,f.sourceInfo);if(!h||!f.graph)return null;let y=[...f.graph.elements.values()].filter(R=>CE(R,f.currentFile,h.componentName,h.exportName));if(y.length!==1)return null;let x=y[0],E=x.attributes?.find(R=>R.name===h.propName);if(E&&!E.source){let R=await u({caller:x,propName:h.propName,remainingPath:h.remainingPath,readFile:f.readFile,fileCache:f.fileCache});if(R)return Xf(R,{componentName:h.componentName,propName:h.propName,file:x.sourceFile})}if(!E?.source){let R=await d({caller:x,propName:h.propName,remainingPath:h.remainingPath,readFile:f.readFile,exists:f.exists,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:f.fileCache,visited:f.visited});if(R)return Xf(R,{componentName:h.componentName,propName:h.propName,file:x.sourceFile});let A=kx(f.binding,h.componentName,h.propName);if(!A||A.propName!==h.propName)return null;let T=await r(A.expressionPath.node,A.expressionPath.scope,f.currentFile,f.readFile,f.exists,f.fileCache,f.visited);if(T===void 0)return null;let O=h.remainingPath;return O.length>0&&kt(T,O)===void 0?null:{kind:"value",file:f.currentFile,root:{kind:"binding",name:h.propName},path:O,sourceKind:"binding",semanticKind:"component-prop",displayExpression:A.displayPath,chainPrefix:[{kind:"component-prop",file:f.currentFile,displayName:A.displayPath,canEditHere:!0}],editMode:"upstream",diagnostics:[]}}let b=await gn(x.sourceFile,f.readFile,f.fileCache);if(!b.ast)return null;let S=kE(b.ast,b.source,E.source.expression,E.sourceRange)??ls(b.ast,b.source,E.source.expression);if(!S)return null;let N={...E.source,expression:Vo(E.source.expression,h.remainingPath),path:[...E.source.path,...h.remainingPath]},P=await o({currentFile:x.sourceFile,expressionPath:S,sourceInfo:N,readFile:f.readFile,exists:f.exists,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:f.fileCache,visited:f.visited});return P?Xf(P.kind==="external"?P:{...P,displayExpression:N.expression},{componentName:h.componentName,propName:h.propName,file:x.sourceFile}):null}async function u(f){let h=await gn(f.caller.sourceFile,f.readFile,f.fileCache);if(!h.ast)return null;let y=Bc(h.ast,f.caller.sourceRange);if(!y)return null;let x=y.get("openingElement").get("attributes").find(N=>N.isJSXAttribute()&&N.node.name.type==="JSXIdentifier"&&N.node.name.name===f.propName);if(!x?.isJSXAttribute())return null;let E=x.get("value"),b=E.isStringLiteral()?E:E.isJSXExpressionContainer()?E.get("expression"):null;if(!b?.isExpression())return null;let S=cs(b.node);return S?{kind:"value",file:f.caller.sourceFile,root:{kind:"expression",sourceRange:S},path:f.remainingPath,sourceKind:"binding",semanticKind:"component-prop",displayExpression:f.propName,editMode:"upstream",diagnostics:[]}:null}async function d(f){let h=await gn(f.caller.sourceFile,f.readFile,f.fileCache);if(!h.ast)return null;let y=Bc(h.ast,f.caller.sourceRange);if(!y)return null;let x=y.get("openingElement");for(let E of x.get("attributes")){if(!E.isJSXSpreadAttribute())continue;let b=E.get("argument");if(!b.isExpression())continue;let S=await i({expression:b.node,scope:b.scope,source:h.source,currentFile:f.caller.sourceFile,readFile:f.readFile,exists:f.exists,fileCache:f.fileCache,visited:f.visited});if(!S)continue;let N=[{kind:"property",name:f.propName},...f.remainingPath],P={...S,expression:Vo(S.expression,N),path:[...S.path,...N]},R=await o({currentFile:f.caller.sourceFile,expressionPath:b,sourceInfo:P,readFile:f.readFile,exists:f.exists,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:f.fileCache,visited:f.visited});if(R)return R.kind==="external"?R:{...R,displayExpression:P.expression}}return null}async function p(f){let{currentFile:h,binding:y,readFile:x,exists:E,fileCache:b,visited:S}=f,N=y.path.parentPath;if(!N||!N.isImportDeclaration())return null;let P=N.node.source.value;if(typeof P!="string")return null;let R=await Tr(h,P,E);if(!R)return null;if(y.path.isImportDefaultSpecifier()){let Q=await gn(R,x,b),U=Q.ast?zf(Q.ast,"default"):null,H=await m({file:R,exportName:"default",readFile:x,exists:E,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:b,visited:S});return!H||H.kind!=="static"?null:{kind:"static",file:U?.kind==="default-expression"?H.file:R,root:U?.kind==="default-expression"?H.root:{kind:"default-export"},value:H.value,sourceKind:"imported-binding"}}if(!y.path.isImportSpecifier())return null;let A=y.path.node.imported,T=G.isIdentifier(A)?A.name:A.value,O=await gn(R,x,b),D=O.ast?zf(O.ast,T):null,V=await m({file:R,exportName:T,readFile:x,exists:E,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:b,visited:S});return V?V.kind==="external"?V:{kind:"static",file:D?.kind==="re-export"?V.file:R,root:D?.kind==="re-export"||V.root.kind==="binding"&&V.root.name!==D?.name?V.root:{kind:"named-export",name:T},value:V.value,sourceKind:"imported-binding"}:null}async function m(f){let{file:h,exportName:y,readFile:x,exists:E,fileCache:b,visited:S}=f,N=`export::${h}::${y}`;if(!S.has(N)){S.add(N);try{let P=await gn(h,x,b);if(!P.ast)return;let R=zf(P.ast,y);if(!R)return;if(R.kind==="default-expression"){let D=R.expression;if(!D||!G.isIdentifier(D))return;let V=us(P.ast).getBinding(D.name);return V?await s({currentFile:h,binding:V,readFile:x,exists:E,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:b,visited:S})??void 0:void 0}if(R.kind==="re-export"){if(!R.source||!R.name)return;let D=await Tr(h,R.source,E);return D?m({...f,file:D,exportName:R.name}):void 0}let A=R.name;if(!A)return;let T=us(P.ast).getBinding(A);return T?await s({currentFile:h,binding:T,readFile:x,exists:E,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:b,visited:S})??void 0:void 0}finally{S.delete(N)}}}return{resolveExportValue:m,resolveComponentPropBinding:l,resolveComponentPropValues:c,resolveBindingTarget:s}}import*as oe from"@babel/types";function Wf(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=pn(o,t);if(!i)return null;let s=r.parentPath;return!s||!s.isCallExpression()||!cF(s,r)?null:{callPath:s,basePath:i}}function cF(e,t){let n=e.node.callee;return!oe.isMemberExpression(n)||!oe.isIdentifier(n.property)||n.property.name!=="map"?!1:e.node.arguments.some(r=>r===t.node)}function TE(e,t){let n=e.get("callee");if(!n.isMemberExpression())return null;let r=n.get("object");return Array.isArray(r)||!r.isExpression()?null:ic(r,t)}function _E(e,t){return e?oe.isNumericLiteral(e)&&Number.isInteger(e.value)?e.value:null:t}function PE(e,t,n,r,o){let i=oe.isExpression(e.body)?e.body:e.body.body.find(a=>oe.isReturnStatement(a))?.argument;if(!i||!oe.isExpression(i))return;let s=Hf(i,t,n,r,o);return typeof s=="number"?s:void 0}function Hf(e,t,n,r,o){if(oe.isNumericLiteral(e)||oe.isStringLiteral(e)||oe.isBooleanLiteral(e))return e.value;if(oe.isIdentifier(e))return e.name===t?r:e.name===n?o:void 0;if(oe.isMemberExpression(e)){let i=Lc(e,t);if(i)return kt(r,i);let s=Lc(e,n);return s?kt(o,s):void 0}if(oe.isBinaryExpression(e)&&e.operator==="-"){let i=oe.isExpression(e.left)?Hf(e.left,t,n,r,o):void 0,s=oe.isExpression(e.right)?Hf(e.right,t,n,r,o):void 0;return typeof i=="number"&&typeof s=="number"?i-s:void 0}}function lF(e){if(oe.isExpression(e.body))return e.body;for(let t of e.body.body)if(oe.isReturnStatement(t)&&t.argument&&oe.isExpression(t.argument))return t.argument;return null}function uF(e,t,n){let r=to(e,t,n);return typeof r=="boolean"?r:void 0}function to(e,t,n){if(oe.isStringLiteral(e)||oe.isNumericLiteral(e)||oe.isBooleanLiteral(e))return e.value;if(oe.isNullLiteral(e))return null;if(oe.isIdentifier(e))return e.name===t?n:void 0;if(oe.isMemberExpression(e)){let r=Lc(e,t);return r?kt(n,r):void 0}if(oe.isUnaryExpression(e)&&e.operator==="!"){let r=to(e.argument,t,n);return r===void 0?void 0:!r}if(oe.isLogicalExpression(e)){let r=to(e.left,t,n);if(r===void 0)return;if(e.operator==="&&")return r&&to(e.right,t,n);if(e.operator==="||")return r||to(e.right,t,n)}if(oe.isBinaryExpression(e)){let r=oe.isExpression(e.left)?to(e.left,t,n):void 0,o=oe.isExpression(e.right)?to(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 wE(e){let t=[],n=e;for(;oe.isMemberExpression(n)||oe.isOptionalMemberExpression(n);){let r=n.property;if(n.computed)if(oe.isNumericLiteral(r))t.unshift({kind:"index",index:r.value});else if(oe.isStringLiteral(r))t.unshift({kind:"property",name:r.value});else if(oe.isExpression(r))t.unshift({kind:"dynamic",expression:r});else return null;else if(oe.isIdentifier(r))t.unshift({kind:"property",name:r.name});else return null;n=n.object}return oe.isIdentifier(n)?{base:n.name,segments:t}:null}function OE(e){return e.some(t=>t.kind==="dynamic")}function AE(e){return typeof e=="string"?{kind:"property",name:e}:Number.isInteger(e)?{kind:"index",index:e}:null}function FE(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 dF(e,t){let n=[],r=[];for(let o of t){let i=kt(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 LE(e){let{resolveBindingTarget:t,evaluateStaticExpression:n,buildExpressionSourceInfo:r,resolveSourceInfoProvenance:o,resolveComponentPropValues:i}=e;async function s(f){let{currentFile:h,callPath:y,readFile:x,exists:E,fileCache:b,visited:S}=f,N=y.node.callee;if(!oe.isMemberExpression(N)||!oe.isIdentifier(N.property)||N.property.name!=="map")return null;let P=y.get("callee");if(!P.isMemberExpression())return null;let R=P.get("object");if(Array.isArray(R)||!R.isExpression())return null;let A=await a({currentFile:h,expressionPath:R,readFile:x,exists:E,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:b,visited:S});return!A||!Array.isArray(A.value)||A.value.length===0?null:A}async function a(f){let{currentFile:h,expressionPath:y,readFile:x,exists:E,fileCache:b,visited:S}=f;if(y.isIdentifier()){let N=y.scope.getBinding(y.node.name);if(!N)return null;let P=await t({currentFile:h,binding:N,readFile:x,exists:E,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:b,visited:S});return P?.kind==="static"?P:null}if(y.isCallExpression())return l({currentFile:h,callPath:y,readFile:x,exists:E,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:b,visited:S});if(y.isTSAsExpression()||y.isTSSatisfiesExpression()||y.isTSNonNullExpression()){let N=y.get("expression");if(!Array.isArray(N)&&N.isExpression())return a({...f,expressionPath:N})}if(y.isArrayExpression()){let N=cs(y.node);if(!N)return null;let P=await n(y.node,y.scope,h,x,E,b,S);return Array.isArray(P)?{kind:"static",file:h,root:{kind:"expression",sourceRange:N},value:P,sourceKind:"binding"}:null}if(y.isMemberExpression()){let N=await r({expression:y.node,scope:y.scope,currentFile:h,readFile:x,exists:E,fileCache:b,visited:S});if(!N)return null;let P=await o({currentFile:h,expressionPath:y,sourceInfo:N,readFile:x,exists:E,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:b,visited:S});if(!P||P.kind==="external")return null;let R=await c({currentFile:h,expressionPath:y,provenance:P,readFile:x,exists:E,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:b,visited:S});if(!R||R.kind!=="static")return null;if(P.collectionPathMap?.length){let T=dF(R.value,P.collectionPathMap);if(T)return{kind:"static",file:P.file,root:P.root,value:T.value,sourceKind:P.sourceKind,collectionPathMap:T.collectionPathMap}}let A=kt(R.value,P.path);return Array.isArray(A)?{kind:"static",file:P.file,root:P.root,value:A,sourceKind:P.sourceKind,pathPrefix:P.path,collectionIndexMap:P.collectionIndexMap,collectionPathMap:P.collectionPathMap}:null}return null}async function c(f){let{provenance:h}=f;if(h.root.kind==="binding"){let b=f.expressionPath.scope.getBinding(h.root.name);if(!b&&h.file!==f.currentFile){let S=await gn(h.file,f.readFile,f.fileCache);b=S.ast?us(S.ast).getBinding(h.root.name):void 0}return b?await t({currentFile:h.file,binding:b,readFile:f.readFile,exists:f.exists,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:f.fileCache,visited:f.visited}):null}if(h.root.kind!=="expression")return null;let y=await gn(h.file,f.readFile,f.fileCache);if(!y.ast)return null;let x=vE(y.ast,h.root.sourceRange);if(!x)return null;let E=await n(x.node,x.scope,h.file,f.readFile,f.exists,f.fileCache,f.visited);return E===void 0?null:{kind:"static",file:h.file,root:h.root,value:E,sourceKind:h.sourceKind}}async function l(f){return await u(f)??await d(f)??await p(f)}async function u(f){let{callPath:h}=f,y=h.node.callee;if(!oe.isMemberExpression(y)||!oe.isIdentifier(y.property)||y.property.name!=="filter")return null;let x=h.get("callee");if(!x.isMemberExpression())return null;let E=x.get("object");if(Array.isArray(E)||!E.isExpression())return null;let b=await a({currentFile:f.currentFile,expressionPath:E,readFile:f.readFile,exists:f.exists,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:f.fileCache,visited:f.visited});if(!b||!Array.isArray(b.value))return null;let[S]=h.node.arguments;if(!oe.isArrowFunctionExpression(S)&&!oe.isFunctionExpression(S))return null;let N=S.params[0];if(!oe.isIdentifier(N))return null;let P=lF(S);if(!P)return null;let R=[],A=[],T=[];for(let[O,D]of b.value.entries()){let V=uF(P,N.name,D);if(typeof V!="boolean")return null;if(V){R.push(D),A.push(b.collectionIndexMap?.[O]??O);let Q=b.collectionPathMap?.[O];Q&&T.push(Q)}}return{...b,value:R,pathPrefix:b.pathPrefix,collectionIndexMap:A,...T.length>0?{collectionPathMap:T}:{}}}async function d(f){let{callPath:h}=f,y=h.node.callee;if(!oe.isMemberExpression(y)||!oe.isIdentifier(y.property)||y.property.name!=="slice")return null;let x=h.get("callee");if(!x.isMemberExpression())return null;let E=x.get("object");if(Array.isArray(E)||!E.isExpression())return null;let b=await a({currentFile:f.currentFile,expressionPath:E,readFile:f.readFile,exists:f.exists,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:f.fileCache,visited:f.visited});if(!b||!Array.isArray(b.value))return null;let[S,N]=h.node.arguments,P=_E(S,0),R=_E(N,b.value.length);if(P===null||R===null)return null;let A=Math.max(0,P<0?b.value.length+P:P),T=Math.max(0,R<0?b.value.length+R:R),O=b.value.map((V,Q)=>b.collectionIndexMap?.[Q]??Q).slice(A,T),D=b.collectionPathMap?.slice(A,T);return{...b,value:b.value.slice(A,T),pathPrefix:b.pathPrefix,collectionIndexMap:O,...D?{collectionPathMap:D}:{}}}async function p(f){let{callPath:h}=f,y=h.node.callee;if(!oe.isMemberExpression(y)||!oe.isIdentifier(y.property)||y.property.name!=="sort"&&y.property.name!=="toSorted")return null;let x=h.get("callee");if(!x.isMemberExpression())return null;let E=x.get("object");if(Array.isArray(E)||!E.isExpression())return null;let b=await a({currentFile:f.currentFile,expressionPath:E,readFile:f.readFile,exists:f.exists,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:f.fileCache,visited:f.visited});if(!b||!Array.isArray(b.value))return null;let[S]=h.node.arguments;if(!oe.isArrowFunctionExpression(S)&&!oe.isFunctionExpression(S))return null;let[N,P]=S.params;if(!oe.isIdentifier(N)||!oe.isIdentifier(P))return null;let R=b.value.map((T,O)=>({value:T,sourceIndex:b.collectionIndexMap?.[O]??O,originalIndex:O})),A=[...R];for(let T of R)for(let O of R)if(PE(S,N.name,P.name,T.value,O.value)===void 0)return null;return A.sort((T,O)=>{let D=PE(S,N.name,P.name,T.value,O.value)??0;return D===0?T.originalIndex-O.originalIndex:D}),{...b,value:A.map(T=>T.value),pathPrefix:b.pathPrefix,collectionIndexMap:A.map(T=>T.sourceIndex),...b.collectionPathMap?{collectionPathMap:A.map(T=>b.collectionPathMap?.[T.originalIndex]).filter(T=>!!T)}:{}}}async function m(f){let h=null,y=!1,x,E=[];for(let S of f.segments){if(S.kind!=="dynamic")continue;let N=await r({expression:S.expression,scope:f.expressionPath.scope,source:f.fileCache.get(f.currentFile)?.source,currentFile:f.currentFile,readFile:f.readFile,exists:f.exists,fileCache:f.fileCache,visited:f.visited});if(!N)return null;let P=Wf(f.expressionPath,N.base),R;if(P){y=!0;let A=await s({currentFile:f.currentFile,callPath:P.callPath,readFile:f.readFile,exists:f.exists,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:f.fileCache,visited:f.visited});if(!A||!Array.isArray(A.value))return null;R=A.value.map((T,O)=>{let D=kt(A.value,[{kind:"index",index:O},...P.basePath,...N.path]);return AE(D)}),x??=A.collectionIndexMap}else{let A=await i({...f,sourceInfo:N});if(!A)return null;R=A.map(AE)}if(R.some(A=>A===null)||h!==null&&h!==R.length)return null;h=R.length,E.push(R)}if(h===null||h===0)return null;let b=[];for(let S=0;S<h;S+=1){let N=[...f.rootPath],P=0;for(let R of f.segments){if(R.kind==="dynamic"){let A=E[P]?.[S];if(!A)return null;N.push(A),P+=1;continue}N.push({...R})}b.push(N)}return{sourceKind:y||h>1?"repeat-template":"binding",...x?{collectionIndexMap:x}:{},collectionPathMap:b}}return{resolveRepeatCollectionTarget:s,resolveCollectionCallTarget:l,resolveDynamicMemberPathMap:m}}var{normalizeExpressionWithScope:fF,evaluateStaticExpression:jc}=gE({resolveBindingTarget:e=>$c(e)}),{resolveRepeatCollectionTarget:pF,resolveCollectionCallTarget:mF,resolveDynamicMemberPathMap:gF}=LE({resolveBindingTarget:e=>$c(e),evaluateStaticExpression:jc,buildExpressionSourceInfo:wn,resolveSourceInfoProvenance:rn,resolveComponentPropValues:e=>xF(e)}),{resolveExportValue:hF,resolveComponentPropBinding:yF,resolveComponentPropValues:xF,resolveBindingTarget:$c}=NE({resolveExternalExpression:tp,resolveCollectionCallTarget:mF,evaluateStaticExpression:jc,resolveSourceInfoProvenance:rn,buildExpressionSourceInfo:wn});function JE(e){return new Map([...e].map(t=>[t.file,{source:t.source,ast:t.ast}]))}var DE=new WeakMap;function bF(e){let t=DE.get(e);return t||(t=new WeakMap,DE.set(e,t)),t}function ME(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 XE(e){let{file:t,source:n,segment:r,readFile:o,exists:i}=e,s=e.fileCache??new Map,a=Dc(s,t,n);if(!a)return null;let c=Mc(a,r.sourceRange);if(!c)return null;let l=await wn({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:o,exists:i,fileCache:s,visited:new Set});if(!l){let p=await ip({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 p?Zf(p,$o(c.node,n)):null}let u=new Set,d=await VF({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?Zf(d,l.expression):null}async function Uo(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=Dc(i,t,n);if(!s)return null;let a=e.sourceRange?Mc(s,e.sourceRange):e.expression!==void 0?ls(s,n,e.expression):null;if(!a)return null;let c=Vc(a);if(!c.isIdentifier()&&!c.isMemberExpression())return null;let l=new Set,u=await wn({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:r,exists:o,fileCache:i,visited:l}),d=u?await rn({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 QE({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 Zf(d,e.expression??$o(c.node,n))}async function ep(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=Dc(i,t,n);if(!s)return Xt("unsupported-expression","Unable to parse source for provenance resolution");let a=new Set;return e.target.kind==="text-segment"?EF({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}):SF({file:t,source:n,ast:s,candidate:e.target.candidate,readFile:r,exists:o,graph:e.graph,fileCache:i,visited:a})}async function wn(e){if(le.isIdentifier(e.expression))return{kind:"identifier",expression:e.expression.name,base:e.expression.name,path:[]};if(!le.isMemberExpression(e.expression))return null;let t=await fF(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:$o(e.expression,e.source),base:t.base,path:t.path}:null}function Zf(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 EF(e){let{file:t,source:n,ast:r,segment:o,readFile:i,exists:s,fileCache:a,visited:c}=e,l=Mc(r,o.sourceRange),u=l?await wn({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 BE(t,o.value);let p=await ip({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 p?p.kind==="external"?KE(t,p):Qf(t,$o(l.node,n),p):vF({expression:l.node,scope:l.scope,currentFile:t,source:n,readFile:i,exists:s,fileCache:a,visited:c,functionCallContracts:e.functionCallContracts})}if(!l)return Xt("unsupported-expression","Unable to locate text expression for provenance resolution");let d=await rn({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 p=qf(l.node);if(p)return Xt(p.code,p.message);let m=l.scope.getBinding(u.base);if(m?.path.isVariableDeclarator()){let f=qf(m.path.node.init);if(f)return Xt(f.code,f.message)}return m?.path.isVariableDeclarator()&&le.isCallExpression(m.path.node.init)?IF("unsupported-expression",YE(m.path.node.init,e.functionCallContracts)):Xt("unsupported-expression",`Unable to resolve provenance for expression "${u.expression}"`)}return d.kind==="external"?KE(t,d):Qf(t,u.expression,d)}async function SF(e){let{file:t,source:n,ast:r,candidate:o,readFile:i,exists:s,fileCache:a,visited:c}=e;if(!o.conditionSource)return Xt("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let l=ls(r,n,o.conditionExpression);if(!l)return Xt("conditional-branch-unresolved",`Unable to locate conditional expression "${o.conditionExpression}"`);let u=await rn({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 Xt("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);if(u.kind==="external")return Xt("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let d=Qf(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 BE(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 vF(e){let t=await HE(e);if(t.length===0)return Xt("unsupported-expression",`Unsupported expression type: ${e.expression.type}`);if(kF(e.expression))return zE(t);if(GE(e.expression))return Xt("unsupported-expression","i18n helpers require a static message id string");if(le.isMemberExpression(e.expression)&&e.expression.computed&&!le.isNumericLiteral(e.expression.property)&&!le.isStringLiteral(e.expression.property))return Xt("dynamic-key","Computed member expressions are not supported for provenance resolution");let[n]=t;return Xt(n.code,n.message)}function Xt(e,t){return{finalSource:null,chain:[],confidence:"unknown",editMode:"unsupported",diagnostics:[{code:e,message:t}]}}function IF(e,t){return zE([{code:e,message:t}])}function zE(e){return{finalSource:null,chain:[],confidence:"partial",editMode:"readonly",diagnostics:e}}function kF(e){return le.isCallExpression(e)||le.isConditionalExpression(e)||le.isLogicalExpression(e)||le.isBinaryExpression(e)}function fs(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 HE(e){let{expression:t,scope:n,currentFile:r,readFile:o,exists:i,fileCache:s,visited:a,functionCallContracts:c}=e,l=qf(t);if(l)return[l];if(le.isCallExpression(t))return[{code:"unsupported-expression",message:YE(t,c)}];if(le.isMemberExpression(t)&&t.computed){let u=t.property;if(!le.isNumericLiteral(u)&&!le.isStringLiteral(u)){if(!le.isExpression(u))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}];let p=await jc(u,n,r,o,i,s,a);if(typeof p!="string"&&!Number.isInteger(p))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}]}}return le.isBinaryExpression(t)?fs([...await Gf(t.left,t.right,e),{code:"unsupported-expression",message:"Mixed expressions are recognized but remain readonly until a safer composition editing strategy is available"}]):le.isLogicalExpression(t)?fs([...await Gf(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"}]):le.isConditionalExpression(t)?fs([...await Gf(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 qf(e){return GE(e)?jE("i18n helpers require a static message id string"):PF(e)?jE("CMS helpers require static entry id and field path string arguments"):null}async function Gf(...e){let t=e[e.length-1],n=e.slice(0,-1),r=[];for(let o of n)r.push(...await HE({...t,expression:o}));return r}function RF(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:[CF(e.sourceType)]}}async function tp(e){for(let n of OF){if(!$E(e.expressionPath,n.helperNames))continue;let r=await n.resolve(e);if(r)return UE(VE(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(!$E(e.expressionPath,n.helperNames))continue;let r=await n.resolve(t);if(r)return UE(VE(r),e.externalAdapters)}return null}function CF(e){return{code:"missing-adapter",message:`No external adapter is registered for ${e}`}}function NF(e){return{code:"external-source-readonly",message:e}}function jE(e){return{code:"unsupported-expression",message:e}}function np(e){return!e||!le.isCallExpression(e)?null:le.isIdentifier(e.callee)?e.callee.name:le.isMemberExpression(e.callee)&&!e.callee.computed&&le.isIdentifier(e.callee.object)&&le.isIdentifier(e.callee.property)?`${e.callee.object.name}.${e.callee.property.name}`:null}function $E(e,t){if(!t||t.length===0)return!0;let n=np(e.node);return n?t.includes(n):!1}function VE(e){return"match"in e?{match:e.match,editMode:e.editMode,diagnostics:fs(e.diagnostics??[])}:{match:e,diagnostics:[]}}function UE(e,t){let n=RF(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:fs([...e.diagnostics,...e.editMode==="readonly"||n.editMode==="readonly"?n.diagnostics:[]])}}function _F(e){if(!e.isCallExpression())return null;let t=e.node.callee;if(!le.isIdentifier(t)||t.name!=="getCmsField")return null;let[n,r]=e.node.arguments;if(!n||!r||!le.isStringLiteral(n)||!le.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 PF(e){return!!e&&le.isCallExpression(e)&&le.isIdentifier(e.callee)&&e.callee.name==="getCmsField"&&(e.arguments.length<2||!le.isStringLiteral(e.arguments[0])||!le.isStringLiteral(e.arguments[1]))}function WE(e){if(!(!e||!le.isCallExpression(e))){if(le.isIdentifier(e.callee)&&e.callee.name==="t"){let[t]=e.arguments;return t&&le.isStringLiteral(t)?t.value:null}if(le.isMemberExpression(e.callee)&&!e.callee.computed&&le.isIdentifier(e.callee.object)&&e.callee.object.name==="intl"&&le.isIdentifier(e.callee.property)&&e.callee.property.name==="formatMessage"){let[t]=e.arguments;if(!t||!le.isObjectExpression(t))return null;for(let n of t.properties)if(le.isObjectProperty(n)&&!n.computed&&(le.isIdentifier(n.key)&&n.key.name==="id"||le.isStringLiteral(n.key)&&n.key.value==="id")&&le.isStringLiteral(n.value))return n.value.value;return null}}}function GE(e){return WE(e)===null}async function AF(e,t,n){let r=new Set,o=ds.posix.dirname(e);for(;r.add(o),!(o==="."||o==="/");){let i=ds.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"]:[ds.posix.join(i,"locales"),ds.posix.join(i,"messages")];for(let a of s){let c=ds.posix.join(a,`${t}.json`);if(await n(c))return c}}return null}async function TF(e){let t=WE(e.expressionPath.node);if(typeof t!="string"||t.length===0)return null;let n="en",r=await AF(e.currentFile,n,e.exists);return r?{sourceType:"i18n-message",sourceId:`${n}:${t}`,file:r,displayPath:t}:null}async function wF(e){if(!e.expressionPath.isCallExpression())return null;let t=e.expressionPath.node.callee;if(!le.isIdentifier(t)||t.name!=="apiField")return null;let[n,r]=e.expressionPath.node.arguments;if(!n||!le.isExpression(n))return null;let o=await jc(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:[NF("API mapping transforms must stay readonly until a reversible mapping strategy is registered")]}:i}var OF=[{helperNames:["getCmsField"],resolve:({expressionPath:e})=>_F(e)},{helperNames:["apiField"],resolve:e=>wF(e)},{helperNames:["t","intl.formatMessage"],resolve:({currentFile:e,expressionPath:t,exists:n})=>TF({currentFile:e,expressionPath:t,exists:n})}];function rp(e){return{...e,editMode:"readonly",diagnostics:[{code:"unsupported-expression",message:"Derived display values are readonly because no identity-preserving write target exists"}]}}function KE(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 Qf(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=$F(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 FF=[{helperName:"formatPrice",purity:"pure",sourceArgIndex:0},{helperName:"formatDate",purity:"pure",sourceArgIndex:0},{helperName:"pickLabel",purity:"pure",sourceArgIndex:0}];function op(e,t){let n=[...FF,...t??[]];for(let r=n.length-1;r>=0;r-=1){let o=n[r];if(o?.helperName===e)return o}return null}function YE(e,t){let n=e.callee;return le.isIdentifier(n)&&op(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 ip(e){let t=await tp(e);if(t)return t;let n=await ZE({...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 wn({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 rn({...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 BF(e)}async function ZE(e){let t=await hn({...e,allowComposed:!1});if(t?.kind!=="source")return null;let n=Vc(e.expressionPath);return n.isIdentifier()||n.isMemberExpression()?t.provenance:rp(t.provenance)}async function hn(e){let t=Vc(e.expressionPath),n=MF(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 wn({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 rn({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 wn({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 rn({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 hn({...e,expressionPath:r,allowComposed:!0}),a=await hn({...e,expressionPath:o,allowComposed:!1}),c=await hn({...e,expressionPath:i,allowComposed:!1});return Yf(s,a,c)}if(t.isCallExpression())return LF({...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 hn({...e,expressionPath:r,allowComposed:!0}),s=await hn({...e,expressionPath:o,allowComposed:!0});return Yf(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 hn({...e,expressionPath:r,allowComposed:!0}),s=await hn({...e,expressionPath:o,allowComposed:!0});return Yf(i,s)}if(t.isUnaryExpression()){let r=t.get("argument");return Array.isArray(r)||!r.isExpression()?null:hn({...e,expressionPath:r,allowComposed:!0})}return null}finally{n&&e.visited.delete(n)}}function Vc(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 LF(e){let t=np(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:hn({...e,expressionPath:r,allowComposed:!1})}let n=e.expressionPath.get("callee");if(n.isMemberExpression()&&!n.node.computed){let r=n.node.property;if(le.isIdentifier(r)&&(r.name==="toFixed"||r.name==="toString")){let o=n.get("object");return Array.isArray(o)||!o.isExpression()?null:hn({...e,expressionPath:o,allowComposed:!1})}}return null}function Yf(...e){let t=null;for(let n of e){if(!n)return null;if(n.kind!=="none"){if(!t){t=n.provenance;continue}if(!DF(t,n.provenance))return null}}return t?{kind:"source",provenance:t}:{kind:"none"}}function DF(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 MF(e,t){return t.start==null||t.end==null?null:`safe-derived:${e}:${t.start}:${t.end}`}async function BF(e){if(!e.expressionPath.isCallExpression())return null;let t=np(e.expressionPath.node);if(!t)return null;let n=op(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 qE({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?rp(i):null}async function qE(e){let t=await tp({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 wn({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 rn({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 ip({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 jF(e){if(!e.binding.path.isVariableDeclarator())return null;let t=e.binding.path.node.init;if(!t||!le.isCallExpression(t))return null;let n=t.callee;if(!le.isIdentifier(n))return null;let r=op(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 qE({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?rp(a):null}function $F(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=Vo(t,e.path);return{sourceId:o,displayPath:o}}async function VF(e){let t=e.segment.source;return t?rn({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 rn(e){let t=e.sourceInfo,n=Wf(e.expressionPath,t.base);if(n){let l=await pF({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 h=TE(n.callPath,[...n.basePath,...t.path]);return Gi(h)?ME(e.currentFile,h.sourceId,h.displayPath):null}let u=FE(l,[...n.basePath,...t.path]),d=l.collectionIndexMap?.[0]??0,p=[...l.pathPrefix??[],{kind:"index",index:d},...n.basePath,...t.path],m=[{kind:"index",index:0},...n.basePath,...t.path];return kt(l.value,m)===void 0?null:{kind:"value",file:l.file,root:l.root,path:u?.[0]??p,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 Tr(e.currentFile,u.node.source.value,e.exists);if(!d)return null;let p=await hF({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(!p||p.kind==="external")return null;let m=t.path.slice(1);return kt(p.value,m)===void 0?null:{kind:"value",file:p.file,root:p.root,path:m,sourceKind:"imported-binding",collectionIndexMap:p.collectionIndexMap}}let o=vx(r);if(o){let l=o.expressionPath,u=await wn({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 rn({...e,expressionPath:l,sourceInfo:{...u,expression:Vo(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 p=await QE({...e,expressionPath:Vc(l),memberSuffix:t.path});if(p?.kind==="value")return p}finally{e.visited.delete(d)}}if(t.path.length===0){let d=await ZE({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 yF({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 jF({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=rc(r,t.path,bF(e.fileCache));if(Gi(s))return ME(e.currentFile,s.sourceId,s.displayPath);let a=await $c({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:kt(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 QE(e){let t=wE(e.expressionPath.node);if(!t||!OE(t.segments))return null;let n=await rn({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 gF({...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 $c({...e,binding:i}):null;if(s?.kind!=="static"||o.some(a=>kt(s.value,a.slice(n.path.length))===void 0))return null}return{...n,path:o[0]??n.path,sourceKind:r.sourceKind,displayExpression:$o(e.expressionPath.node,e.fileCache.get(e.currentFile)?.source),...r.collectionIndexMap?{collectionIndexMap:r.collectionIndexMap}:{},collectionPathMap:o}}async function eS(e){let t=UF(e.propertyName);if(t.owner==="blocked")return kr(t.owner,t.diagnostic);if(t.owner==="class-name-source"||t.owner==="style")return kr(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 kr("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 JF(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 kr("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}:kr("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?kr("generic",{code:"remove-exposes-spread",message:`Removing '${e.propertyName}' would expose an earlier spread source`}):KF(e,s.attribute)}async function KF(e,t){if(t.resolution&&t.resolution.status!=="resolved"&&!t.source){let r=await Uo({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}}:kr("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 Uo({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"?kr("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 JF(e,t){let n=t.source?.expression;if(!n)return;let r=await Uo({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:XF(r,e.propertyName)}}function XF(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 kr(e,t){return{status:"blocked",owner:e,...t?{diagnostic:t}:{}}}function tS(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(no(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=>GF(a,r.componentName)),s=i.length===1?i[0].identity.key:null;return o.keys.set(r.componentName,s),s};return r=>zF({...r,graph:e},n)}function zF(e,t){let{key:n,element:r,graph:o,provenances:i}=e,s=WF(n,r,o,t),a=s?.tag??(no(r.tag)?r.tag:r.componentName),c=s?.identity.key??t(r,o)??n,l=ZF(s),u=qF(n,r,o,i,s),d=HF(n,r,o,i,c);return{componentName:a,instanceKey:c,templateOwner:YF(s??r,a),...l.length>0?{variantKeys:l}:{},...u.length>0?{slotKeys:u}:{},editableStrategy:d,impactScope:QF(d),alternativeStrategies:eL(d)}}function HF(e,t,n,r,o){for(let i of r.values())if(i?.editMode==="upstream")return"upstream";return sp(e,n)?"instance":!no(t.tag)&&t.sourceFile!==n.routeId&&o!==e?"template":"instance"}function WF(e,t,n,r){if(no(t.tag))return t;let o=sp(e,n);if(o)return o;let i=r(t,n);return i?n.elements.get(i)??null:null}function GF(e,t){return e.exportName===t||e.tag===t||e.exportName==="default"}function YF(e,t){return no(e.tag)&&e.importedFrom?`${e.importedFrom}#${t}`:`${e.sourceFile}#${t}`}function ZF(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 qF(e,t,n,r,o){let i=new Set,s=sp(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&&no(t.tag)&&t.childKeys.length>0&&i.add("children"),[...i]}function sp(e,t){let n=t.elements.get(e)?.parentKey??null;for(;n;){let r=t.elements.get(n);if(!r)break;if(no(r.tag))return r;n=r.parentKey}return null}function no(e){return/^[A-Z]/.test(e)}function QF(e){switch(e){case"template":return"component-template";case"upstream":return"upstream-source";default:return"current-instance"}}function eL(e){switch(e){case"template":return["instance"];case"upstream":return["template"];default:return["template"]}}function oS(e){let t=e.isRepeat??(e.graph?lL(e.element,e.graph):!1),n=e.propertyProvenance??new Map,r=e.repeatTargets??new Map,o=cL(e.element.attributes??[]),i=[...r.values()].some(u=>u.ok),s=o.map(u=>tL({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:uL(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 tL(e){let{attribute:t,provenance:n,repeatTarget:r}=e,o=e.selectionRef?.instanceIndex!==void 0&&r?.ok===!0?r:null,i=nL(t,n,e.isRepeat),s=["selection","template"].map(y=>({scope:y,result:fc({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=rL(t,n,l,e.isRepeat),d=c?sL(c,e.element,t.name):void 0,p=s.filter(({result:y})=>y.ok).map(({scope:y})=>y),m=p.length>0?iL(n,o,e.element):"unsupported",f=o?"repeat-item":e.isRepeat?"repeat-template":"node",h=aL(t,n,r);if(p.length===0&&h.length===0){let y=s.find(({result:x})=>!x.ok)?.result;y&&!y.ok&&h.push({code:y.code,message:y.reason})}return{name:t.name,source:i,resolution:u,editMode:m,sourceScope:f,allowedWriteScopes:p,...d?{effectiveWriteTarget:d}:{},diagnostics:h}}function nL(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 rL(e,t,n,r){return n?nS(n.selectedResolution):t?.status==="blocked"?{status:"unresolved"}:r&&t?.status==="binding"?{status:"unresolved"}:nS(oL(e))}function oL(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 nS(e){return!e||e.status==="unresolved"?{status:"unresolved"}:e.status==="undefined"?{status:"undefined"}:{status:"resolved",value:e.value}}function iL(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 sL(e,t,n){return e.kind==="repeat-property"?{kind:"value-path",file:e.target.sourceFile,isProxy:e.target.sourceFile!==t.sourceFile,displayPath:rS({...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:rS(e.locator)}:{kind:"jsx-node",file:t.sourceFile,isProxy:!1,displayPath:t.componentName+" > "+n}}function aL(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 cL(e){let t=new Set;return e.filter(n=>t.has(n.name)?!1:(t.add(n.name),!0))}function lL(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 rS(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 uL(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 dL(e){return e==="api-field"||e==="cms-field"||e==="i18n-message"||e==="config-entry"}var fL=160;function iS(e,t,n,r={}){let o=po(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 sS(e,t,n,r,o,i,s,a,c,l,u){let d=po(t),p=t.elements.get(e),m=n.nodes.get(e),f=r.get(e);if(!p||!m||!f)throw new Error(`Node not found: ${e}`);let h=dS(p.textSegments,s),y=fS(e,t,p,f,h),x=h?hL(h):void 0,E=yL(i,h),b=p.textSegments.map(R=>({index:R.index,value:R.value,editable:pS(R,f,s?.get(R.index)??null),source:o.get(R.index)??null})),S=lS(p,t),N=p.childKeys.map(R=>{let A=t.elements.get(R);return A?{key:R,tag:A.tag,label:A.tag}:null}).filter(R=>R!==null),P=[];if(p.parentKey){let R=t.elements.get(p.parentKey);if(R)for(let A of R.childKeys){if(A===e)continue;let T=t.elements.get(A);T&&P.push({key:A,tag:T.tag,label:T.tag})}}return{composition:d,key:e,tag:p.tag,componentName:p.componentName,sourceFile:p.sourceFile,sourceLocator:cS(p),label:p.tag,capabilities:y,writeTarget:i,effectiveWriteTarget:E,provenanceChain:x,componentSemantic:c,styleSource:l,conditional:a,...u?{dynamicData:u}:{},textSegments:b,boundaryKind:p.boundaryKind,isOpaque:p.isOpaque,ancestors:S,children:N,siblings:P}}function aS(e,t,n,r,o,i,s,a){let c=po(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 p=dS(l.textSegments,i),m=pL(l);return{composition:c,key:e,tag:l.tag,...m?{linkSourceKind:m}:{},componentName:l.componentName,sourceFile:l.sourceFile,sourceLocator:cS(l),label:l.tag,capabilities:fS(e,t,l,d,p),provenanceChain:p?{editMode:p.editMode,diagnostics:p.diagnostics.map(f=>({code:f.code,message:f.message}))}:void 0,...s?{dynamicData:s}:{},...a?{properties:a}:{},textSegments:l.textSegments.map(f=>{let h=o.get(f.index);return{index:f.index,editable:pS(f,d,i?.get(f.index)??null),source:h?{kind:h.kind}:null}}),boundaryKind:l.boundaryKind,isOpaque:l.isOpaque,ancestors:lS(l,t)}}function pL(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 cS(e){return{sourceFile:e.sourceFile,componentName:e.componentName,openingElementRange:mL(e.sourceRange),structuralPath:e.identity.structuralPath,...gL(e.textSegments)}}function lS(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 mL(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function gL(e){let t=e.map(n=>n.value.trim()).filter(Boolean).join(" ").replace(/\s+/g," ").trim();return t?{textPreview:t.slice(0,fL)}:{}}function uS(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 dS(e,t){if(!t)return null;for(let n of e){let r=t.get(n.index);if(r)return r}return null}function fS(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 pS(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 hL(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 yL(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}:dL(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 ap=["set-class-name-source","apply-style-draft"];function gS(e){let t=e.attributes?.find(n=>n.name==="className");if(!t)return{kind:"class-name-source",className:"",sourceKind:"missing",editable:!0,operationBoundary:ap,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:ap,sourcePath:n}}return{kind:"class-name-source",className:t.value,sourceKind:t.resolvedValue===void 0?"static-attribute":"static-expression",editable:!0,operationBoundary:ap}}import hS from"node:path";function lp(){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 xS(e,t,n){let r=[],o=new Set;for(let i of e.intents){let s=SL(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 Uc(e){let t=()=>xL(e);return e.mutex?e.mutex.runExclusive(t):t()}async function xL(e){let t=await xS(e.plan,e.overlay,e.exists);if(!t.ok)return{ok:!1,stage:"precheck",reason:t.reason,error:t,recoveryRequired:!1};let n=bL(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 cp({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 cp({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 cp({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 yS("swap",l,"Live state swap failed after durable publish.")}try{await e.finalizeCandidate?.(c)}catch(l){return yS("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 bL(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 cp(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:EL(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 yS(e,t,n){return{ok:!1,stage:e,reason:n,error:t,recoveryRequired:!0}}function EL(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 SL(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)||hS.isAbsolute(e))return{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`};let t=hS.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 vL=50,IL=8*1024*1024;function vS(e,t={}){let n=[],r=[],o=t.externalAdapters??[],i=Math.max(0,t.maxUndoEntries??vL),s=Math.max(0,t.maxUndoBytes??IL);return{prepareRewritePlan:a,execute:c,executeFilePlan:l,undo:u,redo:d};async function a(R){let A=[...R.steps].sort((U,H)=>U.order-H.order),T=A.filter(U=>U.type!=="invoke-external-adapter");if(T.length!==A.length)return{ok:!1,errorCode:"unsupported-operation",reason:"External adapter writes require a transactional prepare/commit/rollback contract."};let O=new Set(T.map(U=>U.file)),D=await E(O),V=new Map(D.map(U=>[U.file,U.exists===!1?"":U.content])),Q;for(let U of T){let H=SS(U,V.get(U.file)??"");if(!H.ok)return{ok:!1,errorCode:H.errorCode,reason:H.reason};V.set(U.file,H.source),Q=H.selectionRef??Q}return{ok:!0,filePlan:{operationId:R.operationId,kind:"source-edit",target:R.target,documentVersion:R.documentVersion,conflictPolicy:"compare-and-swap",edits:[...V].map(([U,H])=>({operation:"upsert",file:U,content:H,baseContentHash:D.find(ye=>ye.file===U)?.sha256??null}))},...Q?{selectionRef:Q}:{}}}async function c(R){let A=[...R.steps].sort((ye,st)=>ye.order-st.order),T=A.filter(ye=>ye.type!=="invoke-external-adapter"),O=A.filter(ye=>ye.type==="invoke-external-adapter"),D=new Set(T.map(ye=>ye.file));if(T.length>0&&O.length>0)return{ok:!1,operationId:R.operationId,errorCode:"unsupported-operation",reason:"Mixed local file rewrites and external adapter writes require an explicit compensation contract.",rolledBack:!1};if(T.length===0)return y(R,O);let V=await E(D),Q=new Map;for(let ye of V)Q.set(ye.file,ye.exists===!1?"":ye.content);let U;for(let ye of T){let st=Q.get(ye.file)??"",pt=SS(ye,st);if(!pt.ok)return{ok:!1,operationId:R.operationId,errorCode:pt.errorCode,reason:pt.reason,rolledBack:!1};Q.set(ye.file,pt.source),pt.selectionRef&&(U=pt.selectionRef)}let H=await S([...Q].map(([ye,st])=>({file:ye,content:st,exists:!0,version:0,sha256:ve(st)})),V);return H.ok===!1?{ok:!1,operationId:R.operationId,errorCode:H.rolledBack?"writeback-failed":"rollback-failed",reason:H.reason,rolledBack:H.rolledBack}:(n.push({operationId:R.operationId,preSnapshots:V,postSnapshots:H.snapshots,plan:R}),p(),r.length=0,{ok:!0,operationId:R.operationId,kind:R.kind,target:R.target,resultVersion:Math.max(...H.snapshots.map(ye=>ye.version)),affectedFiles:[...D],...U?{selectionRef:U}:{}})}async function l(R){let A=new Set(R.edits.map(H=>H.file)),T=await E(A),O=x(R,T);if(O)return{ok:!1,operationId:R.operationId,errorCode:"stale-version",reason:O.reason,affectedFiles:[O.file],rolledBack:!1};let D=new Map(T.map(H=>[H.file,H])),V=R.edits.find(H=>H.operation==="create-only"&&D.get(H.file)?.exists!==!1);if(V)return{ok:!1,operationId:R.operationId,errorCode:"stale-version",reason:`MATERIALIZATION_INSTANCE_CONFLICT: create-only target already exists: ${V.file}`,affectedFiles:[V.file],rolledBack:!1};let Q=R.edits.map(H=>H.operation==="delete"?{file:H.file,content:"",exists:!1,version:0}:{file:H.file,content:H.content,exists:!0,version:0,sha256:ve(H.content)}),U=await S(Q,T,new Set(R.edits.filter(H=>H.operation==="create-only").map(H=>H.file)));return U.ok===!1?{ok:!1,operationId:R.operationId,errorCode:U.rolledBack?"writeback-failed":"rollback-failed",reason:U.reason,rolledBack:U.rolledBack}:(n.push({operationId:R.operationId,preSnapshots:T,postSnapshots:U.snapshots,plan:{operationId:R.operationId,kind:R.kind,target:R.target,documentVersion:R.documentVersion,steps:[],preSnapshots:T}}),p(),r.length=0,{ok:!0,operationId:R.operationId,kind:R.kind,target:R.target,resultVersion:Math.max(...U.snapshots.map(H=>H.version)),affectedFiles:[...A]})}async function u(){let R=n.at(-1);if(!R)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to undo"};let A=await S(R.preSnapshots,R.postSnapshots);return A.ok===!1?{ok:!1,operationId:R.operationId,errorCode:A.rolledBack?"writeback-failed":"rollback-failed",reason:A.reason,rolledBack:A.rolledBack}:(n.pop(),r.push(R),{ok:!0,operationId:R.operationId,kind:R.plan.kind,target:R.plan.target,resultVersion:Math.max(...A.snapshots.map(T=>T.version)),affectedFiles:R.preSnapshots.map(T=>T.file)})}async function d(){let R=r.at(-1);if(!R)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to redo"};let A=await S(R.postSnapshots,R.preSnapshots);return A.ok===!1?{ok:!1,operationId:R.operationId,errorCode:A.rolledBack?"writeback-failed":"rollback-failed",reason:A.reason,rolledBack:A.rolledBack}:(r.pop(),n.push(R),p(),{ok:!0,operationId:R.operationId,kind:R.plan.kind,target:R.plan.target,resultVersion:Math.max(...A.snapshots.map(T=>T.version)),affectedFiles:R.postSnapshots.map(T=>T.file)})}function p(){for(;n.length>i;)n.shift();for(;n.length>0&&m()>s;)n.shift()}function m(){return n.reduce((R,A)=>R+f(A),0)}function f(R){return h(R.preSnapshots)+h(R.postSnapshots)}function h(R){return R.reduce((A,T)=>A+T.file.length+T.content.length,0)}async function y(R,A){let T=[];for(let O of A){let D=O.capability??"write-text",V=o.find(U=>U.sourceType===O.sourceType&&(O.adapterId===void 0||U.adapterId===O.adapterId)&&(U.capabilities===void 0||U.capabilities.includes(D)));if(!V)return{ok:!1,operationId:R.operationId,errorCode:"unsupported-operation",reason:`No external adapter registered for ${O.sourceType}`,rolledBack:!1};let Q=await V.execute(O);if(!Q.ok)return{ok:!1,operationId:R.operationId,errorCode:"writeback-failed",reason:Q.reason??`External adapter failed for ${O.sourceType}`,rolledBack:!1};T.push(O.file)}return{ok:!0,operationId:R.operationId,kind:R.kind,target:R.target,resultVersion:0,affectedFiles:T}}function x(R,A){if(R.conflictPolicy!=="compare-and-swap")return null;let T=new Map(A.map(O=>[O.file,O]));for(let O of R.edits){if(O.operation==="create-only")continue;if(O.baseContentHash===void 0)return{file:O.file,reason:`Source file ${O.file} is missing baseContentHash. Reopen the file before saving.`};let D=T.get(O.file),V=O.baseContentHash;if(V===null){if(D?.exists!==!1)return{file:O.file,reason:`Source file ${O.file} was created or changed before save.`};continue}if(!V)return{file:O.file,reason:`Source file ${O.file} is missing baseContentHash. Reopen the file before saving.`};if(D?.exists===!1||D?.sha256!==V)return{file:O.file,reason:`Source file ${O.file} changed before save. Reload or explicitly overwrite the newer version.`}}return null}async function E(R){let A=[];for(let T of R)A.push(await b(T));return A}async function b(R){if(!await e.exists(R))return{file:R,content:"",version:0,exists:!1};let T=Math.max(1,e.getVersion(R)),O=await e.readFile(R);return{file:R,content:O,version:T,exists:!0,sha256:ve(O)}}async function S(R,A,T=new Set){let O=[];try{for(let D of R){if(T.has(D.file)){if(!e.createExclusive)throw new Error("Create-only write requires atomic exclusive-create support.");await e.createExclusive(D.file,D.content)}else await N(D);let V=e.bumpVersion(D.file);O.push(D.file),D.version=V}}catch(D){let V=await P(A.filter(U=>O.includes(U.file)));if(V.ok===!1)return{ok:!1,reason:`Writeback failed, then rollback failed for ${V.failedFiles.join(", ")}: ${ES(D)}`,rolledBack:!1,instanceConflict:bS(D)};let Q=bS(D);return{ok:!1,reason:`${Q?"MATERIALIZATION_INSTANCE_CONFLICT: ":""}Writeback failed and committed files were restored: ${ES(D)}`,rolledBack:!0,instanceConflict:Q}}return{ok:!0,snapshots:R.map(kL)}}async function N(R){if(R.exists===!1){await e.deleteFile(R.file);return}await e.writeFile(R.file,R.content)}async function P(R){let A=[];for(let T of R)try{await N(T),e.bumpVersion(T.file)}catch{A.push(T.file)}return A.length===0?{ok:!0}:{ok:!1,failedFiles:A}}}function bS(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="EEXIST"}function kL(e){let t=e.exists!==!1;return{file:e.file,content:t?e.content:"",version:e.version,exists:t,...t?{sha256:ve(e.content)}:{}}}function ES(e){return e instanceof Error?e.message:String(e)}function SS(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 yt(Zt({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-import":return yt(fo({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-node":return yt(jr({source:t,locator:e.locator,removeWhitespace:e.removeWhitespace}));case"insert-child":return yt(Yt({source:t,locator:e.parentLocator,node:e.node,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"update-text":return yt(Hs({source:t,locator:e.locator,segmentIndex:e.segmentIndex,newText:e.newText}));case"update-value":return yt(pi({source:t,locator:e.locator,next:e.value}));case"update-array-item":return yt(pi({source:t,locator:e.locator,next:e.value}));case"insert-bound-array-item":return yt(Qs({source:t,locator:e.locator,index:e.index,value:e.value}));case"insert-jsx-expression-child":return yt(Ws({source:t,locator:e.parentLocator,expression:e.expression,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"remove-bound-array-item":return yt(ea({source:t,locator:e.locator,index:e.index}));case"move-array-item":return yt(ta({source:t,locator:e.locator,fromIndex:e.fromIndex,toIndex:e.toIndex}));case"move-node":return yt(Vr({source:t,locator:e.locator,targetParentLocator:e.targetParentLocator,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"move-repeat-template-child":return yt(Gs({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 RL(e,t);case"set-property-changes":return yt(Ys({source:t,locator:e.locator,changes:e.changes}));case"set-link-target":return yt(Zs({source:t,locator:e.locator,link:e.link,changes:e.changes}));case"set-property-binding":return yt(qs({source:t,locator:e.locator,name:e.name,object:e.object,property:e.property}));case"upsert-object-property":return yt(ra({source:t,objectLocator:e.locator,name:e.name,value:e.value}));default:return{ok:!1,reason:`Unknown step type: ${e.type}`,errorCode:"unknown"}}}function RL(e,t){let{request:n}=e;if(n.newAttrRaw!==null&&!Og(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!==ve(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:wg({source:t,oldAttrRange:n.oldAttrRange,openingElementRange:n.openingElementRange,newAttrRaw:n.newAttrRaw})}}function yt(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 Kc,SiteEditCompositionContextSchema as CL,SiteEditCompositionSelectorSchema as NL}from"@vcp-dev/contracts";var Rt=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="SiteEditCompositionError"}};function IS(e,t){throw new Rt("INVALID_COMPOSITION",e,{value:t})}function Jc(e){let t=CL.safeParse(e);return t.success?t.data:IS("Invalid SiteEditCompositionContext.",e)}function kS(e){let t=[],n=new Map,r=new Map;for(let l of e.compositions){let u=Jc(l?.context);if(typeof l.entryFile!="string"||!l.entryFile)throw new Rt("INVALID_COMPOSITION","A registered composition must have a non-empty entryFile.");let d=Kc(u);if(n.has(d))throw new Rt("DUPLICATE_COMPOSITION",`Composition key ${d} is registered more than once.`,{key:d,context:u});let p=r.get(l.entryFile);if(p)throw new Rt("DUPLICATE_COMPOSITION",`Entry file ${l.entryFile} is registered more than once.`,{entryFile:l.entryFile,context:p});let m={context:u,entryFile:l.entryFile,key:d};t.push(m),n.set(d,m),r.set(l.entryFile,d)}if(t.length===0)throw new Rt("INVALID_COMPOSITION","At least one composition must be registered.");let o=new Map;for(let l of e.initialDocumentVersions??[]){let u=Jc(l?.composition);if(!Number.isInteger(l?.version)||(l?.version??-1)<0)throw new Rt("INVALID_INITIAL_DOCUMENT_VERSION","Initial document version must be a non-negative integer.",{context:u,version:l?.version});let d=Kc(u);if(!n.has(d))throw new Rt("UNKNOWN_COMPOSITION","Initial document version references an unregistered composition.",{context:u,key:d});if(o.has(d))throw new Rt("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=NL.safeParse(l);if(!u.success)return IS("Invalid SiteEditCompositionSelector.",l);let d=t.filter(({context:p})=>p.routeId===u.data.routeId&&(u.data.templateId===void 0?p.effectiveTemplateId===void 0:p.effectiveTemplateId===u.data.templateId));if(d.length===1)return d[0];throw d.length>1?new Rt("AMBIGUOUS_COMPOSITION","The composition selector matches multiple registered contexts.",{selector:u.data}):new Rt("UNKNOWN_COMPOSITION","The composition selector is not registered.",{selector:u.data})}function s(l){let u=Jc(l),d=Kc(u),p=n.get(d);if(!p)throw new Rt("UNKNOWN_COMPOSITION","The composition context is not registered.",{context:u,key:d});return p}function a(l){let u=Jc(l?.context);if(typeof l.entryFile!="string"||!l.entryFile)throw new Rt("INVALID_COMPOSITION","A registered composition must have a non-empty entryFile.");let d=Kc(u),p=n.get(d);if(p){if(p.entryFile===l.entryFile)return p;throw new Rt("DUPLICATE_COMPOSITION",`Composition key ${d} is registered more than once.`,{key:d,context:u})}let m=[...n.values()].find(h=>h.entryFile===l.entryFile);if(m)throw new Rt("DUPLICATE_COMPOSITION",`Entry file ${l.entryFile} is registered more than once.`,{entryFile:l.entryFile,context:m.context});let f={context:u,entryFile:l.entryFile,key:d};return t.push(f),n.set(d,f),f}function c(l){let u=n.get(l);if(!u)return;n.delete(l);let d=t.findIndex(p=>p.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 up(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 RS(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 _L,stripSiteEditRepeatInstanceKeys as CS}from"@vcp-dev/contracts";function NS(e){let t=new Map,n=new Map,r=new Map;for(let o of e.entries){t.set(o.key,o);let i=CS(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 PL(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 Xc(e){return e?.map(t=>({...t}))}function dp(e,t){if(t===null||e?.kind!=="value-binding"||e.sourceKind!=="repeat-template")return e;let n=e.collectionIndexMap?.[t]??t,r=Xc(e.collectionPathMap?.[t])??Xc(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:Xc(e.path),locator:e.locator?{...e.locator,path:r}:e.locator,collectionIndexMap:e.collectionIndexMap?[...e.collectionIndexMap]:void 0,collectionPathMap:e.collectionPathMap?.map(o=>Xc(o)??[])}}function _S(e,t,n){let r=new Set;for(let m of t.regions)if(m.kind==="repeat-region")for(let f of m.childKeys)r.add(f);if(r.size===0)return e;let o=new Map(e.entries.map(m=>[m.key,m])),i=[],s=new Map,a=(m,f)=>_L(m,f),c=(m,f,h)=>{let y=o.get(m);if(!y)return a(m,h);let x=a(m,h),E={...y,key:x,parentKey:f,childKeys:[]};return i.push(E),E.childKeys=y.childKeys.flatMap(b=>l(b,h,x)),x},l=(m,f,h)=>{if(!r.has(m))return[c(m,h,f)];let y=d(m,f),x=[];for(let E=0;E<y;E+=1)x.push(c(m,h,[...f,E]));return x},u=Array.from(new Set([...e.rootKeys,...e.entries.filter(m=>m.parentKey===null).map(m=>m.key)]));for(let m of u){if(!r.has(m)){c(m,null,[]);continue}let f=d(m,[]);for(let h=0;h<f;h+=1)c(m,null,[h])}return{...e,rootKeys:[...e.rootKeys],entries:i};function d(m,f){let h=new Set;for(let y of p(m)){let x=n.get(y);if(x){for(let E of[...x.textTargets.values(),...x.elementPropertyTargets.values()])if(!(E?.kind!=="value-binding"||E.sourceKind!=="repeat-template"))for(let b of AL(E))b.length<=f.length||TL(b,f)&&h.add(b[f.length])}}return h.size>0?h.size:PL(n.get(m))}function p(m){let f=s.get(m);if(f)return f;let h=[m],y=o.get(m);for(let x of y?.childKeys??[])h.push(...p(x));return s.set(m,h),h}}function PS(e){let t=e.parts.at(-1);return typeof t?.repeatIndex=="number"?t.repeatIndex:null}function AS(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((CS(s.key)??s.key)===n){if(s.key===t)return i;i+=1}return null}function AL(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 TL(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 TS(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 wS(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 OS(e){return{path:e.path,code:e.code,message:e.message,...e.details?{details:JSON.parse(JSON.stringify(e.details))}:{}}}function wL(e){return e.map(t=>`${t.code} (${t.path}): ${t.message}`).join("; ")}var ps=class extends Error{constructor(t){let n=t.map(OS);super(wL(n)),this.name="RouteBuildDiagnosticsError",this.diagnostics=n}};function FS(e,t){let n=t instanceof Error&&t.message?t.message:String(t);return t instanceof ps?{routeId:e,message:n,diagnostics:t.diagnostics.map(OS)}:{routeId:e,message:n}}function fp(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 Ko(e,t){e.clear();for(let[n,r]of t)e.set(n,r)}function LS(e,t){for(let n of t){if(n.exists===!1){e.delete(n.file);continue}e.set(n.file,n.content)}}function mp(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 DS(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 $L=/^(?:src\/)?app\/.*\/?page\.[cm]?[jt]sx?$/,VL=["layout.tsx","layout.ts","layout.jsx","layout.js","layout.mjs","layout.cjs"],MS=32,gp=256;function UL(e){return{expectedIndexDigest:e.digest,publishedIndexDigest:e.digest,publishedCursor:e.cursor,publishedCurrentId:e.currentId}}var BS={maxEntries:50,maxBytes:8*1024*1024};function KL(){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 sa(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 jS(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 JL(){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>BS.maxEntries||XL(e)>BS.maxBytes;)e.shift()}}function XL(e){return e.reduce((t,n)=>t+zL(n),0)}function zL(e){return $S(e.preSnapshots)+$S(e.postSnapshots)+HL(e.provenance)}function HL(e){return e?new TextEncoder().encode(JSON.stringify(e)).byteLength:0}function $S(e){return e.reduce((t,n)=>t+n.file.length+n.content.length,0)}function VS(e,t){return{key:FL(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 Hc=class extends Error{constructor(t){super(t.reason),this.result=t}},ro=class extends Error{constructor(t){super(fp(t)),this.failedRoutes=t}};function US(e,t){if(!e)return;let n=[...t];if(n.some(o=>o?.entries.some(i=>i.key===e.key)))return e;let r=Lt(e.key)??e.key;for(let o of n){let i=o?.entries.find(s=>(Lt(s.key)??s.key)===r);if(i)return{...e,key:i.key}}return e}function WL(e,t,n){if(!n)return;let r=Lt(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 GL=/\.(?:[cm]?[jt]sx?)$/i,YL=/\.json$/i,ZL=/\.(?:css|scss|sass)$/i,qL=/\.mdx$/i,QL=/\.ya?ml$/i;function eD(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 tD(e){return{kind:e.isProxy?"component-proxy":"jsx-node",file:e.file,componentName:e.componentName,isProxy:e.isProxy}}function nD(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=WS(await e.listFiles(i)),a=new Map(s.files.map(l=>[l.path,l]));for(let[l,u]of n)if(rD(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 rD(e,t){return t.length===0?!0:t.some(n=>e===n||e.startsWith(`${n}/`))}function WS(e){return Array.isArray(e)?{files:e}:e}function oD(e){if(!DL(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!==BL||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=LL(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(GL.test(e.path)){let t=bn({source:e.content,profile:Or({filePath:e.path,source:e.content})});if(!t.ok)return{ok:!1,errorCode:"ast-error",message:t.diagnostic.message,details:{path:e.path}}}if(YL.test(e.path))try{JSON.parse(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`JSON parse failed: ${Nt(t)}`,details:{path:e.path}}}if(ZL.test(e.path)){let t=KS({content:e.content,path:e.path,profile:"css"});if(!t.ok)return t}if(qL.test(e.path)){let t=KS({content:e.content,path:e.path,profile:"mdx"});if(!t.ok)return t}if(QL.test(e.path))try{jL(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`YAML parse failed: ${Nt(t)}`,details:{path:e.path}}}return{ok:!0}}function KS({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 p=e[d]??"",m=e[d+1]??"";if(n==="mdx"&&l&&e.startsWith("```",d)){c=!c;let f=e.indexOf(`
|
|
8
|
-
`,d);if(
|
|
9
|
-
`||
|
|
10
|
-
`||
|
|
11
|
-
`||
|
|
12
|
-
`||
|
|
13
|
-
`||
|
|
14
|
-
`||p==="\r"}if(s)return Jo(t,`Unterminated block comment in ${t}.`);if(o)return Jo(t,`Unterminated string literal in ${t}.`);if(c)return Jo(t,`Unterminated MDX code fence in ${t}.`);let u=r.at(-1);return u?Jo(t,`Unclosed token "${u.char}" in ${t}.`):{ok:!0}}function Jo(e,t){return{ok:!1,errorCode:"ast-error",message:t,details:{path:e}}}function Wc(e){let t="idle",n=e.fileSystem??KL(),r=Fg(),o=kS({compositions:e.compositions,initialDocumentVersions:e.initialDocumentVersions}),i=new Map,s=new Map,a=new Set,c=null,l=e.history??(e.historyStore?Ih(e.historyStore):JL()),u=vS(n,{externalAdapters:e.externalAdapters}),d=new Map,p=Jg(gp),m=new Set,f=0,h=e.historyStore?.recoveryRequired??!1,y=lp(),x=N();function E(g){return(zc.isAbsolute(g)?zc.relative(e.projectRoot,g):g).replace(/\\/g,"/").replace(/^\.\//,"")}function b(g,k){let I=zc.posix.dirname(g),_=k.replace(/\.(?:tsx?|jsx?)$/i,""),F=zc.posix.relative(I,_);return F.startsWith(".")?F:`./${F}`}function S(g,k){return g.startLine===k.startLine&&g.startColumn===k.startColumn&&g.endLine===k.endLine&&g.endColumn===k.endColumn}async function N(){let g=e.historyStore;if(g)try{let k=await g.readTransactionJournal();if(!k)return;let I=await g.readIndex(),_=await Promise.all(k.files.map(async L=>await n.exists(L.path)?ve(await n.readFile(L.path)):null));if(DS({journal:k,index:I,observedFileDigests:_})!=="ambiguous"){await g.clearTransactionJournal(k.transactionId);let L=await g.readStatus();L.recoveryRequired||(await g.cleanupTmp(),L=await g.readStatus()),h=L.recoveryRequired;return}await g.markRecoveryRequired(`Ambiguous transaction journal ${k.transactionId} at phase ${k.phase}`),h=!0}catch(k){h=!0,await g.markRecoveryRequired(`Transaction journal recovery failed: ${Nt(k)}`).catch(()=>{})}}function P(){return t==="disposed"}e.onEvent&&r.subscribe(e.onEvent);for(let g of o.entries){let k=VS(g.context,g.entryFile);i.set(g.key,k),R(k,k.dependencyFiles)}function R(g,k){let I=new Set(k);A(g),g.dependencyFiles=I;for(let _ of g.dependencyFiles){let F=s.get(_);F||(F=new Set,s.set(_,F)),F.add(g.key)}}function A(g){for(let k of g.dependencyFiles){let I=s.get(k);I&&(I.delete(g.key),I.size===0&&s.delete(k))}g.dependencyFiles.clear()}function T(g){let k=new Set;for(let I of g)for(let _ of s.get(I)??[])k.add(_);return k}function O(g){for(let k of g)if(!s.has(k))return!1;return!0}async function D(g,k,I,_,F,L){let $=new Map,J=tS(g),Z=JE(F.values()),z=Ub(F.values()),X=typeof L.exists=="function"?te=>L.exists(te):async()=>!1;for(let[te,ae]of g.elements){let Se=k.nodes.get(te);if(!Se)continue;let re=I.get(ae.sourceFile)??_.get(ae.sourceFile),Ne=new Map,be=new Map,M=new Map,Y=[];for(let Xe of ae.textSegments){if(!re){Ne.set(Xe.index,null);continue}let ti=await XE({file:ae.sourceFile,source:re,segment:Xe,readFile:Dt=>L.readFile(Dt),exists:X,graph:g,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Dt,adapterId:Ar,capabilities:Nl})=>({sourceType:Dt,adapterId:Ar,capabilities:Nl})),functionCallContracts:e.functionCallContracts,fileCache:Z}),Ct=await ep({file:ae.sourceFile,source:re,target:{kind:"text-segment",segment:Xe},readFile:Dt=>L.readFile(Dt),exists:X,graph:g,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Dt,adapterId:Ar,capabilities:Nl})=>({sourceType:Dt,adapterId:Ar,capabilities:Nl})),functionCallContracts:e.functionCallContracts,fileCache:Z}),Ht=eD(ti);Ne.set(Xe.index,Ht),be.set(Xe.index,ti),M.set(Xe.index,Ct),Y.push({editable:Xe.editable,source:Ht})}let fe=new Map,ke=new Map;if(re)for(let Xe of ae.attributes??[]){let ti=await Uo({file:ae.sourceFile,source:re,sourceRange:Xe.sourceRange,expression:Xe.source?.expression??Xe.value,sourceInfo:Xe.source,readFile:Ht=>L.readFile(Ht),exists:X,graph:g,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Ht,adapterId:Dt,capabilities:Ar})=>({sourceType:Ht,adapterId:Dt,capabilities:Ar})),functionCallContracts:e.functionCallContracts,fileCache:Z}),Ct=await eS({element:ae,file:ae.sourceFile,source:re,propertyName:Xe.name,readFile:Ht=>L.readFile(Ht),exists:X,graph:g,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Ht,adapterId:Dt,capabilities:Ar})=>({sourceType:Ht,adapterId:Dt,capabilities:Ar})),functionCallContracts:e.functionCallContracts,fileCache:Z});ke.set(Xe.name,Ct),fe.set(Xe.name,ti)}let _e=uS(tD(Se.writeTarget),Y),Ye=J({key:te,element:ae,provenances:M}),Zn=gS(ae),Ln=re?await Kb({element:ae,graph:g,file:ae.sourceFile,source:re,readFile:Xe=>L.readFile(Xe),exists:X,fileCache:z}):void 0,Pr=g.regions.find(Xe=>Xe.kind==="conditional-region"&&Xe.childKeys.includes(te)),At,Dn=Pr?.sourceCandidates?.[0];if(re&&Pr&&Dn?.kind==="conditional-branch"){let Xe=await ep({file:ae.sourceFile,source:re,target:{kind:"conditional-branch",candidate:Dn},readFile:Ct=>L.readFile(Ct),exists:X,graph:g,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Ct,adapterId:Ht,capabilities:Dt})=>({sourceType:Ct,adapterId:Ht,capabilities:Dt})),functionCallContracts:e.functionCallContracts,fileCache:Z});At={currentBranch:Pr.childKeys.indexOf(te)<=0?"then":"else",availableBranches:Pr.childKeys.length>1?["then","else"]:["then"],conditionExpression:Dn.conditionExpression,provenance:{finalSource:Xe.finalSource?{kind:Xe.finalSource.kind,file:Xe.finalSource.file,displayPath:Xe.finalSource.displayPath}:null,chain:Xe.chain.map(Ct=>({kind:Ct.kind,file:Ct.file,displayName:Ct.displayName,canEditHere:Ct.canEditHere})),confidence:Xe.confidence,editMode:Xe.editMode,diagnostics:Xe.diagnostics.map(Ct=>({code:Ct.code,message:Ct.message}))}}}$.set(te,{textSources:Ne,textTargets:be,elementPropertyTargets:fe,propertyProvenances:ke,isRepeat:ED(te,g),provenances:M,writeTarget:_e,componentSemantic:Ye,styleSource:Zn,conditional:At,dynamicData:Ln})}return $}function V(g){return typeof n.getVersion=="function"?n.getVersion(g):0}function Q(g,k){let I=o.initialVersions.get(g.key)??0;for(let _ of k.values())I=Math.max(I,_);return Math.max(I,g.graph?.version??0)}function U(g){return i.get(g)?.graph?.version??o.initialVersions.get(g)??0}function H(g){try{return U(o.resolveSelector(g.composition).key)}catch{return 0}}async function ye(g,k,I=n,_={}){let F=await ha(g,k,L=>I.readFile(L),L=>I.exists(L),{additionalEntries:await pt(g,I),..._});if(F.diagnostics.length>0)throw new ps(F.diagnostics);return _.validationOnly||p.remember(F.parsedModules.values()),F}async function st(g,k,I={}){let _=i.get(g);if(!_)return null;let F=I.sourceCache??pp(d,[]),L=I.fileSystem??up(n),{graph:$,allSources:J,parsedModules:Z,entryModule:z}=await ye(_.entryFile,k,L,{version:_.graph?.version??1}),X=new Map;for(let At of J.keys())X.set(At,V(At));let te=Math.max(Q(_,X),I.minimumVersion??0);I.changed&&te<=(_.graph?.version??0)&&(te=(_.graph?.version??0)+1),$.version=te;for(let[At,Dn]of J)mp(F,At,Dn,gp);let ae=await Qo(_.composition,_.entryFile,J,F,L);$.routeId=_.routeId,$.composition=_.composition;let Se=Xa($),re=oa(Se,$),Ne=await D($,Se,J,F,Z,L);rt(re,Ne);let be=xe($,re,Ne),M=ei(Ne),Y=_S(iS($,Se,re,{canUpdateTextByKey:be,dynamicDataSummaryByKey:M}),$,Ne),fe=un({route:_.routeId,composition:_.composition,entryFile:_.entryFile,version:te,source:k,ast:z?.ast}),ke=Ry(fe),_e=null,Ye=[];if(fe.ok){sD(Y,$,fe.projection,Z);let At=Ja({composition:_.composition,entryFile:_.entryFile,graph:$,parsedModules:Z,projection:fe.projection});if(At.diagnostics.length===0){let Dn=Bi({composition:_.composition,entryFile:_.entryFile,graph:$,parsedModules:Z,projection:fe.projection,documentVersion:te,roots:At.roots});Dn.diagnostics.length===0&&(_e=Dn,Ye=Dn.descriptors)}}let Zn={...Y,composition:_.composition,pageBlocks:Ye,...ae?{styleContext:ae}:{},pageComposition:ke},Ln=new Set([_.entryFile,...J.keys()]);if(ae){Ln.add(ae.entryCss.path);for(let At of ae.stylesheets)Ln.add(At.path)}let Pr={..._,dependencyFiles:Ln,graph:$,topology:Se,capabilities:re,document:Zn,pageBlockIndex:_e,pageComposition:ke,pageCompositionProjection:fe.projection,pagePlacementByKey:fe.ok?fe.projection.placementByKey:null,pagePlacementUnitByKey:fe.ok?fe.projection.placementUnitByKey:null,pageUnitByKey:fe.ok?fe.projection.unitByKey:null,pagePlacementsByUnitKey:fe.ok?fe.projection.placementsByUnitKey:null,documentIndex:NS(Zn),detailProjections:Ne,fileVersions:X,styleContext:ae};if(I.publish===!1)return Pr;Ko(d,F);for(let At of F.keys())m.delete(At);return R(_,Ln),Object.assign(_,Pr),_}async function pt(g,k=n){let I=[];for(let _ of mD(g))typeof k.exists=="function"&&await k.exists(_)&&I.push({file:_,source:await k.readFile(_)});return I}async function Qo(g,k,I,_,F){let L=[];for(let[X,te]of I){if(hp(X)){L.push(X);continue}for(let ae of hD(te)){let Se=HS(X,ae);Se&&L.push(Se)}}if(!L.length){for(let X of gD(k))if(await F.exists(X)){L.push(X);break}}let $=new Map,J=bD(L).slice(0,MS);for(;J.length>0&&$.size<MS;){let X=J.shift();if($.has(X)||!hp(X))continue;let te=await on(X,_,F);if(te!==null){$.set(X,{path:X,content:te});for(let ae of yD(te)){let Se=HS(X,ae);Se&&!$.has(Se)&&!J.includes(Se)&&J.push(Se)}}}let Z=[...$.values()].map(X=>({...X,hash:ve(X.content)})),z=Z[0];return z?{composition:g,revision:ve(JSON.stringify(Z.map(({path:X,hash:te})=>({path:X,hash:te})))),entryCss:z,stylesheets:Z.slice(1)}:null}async function on(g,k,I){let _=k.get(g);if(_!==void 0)return _;if(!await I.exists(g))return null;let F=await I.readFile(g);return mp(k,g,F,gp),F}function ei(g){let k=new Map;for(let[I,_]of g)_.dynamicData?.bindings.length&&k.set(I,tE(_.dynamicData.bindings));return k}function xe(g,k,I){let _=new Map;for(let[F,L]of g.elements){if(!k.get(F)?.canUpdateText){_.set(F,!1);continue}let J=I.get(F),Z=L.textSegments.some(z=>{if(!z.editable)return!1;let X=J?.provenances.get(z.index)??null;return!X||Te(X)});_.set(F,Z)}return _}function rt(g,k){for(let[I,_]of k){let F=g.get(I);F?.canUpdateText&&_.dynamicData?.bindings.some(L=>L.readonly&&(L.targetKind==="text"||L.targetKind==="richtext"))&&g.set(I,{...F,canUpdateText:!1})}}function Te(g){return g.editMode==="direct"||g.editMode==="proxy"||g.editMode==="upstream"}async function ue(g,k={}){let I=[...new Set(g)],_=k.affectedCompositionKeys!==void 0,F=_?new Set(k.affectedCompositionKeys):T(I);if(!_&&(F.size===0||!O(I)))for(let z of i.values())sm(z,I)&&F.add(z.key);let L=!_&&F.size===0&&I.some(zS),$=k.publish===!1?pp(d,I):void 0,J={rebuiltRoutes:[],failedRoutes:[],...k.publish===!1?{candidateRouteStates:[],candidateSourceCache:$}:{}},Z=up(n);for(let z of i.values())if(!(k.excludedCompositionKeys?.has(z.key)||!(F.has(z.key)||L)))try{let te=!!z.graph,ae=await Z.readFile(z.entryFile),Se=await st(z.key,ae,{...k,fileSystem:Z,...$?{sourceCache:$}:{}});Se?.graph&&(J.rebuiltRoutes.push({documentChanged:te,composition:z.composition,routeId:z.routeId,version:Se.graph.version}),J.candidateRouteStates?.push({composition:z.composition,key:z.key,routeId:z.routeId,state:Se}))}catch(te){J.failedRoutes.push({...FS(z.routeId,te),composition:z.composition})}return J}function Le(g){let k=[...new Set(g)],I=T(k);if(I.size>0&&O(k))return[...I];for(let _ of i.values())sm(_,k)&&I.add(_.key);return[...I]}function bt(g){let k=new Set(Le(g));return o.entries.filter(I=>k.has(I.key)).map(I=>I.context)}function sn(g){return[...new Set(Le(g))].sort((I,_)=>I<_?-1:I>_?1:0).map(I=>o.getByKey(I)?.context).filter(I=>I!==void 0)}function Et(g,k){let I=new Set(Le(k)),_=g.provenance?.affectedCompositions??[];if(_.length===0)return I;if([...new Set(_.map(L=>o.resolveContext(L).key))].some(L=>!I.has(L)))throw new Error("History provenance does not match the affected composition index.");return I}function ks(g,k){let I=g.composition??g.provenance?.initiatingComposition;if(I){let L=o.resolveContext(I);return{context:L.context,key:L.key}}let _=[...new Set(Le(k))];if(_.length!==1)throw new Error(`Legacy history entry cannot be attributed to a unique composition (affected composition count: ${_.length}).`);let F=o.getByKey(_[0]);if(!F)throw new Error("Legacy history entry references an unknown affected composition.");return{context:F.context,key:F.key}}function El(g,k){r.emit({type:"operation-completed",composition:g.composition,result:g});for(let{composition:I,version:_}of k.rebuiltRoutes)r.emit({type:"document-changed",composition:I,version:_});for(let{composition:I,message:_}of k.failedRoutes)r.emit({type:"graph-error",composition:I,message:_})}function sm(g,k){return k.some(I=>g.dependencyFiles.has(I)||g.entryFile===I||g.graph?.fileIndex.has(I))}function am(g){for(let k of g)a.add(k);c||P()||(c=(async()=>{t="building";let k=!1;try{for(;a.size>0;){if(P())return;await aI(),await y.runExclusive(async()=>{if(f>0||P())return;let I=[...a];a.clear();let _=await cm(I);if(_.length===0)return;let F=Le(_);for(let J of F){let Z=i.get(J)?.composition;Z&&r.emit({type:"graph-invalidated",composition:Z})}let{rebuiltRoutes:L,failedRoutes:$}=await ue(_,{changed:!0});for(let{documentChanged:J,composition:Z,version:z}of L)r.emit({type:"graph-ready",composition:Z,version:z}),J&&r.emit({type:"document-changed",composition:Z,version:z});for(let{composition:J,message:Z}of $)k=!0,r.emit({type:"graph-error",composition:J,message:Z})})}}finally{c=null,t!=="disposed"&&(t=!k&&[...i.values()].some(I=>I.graph)?"ready":"idle"),a.size>0&&am([])}})())}async function aI(){for(;f>0;)await new Promise(g=>setTimeout(g,0))}async function cm(g){let k=[];for(let I of new Set(g)){let _=d.get(I);if(_===void 0){if(m.has(I)&&!await n.exists(I))continue;m.delete(I),k.push(I);continue}try{await n.readFile(I)!==_&&(m.delete(I),k.push(I))}catch(F){if(!iD(F))try{if(await n.exists(I))continue}catch{continue}m.add(I),k.push(I)}}return k}function lm(g){LS(d,g);for(let k of g)k.exists===!1?m.add(k.file):m.delete(k.file)}function um(g){m.clear();for(let k of g)m.add(k)}async function dm(g){let k=await cm(g);if(k.length===0)return;let I=Le(k);for(let L of I){let $=i.get(L)?.composition;$&&r.emit({type:"graph-invalidated",composition:$})}let{rebuiltRoutes:_,failedRoutes:F}=await ue(k,{changed:!0});for(let{documentChanged:L,composition:$,version:J}of _)r.emit({type:"graph-ready",composition:$,version:J}),L&&r.emit({type:"document-changed",composition:$,version:J});for(let{composition:L,message:$}of F)r.emit({type:"graph-error",composition:L,message:$})}async function cI(g,k){let I=ao(g,k);if(!I?.graph)return;let _=Lt(g)??g,F=I.graph.elements.get(_);F&&await dm([F.sourceFile])}async function fm(g){let k=new Set;if(g.target.kind==="node"){let I=ao(g.target.key,g.composition),_=Lt(g.target.key)??g.target.key,F=I?.graph?.elements.get(_);F&&k.add(F.sourceFile)}else if(g.target.kind==="route"){let I=i.get(o.resolveSelector(g.target.composition).key);I&&k.add(I.entryFile)}else if(g.target.kind==="page-unit"){let I=i.get(o.resolveSelector(g.target.composition).key);I&&k.add(I.entryFile)}else if(g.target.kind==="page-block"){let I=i.get(o.resolveSelector(g.target.composition).key),_=I?.pageBlockIndex?.bindings.get(g.target.blockKey);if(_&&(k.add(_.ownerFile),k.add(_.descriptor.source.file)),I?.pageBlockIndex&&g.params.kind==="move-node"&&"kind"in g.params.target&&g.params.target.kind==="block-boundary"){let F=I.pageBlockIndex.bindings.get(g.params.target.anchorBlockKey);F&&(k.add(F.ownerFile),k.add(F.descriptor.source.file))}}else if(g.target.kind==="source-file")k.add(g.target.path);else if(g.target.kind==="source-batch")for(let I of g.target.paths)k.add(I);if(g.params.kind==="move-node"&&!("kind"in g.params.target)){let I=[g.params.target.parentKey,...g.params.target.relation==="before"||g.params.target.relation==="after"?[g.params.target.anchorKey]:[]];for(let _ of I){let F=ao(_,g.composition),L=Lt(_)??_,$=F?.graph?.elements.get(L);$&&k.add($.sourceFile)}}await dm(k)}async function lI(g){if(g.params.kind!=="source-edit")return Il(g,"invalid-params","source-edit requires source-edit params");for(let k of g.params.edits){let I=oD(k);if(!I.ok)return Il(g,I.errorCode,I.message,I.details)}f+=1;try{let k=await xI(g.params.edits);if(!k.ok)return Il(g,k.errorCode,k.message,k.details);await fm(g);let I={operationId:g.id,kind:"source-edit",target:g.target,documentVersion:g.documentVersion,conflictPolicy:g.params.conflictPolicy,edits:g.params.edits.map(_=>_.operation==="delete"?{operation:"delete",file:_.path,baseContentHash:_.baseContentHash??null}:{operation:"upsert",file:_.path,baseContentHash:_.baseContentHash??null,content:_.content})};return await Yn({request:g,filePlan:I})}catch(k){return{composition:o.resolveSelector(g.composition).context,requestId:g.id,kind:g.kind,target:g.target,ok:!1,resultVersion:H(g),error:{code:B.INTERNAL_ERROR,message:Nt(k)}}}finally{f-=1}}async function uI(g){if(g.target.kind!=="project"||g.params.kind!=="insert-page-resource")return W(g,B.INVALID_PARAMS,"insert-page-resource requires project target and matching params.");f+=1;try{let k=await ri({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:[...g.params.artifact.components.flatMap(_=>_.materialization.files.map(F=>({path:F.pathTemplate,content:F.content}))),...g.params.artifact.pages.flatMap(_=>_.materialization.files.map(F=>({path:F.pathTemplate,content:F.content})))],exists:_=>n.exists(_),readFile:_=>n.readFile(_)});if(!k.ok)return W(g,B.MATERIALIZATION_REJECTED,k.message);let I=await Uu({artifact:g.params.artifact,exists:_=>n.exists(_)});return I.ok?await Yn({request:g,filePlan:{operationId:g.id,kind:"source-edit",target:g.target,documentVersion:g.documentVersion,conflictPolicy:"overwrite",edits:I.files},output:{kind:"insert-page-resource",package_instance_id:I.packageInstanceId,pages:I.pages},historyPolicy:"none"}):W(g,I.code==="MATERIALIZATION_CONFLICT"?B.MATERIALIZATION_CONFLICT:B.MATERIALIZATION_REJECTED,I.message,I.path?{path:I.path}:void 0)}catch(k){return W(g,B.INTERNAL_ERROR,Nt(k))}finally{f-=1}}async function dI(g){if(g.target.kind!=="project"||g.params.kind!=="delete-page-source")return W(g,B.INVALID_PARAMS,"delete-page-source requires project target and matching params.");if(!n.listFiles)return W(g,B.PLAN_FAILED,"Complete project file listing is required for page deletion.");f+=1;try{let k=WS(await n.listFiles({maxFiles:5e4,maxDepth:64}));if(k.truncated)return W(g,B.PLAN_FAILED,"Project file listing is incomplete; page deletion was refused.",{truncationReasons:k.truncated.reasons});let I=k.files.filter(({path:$})=>/\.(?:tsx?|jsx?)$/.test($)),_=Object.fromEntries(await Promise.all(I.map(async({path:$})=>[$,await n.readFile($)]))),F=Sx({expectedUrlPath:g.params.expectedUrlPath,files:_});if(!F.ok)return W(g,F.code==="HOME_PAGE_LOCKED"?B.HOME_PAGE_LOCKED:F.code==="ROUTE_NOT_FOUND"?B.ROUTE_NOT_FOUND:B.PLAN_FAILED,F.message);let L=await Promise.all(F.edits.map(async $=>({...$,baseContentHash:ve(await n.readFile($.file))})));return Yn({request:g,filePlan:{operationId:g.id,kind:"source-edit",target:g.target,documentVersion:g.documentVersion,conflictPolicy:"compare-and-swap",edits:L},output:{kind:"delete-page-source",deleted_files:F.deletedFiles,updated_files:F.updatedFiles,preserved_shared_files:F.preservedSharedFiles,warnings:F.warnings},historyPolicy:"none"})}catch(k){return W(g,B.INTERNAL_ERROR,Nt(k))}finally{f-=1}}async function fI(g,k){if(g.kind!=="insert-child"&&g.kind!=="replace-node")return W(g,B.UNSUPPORTED_OPERATION,"Only page-unit insert-child and replace-node materialization are supported by this transaction.");if(g.params.kind!=="insert-child"&&g.params.kind!=="replace-node"||g.kind!==g.params.kind)return W(g,B.INVALID_PARAMS,"Page-unit materialization operation kind must match its params.");if(g.params.kind==="insert-child"){if(!("kind"in g.params.position)||g.params.position.kind!=="page-composition")return W(g,B.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.");if(g.params.position.documentVersion!==g.documentVersion)return W(g,B.VERSION_STALE,"Page-unit insert-child placement belongs to a different document version.")}let I=k.document,_=k.pageCompositionProjection;if(!I||I.pageComposition?.status!=="supported"||!_||_.status!=="supported")return W(g,B.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(g.documentVersion!==I.version||_.documentVersion!==I.version)return W(g,B.VERSION_STALE,`Document version ${g.documentVersion} is stale (current: ${I.version}).`);let F=g.params.node.kind==="component-call"?g.params.node.materialization:void 0;if(!F)return W(g,B.UNSUPPORTED_OPERATION,"Page-unit insertion currently requires a static materialization manifest.");let L=g.params.kind==="insert-child"?g.params.position:null,$=await ri({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:F.files.map(z=>({path:z.pathTemplate,content:z.content})),exists:z=>n.exists(z),readFile:z=>n.readFile(z)});if(!$.ok)return W(g,B.MATERIALIZATION_REJECTED,$.message);let J=await jS(n,Object.keys(F.projectDependencies??{})),Z=await Wu({manifest:F,generatedRoot:"components/site/generated",controlledFiles:F.files.map(z=>({pathTemplate:z.pathTemplate})),exists:z=>n.exists(z),availableHostDependencies:J,hostCapabilities:Mu(),commit:async z=>{let X=await n.readFile(k.entryFile),te=k.document,ae=k.pageCompositionProjection;if(!te||te.pageComposition?.status!=="supported"||te.version!==g.documentVersion||!ae||ae.status!=="supported"||ae.documentVersion!==te.version)return{ok:!0,data:W(g,B.VERSION_STALE,"The route changed before the page-unit insertion could commit.")};let Se=z.entry.path,re=RI(z.instanceName),Ne,be=[];if(g.params.kind==="insert-child"){if(!L||!("kind"in L)||L.kind!=="page-composition")return{ok:!0,data:W(g,B.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.")};let ke=Ai({routeId:k.routeId,entryFile:k.entryFile,currentDocumentVersion:te.version,expectedDocumentVersion:g.documentVersion,source:X,projection:ae,placementKey:L.placementKey,component:{source:Se,exportName:z.entry.export.kind==="default"?"default":z.entry.export.name,localName:re}});if(!ke.ok)return{ok:!0,data:W(g,Cl(ke.error.code),ke.error.message,{diagnostics:ke.error.diagnostics})};let _e=ke.plan.rewriteStep,Ye;switch(_e.kind){case"insert-root-expression":Ye=Ti({source:X,locator:_e.locator,expectedSourceHash:_e.sourceHash,action:{kind:"insert",jsx:_e.node.jsx,placement:_e.placement,replaceOriginal:_e.replaceOriginal}});break;case"insert-child":Ye=Yt({source:X,locator:_e.parentLocator,node:_e.node,placement:_e.placement,..._e.anchorLocator?{anchorLocator:_e.anchorLocator}:{}});break;default:Ye={ok:!1,source:X,diagnostic:{code:"unsupported-syntax",message:`Unsupported route composition rewrite: ${String(_e)}`}}}if(!Ye.ok)return{ok:!0,data:W(g,B.AST_PARSE_ERROR,Ye.diagnostic.message)};Ne=Ye.source}else{let ke=pd({routeId:k.routeId,composition:k.composition,entryFile:k.entryFile,currentDocumentVersion:te.version,expectedDocumentVersion:g.documentVersion,source:X,projection:ae,placementUnitKey:g.target.placementUnitKey,operation:"replace-node"});if(!ke.ok)return{ok:!0,data:W(g,Cl(ke.error.code),ke.error.message,{diagnostics:ke.error.diagnostics})};let _e=ke.plan.rewriteStep,Ye;switch(_e.kind){case"replace-root-expression":Ye=Ti({source:X,locator:_e.locator,expectedSourceHash:_e.sourceHash,action:{kind:"replace",jsx:`<${re} />`}});break;case"replace-node":Ye=lo({source:X,locator:_e.locator,node:{jsx:`<${re} />`}});break;default:Ye={ok:!1,source:X,diagnostic:{message:`Unsupported page-unit replacement rewrite: ${_e.kind}`}}}if(!Ye.ok)return{ok:!0,data:W(g,B.AST_PARSE_ERROR,Ye.diagnostic.message)};let Zn=await vl({routeState:k,placementUnitKey:g.target.placementUnitKey,source:X,mutatedSource:Ye.source});Ne=Zn.source,be=await Promise.all(Zn.files.map(async Ln=>({operation:"delete",file:Ln,baseContentHash:ve(await n.readFile(Ln))})))}let M=Zt({source:Ne,moduleSpecifier:b(k.entryFile,Se),imports:z.entry.export.kind==="default"?[{kind:"default",local:re}]:[{kind:"named",imported:z.entry.export.name,local:re}]});if(!M.ok)return{ok:!0,data:W(g,B.AST_PARSE_ERROR,M.diagnostic.message)};let Y=z.files.map(ke=>({operation:"create-only",file:ke.path,content:ke.content})),fe=[{operation:"upsert",file:k.entryFile,content:M.source,baseContentHash:ve(X)},...Y,...be];f+=1;try{let ke=await Yn({request:g,filePlan:{operationId:g.id,kind:"source-edit",target:{kind:"source-file",path:k.entryFile},documentVersion:g.documentVersion,conflictPolicy:"compare-and-swap",edits:fe}});return!ke.ok&&ke.error?.message.includes("MATERIALIZATION_INSTANCE_CONFLICT")?{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:ke.error?.message??"Static prefab instance conflicted during commit."}}:{ok:!0,data:ke}}finally{f-=1}}});return Z.ok?Z.data:W(g,Z.error.code==="MATERIALIZATION_INSTANCE_CONFLICT"?B.MATERIALIZATION_CONFLICT:B.MATERIALIZATION_REJECTED,Z.error.message,{materializationCode:Z.error.code})}async function pI(g,k){if(g.kind!=="insert-child"&&g.kind!=="replace-node")return W(g,B.UNSUPPORTED_OPERATION,"Only page-block insert-child and replace-node use this materialization transaction.");if(g.params.kind!==g.kind||g.kind==="replace-node"&&g.params.kind!=="replace-node"||g.kind==="insert-child"&&g.params.kind!=="insert-child")return W(g,B.INVALID_PARAMS,"Page-block materialization operation kind must match its params.");let I=k.document,_=k.pageBlockIndex;if(!I||!_||_.diagnostics.length>0)return W(g,B.UNSUPPORTED_OPERATION,"The current route has no complete verified page-block index.");if(g.documentVersion!==I.version||_.documentVersion!==I.version)return W(g,B.VERSION_STALE,`Document version ${g.documentVersion} is stale (current: ${I.version}).`);let F=Ro(_,g.target,g.documentVersion,g.selectionRef);if(!F.ok)return W(g,Rs(F.code),F.message);let L=F.binding;if(!(g.kind==="insert-child"?L.descriptor.capabilities.insert:L.descriptor.capabilities.replace)){let re=L.descriptor.unavailableReasons?.[g.kind==="insert-child"?"insert":"replace"]?.reason??"The selected page block does not permit this operation.";return W(g,B.UNSUPPORTED_OPERATION,re)}let J=(g.kind==="insert-child",g.params);if(J.kind!==g.kind)return W(g,B.INVALID_PARAMS,"Page-block materialization operation kind must match its params.");let Z=J.node;if(Z.kind!=="component-call"||!Z.materialization)return W(g,B.UNSUPPORTED_OPERATION,"Page-block materialization requires a static component manifest.");let z;if(J.kind==="insert-child"){let re=J.position;if(!("kind"in re&&re.kind==="block-boundary"))return W(g,B.INVALID_PARAMS,"Page-block insert-child requires a block-boundary position.");if(re.documentVersion!==g.documentVersion)return W(g,B.VERSION_STALE,"The block insertion boundary belongs to a different document version.");let Ne=za(_,re);if(!Ne.ok)return W(g,Rs(Ne.code),Ne.message);z=Ne.boundary}let X=Z.materialization,te=await ri({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:X.files.map(re=>({path:re.pathTemplate,content:re.content})),exists:re=>n.exists(re),readFile:re=>n.readFile(re)});if(!te.ok)return W(g,B.MATERIALIZATION_REJECTED,te.message);let ae=await jS(n,Object.keys(X.projectDependencies??{})),Se=await Wu({manifest:X,generatedRoot:"components/site/generated",controlledFiles:X.files.map(re=>({pathTemplate:re.pathTemplate})),exists:re=>n.exists(re),availableHostDependencies:ae,hostCapabilities:Mu(),commit:async re=>{let Ne=k.document,be=k.pageBlockIndex;if(!Ne||!be||Ne.version!==g.documentVersion||be.documentVersion!==Ne.version||!be.bindings.has(L.blockKey))return{ok:!0,data:W(g,B.VERSION_STALE,"The route or selected block changed before materialization could commit.")};let M=be.bindings.get(L.blockKey);if(!M||M.ownerFile!==L.ownerFile||M.ownerSourceHash!==L.ownerSourceHash||M.sourceHash!==L.sourceHash)return{ok:!0,data:W(g,B.VERSION_STALE,"The selected block owner or source changed before materialization could commit.")};let Y=new Set([L.ownerFile,L.descriptor.source.file,...z?[z.ownerFile,z.anchorLocator.file,...z.parentLocator?[z.parentLocator.file]:[]]:[]]),fe=new Map;try{for(let _e of Y)fe.set(_e,await n.readFile(_e))}catch{return{ok:!0,data:W(g,B.VERSION_STALE,"A selected owner, root, or boundary file is no longer readable.")}}let ke=tx({operationId:g.id,documentVersion:g.documentVersion,target:g.target,binding:L,...z?{boundary:z}:{},operation:J.kind,materialization:re,files:fe});if(!ke.ok){let _e=yI(ke.code);return{ok:!0,data:W(g,_e,ke.message,{materializationCode:ke.code})}}f+=1;try{let _e=await Yn({request:g,filePlan:ke.plan});return!_e.ok&&_e.error?.message.includes("MATERIALIZATION_INSTANCE_CONFLICT")?{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:_e.error.message||"Static prefab instance conflicted during commit."}}:{ok:!0,data:_e}}finally{f-=1}}});return Se.ok?Se.data:W(g,Se.error.code==="MATERIALIZATION_INSTANCE_CONFLICT"?B.MATERIALIZATION_CONFLICT:B.MATERIALIZATION_REJECTED,Se.error.message,{materializationCode:Se.error.code})}async function mI(g,k){if(g.kind!=="move-node"&&g.kind!=="remove-node")return W(g,B.UNSUPPORTED_OPERATION,"Only page-unit move-node and remove-node are currently supported by the page composition transaction.");let I=k.document,_=k.pageCompositionProjection;if(!I||I.pageComposition?.status!=="supported"||!_||_.status!=="supported")return W(g,B.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(g.documentVersion!==I.version||_.documentVersion!==I.version)return W(g,B.VERSION_STALE,`Document version ${g.documentVersion} is stale (current: ${I.version}).`);let F=await n.readFile(k.entryFile),L=pd({routeId:k.routeId,composition:k.composition,entryFile:k.entryFile,currentDocumentVersion:I.version,expectedDocumentVersion:g.documentVersion,source:F,projection:_,placementUnitKey:g.target.placementUnitKey,operation:g.kind,targetPlacement:g.kind==="move-node"&&g.params.kind==="move-node"&&"kind"in g.params.target&&g.params.target.kind==="page-composition"?g.params.target:void 0});if(!L.ok)return W(g,Cl(L.error.code),L.error.message,{diagnostics:L.error.diagnostics});let $=L.plan.rewriteStep,J;switch($.kind){case"move-node":J=Vr({source:F,locator:$.locator,targetParentLocator:$.targetParentLocator,placement:$.placement,...$.anchorLocator?{anchorLocator:$.anchorLocator}:{}});break;case"remove-node":J=jr({source:F,locator:$.locator});break;case"remove-root-expression":J=Ti({source:F,locator:$.locator,expectedSourceHash:$.sourceHash,action:{kind:"remove"}});break;default:J={ok:!1,source:F,diagnostic:{message:`Unsupported page-unit mutation rewrite: ${$.kind}`}}}if(!J.ok)return W(g,B.AST_PARSE_ERROR,J.diagnostic.message);let Z=J.source,z=[];if(g.kind==="remove-node"){let te=await vl({routeState:k,placementUnitKey:g.target.placementUnitKey,source:F,mutatedSource:Z});Z=te.source,z=await Promise.all(te.files.map(async ae=>({operation:"delete",file:ae,baseContentHash:ve(await n.readFile(ae))})))}let X=[{operation:"upsert",file:k.entryFile,content:Z,baseContentHash:ve(F)},...z];f+=1;try{return await Yn({request:g,filePlan:{operationId:g.id,kind:"source-edit",target:{kind:"source-file",path:k.entryFile},documentVersion:g.documentVersion,conflictPolicy:"compare-and-swap",edits:X}})}finally{f-=1}}async function gI(g,k){if(g.kind!=="move-node"&&g.kind!=="remove-node")return W(g,B.UNSUPPORTED_OPERATION,"Only page-block move-node and remove-node use this source transaction.");let I=k.document,_=k.pageBlockIndex;if(!I||!_||_.diagnostics.length>0)return W(g,B.UNSUPPORTED_OPERATION,"The current route has no complete verified page-block index.");if(g.documentVersion!==I.version||_.documentVersion!==I.version)return W(g,B.VERSION_STALE,`Document version ${g.documentVersion} is stale (current: ${I.version}).`);let F=Ro(_,g.target,g.documentVersion,g.selectionRef);if(!F.ok)return W(g,Rs(F.code),F.message);let L=F.binding;if(L.documentVersion!==I.version)return W(g,B.VERSION_STALE,"The resolved page-block binding is stale.");if(!(g.kind==="move-node"?L.descriptor.capabilities.move:L.descriptor.capabilities.remove)){let be=L.descriptor.unavailableReasons?.[g.kind==="move-node"?"move":"remove"]?.reason??"The selected block does not permit this operation.";return W(g,B.UNSUPPORTED_OPERATION,be)}if(g.kind==="remove-node"){let be=[...i.values()].filter(M=>M.dependencyFiles.has(L.ownerFile));if(be.includes(k)||be.push(k),be.some(M=>!M.pageBlockIndex||M.pageBlockIndex.descriptors.length<=1))return W(g,B.UNSUPPORTED_OPERATION,"The selected source is the last editable page block in an affected composition.")}let J=null;if(g.kind==="move-node"){if(g.params.kind!=="move-node"||!("kind"in g.params.target)||g.params.target.kind!=="block-boundary")return W(g,B.INVALID_PARAMS,"Page-block move requires a block-boundary target.");if(g.params.target.anchorBlockKey===L.blockKey)return W(g,B.INVALID_TARGET,"A page block cannot be moved relative to itself.");let be=za(_,g.params.target);if(!be.ok)return W(g,Rs(be.code),be.message);let M=_.bindings.get(g.params.target.anchorBlockKey);if(!M||!L.descriptor.siblingBlockKeys.includes(M.blockKey)||!M.descriptor.siblingBlockKeys.includes(L.blockKey)||M.ownerFile!==L.ownerFile||M.root.ownerNode.kind!==L.root.ownerNode.kind||M.root.ownerNode.key!==L.root.ownerNode.key||M.root.parentStructuralPath!==L.root.parentStructuralPath)return W(g,B.INVALID_TARGET,"The selected block and boundary anchor are not verified same-owner source siblings.");if(J=be.boundary,J.ownerFile!==L.ownerFile||J.sourceHash!==L.ownerSourceHash||!J.parentLocator)return W(g,B.INVALID_TARGET,"The move boundary does not belong to the selected block's source owner.")}let Z=L.ownerFile,z=await n.readFile(Z);if(ve(z)!==L.ownerSourceHash)return W(g,B.VERSION_STALE,"The page-block owner source changed after resolution.");let X=L.descriptor.source.file===Z?z:await n.readFile(L.descriptor.source.file);if(ve(X)!==L.descriptor.source.contentHash)return W(g,B.VERSION_STALE,"The selected page-block source changed after resolution.");let te=hI(L),ae=g.kind==="remove-node"?jr({source:z,locator:te}):Vr({source:z,locator:te,targetParentLocator:Sl(J.parentLocator),anchorLocator:Sl(J.anchorLocator),placement:J.placement});if(!ae.ok)return W(g,B.AST_PARSE_ERROR,ae.diagnostic.message);let Se=ae.source,re=[];if(g.kind==="remove-node"&&L.root.ownerNode.kind==="route-member"&&L.root.callChain.length>0&&L.descriptor.placementUnitKey){let be=await vl({routeState:k,placementUnitKey:L.descriptor.placementUnitKey,source:z,mutatedSource:Se});Se=be.source,re=be.files}let Ne=[{operation:"upsert",file:Z,content:Se,baseContentHash:L.ownerSourceHash},...await Promise.all(re.map(async be=>({operation:"delete",file:be,baseContentHash:ve(await n.readFile(be))})))];f+=1;try{return await Yn({request:g,filePlan:{operationId:g.id,kind:"source-edit",target:g.target,documentVersion:g.documentVersion,conflictPolicy:"compare-and-swap",edits:Ne}})}finally{f-=1}}function hI(g){return Sl(g.ownerLocator)}function Sl(g){return{kind:"jsx-node",strategy:"source-range",sourceRange:g.sourceRange,...g.structuralPath&&g.componentName?{expectedIdentity:{file:g.file,component:g.componentName,structuralPath:g.structuralPath}}:{}}}function Rs(g){return g==="VERSION_STALE"?B.VERSION_STALE:g==="INVALID_PARAMS"?B.INVALID_PARAMS:B.INVALID_TARGET}function yI(g){return g==="VERSION_STALE"?B.VERSION_STALE:g==="INVALID_PARAMS"?B.INVALID_PARAMS:g==="INVALID_TARGET"?B.INVALID_TARGET:g.startsWith("MATERIALIZATION_")?B.MATERIALIZATION_REJECTED:B.UNSUPPORTED_OPERATION}async function vl(g){let k={source:g.mutatedSource,files:[]},I=g.routeState.graph,_=g.routeState.pageCompositionProjection;if(!I||!_||_.status!=="supported"||!n.listFiles)return k;let L=_.placementUnitByKey.get(g.placementUnitKey)?.sourceRange;if(!L)return k;let $=[...I.elements.values()].find(M=>M.sourceFile===g.routeState.entryFile&&M.importedFrom&&S(M.sourceRange,L));if(!$?.importedFrom||!$.exportName)return k;let J=E($.importedFrom),Z="components/site/generated/";if(!J.startsWith(Z))return k;let z=J.slice(Z.length).split("/")[0];if(!z||!/-[0-9a-f]{8}$/i.test(z))return k;let X=`${Z}${z}`;if([...I.elements.values()].filter(M=>M.sourceFile===g.routeState.entryFile&&E(M.importedFrom??"")===J).length!==1)return k;let ae=await n.listFiles({maxFiles:5e3,maxDepth:32}),Se=Array.isArray(ae)?ae:ae.files;if(!Array.isArray(ae)&&ae.truncated)return k;let re=Se.map(({path:M})=>M).filter(M=>M===X||M.startsWith(`${X}/`));if(re.length===0||!re.includes(J))return k;for(let{path:M}of Se)if(!(M===g.routeState.entryFile||M===X||M.startsWith(`${X}/`)))try{if((await n.readFile(M)).includes(z))return k}catch{return k}let Ne=b(g.routeState.entryFile,J),be=fo({source:g.mutatedSource,moduleSpecifier:Ne,imports:$.exportName==="default"?[{kind:"default"}]:[{kind:"named",imported:$.exportName}]});return be.ok?be.source.includes(z)?{source:be.source,files:[]}:{source:be.source,files:re.sort((M,Y)=>M.localeCompare(Y))}:k}async function xI(g){if(n.getFileInfo){for(let $ of g)if(await n.exists($.path)&&await n.getFileInfo($.path)===null)return{ok:!1,errorCode:"invalid-params",message:`Source edit path must resolve to a regular non-symbolic-link file: ${$.path}`,details:{path:$.path}}}for(let $ of g){if($.operation!=="upsert"||!/^(?:src\/)?app\/globals\.css$/i.test($.path))continue;let J=await n.exists($.path)?await Ul(n,$.path):null;if(J?.ok){let Z=OL(J.content,$.content);if(!Z.ok)return{ok:!1,errorCode:"invalid-params",message:Z.message,details:{path:$.path,code:Z.code}}}}let k=bI(g);if(k.length===0)return{ok:!0};let I=nD(n,g),_=new Map,F=($,J)=>{let Z=_.get($);if(Z?.source===J)return Z.result;let z=Ue($,J);return _.set($,{source:J,result:z}),z},L;try{L=await RS(k,async $=>{let J=i.get($);return J?[...(await ye(J.entryFile,await I.readFile(J.entryFile),I,{validationOnly:!0,parseModule:F,validatedImports:p.getImports})).parsedModules.values()]:[]})}catch($){return{ok:!1,errorCode:"ast-error",message:`Source edit preflight failed: ${Nt($)}`,details:{compositionKeys:k}}}for(let $ of L)p.remember($);return{ok:!0}}function bI(g){return g.map(I=>I.path).some(zS)?[...i.keys()]:[]}function Il(g,k,I,_){let F=ms(k);return{composition:o.resolveSelector(g.composition).context,requestId:g.id,kind:g.kind,target:g.target,ok:!1,resultVersion:H(g),error:{code:F,message:I,..._?{details:_}:{}}}}async function kl(g){let k=[];for(let I of new Set(g))k.push(await EI(I));return k}async function EI(g){if(!(typeof n.exists=="function"?await n.exists(g):!0))return{file:g,content:"",version:Math.max(0,V(g)),exists:!1};let I=await n.readFile(g);return{file:g,content:I,version:Math.max(1,V(g)),exists:!0,sha256:ve(I)}}async function pm(g,k,I,_){if(!e.historyStore)return null;let F=new Map(k.map(J=>[J.file,J])),L=new Map(I.map(J=>[J.file,J])),$=[...new Set([...F.keys(),...L.keys()])].sort().map(J=>{let Z=F.get(J),z=L.get(J);return{path:J,preDigest:Z?.exists===!1||!Z?null:ve(Z.content),postDigest:z?.exists===!1||!z?null:ve(z.content)}});return{schemaVersion:2,transactionId:`${g}:${_.expectedIndexDigest}`,operationId:g,phase:"prepared",historyTransition:_,files:$}}async function mm(g){return!g||!e.historyStore||await e.historyStore.writeTransactionJournal(g),g}async function so(g){g&&e.historyStore&&await e.historyStore.clearTransactionJournal(g.transactionId)}async function Rl(g,k){let I=[];try{for(let _ of g)await gm(_),typeof n.bumpVersion=="function"&&n.bumpVersion(_.file),I.push(_.file)}catch(_){let F=await SI(k.filter(L=>I.includes(L.file)));return F.ok?{ok:!1,reason:`Writeback failed and committed files were restored: ${Nt(_)}`,rolledBack:!0}:{ok:!1,reason:`Writeback failed, then rollback failed for ${F.failedFiles.join(", ")}: ${Nt(_)}`,rolledBack:!1}}return{ok:!0,snapshots:g.map(vI)}}async function gm(g){if(g.exists===!1){await n.deleteFile(g.file);return}await n.writeFile(g.file,g.content)}async function SI(g){let k=[];for(let I of g)try{await gm(I),typeof n.bumpVersion=="function"&&n.bumpVersion(I.file)}catch{k.push(I.file)}return k.length===0?{ok:!0}:{ok:!1,failedFiles:k}}function vI(g){let k=g.exists!==!1;return{file:g.file,content:k?g.content:"",version:g.version,exists:k,...k?{sha256:ve(g.content)}:{}}}async function Yn(g){return y.runExclusive(()=>II(g))}async function II(g){let k=g.filePlan.edits.map(M=>M.file),I=o.resolveSelector(g.request.composition),_=I.context,F=g.historyPolicy==="none"?void 0:{initiatingComposition:_,affectedCompositions:sn(k)},L=await kl(k),$=new Map(L.filter(M=>M.exists!==!1).map(M=>[M.file,M.content])),J=ym(),Z=new Map(d),z=new Set(m),X=new Set([...i.values()].filter(M=>g.filePlan.edits.some(Y=>Y.operation==="delete"&&Y.file===M.entryFile)).map(M=>M.key)),te=g.filePlan.edits.map(M=>M.operation==="delete"?{file:M.file,content:"",version:0,exists:!1}:{file:M.file,content:M.content,version:0,exists:!0,sha256:ve(M.content)}),ae={operationId:g.filePlan.operationId,intents:g.filePlan.edits.map(M=>M.operation==="delete"?{kind:"delete",path:M.file}:{kind:M.operation==="create-only"?"create-only":"upsert",path:M.file,content:M.content})},Se=null,re=!1,Ne=await Uc({overlay:$,exists:M=>n.exists(M),plan:ae,buildCandidate:async({plan:M})=>({plan:M}),prepareHistory:async()=>{let M=g.historyPolicy==="none"?null:await l.prepareAppend({composition:o.resolveSelector(g.request.composition).context,operationId:g.request.id,kind:g.request.kind,target:g.request.target,preSnapshots:L,postSnapshots:te,...g.selectionRef?{selectionRef:g.selectionRef}:{},...g.output?{output:g.output}:{},...F?{provenance:F}:{}}),Y=M?.historyTransition?M.historyTransition:e.historyStore?UL(await e.historyStore.readIndex()):null;if(e.historyStore&&!Y)throw new Error("Durable history did not provide an exact index transition.");return Se=await pm(g.request.id,L,te,Y),Se=await mm(Se),{history:M,historyTransition:Y}},reverify:async()=>{},writeCandidate:async()=>{let M=await u.executeFilePlan(g.filePlan);if(!M.ok)throw new Hc(M);return{postSnapshots:await kl(M.affectedFiles),affectedFiles:M.affectedFiles,internalResultVersion:M.resultVersion}},validateCandidate:async({candidate:M,receipt:Y})=>{let fe=await ue(Y.affectedFiles,{changed:!0,minimumVersion:Y.internalResultVersion,publish:!1,excludedCompositionKeys:X});if(fe.failedRoutes.length>0)throw new ro(fe.failedRoutes);let ke=bm(J,fe.candidateRouteStates??[]),_e=xm(ke,I.key);return{...M,rebuild:fe,routeSnapshots:ke,resultVersion:_e,...US(g.selectionRef,ke.map(Ye=>Ye.state.document))?{selectionRef:US(g.selectionRef,ke.map(Ye=>Ye.state.document))}:{}}},publishCandidate:async({candidate:M,history:Y,receipt:fe})=>{Y?.history&&(await l.publishPrepared(Y.history),re=!0);let ke=M.resultVersion??fe.internalResultVersion;return{composition:_,requestId:g.request.id,kind:g.request.kind,target:g.request.target,ok:!0,resultVersion:ke,affectedFiles:fe.affectedFiles,fileChanges:fe.postSnapshots.map(_e=>({path:_e.file,operation:_e.exists===!1?"delete":"upsert"})),...g.output?{output:g.output}:{},...M.selectionRef?{selectionRef:M.selectionRef}:{}}},swapCandidate:({candidate:M,receipt:Y})=>{M.routeSnapshots&&Cs(M.routeSnapshots),M.rebuild?.candidateSourceCache&&Ko(d,M.rebuild.candidateSourceCache),lm(Y.postSnapshots)},finalizeCandidate:async()=>{await so(Se);for(let M of X)i.delete(M)},emitCommitted:({candidate:M,published:Y})=>{El(Y,M.rebuild??{rebuiltRoutes:[],failedRoutes:[]})},rollbackCandidate:async({history:M,receipt:Y})=>{if(re)throw new Error("history was published before transaction finalization failed");if(Y){let fe=await Rl(L,Y.postSnapshots);if(!fe.ok)throw new Error(fe.reason)}Cs(J),Ko(d,Z),um(z),M?.history&&await l.discardPrepared?.(M.history),await so(Se)}});if(Ne.ok)return Ne.published;if(Ne.stage==="precheck"||Ne.stage==="build")try{await so(Se)}catch(M){let Y=await _s(Nt(M));return W(g.request,Y,"Unable to clear an uncommitted transaction journal.")}if(Ne.recoveryRequired){let M=await _s(Ne.reason);return W(g.request,M===B.RECOVERY_PERSIST_FAILED?M:B.ROLLBACK_FAILED,Ne.reason)}let be=Ne.error;return be instanceof Hc?{...W(g.request,ms(be.result.errorCode),be.result.reason),...be.result.affectedFiles?{affectedFiles:be.result.affectedFiles}:{}}:be instanceof ro?W(g.request,B.ROUTE_REBUILD_FAILED,`Route rebuild failed and source was rolled back: ${fp(be.failedRoutes)}`,{failedRoutes:be.failedRoutes}):W(g.request,Sm(Ne.stage),Nt(be))}async function hm(g){return y.runExclusive(async()=>{let k=g==="undo"?await l.prepareUndo():await l.prepareRedo();return k?kI(g,k):{composition:o.entries[0].context,requestId:g,kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:o.initialVersions.get(o.entries[0].key)??0,error:{code:B.INTERNAL_ERROR,message:g==="undo"?"Nothing to undo":"Nothing to redo"}}})}async function kI(g,k){let I=k.entry,_=g==="undo"?I.preSnapshots:I.postSnapshots,F=g==="undo"?I.postSnapshots:I.preSnapshots,L=_.map(Y=>Y.file),{context:$,key:J}=ks(I,L),Z=await kl(L),z=new Map(Z.filter(Y=>Y.exists!==!1).map(Y=>[Y.file,Y.content])),X=U(J),te=ym(),ae=new Map(d),Se=new Set(m),re=null,Ne=!1,be,M=await Uc({overlay:z,plan:{operationId:`${g}:${I.operationId}`,intents:_.map(Y=>Y.exists===!1?{kind:"delete",path:Y.file}:{kind:"upsert",path:Y.file,content:Y.content})},buildCandidate:async()=>({}),prepareHistory:async()=>(re=await pm(`${g}:${I.operationId}`,Z,_,k.historyTransition),re=await mm(re),k),reverify:async()=>{},writeCandidate:async()=>{let Y=await Rl(_,F);if(!Y.ok)throw new Error(Y.reason);return{snapshots:Y.snapshots}},validateCandidate:async({candidate:Y})=>{be=Et(I,L);let fe=await ue(L,{changed:!0,minimumVersion:X+1,publish:!1,affectedCompositionKeys:be});if(fe.failedRoutes.length>0)throw new ro(fe.failedRoutes);let ke=bm(te,fe.candidateRouteStates??[]),_e=xm(ke,J);return{...Y,rebuild:fe,routeSnapshots:ke,resultVersion:_e}},publishCandidate:async({candidate:Y,history:fe,receipt:ke})=>{if(!fe)throw new Error("history cursor intent is missing");await l.publishPrepared(fe),Ne=!0;let _e=Y.resultVersion??X+1;return{composition:$,requestId:g,kind:I.kind,target:I.target,ok:!0,resultVersion:_e,affectedFiles:L,fileChanges:ke.snapshots.map(Ye=>({path:Ye.file,operation:Ye.exists===!1?"delete":"upsert"})),...I.output?{output:I.output}:{}}},swapCandidate:({candidate:Y,receipt:fe})=>{Y.routeSnapshots&&Cs(Y.routeSnapshots),Y.rebuild?.candidateSourceCache&&Ko(d,Y.rebuild.candidateSourceCache),lm(fe.snapshots)},finalizeCandidate:async()=>{await so(re)},emitCommitted:({candidate:Y,published:fe})=>El(fe,Y.rebuild??{rebuiltRoutes:[],failedRoutes:[]}),rollbackCandidate:async({history:Y,receipt:fe})=>{if(Ne)throw new Error("history cursor was published before transaction finalization failed");if(fe){let ke=await Rl(F,fe.snapshots);if(!ke.ok)throw new Error(ke.reason)}Cs(te),Ko(d,ae),um(Se),Y&&await l.discardPrepared?.(Y),await so(re)}});if(M.ok)return M.published;if(M.stage==="precheck"||M.stage==="build")try{await so(re)}catch(Y){let fe=await _s(Nt(Y));return{composition:$,requestId:g,kind:I.kind,target:I.target,ok:!1,resultVersion:X,error:{code:fe,message:"Unable to clear an uncommitted transaction journal."}}}if(M.recoveryRequired){let Y=await _s(M.reason);return{composition:$,requestId:g,kind:I.kind,target:I.target,ok:!1,resultVersion:X,affectedFiles:L,error:{code:Y===B.RECOVERY_PERSIST_FAILED?Y:B.ROLLBACK_FAILED,message:M.reason}}}return{composition:$,requestId:g,kind:I.kind,target:I.target,ok:!1,resultVersion:X,affectedFiles:L,error:{code:M.error instanceof ro?B.ROUTE_REBUILD_FAILED:Sm(M.stage),message:Nt(M.error),...M.error instanceof ro?{details:{failedRoutes:M.error.failedRoutes}}:{}}}}function ym(){return[...i.values()].map(g=>({composition:g.composition,key:g.key,routeId:g.routeId,state:{...g,dependencyFiles:new Set(g.dependencyFiles),fileVersions:new Map(g.fileVersions)}}))}function xm(g,k){return g.find(_=>_.key===k)?.state.graph?.version??o.initialVersions.get(k)??0}function bm(g,k){let I=new Map(g.map(_=>[_.key,_]));for(let _ of k)I.set(_.key,_);return[...I.values()]}function Cs(g){for(let k of i.values())A(k);for(let k of g){let I={...k.state,dependencyFiles:new Set(k.state.dependencyFiles),fileVersions:new Map(k.state.fileVersions)};i.set(k.key,I),R(I,I.dependencyFiles)}}async function Ns(g){let k=i.get(g);if(!k)throw new Error(`Composition not found: ${g}`);if(k.graph)return;let I=await n.readFile(k.entryFile);await st(g,I)}function ao(g,k){let I=i.get(o.resolveSelector(k).key)??null;return!I||!Em(I,g)?null:I}function Em(g,k){if(g.documentIndex?.entriesByKey.has(k)||g.graph?.elements.has(k))return!0;let I=Lt(k);return I&&I!==k?g.graph?.elements.has(I)===!0:!1}function W(g,k,I,_){return{composition:o.resolveSelector(g.composition).context,requestId:g.id,kind:g.kind,target:g.target,ok:!1,resultVersion:H(g),error:{code:k,message:I,..._?{details:_}:{}}}}function Sm(g){return g==="validate"?B.ROUTE_REBUILD_FAILED:g==="publish"?B.HISTORY_COMMIT_FAILED:B.WRITE_IO_ERROR}async function _s(g){if(h=!0,!l.markRecoveryRequired)return B.RECOVERY_REQUIRED;try{return await l.markRecoveryRequired(g),B.RECOVERY_REQUIRED}catch{return B.RECOVERY_PERSIST_FAILED}}function RI(g){let I=g.split(/[^a-zA-Z0-9]+/).filter(Boolean).map(_=>_.charAt(0).toUpperCase()+_.slice(1)).join("").replace(/^[^a-zA-Z_$]+/,"");return I?`Prefab${I}`:"GeneratedPrefab"}function Cl(g){return g==="VERSION_STALE"?B.VERSION_STALE:g==="CROSS_PAGE_MOVE_UNSUPPORTED"?B.CROSS_PAGE_MOVE_UNSUPPORTED:B.UNSUPPORTED_OPERATION}async function vm(g){if(g.target.kind==="route"){let I=i.get(o.resolveSelector(g.target.composition).key)??null;return I?(I.graph||await Ns(I.key),I):W(g,B.ROUTE_NOT_FOUND,"Composition not found for route target.")}if(g.target.kind==="page-unit"){let I=i.get(o.resolveSelector(g.target.composition).key)??null;return I?(I.graph||await Ns(I.key),I):W(g,B.ROUTE_NOT_FOUND,"Composition not found for page-unit target.")}if(g.target.kind==="page-block"){let I=i.get(o.resolveSelector(g.target.composition).key)??null;return I?(I.graph||await Ns(I.key),I):W(g,B.ROUTE_NOT_FOUND,"Composition not found for page-block target.")}if(g.target.kind!=="node")return W(g,B.UNSUPPORTED_OPERATION,`${g.kind} source target execution is not implemented yet.`);let k=i.get(o.resolveSelector(g.composition).key)??null;return k?(k.graph||await Ns(k.key),Em(k,g.target.key)?k:W(g,B.NODE_NOT_FOUND,`Target key not found: ${g.target.key}`)):W(g,B.ROUTE_NOT_FOUND,"Composition not found for node target.")}return{get status(){return t},dispose(){t="disposed",a.clear(),i.clear(),s.clear(),d.clear(),p.clear(),m.clear()},registerComposition(g,k){let I=o.register({context:g,entryFile:k}),_=i.get(I.key);if(_?.entryFile===k)return;_&&A(_);let F=VS(I.context,k);i.set(I.key,F),R(F,F.dependencyFiles),r.emit({type:"graph-invalidated",composition:I.context})},unregisterComposition(g){let k=o.resolveSelector(g),I=i.get(k.key);I&&(A(I),i.delete(k.key),o.unregister(k.key),i.size===0&&(t="idle"),r.emit({type:"graph-invalidated",composition:k.context}))},getCompositionEntryFiles(){return[...i.values()].map(g=>g.entryFile)},getCompositionContext(g){return o.resolveSelector(g).context},async initializeComposition(g){let k=o.resolveSelector(g),I=i.get(k.key);if(!I)throw new Error(`Composition not registered: ${k.key}`);if(I.graph)t="ready";else{t="building";try{let _=await n.readFile(I.entryFile);await st(k.key,_),t="ready",r.emit({type:"graph-ready",composition:k.context,version:i.get(k.key)?.graph?.version??0})}catch(_){throw t="idle",r.emit({type:"graph-error",composition:k.context,message:Nt(_)}),_}}},getDocument(g){let k=o.resolveSelector(g),I=i.get(k.key);if(!I)throw new Error(`Composition not registered: ${k.key}`);if(!I.document)throw new Error(`Composition not built: ${k.key}`);return I.document},async getHistoryStatus(){await x;let g=await l.getStatus?.();return g?{...g,recoveryRequired:h}:{canUndo:!1,canRedo:!1,undoDepth:0,redoDepth:0,recoveryRequired:h}},getObjectEditContext(g,k,I){let _=ao(g,k),F=Lt(g)??g;if(_?.graph&&_.topology&&_.capabilities&&_.detailProjections){let L=_.detailProjections.get(F);if(L){let $=_.graph.elements.get(F);if(!$)throw new Error(`Key not found: ${g}`);let J=WL(g,F,I),Z=new Map;if(L.isRepeat&&J?.instanceIndex!==void 0)for(let te of $.attributes??[])Z.set(te.name,Vf({file:$.sourceFile,source:d.get($.sourceFile)??"",element:$,propertyName:te.name,selectionRef:J,graph:_.graph,sources:d}));let z=oS({element:$,graph:_.graph,source:d.get($.sourceFile),documentVersion:_.graph.version,selectionRef:I,isRepeat:L.isRepeat,propertyProvenance:L.propertyProvenances,repeatTargets:Z}),X=aS(F,_.graph,_.topology,_.capabilities,L.textSources,L.provenances,L.dynamicData,z);return g===F?X:wS(X,g,_.document??null,_.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${g}`)},getRenderDetail(g,k){let I=ao(g,k),_=Lt(g)??g;if(I?.graph&&I.topology&&I.capabilities&&I.detailProjections){let F=I.detailProjections.get(_);if(F){let L=sS(_,I.graph,I.topology,I.capabilities,F.textSources,F.writeTarget,F.provenances,F.conditional,F.componentSemantic,F.styleSource,F.dynamicData);return g===_?L:TS(L,g,I.document??null,I.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${g}`)},getClassNameSource(g,k){let I=ao(g,k),_=Lt(g)??g;if(!I?.graph)throw new Error(`Key not found: ${g}`);let F=I.graph.elements.get(_);if(!F)throw new Error(`Key not found: ${g}`);let L=d.get(F.sourceFile);if(L===void 0)throw new Error(`Source not loaded: ${F.sourceFile}`);return au({key:_,route:{composition:I.composition,routeId:I.routeId,graph:I.graph,source:L}})},refreshSourceForKey:cI,async execute(g){if(await x,h)return W(g,B.RECOVERY_REQUIRED,"The edit engine requires explicit recovery before accepting mutations.");if(g.kind==="source-edit")return lI(g);if(g.kind==="insert-page-resource")return uI(g);if(g.kind==="delete-page-source")return dI(g);let k=await vm(g);if("ok"in k)return k;await fm(g);let I=await vm(g);if("ok"in I)return I;let _=I;if(g.target.kind==="page-unit"){let X=g;return g.kind==="insert-child"||g.kind==="replace-node"?fI(X,_):g.kind==="move-node"||g.kind==="remove-node"?mI(X,_):W(g,B.UNSUPPORTED_OPERATION,"Only page-unit insert-child, replace-node, move-node, and remove-node are currently supported by the page composition transaction.")}if(g.target.kind==="page-block"){let X=g;return g.kind==="insert-child"||g.kind==="replace-node"?pI(X,_):g.kind==="move-node"||g.kind==="remove-node"?gI(X,_):W(g,B.UNSUPPORTED_OPERATION,"Page-block operation is not supported by the current structural transaction.")}let L=g.params,$=g.target.kind==="node"?g.target.key:null;if(L.kind==="move-node"&&"kind"in L.target&&L.target.kind==="source-sibling"){let X=L.target,te=$?_.document?.entries.find(Y=>Y.key===$):null,ae=_.document?.entries.find(Y=>Y.key===X.anchorKey),Se=te?.pageCompositionActionScope,re=Se?.kind==="source-siblings"?Se.siblingKeys:null,Ne=re?.indexOf(te?.key??"")??-1,be=re?.indexOf(X.anchorKey)??-1,M=X.relation==="before"?Ne-1:Ne+1;if(!te||!ae||!re||Ne<0||be!==M||ae.pageCompositionActionScope?.kind!=="source-siblings"||ae.pageCompositionActionScope.siblingKeys.length!==re.length||ae.pageCompositionActionScope.siblingKeys.some((Y,fe)=>Y!==re[fe])||!te.operationSummary.canMove)return W(g,B.INVALID_TARGET,"Source sibling move is unavailable because the current source sibling scope or adjacent anchor no longer matches.")}if(!_.graph||!_.topology||!_.capabilities)return{composition:o.resolveSelector(g.composition).context,requestId:g.id,kind:g.kind,target:g.target,ok:!1,resultVersion:H(g),error:{code:g.target.kind==="route"?B.ROUTE_NOT_FOUND:B.NODE_NOT_FOUND,message:g.target.kind==="route"?"Composition not ready for route target.":g.target.kind==="node"?`Target key not found: ${g.target.key}`:`${g.kind} source target execution is not implemented yet.`}};let J=fD(_,_.graph,_.capabilities,d,i),Z=await new xc(J).plan(g);if(!Z.ok)return{composition:o.resolveSelector(g.composition).context,requestId:g.id,kind:g.kind,target:g.target,ok:!1,resultVersion:H(g),error:{code:ms(Z.errorCode),message:Z.reason}};let z=Z.plan;if(z.steps.length===0)return g.kind==="set-props"?{composition:o.resolveSelector(g.composition).context,requestId:g.id,kind:g.kind,target:g.target,ok:!0,resultVersion:H(g),affectedFiles:[]}:{composition:o.resolveSelector(g.composition).context,requestId:g.id,kind:g.kind,target:g.target,ok:!1,resultVersion:H(g),error:{code:B.PLAN_FAILED,message:"Planner could not generate a valid execution plan"}};f+=1;try{if(z.steps.some(te=>te.type==="invoke-external-adapter")){let te=await u.execute(z);if(!te.ok)return W(g,ms(te.errorCode),te.reason);let ae={composition:o.resolveSelector(g.composition).context,requestId:g.id,kind:g.kind,target:g.target,ok:!0,resultVersion:Math.max(H(g),te.resultVersion),affectedFiles:te.affectedFiles,...te.selectionRef?{selectionRef:te.selectionRef}:{}};return El(ae,{rebuiltRoutes:[],failedRoutes:[]}),ae}let X=await u.prepareRewritePlan(z);return X.ok?await Yn({request:g,filePlan:X.filePlan,...X.selectionRef?{selectionRef:X.selectionRef}:{}}):W(g,ms(X.errorCode),X.reason)}catch(X){return{composition:o.resolveSelector(g.composition).context,requestId:g.id,kind:g.kind,target:g.target,ok:!1,resultVersion:H(g),error:{code:B.INTERNAL_ERROR,message:Nt(X)}}}finally{f-=1}},async undo(g){if(await x,h)return{composition:o.entries[0].context,requestId:"undo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:U(o.entries[0].key),error:{code:B.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting undo."}};f+=1;try{return await hm("undo")}finally{f-=1}},async redo(g){if(await x,h)return{composition:o.entries[0].context,requestId:"redo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:U(o.entries[0].key),error:{code:B.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting redo."}};f+=1;try{return await hm("redo")}finally{f-=1}},notifyFileChanged(g){am([g])},getAffectedCompositions(g){return bt(g)},subscribe(g){return r.subscribe(g)}}}function iD(e){return e instanceof Error&&"code"in e&&(e.code==="ENOENT"||e.code==="ENOTDIR")}function sD(e,t,n,r){let o=new Map,i=new Map,s=(d,p,m)=>{let f=d.get(p)??new Set,h=f.size;return f.add(m),d.set(p,f),f.size!==h},a=(d,p)=>{if(!d.importedFrom)return!1;if(d.exportName==="default")return s(i,d.importedFrom,p);let m=s(o,`${d.importedFrom}#${d.tag}`,p);return d.exportName&&d.exportName!==d.tag&&(m=s(o,`${d.importedFrom}#${d.exportName}`,p)||m),m},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 p=n.placements.find(f=>f.members.some(h=>h.sourceRange!==null&&gs(d.sourceRange,h.sourceRange)));if(!p)continue;let m=p.placementUnitKey;a(d,m)}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 p=c(d);if(p)for(let m of p)l=a(d,m)||l}}let u=n.placements.find(d=>d.placementKey===n.container.placementKey&&d.relation==="append");for(let d of e.entries){let p=Lt(d.key)??d.key,m=t.elements.get(d.key)??t.elements.get(p);if(!m)continue;if(m.sourceFile===n.entryFile){if(n.container.sourceRange&&gs(m.sourceRange,n.container.sourceRange)&&u){d.pageCompositionUnitKey=u.placementUnitKey;continue}let y=n.placements.find(x=>x.members.some(E=>E.sourceRange!==null&&(gs(m.sourceRange,E.sourceRange)||dD(E.sourceRange,m.sourceRange))));if(y){d.pageCompositionUnitKey=y.placementUnitKey;continue}}let f=o.get(`${m.sourceFile}#${m.componentName}`);if(f){f.size===1&&(d.pageCompositionUnitKey=f.values().next().value);continue}let h=i.get(m.sourceFile);h?.size===1&&(d.pageCompositionUnitKey=h.values().next().value)}aD(e,t,n,r)}function aD(e,t,n,r){let o=new Map(e.entries.map(p=>[p.key,p])),i=e.entries.filter(p=>{let m=p.pageCompositionUnitKey;return m?p.parentKey?o.get(p.parentKey)?.pageCompositionUnitKey!==m:!0:!1}),s=new Map,a=(p,m)=>{s.set(p,Math.min(2,(s.get(p)??0)+m))},c=p=>n.placements.some(m=>m.members.some(f=>f.sourceRange!==null&&gs(p.sourceRange,f.sourceRange)));for(let p of t.elements.values())p.sourceFile!==n.entryFile||!p.importedFrom||!/^[A-Z]/.test(p.tag)||!c(p)||a(`${p.importedFrom}#${p.exportName??p.tag}`,1);let l=[...t.elements.values()].flatMap(p=>p.sourceFile!==n.entryFile&&p.importedFrom&&/^[A-Z]/.test(p.tag)?[{owner:`${p.sourceFile}#${p.componentName}`,ownerDefault:`${p.sourceFile}#default`,target:`${p.importedFrom}#${p.exportName??p.tag}`}]:[]);for(let p=0;p<=l.length;p+=1){let m=!1;for(let f of l){let h=s.get(f.owner)??s.get(f.ownerDefault)??0;if(!h)continue;let y=s.get(f.target)??0,x=Math.min(2,y+h);x!==y&&(s.set(f.target,x),m=!0)}if(!m)break}let u=p=>s.get(`${p.sourceFile}#${p.componentName}`)??s.get(`${p.sourceFile}#default`)??0;for(let p of i){p.pageCompositionActionScope={kind:"unavailable"};let m=t.elements.get(p.key);p.pageCompositionUnitKey&&m?.sourceFile===n.entryFile&&(p.pageCompositionActionScope={kind:"route-unit"})}let d=new Map;for(let p of i){let m=t.elements.get(p.key);if(!m||m.sourceFile===n.entryFile||p.key!==(Lt(p.key)??p.key))continue;let f=r.get(m.sourceFile);if(!f)continue;let h=Ee(f.ast,{kind:"jsx-node",strategy:"source-range",sourceRange:m.sourceRange});if(!h.ok||!h.match.path.isJSXElement())continue;let y=h.match.path,x=y.parentPath;if(!x||!x.isJSXFragment()&&!(x.isJSXElement()&&ze(x))){u(m)===1&&JS(y)&&(p.pageCompositionActionScope={kind:"route-unit"});continue}if(!JS(x))continue;let E=d.get(x.node)??[];E.push({entry:p,element:m,parentPath:x}),d.set(x.node,E)}for(let p of d.values()){let m=p[0];if(!m)continue;let f=m.entry.pageCompositionUnitKey,h=[],y=!!(f&&u(m.element)===1);for(let E of m.parentPath.node.children){if(cD(E))continue;if(!lD(E)){y=!1;break}let b=[...t.elements.values()].find(N=>N.sourceFile===m.element.sourceFile&&N.componentName===m.element.componentName&&gs(N.sourceRange,uD(E))),S=b?o.get(b.identity.key):null;if(!b||!S||S.parentKey||S.pageCompositionUnitKey!==f||u(b)!==1){y=!1;break}h.push(S)}if(!y||h.length!==p.length||p.some(({entry:E})=>!h.some(b=>b.key===E.key)))continue;if(h.length===1){h[0].pageCompositionActionScope={kind:"route-unit"};continue}if(h.length<2)continue;let x=h.map(E=>E.key);for(let E of h)E.pageCompositionActionScope={kind:"source-siblings",siblingKeys:x}}}function JS(e){let t=e.parentPath;return!!(t?.isReturnStatement?.()||t?.isArrowFunctionExpression?.()&&t.node.body===e.node)}function cD(e){return!!(e&&typeof e=="object"&&e.type==="JSXText"&&!(e.value??"").trim())}function lD(e){return!!(e&&typeof e=="object"&&e.type==="JSXElement")}function uD(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 gs(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function dD(e,t){return XS(e.startLine,e.startColumn,t.startLine,t.startColumn)<=0&&XS(e.endLine,e.endColumn,t.endLine,t.endColumn)>=0}function XS(e,t,n,r){return e!==n?e-n:t-r}function fD(e,t,n,r,o){let i=new Map,s=new Map,a=(u,d)=>{if(s.has(u))return;s.set(u,d);let p=t.elements.get(u);for(let m of p?.childKeys??[])a(m,d)};for(let u of t.regions)if(u.kind==="repeat-region")for(let d of u.childKeys)i.set(d,u.ownerKey),a(d,u.ownerKey);return{getNode(u){let d=c(u),p=t.elements.get(d.baseKey);return p?l(u,p):null},getChildNodes(u){let d=c(u),m=e.documentIndex?.entriesByKey.get(u)?.childKeys;if(m)return m.map(h=>{let y=Lt(h)??h,x=t.elements.get(y);return x?l(h,x):null}).filter(h=>h!==null);let f=t.elements.get(d.baseKey);return f?f.childKeys.map(h=>{let y=t.elements.get(h);return y?l(h,y):null}).filter(h=>h!==null):[]},getKnownSourceFiles(){return[...r.entries()].map(([u,d])=>({file:u,content:d}))},getRouteEntryFiles(){return[...o.values()].map(u=>u.entryFile)},getCapability(u){let d=c(u),p=n.get(d.baseKey);return p?{...p,key:u,constraints:p.constraints.map(m=>({...m})),...p.editModes?{editModes:{...p.editModes}}:{}}:{composition:e.composition,key:u,canUpdateText:!1,canRemove:!1,canInsertChild:!1,canMove:!1,constraints:[]}},getFileContent(u){return r.get(u)??""},getFileVersion(u){return Math.max(e.fileVersions.get(u)??0,t.version)},getRouteEntryFile(u){return e.routeId===u?e.entryFile:null},getComponentSemantic(u){let d=c(u);return e.detailProjections?.get(d.baseKey)?.componentSemantic??null},getClassNameSource(u){let d=c(u),p=t.elements.get(d.baseKey),m=p?r.get(p.sourceFile):void 0;return!p||m===void 0?null:au({key:d.baseKey,route:{composition:e.composition,routeId:e.routeId,graph:t,source:m}})},getEditableTextSegmentIndex(u){let d=c(u),m=e.detailProjections?.get(d.baseKey)?.textTargets.keys()?.next();return m&&!m.done?m.value:null},async getTextWriteTarget(u,d){let p=c(u);return dp(e.detailProjections?.get(p.baseKey)?.textTargets.get(d)??null,p.repeatIndex)},async getElementPropertyWriteTarget(u,d){let p=c(u);return dp(e.detailProjections?.get(p.baseKey)?.elementPropertyTargets.get(d)??null,p.repeatIndex)},getPropertyState(u,d,p){let m=c(u),f=t.elements.get(m.baseKey);if(!f)return null;let y=e.detailProjections?.get(m.baseKey)?.propertyProvenances.get(d);if(y)return y;let x=f.attributes?.find(E=>E.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:f.sourceFile,sourceRange:x.sourceRange}}:(f.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,p){let m=c(u),f=t.elements.get(m.baseKey);if(!f)return{ok:!1,errorCode:"repeat-not-found",reason:`Node not found: ${u}`};let h=p?{...p,key:m.baseKey}:m.repeatIndex!==null?{key:m.baseKey,instanceIndex:m.repeatIndex}:void 0;return Vf({file:f.sourceFile,source:r.get(f.sourceFile)??"",element:f,propertyName:d,selectionRef:h,graph:t,sources:r})},getTextProvenance(u,d){let p=c(u);return e.detailProjections?.get(p.baseKey)?.provenances.get(d)??null}};function c(u){let d=ML(u);return d?{baseKey:d.baseKey,repeatIndex:AS(e.document??null,u,d.baseKey,e.documentIndex)??PS(d)}:{baseKey:u,repeatIndex:null}}function l(u,d){let p=Lt(u)??u,m=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:m?.parentKey??d.parentKey??void 0,isRepeatRegion:d.boundaryKind==="repeat-region"||s.has(p),isBoundary:!1,importedFrom:d.importedFrom,exportName:d.exportName,isRepeatItemRoot:i.has(p),repeatOwnerKey:i.get(p)??s.get(p),attributes:d.attributes?.map(f=>({name:f.name,value:f.value,source:f.source?{expression:f.source.expression,base:f.source.base,path:f.source.path.map(h=>({...h}))}:null,resolvedValue:f.resolvedValue}))}}}var pD={"stale-version":B.VERSION_STALE,"capability-denied":B.CAPABILITY_REJECTED,"invalid-params":B.INVALID_PARAMS,"locator-miss":B.LOCATOR_FAILED,"route-not-found":B.ROUTE_NOT_FOUND,"unsupported-operation":B.UNSUPPORTED_OPERATION,"invalid-target":B.INVALID_TARGET,"ast-error":B.AST_PARSE_ERROR,"writeback-failed":B.WRITE_IO_ERROR,"rollback-failed":B.RECOVERY_REQUIRED,unknown:B.INTERNAL_ERROR};function ms(e){return pD[e]}function Nt(e){return e instanceof Error&&e.message?e.message:String(e)}function zS(e){return/\.(?:[cm]?[jt]sx?|css|scss|sass|mdx|json)$/i.test(e)}function mD(e){let t=oo(e);if(!$L.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=>VL.map(a=>`${s}/${a}`))}function gD(e){let n=oo(e).startsWith("src/app/")?"src/app":"app";return[`${n}/globals.css`,`${n}/global.css`]}function hD(e){return GS(e,/\bimport\s+(?:[^'";]+?\s+from\s+)?["']([^"']+\.css(?:\?[^"']*)?)["']/g)}function yD(e){return GS(e,/@import\s+(?:url\(\s*)?["']([^"']+)["']/g)}function GS(e,t){let n=[];for(let r of e.matchAll(t)){let o=YS(r[1]??"");o&&n.push(o)}return n}function HS(e,t){let n=YS(t);return!n||n.startsWith("tailwindcss")||n.startsWith("http:")||n.startsWith("https:")?null:n.startsWith("@/")?oo(`src/${n.slice(2)}`):n.startsWith("./")||n.startsWith("../")?oo(`${xD(e)}/${n}`):n.startsWith("/")?oo(n.slice(1)):hp(n)?oo(n):null}function YS(e){return e.split(/[?#]/,1)[0]?.trim()??""}function hp(e){return/\.css$/i.test(e)}function xD(e){let t=oo(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function bD(e){return Array.from(new Set(e))}function oo(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 ED(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 Gc=class{constructor(t){this.options=t,this.fileSystem=new oi(t.files),this.engine=this.createEngine(this.fileSystem)}get status(){return this.engine.status}initializeComposition(t){return this.engine.initializeComposition(t)}getDocument(t){return Ls(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 Ds(r?this.engine.getObjectEditContext(t,n,r):this.engine.getObjectEditContext(t,n))}getClassNameSource(t,n){return this.engine.getClassNameSource(t,n)}getSourceTree(t){return js(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}getSourceFile(t){return $s(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}resolveSourceLocation(t){return Vs(t,this.engine.getRenderDetail(t.key,t.composition))}async planOperation(t){let n=vD.safeParse(t);if(!n.success)return{result:Fs(t,n.error.issues.map(i=>i.message))};let r=new oi(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:Dr(i)},a=r.getChangedFiles();if(a.length===0)return{result:s};let c=ID.parse({siteId:t.siteId,baseSnapshotId:t.baseSnapshotId,operationId:t.id,reason:`site-edit:${t.kind}`,patches:a.map(l=>kD(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 Wc({projectRoot:"/snapshot",fileSystem:t,compositions:this.options.compositions,onEvent:r&&this.options.onEvent?o=>{let i=Ms(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 kD(e,t){return e.after===void 0?{path:e.path,operation:"delete",...t||e.before===void 0?{}:{expectedHash:ve(e.before)}}:{path:e.path,operation:e.before===void 0?"create":"update",...t||e.before===void 0?{}:{expectedHash:ve(e.before)},fullContent:e.after}}function RD(e){return new Gc(e)}import{SiteEditOperationRequestSchema as _D}from"@vcp-dev/contracts";import yn from"node:fs/promises";import _t from"node:path";import{SITE_EDIT_SOURCE_ALLOWED_DIRS as CD,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as ND}from"@vcp-dev/contracts";var Yc=class{constructor(t){this.options=t,this.fileSystem=this.createFileSystem(),this.engine=Wc({...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 js(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.engine.getCompositionEntryFiles()})}getSourceFile(t){return $s(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.engine.getCompositionEntryFiles()})}resolveSourceLocation(t){return Vs(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 yn.readFile(_t.join(n,r),"utf8")},async readFileBytes(r){return yn.readFile(_t.join(n,r))},async getFileInfo(r){let o=_t.join(n,...r.split("/"));try{let i=await yn.lstat(o);return!i.isFile()||i.isSymbolicLink()?null:{path:r,sizeBytes:i.size}}catch{return null}},async writeFile(r,o){await sa(_t.join(n,r),o)},async createExclusive(r,o){let i=_t.join(n,r);await yn.mkdir(_t.dirname(i),{recursive:!0});let s=await yn.open(i,"wx");try{await s.writeFile(o,"utf8")}catch(a){throw await s.close(),await yn.rm(i,{force:!0}),a}await s.close()},async deleteFile(r){await yn.rm(_t.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=_t.join(n,i),a=_t.dirname(_t.join(n,o));for(;a!==s&&a.startsWith(`${s}${_t.sep}`);){try{await yn.rmdir(a)}catch(c){if(c instanceof Error&&"code"in c&&c.code==="ENOENT"){a=_t.dirname(a);continue}break}a=_t.dirname(a)}},async exists(r){try{return await yn.access(_t.join(n,r)),!0}catch{return!1}},async listFiles(r={}){let o=r.roots??[...ND,...CD],i=[],s=new Set,a=new Set,c=0;for(let d of o)await u(d,i,1);let l=i.sort((d,p)=>d.path.localeCompare(p.path));return a.size>0?{files:l,truncated:{reasons:[...a]}}:{files:l};async function u(d,p,m){if(r.maxDepth!==void 0&&m>r.maxDepth){a.add("max-depth");return}let f=_t.join(n,...d.split("/")),h;try{h=await yn.lstat(f)}catch{return}if(h.isSymbolicLink())return;if(h.isFile()){let x=h.ino>0?`${String(h.dev)}:${String(h.ino)}`:null;if(x&&s.has(x))return;if(r.maxFiles!==void 0&&p.length>=r.maxFiles){a.add("max-files");return}if(r.maxTotalBytes!==void 0&&c+h.size>r.maxTotalBytes){a.add("max-total-bytes");return}x&&s.add(x),p.push({path:d,sizeBytes:h.size}),c+=h.size;return}if(!h.isDirectory())return;if(r.maxFiles!==void 0&&p.length>=r.maxFiles){a.add("max-files");return}let y=await yn.readdir(f,{withFileTypes:!0});for(let x of y)x.isSymbolicLink()||await u(`${d}/${x.name}`,p,m+1)}},getVersion(r){return t.get(r)??1},bumpVersion(r){let o=(t.get(r)??1)+1;return t.set(r,o),o}}}};function yp(e){return new Yc(e)}var Zc=class{constructor(t){this.options=t,this.listeners=new Set,this.engine=yp({projectRoot:t.projectRoot,fileSystem:t.fileSystem,compositions:t.compositions,onEvent:n=>{let r=Ms(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:Ls(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:Ds(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=_D.safeParse(r);if(!o.success)return Fs(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:Dr(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:Dr(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:Dr(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 PD(e){return new Zc(e)}import{GeneratedSiteCapabilitiesSchema as LD}from"@vcp-dev/contracts";import{GeneratedSiteCapabilitiesSchema as AD}from"@vcp-dev/contracts";function qc(e){let t=wD(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)?Wn(e.node,"platform-managed","controlled platform package"):t?OD(e.node.path,t)?Wn(e.node,"host-public","declared Starter runtime dependency"):Wn(e.node,"unsupported-external-private","external package is not declared by the trusted Starter contract"):Wn(e.node,"unknown","trusted host capability contract is invalid"):ZS(e.node.path,n)?Wn(e.node,"platform-managed","controlled platform path"):t?QS(e.node.path,t.generated_sections_path)?Wn(e.node,"private","site-generated section path"):ZS(e.node.path,t.public_paths)?Wn(e.node,"host-public","declared Starter public path"):Wn(e.node,"private","site-local file outside host public paths"):Wn(e.node,"unknown","trusted host capability contract is invalid")}function TD(e){return e.nodes.map(t=>qc({...e,node:t})).sort((t,n)=>t.path===n.path?t.ownership.localeCompare(n.ownership):t.path.localeCompare(n.path))}function Wn(e,t,n){return{path:e.path,kind:e.kind,ownership:t,reason:n}}function wD(e){let t=AD.safeParse(e);return t.success?t.data:null}function OD(e,t){return t.runtime_dependencies.some(({name:n})=>e===n||e.startsWith(`${n}/`))}function ZS(e,t){return t.some(n=>QS(e,n))}function QS(e,t){let n=FD(t),r=ev(e);return n.endsWith("/*")?r.startsWith(n.slice(0,-1)):qS(r)===qS(n)}function FD(e){return ev(e.split("#",1)[0]??e)}function ev(e){return e.replace(/^@\//u,"").replace(/\\/g,"/").replace(/^\.\//u,"")}function qS(e){return e.replace(/\.(?:jsx?|tsx?|json)$/iu,"")}function DD(e){let t=LD.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=qc({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=MD(n).sort(BD);return{complete:o.length===0,nodes:r.sort(jD),edges:[...e.closure.edges].sort($D),errors:o}}function MD(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function BD(e,t){return zt(e.path,t.path)||zt(e.code,t.code)||zt(e.specifier??"",t.specifier??"")||zt(e.message,t.message)}function jD(e,t){return zt(e.path,t.path)||zt(e.kind,t.kind)||zt(e.ownership,t.ownership)||zt(e.status,t.status)}function $D(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*as Pt from"@babel/types";var tv=[".tsx",".ts",".jsx",".js"],VD=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 hs(e){let t=XD(e.files),n=rv(e.max_depth??32,"max_depth"),r=rv(e.max_nodes??512,"max_nodes"),o=[...new Set(e.entry_files.map(sv).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 h of o)if(!(!h||l.has(h))){if(!Xo(h,c,r)){a.push({code:"SOURCE_NODE_BUDGET_EXHAUSTED",path:h,message:"Portable source closure node budget was exhausted."});continue}l.add(h),d.push({path:h,depth:0})}for(;d.length>0;){let h=d.shift();if(u.has(h.path))continue;u.add(h.path);let y=t.get(h.path);if(y===void 0){let P=o.includes(h.path)?"SOURCE_ENTRY_UNRESOLVED":zo(h.path)?"SOURCE_ASSET_UNRESOLVED":"SOURCE_FILE_UNRESOLVED";Rr(i,{path:h.path,kind:zo(h.path)?"asset":"source",depth:h.depth,status:"unresolved"}),a.push({code:P,path:h.path,message:`Portable source closure could not read ${h.path}.`});continue}let x=zo(h.path)?"asset":"source";if(x==="asset"){let P=zD(h.path,y);Rr(i,{path:h.path,kind:x,depth:h.depth,status:P?"parse-failed":"complete"}),P&&a.push(P);continue}let E=bp(y),b=Ue(h.path,E);if(!b.ok){Rr(i,{path:h.path,kind:x,depth:h.depth,status:"parse-failed"}),a.push({code:"SOURCE_PARSE_FAILED",path:h.path,message:b.diagnostic.message});continue}let S=KD(b.module.ast),N=!1;for(let P of S){let R=UD({from:h.path,depth:h.depth,reference:P,files:t,nodes:i,errors:a,maxDepth:n,maxNodes:r,visited:u,queued:l,discovered:c});s.push(R.edge),R.next&&(R.next.depth>n?N=!0:!u.has(R.next.path)&&!l.has(R.next.path)&&(l.add(R.next.path),d.push(R.next))),R.depthExhausted&&(N=!0)}Rr(i,{path:h.path,kind:x,depth:h.depth,status:N?"depth-exhausted":"complete"}),N&&a.push({code:"SOURCE_DEPTH_EXHAUSTED",path:h.path,message:`Portable source closure reached max_depth=${n} before closing all dependencies.`})}let p=[...i.values()].sort(qD),m=YD(s).sort(QD),f=ZD(a).sort(eM);return{entry_files:o.sort(On),nodes:p,edges:m,errors:f,complete:f.length===0,budget:{max_depth:n,max_nodes:r}}}function UD(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(!mt(t.specifier)){let o=WD(t.specifier);return Xo(o,e.discovered,e.maxNodes)?(Rr(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=Ep(e.from,t.specifier);if(av(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}.`}),Xo(n,e.discovered,e.maxNodes)?Rr(e.nodes,{path:n,kind:zo(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=iv(e.from,t.specifier,e.files);if(!r){let o=zo(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}.`}),Xo(n,e.discovered,e.maxNodes)?Rr(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=zo(r)?"asset":"source";return Xo(r,e.discovered,e.maxNodes)?Rr(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 Xo(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 KD(e){let t=[];for(let n of e.program.body)Pt.isImportDeclaration(n)?t.push({specifier:n.source.value,kind:n.importKind==="type"?"type":"import"}):Pt.isExportNamedDeclaration(n)&&n.source?t.push({specifier:n.source.value,kind:"export"}):Pt.isExportAllDeclaration(n)&&t.push({specifier:n.source.value,kind:"export"});return xp(e.program,n=>{if(Pt.isCallExpression(n)&&Pt.isImport(n.callee)){let r=n.arguments[0];Pt.isStringLiteral(r)?t.push({specifier:r.value,kind:"dynamic"}):t.push({specifier:null,kind:"dynamic"})}Pt.isTSImportType(n)&&t.push({specifier:Pt.isStringLiteral(n.argument)?n.argument.value:null,kind:"type"})}),GD(t)}function xp(e,t){t(e);for(let n of Object.values(e))if(Array.isArray(n))for(let r of n)ov(r)&&xp(r,t);else ov(n)&&xp(n,t)}function JD(e,t,n){let r=Ep(e,t);return!mt(t)||av(e,t,r)?null:iv(e,t,n)}function iv(e,t,n){let r=Ep(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(HD(o))return null;for(let i of tv){let s=`${o}${i}`;if(n.has(s))return s}for(let i of tv){let s=`${o}/index${i}`;if(n.has(s))return s}return null}function Ep(e,t){let n=xn(e,t);return sv(n)}function sv(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 XD(e){return e instanceof Map?e:new Map(Object.entries(e))}function bp(e){return typeof e=="string"?e:Buffer.from(e).toString("utf8")}function zD(e,t){if(e.toLowerCase().endsWith(".css")&&/[@\\]|url\s*\(/iu.test(bp(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(bp(t))}catch{return{code:"SOURCE_ASSET_INVALID",path:e,message:`Portable source closure found invalid JSON asset: ${e}.`}}return null}function Rr(e,t){let n=e.get(t.path);(!n||nv(t.status)>nv(n.status))&&e.set(t.path,t)}function Xo(e,t,n){return t.has(e)?!0:t.size>=n?!1:(t.add(e),!0)}function nv(e){return e==="complete"?1:0}function zo(e){let n=e.replace(/[?#].*$/u,"").split(".").pop()?.toLowerCase();return n!==void 0&&VD.has(n)}function HD(e){return/\.[a-z0-9]+$/iu.test(e)}function WD(e){return e.startsWith("@")?e.split("/").slice(0,2).join("/"):e.split("/")[0]??e}function GD(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 YD(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 qD(e,t){return On(e.path,t.path)||On(e.kind,t.kind)}function QD(e,t){return On(e.from,t.from)||On(e.target??"",t.target??"")||On(e.specifier??"",t.specifier??"")||On(e.kind,t.kind)}function eM(e,t){return On(e.path,t.path)||On(e.code,t.code)||On(e.specifier??"",t.specifier??"")}function On(e,t){return e<t?-1:e>t?1:0}function rv(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`Portable source closure ${t} must be a positive safe integer.`);return e}function ov(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}function av(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("/")}import{parse as sl}from"@babel/parser";import*as j from"@babel/types";import{PortableCollectionRecipeFactsSchema as SM}from"@vcp-dev/contracts";import{parse as Cr}from"@babel/parser";import Sp from"@babel/traverse";import*as K from"@babel/types";var tM=typeof Sp=="function"?Sp:Sp.default;function Cp(e){let t=gv(e.files),n=(d,p,m)=>({complete:!1,relation:null,errors:[{code:d,path:p,message:m}]}),r=Ho(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(!oM(o,r,"listStrict"))return{complete:!0,relation:null,errors:[]};let i=rM(o,r),s=i?Qc(r,o,i,"listStrict"):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.entries()].flatMap(([d,p])=>{if(typeof p!="string"||!/\[slug\]\/page\.(?:[cm]?[jt]sx?)$/u.test(d))return[];let m=Qc(d,p,i,"getByUrlStrict",e.detail_prefix??`/${i}`);return m&&_p(m.ast,e.detail_prefix??`/${i}`)!==null?[m]:[]});if(a.length!==1)return n("RELATED_COLLECTION_DETAIL_CONSUMER_UNPROVEN",e.list_entry_file,"Exactly one dynamic detail route must consume the selected collection.");let c=a[0];if(c.adapter_source!==s.adapter_source||c.interface_name!==s.interface_name)return n("RELATED_COLLECTION_ADAPTER_UNPROVEN",c.path,"The list and detail routes do not share the selected collection adapter and view interface.");let l=zn(c.source,{filePath:c.path,exportName:"default"}).components.flatMap(d=>{let p=Ho(c.path,d.source,t),m=p?t.get(p):void 0;return!p||typeof m!="string"||!dv(m,d.export_name)||!kp(m,c.adapter_source,c.interface_name)?[]:[{path:p,export_name:d.export_name}]});if(l.length!==1)return n("RELATED_COLLECTION_DETAIL_CONSUMER_UNPROVEN",c.path,"The collection detail route does not prove one private detail view.");let u=l[0];return{complete:!0,relation:{slug:i,requirement_key:`cms-${i}`,list_entry_file:e.list_entry_file,detail_entry_file:c.path,detail_view_file:u.path,detail_view_export:u.export_name},errors:[]}}function Np(e){let t=gv(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."}),vp(t,e.collection.list_entry_file,"RELATED_LIST_ENTRY_MISSING",n),vp(t,e.collection.detail_entry_file,"RELATED_DETAIL_ENTRY_MISSING",n),vp(t,e.collection.detail_view_file,"RELATED_DETAIL_VIEW_MISSING",n),Ip(o,{path:e.collection.list_entry_file,kind:"route",requirementKey:e.collection.requirement_key}),Ip(o,{path:e.collection.detail_entry_file,kind:"route",requirementKey:e.collection.requirement_key});let s=hs({entry_files:[e.collection.detail_entry_file],files:t});s.complete||n.push(...s.errors.map(p=>({code:"RELATED_DETAIL_SOURCE_INCOMPLETE",path:p.path,message:p.message})));let a=s.nodes.find(p=>p.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 p of s.nodes)if(p.kind!=="external"&&p.path!==e.collection.detail_entry_file&&p.path!==e.collection.detail_view_file){if(fM(p.path,e.collection)){Ip(o,{path:p.path,kind:p.path.includes("/page.")?"route":"adapter",requirementKey:e.collection.requirement_key});continue}pM(p.path,e.collection.detail_view_file,e.collection.slug)&&r.push({path:p.path,export:{kind:"default"},purpose:"i18n-companion"})}let c=t.get(e.collection.detail_view_file);typeof c=="string"&&uM(c,e.collection.detail_view_file,s.nodes,t,r),e.page_template&&(i=dM(e.page_template,t,n));let l=e.trusted_schema===void 0?null:nM(e,t,n,e.trusted_schema),u=hM(r).map((p,m)=>({key:xM(p,m),pathTemplate:p.path,export:p.export,purpose:p.purpose,requirementKey:e.collection.requirement_key})),d=bM(n).sort(EM);return{complete:d.length===0,entries:u.sort((p,m)=>p.pathTemplate.localeCompare(m.pathTemplate)||p.purpose.localeCompare(m.purpose)||p.key.localeCompare(m.key)),managed_requirements:o.sort(yM),thin_entry_plan:i,collection_wiring:l,errors:d}}function nM(e,t,n,r){let o=n.length,i=r.fields.map(S=>({...S}));(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(S=>S.kind==="source"&&S.status==="complete"&&S.path!==e.collection.list_entry_file).flatMap(S=>{let N=t.get(S.path);if(typeof N!="string")return[];let P=Qc(S.path,N,e.collection.slug,"listStrict");return P?[P]:[]});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?cv(a,t,S=>S!==e.collection.detail_view_file):null;c?a&&!kp(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"?Qc(e.collection.detail_entry_file,l,e.collection.slug,"getByUrlStrict"):null,d=u?cv(u,t,S=>S===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."}):kp(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 p=new Set(i.map(S=>S.name)),m=a?Ho(a.path,a.adapter_source,t):null,f=m?t.get(m):null,h=[...e.required_fields??i.filter(S=>S.required).map(S=>S.name)].sort(Rp),y=[...e.force_multi_media??(typeof f=="string"?fv(f):[])].sort(Rp);for(let S of[...h,...y])p.has(S)||n.push({code:"RELATED_COLLECTION_FIELD_UNPROVEN",path:`trusted-schema:${e.collection.slug}.${S}`,message:`Collection field ${S} is not present in the trusted schema.`});if(a&&y.length)for(let S of y)(typeof f!="string"||!lM(f,S))&&n.push({code:"RELATED_COLLECTION_FIELD_UNPROVEN",path:m??a.adapter_source,message:`The generated adapter does not prove multi-media handling for ${S}.`});let x=u?_p(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 E=u?aM(u.ast):null;E||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?cM(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},...E?{title:E}:{},...b&&b!=="unproven"?{breadcrumb:b}:{},...h.length>0?{required_fields:h}:{},...y.length>0?{force_multi_media:y}:{}}}function Qc(e,t,n,r,o=`/${n}`){let i;try{i=Cr(t,{sourceType:"module",sourceFilename:e,plugins:["jsx","typescript"]})}catch{return null}let s=io(i,l=>{if(!K.isCallExpression(l)||!el(l.callee,r))return!1;let u=l.arguments[0];return r==="listStrict"?K.isStringLiteral(u)&&u.value===n:!0});if(r==="listStrict"&&s.length!==1||r==="getByUrlStrict"&&(s.length===0||_p(i,o)===null))return null;let c=i.program.body.flatMap(l=>K.isImportDeclaration(l)?l.specifiers.flatMap(u=>{if(!K.isImportSpecifier(u))return[];let d=K.isIdentifier(u.imported)?u.imported.name:u.imported.value,p=/^to([A-Za-z_$][A-Za-z0-9_$]*View)$/u.exec(d);return p?[{source:l.source.value,local_name:u.local.name,interface_name:p[1]}]:[]}):[]).filter(l=>io(i,u=>K.isIdentifier(u,{name:l.local_name})).length>1);return c.length!==1?null:{path:e,source:t,ast:i,adapter_source:c[0].source,interface_name:c[0].interface_name}}function rM(e,t){let n;try{n=Cr(e,{sourceType:"module",sourceFilename:t,plugins:["jsx","typescript"]})}catch{return null}let r=io(n,o=>K.isCallExpression(o)&&el(o.callee,"listStrict")&&K.isStringLiteral(o.arguments[0])).map(o=>o.arguments[0].value);return r.length===1&&/^[a-z0-9]{1,30}$/u.test(r[0])?r[0]:null}function oM(e,t,n){let r;try{r=Cr(e,{sourceType:"module",sourceFilename:t,plugins:["jsx","typescript"]})}catch{return!1}return io(r,o=>K.isCallExpression(o)&&el(o.callee,n)).length>0}function cv(e,t,n){let r=zn(e.source,{filePath:e.path,exportName:"default"});if(r.diagnostics.length>0)return null;let o=r.components.flatMap(i=>{let s=Ho(e.path,i.source,t),a=s?t.get(s):null;return!s||!n(s)||typeof a!="string"||!dv(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 dv(e,t){let n;try{n=Cr(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return!1}for(let r of n.program.body){if(t==="default"&&K.isExportDefaultDeclaration(r))return!0;if(K.isExportNamedDeclaration(r)&&(r.declaration&&(K.isFunctionDeclaration(r.declaration)||K.isClassDeclaration(r.declaration)||K.isTSInterfaceDeclaration(r.declaration)||K.isTSTypeAliasDeclaration(r.declaration))&&r.declaration.id?.name===t||K.isVariableDeclaration(r.declaration)&&r.declaration.declarations.some(o=>K.isIdentifier(o.id,{name:t}))||r.specifiers.some(o=>K.isExportSpecifier(o)?(K.isIdentifier(o.exported)?o.exported.name:o.exported.value)===t:!1)))return!0}return!1}function kp(e,t,n){if(typeof e!="string")return!1;let r;try{r=Cr(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return!1}return r.program.body.flatMap(i=>!K.isImportDeclaration(i)||i.source.value!==t?[]:i.specifiers.flatMap(s=>K.isImportSpecifier(s)?(K.isIdentifier(s.imported)?s.imported.name:s.imported.value)===n?[s.local.name]:[]:[])).some(i=>io(r,s=>K.isIdentifier(s,{name:i})).length>1)}function el(e,t){return K.isMemberExpression(e)&&!e.computed&&K.isIdentifier(e.property,{name:t})&&K.isMemberExpression(e.object)&&!e.object.computed&&K.isIdentifier(e.object.property,{name:"collections"})&&K.isIdentifier(e.object.object,{name:"cms"})}function _p(e,t){let n=[];return tM(e,{CallExpression(r){el(r.node.callee,"getByUrlStrict")&&n.push(iM(r.node.arguments[0],o=>sM(r,o)))}}),n.length===0?null:n.every(r=>r===t)?t:null}function iM(e,t){return K.isBinaryExpression(e,{operator:"+"})&&K.isStringLiteral(e.left)&&K.isIdentifier(e.right)&&t(e.right.name)&&/^\/[A-Za-z0-9_-]+\/$/u.test(e.left.value)?e.left.value.slice(0,-1):K.isTemplateLiteral(e)&&e.expressions.length===1&&K.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 sM(e,t){let n=e.scope.getBinding(t);if(!n?.constant||!n.path.isVariableDeclarator())return!1;let r=n.path.node;if(K.isObjectPattern(r.id)&&K.isAwaitExpression(r.init)&&K.isIdentifier(r.init.argument))return r.id.properties.some(a=>K.isObjectProperty(a)&&!a.computed&&tl(a.key)==="slug"&&K.isIdentifier(a.value,{name:t}))&&lv(n.path,r.init.argument.name);let o=r.init;if(!K.isIdentifier(r.id,{name:t})||!K.isCallExpression(o)||!K.isIdentifier(o.callee)||o.arguments.length!==1)return!1;let i=n.path.scope.getBinding(o.callee.name);if(!i?.constant||!i.path.isImportSpecifier()||!K.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 K.isMemberExpression(s)&&!s.computed&&K.isIdentifier(s.property,{name:"slug"})&&K.isAwaitExpression(s.object)&&K.isIdentifier(s.object.argument)&&lv(n.path,s.object.argument.name)}function lv(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=>K.isObjectPattern(i)&&i.properties.some(s=>K.isObjectProperty(s)&&!s.computed&&tl(s.key)==="params"&&K.isIdentifier(s.value,{name:t})))}function aM(e){for(let t of e.program.body)if(K.isVariableDeclaration(t))for(let n of t.declarations){if(!K.isIdentifier(n.id,{name:"PAGE_SEO"}))continue;let r=pv(n.init);if(!K.isObjectExpression(r))return null;let o=r.properties.find(i=>K.isObjectProperty(i)&&!i.computed&&tl(i.key)==="title");return o&&K.isStringLiteral(o.value)?o.value.value:null}return null}function cM(e,t,n){let o=zn(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=Ho(e.path,o[0].source,t),s=i?t.get(i):null;if(typeof s!="string")return"unproven";let a;try{a=Cr(s,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return"unproven"}for(let c of io(a,l=>K.isArrayExpression(l))){let l=c.elements.flatMap(p=>{if(!K.isObjectExpression(p))return[];let m=new Map;for(let f of p.properties){if(!K.isObjectProperty(f)||f.computed)continue;let h=tl(f.key);h&&K.isStringLiteral(f.value)&&m.set(h,f.value.value)}return m.has("name")&&m.has("href")?[m]:[]}),u=l.find(p=>p.get("href")==="/"),d=l.find(p=>p.get("href")===n);if(u&&d)return{homeLabel:u.get("name"),collectionLabel:d.get("name")}}return"unproven"}function fv(e){let t;try{t=Cr(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return[]}return[...new Set(io(t,n=>{if(!K.isCallExpression(n))return!1;let r=n.callee;if(!K.isMemberExpression(r)||r.computed||!K.isIdentifier(r.property,{name:"images"}))return!1;let o=n.arguments[0];return K.isMemberExpression(o)&&!o.computed&&K.isIdentifier(o.object,{name:"d"})&&K.isIdentifier(o.property)}).flatMap(n=>{let r=n.arguments[0];return K.isMemberExpression(r)&&!r.computed&&K.isIdentifier(r.property)?[r.property.name]:[]}))].sort(Rp)}function lM(e,t){return fv(e).includes(t)}function io(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)uv(s)&&r(s);else uv(i)&&r(i)};return r(e),n}function uv(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}function pv(e){return e?K.isTSAsExpression(e)||K.isTSTypeAssertion(e)||K.isTSNonNullExpression(e)?pv(e.expression):e:null}function tl(e){return K.isIdentifier(e)?e.name:K.isStringLiteral(e)?e.value:null}function Rp(e,t){return e.localeCompare(t)}function uM(e,t,n,r,o){let i=zn(e,{filePath:t,exportName:"default"});for(let s of i.components){let a=Ho(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"||mM(l)&&o.push({path:a,export:s.export_name==="default"?{kind:"default"}:{kind:"named",name:s.export_name},purpose:"client-importer"})}}function dM(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=zn(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 vp(e,t,n,r){e.has(t)||r.push({code:n,path:t,message:`Portable related-entry analysis could not read ${t}.`})}function fM(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 pM(e,t,n){let r=e.replace(/\\/g,"/"),o=t.replace(/\.(?:tsx?|jsx?)$/u,""),i=mv(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 mM(e){try{let n=Cr(e,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0];return n?.type==="ExpressionStatement"&&n.expression.type==="StringLiteral"&&n.expression.value==="use client"}catch{return!1}}function Ho(e,t,n){let r=t.startsWith("@/")?t.slice(2):gM(`${mv(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 mv(e){let t=e.lastIndexOf("/");return t<0?"":e.slice(0,t)}function gM(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 gv(e){return e instanceof Map?e:new Map(Object.entries(e))}function hM(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 Ip(e,t){e.some(r=>r.path===t.path&&r.kind===t.kind)||e.push(t)}function yM(e,t){return e.path.localeCompare(t.path)||e.kind.localeCompare(t.kind)||e.requirementKey.localeCompare(t.requirementKey)}function xM(e,t){return`${`related.${e.purpose}.${e.path.replace(/[^A-Za-z0-9]+/gu,"-").replace(/^-|-$/gu,"")}`.slice(0,112)}.${t}`}function bM(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function EM(e,t){return e.path.localeCompare(t.path)||e.code.localeCompare(t.code)||e.message.localeCompare(t.message)}var vM=new Set(["blockId","block_id","targetBlockId","target_block_id","sourceBlockId","source_block_id"]),IM=new Set(["data-vcp-block-id","data-vcp-edit-key"]),kM=new Set(["data-vcp-order","sourceOrder","source_order"]);function Wo(e){let t=p=>({complete:!1,entry_file:e.file_path,target:e.target,call:null,bindings:[],original_block_id:null,original_order:null,semantic_props:{},errors:[...p].sort(xs)}),n;try{n=sl(e.source,{sourceType:"module",sourceFilename:e.file_path,plugins:["jsx","typescript"]})}catch(p){return t([{code:"INVOCATION_PARSE_FAILED",path:e.file_path,message:p instanceof Error?p.message:String(p)}])}let r=FM(n),o=zn(e.source,{filePath:e.file_path,exportName:e.export_name??"default"}),i=o.diagnostics.map(p=>({code:"INVOCATION_RENDER_GRAPH_INCOMPLETE",path:p.file_path||e.file_path,message:p.message})),s=new Set(o.rendered_component_openings.filter(p=>p.source===e.target.source&&p.export_name===e.target.export_name).map(p=>p.start_offset)),a=[],c=0;if(ol(n,new Set,(p,m)=>{if(!j.isJSXElement(p))return;let f=p.openingElement,h=f.start;if(typeof h!="number"||e.call_source_range&&(f.loc?.start.line!==e.call_source_range.start_line||f.loc.start.column!==e.call_source_range.start_column))return;let y=vv(f.name);if(!y)return;let x=MM(f.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(h)&&a.push({node:f,element:p,local:x,context:m,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(p=>bv(e,p.node,p.element,{kind:"import",component_source:p.local.source,export_name:p.local.export_name,local_name:p.local.local_name},p.context,p.ordinal)),u=Ev(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:Op(d).sort(xs)}}function xv(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(xs)}),n;try{n=sl(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(ol(n,new Set,(a,c)=>{if(!j.isJSXElement(a))return;let l=a.openingElement;if(typeof l.start!="number"||vv(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=>bv(e,a.node,a.element,{kind:"local",local_name:e.target.local_name},a.context,a.ordinal)),s=Ev(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:Op(s.errors).sort(xs)}: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 RM(e){let t;try{t=sl(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=un({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=zn(e.source,{filePath:e.file_path,exportName:"default"});if(i.components.length===0)return{invocation:null,errors:[]};let s=i.components.map(a=>Wo({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 CM(e){let t=Wo(e),n=Np({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 p of n.errors)r.push({code:PM(p.code),path:p.path,message:p.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=AM(e.files),s=n.collection_wiring,a=TM(e.file_path,e.target.source,i),c=a?i.get(a):null,l=a&&typeof c=="string"?NM(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 p=t.bindings.filter(m=>m.propName==="searchParams"&&m.value.kind==="route-search-params");(l.paginate&&p.length!==1||!l.paginate&&p.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 p={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(f=>({...f})),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},m=SM.safeParse(p);m.success?(u=m.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:m.error.issues[0]?.message??"Observed collection facts do not satisfy the portable recipe contract."})}let d=Op(r).sort(xs);return{...t,complete:d.length===0&&u!==null,errors:d,collection_recipe:u,collection_evidence:o.sort(OM),related_entries:n}}function NM(e,t,n){let r;try{r=sl(e,{sourceType:"module",sourceFilename:t,plugins:["jsx","typescript"]})}catch{return null}let o=_M(r);if(!o)return null;let i=Pp(o,p=>{if(!j.isCallExpression(p))return!1;let m=p.callee;return j.isMemberExpression(m)&&!m.computed&&j.isIdentifier(m.property,{name:"listStrict"})&&j.isMemberExpression(m.object)&&!m.object.computed&&j.isIdentifier(m.object.property,{name:"collections"})&&j.isIdentifier(m.object.object,{name:"cms"})&&j.isStringLiteral(p.arguments[0],{value:n})});if(i.length!==1)return null;let s=i[0].arguments[1];if(!j.isObjectExpression(s)||s.properties.some(p=>j.isSpreadElement(p)))return null;let a=s.properties.find(p=>j.isObjectProperty(p)&&!p.computed&&rl(p.key)==="pageSize");if(!a||!j.isNumericLiteral(a.value)||!Number.isSafeInteger(a.value.value)||a.value.value<=0||!s.properties.some(p=>j.isObjectProperty(p)&&!p.computed&&rl(p.key)==="page"))return null;let l=s.properties.some(p=>j.isObjectProperty(p)&&!p.computed&&rl(p.key)==="category"),u=Pp(o,p=>j.isAwaitExpression(p)&&j.isIdentifier(p.argument,{name:"searchParams"})).length;if(u>1)return null;let d=Pp(o,p=>{if(!j.isCallExpression(p))return!1;let m=p.callee;return j.isMemberExpression(m)&&!m.computed&&j.isIdentifier(m.property,{name:"categories"})&&j.isMemberExpression(m.object)&&!m.object.computed&&j.isIdentifier(m.object.property,{name:"collections"})&&j.isIdentifier(m.object.object,{name:"cms"})&&j.isStringLiteral(p.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 _M(e){let t=e.program.body.find(n=>j.isExportDefaultDeclaration(n));return j.isExportDefaultDeclaration(t)&&(j.isFunctionDeclaration(t.declaration)||j.isFunctionExpression(t.declaration)||j.isArrowFunctionExpression(t.declaration))?t.declaration:null}function Pp(e,t){let n=[],r=o=>{if(!(o!==e&&wp(o))){t(o)&&n.push(o);for(let i of Object.values(o))if(Array.isArray(i))for(let s of i)il(s)&&r(s);else il(i)&&r(i)}};return r(e),n}function PM(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 AM(e){return e instanceof Map?e:new Map(Object.entries(e))}function TM(e,t,n){let r=e.includes("/")?e.slice(0,e.lastIndexOf("/")):"",o=t.startsWith("@/")?t.slice(2):wM(`${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 wM(e){let t=[];for(let n of e.split("/"))!n||n==="."||(n===".."?t.pop():t.push(n));return t.join("/")}function OM(e,t){return e.fact.localeCompare(t.fact)||e.path.localeCompare(t.path)}function FM(e){let t=new Map;for(let n of e.program.body){if(!j.isImportDeclaration(n))continue;let r=n.source.value;for(let o of n.specifiers)if(j.isIdentifier(o.local)){if(j.isImportDefaultSpecifier(o))t.set(o.local.name,{source:r,export_name:"default",local_name:o.local.name});else if(j.isImportNamespaceSpecifier(o))t.set(o.local.name,{source:r,export_name:"*",local_name:o.local.name});else if(j.isImportSpecifier(o)){let i=j.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 bv(e,t,n,r,o,i){let s=jM(t),a=[],c=[],l={},u=new Set,d=null,p=null,m=(h,y)=>{if(u.has(h)){a.push({code:"INVOCATION_DUPLICATE_PROP",path:`${e.file_path}:${h}`,message:`Portable invocation contains duplicate prop ${h}.`,source_range:s});return}u.add(h),c.push({propName:h,value:y}),(h==="type"||h==="variant")&&y.kind==="json-literal"&&(l[h]=y.value)};for(let h of t.attributes){if(j.isJSXSpreadAttribute(h)){let S=Nr(h.argument);if(!S.ok||!Sv(S.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[N,P]of Object.entries(S.value)){if(!yv(N)){a.push({code:"INVOCATION_VALUE_UNRESOLVED",path:`${e.file_path}:${N}`,message:`Portable invocation cannot encode prop ${N}.`,source_range:s});continue}m(N,Ap(P))}continue}let y=BM(h.name);if(!y)continue;let x=h.value,E=x&&j.isJSXExpressionContainer(x)?x.expression:null;if(IM.has(y)){let S=x?nl(x):{ok:!0,value:!0};!S.ok||typeof S.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=S.value;continue}if(kM.has(y)){let S=x?nl(x):{ok:!0,value:!0};!S.ok||typeof S.value!="number"||!Number.isSafeInteger(S.value)?a.push({code:"INVOCATION_ORDER_UNRESOLVED",path:`${e.file_path}:${y}`,message:"Portable invocation requires a literal original order.",source_range:s}):p=S.value;continue}if(!yv(y)){a.push({code:"INVOCATION_VALUE_UNRESOLVED",path:`${e.file_path}:${y}`,message:`Portable invocation cannot encode prop ${y}.`,source_range:s});continue}if(vM.has(y)){let S=x?nl(x):{ok:!0,value:!0};S.ok&&typeof S.value=="string"?d=S.value:E&&hv(E,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}),m(y,{kind:"target-block-id"});continue}if(E&&hv(E,o)){m(y,{kind:"route-search-params"});continue}let b=x?nl(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}m(y,Ap(b.value))}let f=LM(n);return f.ok?f.value!==void 0&&m("children",Ap(f.value)):a.push({code:"INVOCATION_CHILDREN_UNRESOLVED",path:`${e.file_path}:children`,message:f.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:p,semantic_props:l,errors:a}}function Ev(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 nl(e){return e===null?{ok:!0,value:!0}:j.isStringLiteral(e)?{ok:!0,value:e.value}:j.isJSXExpressionContainer(e)?Nr(e.expression):{ok:!1}}function Nr(e){if(!e)return{ok:!1};if(j.isStringLiteral(e))return{ok:!0,value:e.value};if(j.isNumericLiteral(e)&&Number.isFinite(e.value))return{ok:!0,value:e.value};if(j.isBooleanLiteral(e))return{ok:!0,value:e.value};if(j.isNullLiteral(e))return{ok:!0,value:null};if(j.isTemplateLiteral(e)&&e.expressions.length===0)return{ok:!0,value:e.quasis[0]?.value.cooked??""};if(j.isTSAsExpression(e)||j.isTSTypeAssertion(e)||j.isTSNonNullExpression(e))return Nr(e.expression);if(j.isUnaryExpression(e)){let t=Nr(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(j.isArrayExpression(e)){let t=[];for(let n of e.elements){let r=Nr(n);if(!r.ok)return{ok:!1};t.push(r.value)}return{ok:!0,value:t}}if(j.isObjectExpression(e)){let t={};for(let n of e.properties){if(j.isSpreadElement(n)){let i=Nr(n.argument);if(!i.ok||!Sv(i.value))return{ok:!1};Object.assign(t,i.value);continue}if(!j.isObjectProperty(n)||n.computed)return{ok:!1};let r=rl(n.key);if(!r)return{ok:!1};let o=Nr(n.value);if(!o.ok)return{ok:!1};t[r]=o.value}return{ok:!0,value:t}}return{ok:!1}}function LM(e){if(e.children.length===0)return{ok:!0,value:void 0};let t=[];for(let n of j.react.buildChildren(e)){let r=Nr(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 ol(e,t,n){let r=wp(e)?new Set([...t,...DM(e)]):t;n(e,{names:r});for(let o of Object.values(e))if(Array.isArray(o))for(let i of o)il(i)&&ol(i,r,n);else il(o)&&ol(o,r,n)}function DM(e){if(!wp(e))return[];let t=[];for(let n of e.params)ys(n,t);return t}function ys(e,t){if(j.isIdentifier(e)){t.push(e.name);return}if(j.isAssignmentPattern(e)){ys(e.left,t);return}if(j.isObjectPattern(e)){for(let n of e.properties)j.isRestElement(n)?ys(n.argument,t):j.isObjectProperty(n)&&ys(n.value,t);return}if(j.isArrayPattern(e))for(let n of e.elements)n&&ys(n,t)}function hv(e,t){return j.isIdentifier(e)?e.name==="searchParams"&&t.names.has(e.name):j.isMemberExpression(e)&&!e.computed&&j.isIdentifier(e.property)&&e.property.name==="searchParams"&&j.isIdentifier(e.object)&&t.names.has(e.object.name)}function Ap(e){return{kind:"json-literal",value:e}}function Sv(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function yv(e){return/^[A-Za-z][A-Za-z0-9_]{0,127}$/u.test(e)}function vv(e){if(j.isJSXIdentifier(e))return e.name;if(!j.isJSXMemberExpression(e))return null;let t=Tp(e.object);return t?`${t}.${e.property.name}`:null}function Tp(e){if(j.isJSXIdentifier(e))return e.name;if(!j.isJSXMemberExpression(e))return null;let t=Tp(e.object);return t?`${t}.${e.property.name}`:null}function MM(e,t){if(j.isJSXIdentifier(e))return t.get(e.name)??null;if(!j.isJSXMemberExpression(e))return null;let n=Tp(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 BM(e){return j.isJSXIdentifier(e)?e.name:j.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function rl(e){return j.isIdentifier(e)?e.name:j.isStringLiteral(e)||j.isNumericLiteral(e)?String(e.value):null}function wp(e){return j.isFunctionDeclaration(e)||j.isFunctionExpression(e)||j.isArrowFunctionExpression(e)}function il(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}function jM(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 Op(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function xs(e,t){return e.path.localeCompare(t.path)||e.code.localeCompare(t.code)||e.message.localeCompare(t.message)}import Fp from"@babel/generator";import{parse as $M}from"@babel/parser";import VM from"@babel/traverse";import*as lt from"@babel/types";var Lp=VM,UM=typeof Lp=="function"?Lp:Lp.default,KM=typeof Fp=="function"?Fp:Fp.default,_v="components/site/generated/{{$INSTANCE}}/",Pv=new Set([".tsx",".ts",".jsx",".js"]),Iv=new Set(["data-site-block-id","data-vcp-block-id","data-vcp-edit-key"]),JM=new Set(["data-site-block-order","data-vcp-order"]);function XM(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 S=Gn(b.path);if(!S||n.has(S)){t.push({code:"SOURCE_INPUT_INVALID",path:b.path,message:"Portable source files must have unique safe paths."});continue}n.set(S,{...b,path:S})}for(let b of e.ownership){let S=Gn(b.path);if(!S||r.has(S)){t.push({code:"SOURCE_INPUT_INVALID",path:b.path,message:"Portable source ownership entries must be unique and safe."});continue}r.set(S,{...b,path:S})}let o=Gn(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,S)=>b.localeCompare(S)),a=s.map(b=>({source_path:b,path_template:QM(b)})),c=new Map(a.map(b=>[b.source_path,b.path_template])),l=zM(e.source_mapping??[],c,t),u=HM(e.required_source_paths??[],c,t),d=[],p=new Map,m=[];for(let b of s){let S=n.get(b);if(!S)continue;let N=GM(b,S.content,r,c,d,p,t);N!==null&&m.push({path_template:c.get(b),content:N,...S.role?{role:S.role}:{}})}let f=Cv(t).sort(Nv);if(f.length>0)return{complete:!1,entry_path_template:null,files:[],source_path_mappings:[],required_path_mappings:[],source_mapping:[],managed_rebindings:[],block_metadata:[],errors:f};let h=m.map(b=>{let S=a.find(P=>P.path_template===b.path_template)?.source_path,N=n.get(S)?.content??"";return{source_path:S,path_template:b.path_template,original_byte_size:kv(N),output_byte_size:kv(b.content),original_line_count:Rv(N),output_line_count:Rv(b.content)}}),y=[...p.values()].map(b=>({...b,normalized:!0})).sort((b,S)=>b.source_path.localeCompare(S.source_path)),x=c.get(o)??null;if(e.thin_entry_plan){let b=WM(e.thin_entry_plan,c,t);b&&(m.push(b),x=b.path_template)}let E=Cv(t).sort(Nv);return E.length>0?{complete:!1,entry_path_template:null,files:[],source_path_mappings:[],required_path_mappings:[],source_mapping:[],managed_rebindings:[],block_metadata:[],errors:E}:{complete:!0,entry_path_template:x,files:m.sort((b,S)=>b.path_template.localeCompare(S.path_template)),source_path_mappings:h.sort((b,S)=>b.path_template.localeCompare(S.path_template)),required_path_mappings:u,source_mapping:l,managed_rebindings:d.sort(oB),block_metadata:y,errors:[]}}function zM(e,t,n){let r=new Set,o=[];for(let[i,s]of e.entries()){let a=Gn(s.generated_path),c=Gn(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 HM(e,t,n){let r=new Set,o=new Set,i=[];for(let[s,a]of e.entries()){let c=Gn(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 WM(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(Gn(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=Av(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}
|
|
1
|
+
import*as NI from"@babel/parser";import*as vt from"@babel/types";import*as qn from"node:path";var _l=[".tsx",".ts",".jsx",".js"],PI=_l.map(e=>`/index${e}`),_I=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 km(e){let t=e.replace(/[?#].*$/,""),n=/\.([a-z0-9]+)$/i.exec(t);return n!==null&&_I.has(n[1].toLowerCase())}function Rm(e){let t=[];for(let n of e.program.body)vt.isImportDeclaration(n)&&typeof n.source.value=="string"&>(n.source.value)&&t.push(n.source.value),vt.isExportNamedDeclaration(n)&&n.source&&typeof n.source.value=="string"&>(n.source.value)&&t.push(n.source.value),vt.isExportAllDeclaration(n)&&typeof n.source.value=="string"&>(n.source.value)&&t.push(n.source.value);return vt.traverseFast(e.program,n=>{let r=vt.isImportExpression(n)?n.source:vt.isCallExpression(n)&&vt.isImport(n.callee)?n.arguments[0]:null;vt.isStringLiteral(r)&>(r.value)&&t.push(r.value)}),t}function gt(e){return e.startsWith("./")||e.startsWith("../")||e.startsWith("@/")}function En(e,t){if(t.startsWith("@/"))return t.slice(2).replace(/\\/g,"/");let n=qn.dirname(e);return qn.join(n,t).replace(/\\/g,"/")}async function AI(e,t){for(let n of Cm(e))if(await t(n))return n;return null}function Cm(e){return[..._l.some(t=>e.endsWith(t))?[e]:[],..._l.map(t=>`${e}${t}`),...PI.map(t=>`${e}${t}`)]}function Qn(e,t,n){let r=En(e,t);if(!gt(t)||!Nm(e,t,r))return null;for(let o of Cm(r))if(n.has(o))return o;return null}async function Tr(e,t,n){let r=await Ps(e,t,n);return r.ok?r.path:null}async function Ps(e,t,n){let r=En(e,t);try{if(!Nm(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 AI(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 Nm(e,t,n){if(!gt(t)||t.includes("\0")||t.includes("\\")||qn.posix.isAbsolute(n))return!1;let r=qn.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!qn.posix.isAbsolute(e)}import{createHash as wI}from"node:crypto";import*as Pm from"@babel/parser";function wr(e,t,n,r){return{code:e,message:t,locatorKind:n,details:r}}function Q(e,t,n,r,o){return{ok:!1,source:e,diagnostic:wr(t,n,r,o)}}function Al(e,t,n,r,o){return{ok:!1,source:e,diagnostic:wr(t,n,r,o)}}var TI={"tsx-module":["jsx","typescript"],"ts-module":["typescript"],"next-app-entry":["jsx","typescript"]};function Sn(e){let{source:t,profile:n}=e;try{return{ok:!0,ast:Pm.parse(t,{sourceType:"module",plugins:TI[n]})}}catch(r){return{ok:!1,source:t,diagnostic:wr("parse-failed",`AST parse failed: ${r instanceof Error?r.message:String(r)}`)}}}function Tl(e,t){return Sn({source:e,profile:_m(t.kind)})}function ti(e,t){return Sn({source:e,profile:_m(t)})}function _m(e){return"next-app-entry"}function Or(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 Ue=(e,t)=>{let n=Sn({source:t,profile:Or({filePath:e,source:t})});return n.ok?{ok:!0,module:{file:e,source:t,sourceHash:`sha256:${wI("sha256").update(t).digest("hex")}`,ast:n.ast,imports:Rm(n.ast).map(r=>({specifier:r}))}}:{ok:!1,diagnostic:{path:e,code:"parse-failed",message:n.diagnostic.message}}};function OI(e,t){return Ue(e,t)}function FI(e,t){return En(e,t)}import{COMPONENT_I18N_FILE_SUFFIX as LI,parseComponentI18nResourcesJson as DI,resolveSiteTextDirection as MI,SiteLocaleSchema as BI}from"@vcp-dev/contracts";var jI=["i18next","react-i18next"],$I="components/ui/site-locale-provider.tsx",VI="components/ui/component-i18n-provider.tsx",Am="app/layout.tsx";async function ni(e){let t=e.files.filter(f=>f.path.endsWith(LI));if(t.length===0)return{ok:!0};for(let f of["package.json",Am,$I,VI])if(!await e.exists(f))return er(`Target snapshot is missing required i18n host file: ${f}`);let n;try{n=JSON.parse(await e.readFile("package.json"))}catch{return er("Target snapshot package.json is invalid.")}let r=Tm(n)&&Tm(n.dependencies)?n.dependencies:{},o=jI.filter(f=>typeof r[f]!="string"||r[f].trim().length===0);if(o.length>0)return er(`Target snapshot must already declare: ${o.join(", ")}.`);let i=await e.readFile(Am),s=wl(i,"html","lang"),a=wl(i,"html","dir"),c=wl(i,"SiteLocaleProvider","locale"),l=BI.safeParse(s);if(!l.success||!a||!c||s!==c||a!==MI(l.data))return er("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 er("Target snapshot root layout is not wired to SiteLocaleProvider.");let u=l.data;if(e.targetLocale&&e.targetLocale!==u)return er("Target snapshot locale does not match the authoritative site language.");let d=u.split("-")[0];for(let f of t){let g=DI(f.content);if(!g.success)return er(`Component i18n resource is invalid: ${f.path}.`);if(!e.deferTargetLocale&&!Object.hasOwn(g.data,u)&&!Object.hasOwn(g.data,d))return er(`Component i18n resource ${f.path} has no locale for ${u} or ${d}.`)}return{ok:!0}}function wl(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 Tm(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function er(e){return{ok:!1,message:e}}import Fl from"@babel/generator";import*as Mm from"@babel/parser";import Ll from"@babel/traverse";import*as Ke from"@babel/types";import{computeSiteEditSourceIdentityKey as KI}from"@vcp-dev/contracts";var wm="data-vcp-ui-component",_s="components/ui";function Mn(e){if(!e)return!1;let t=Ol(e);return t===_s||t.startsWith(`${_s}/`)||t.includes(`/${_s}/`)||t.endsWith(`/${_s}`)}function Fr(e,t){return e?e.startsWith("@/")||e.startsWith("~/")?Mn(e.slice(2)):e.startsWith("./")||e.startsWith("../")?Mn(Ol(`${UI(t)}/${e}`)):Mn(e):!1}function Ol(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 UI(e){let t=Ol(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}import{stripSiteEditRepeatInstanceKeys as a0}from"@vcp-dev/contracts";import{isSiteEditRuntimeContainerTag as l0,isSiteEditRuntimeTextTag as u0}from"@vcp-dev/contracts/site-edit-runtime-capability";var Om={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 JI=typeof Fl=="function"?Fl:Fl.default,XI=typeof Ll=="function"?Ll:Ll.default,zI=new Set(["base","body","head","html","link","meta","noscript","script","style","template","title"]),HI="suppressHydrationWarning",WI=new Set(["SiteEditBootstrap"]);function GI(e){let t=qI(e.file,e.projectRoot);if(!ZI(e.source)||Mn(t))return{code:e.source,elements:[]};let n=e.attributes??Om,r=Mm.parse(e.source,{sourceType:"module",plugins:["jsx","typescript"]}),o=[],i=ek(r,t);return XI(r,{JSXElement(s){let a=s.node.openingElement,c=a.name;if(!nk(c)||Bm(a,n.key))return;let l=ok(s)??"default",u=sk(s),d=KI(t,l,u),f=Ts(c)??"unknown",g=QI(c)?"jsx":"component-call";if(g==="component-call"&&!ik(s.node.children)&&WI.has(f))return;let p=g==="component-call"&&tk(f,i);rk(a,n.key,d),p&&Fm(a,wm),YI(s)&&Fm(a,HI),o.push({key:d,tag:f,componentName:l,sourceFile:t,sourceKind:g})}}),o.length===0?{code:e.source,elements:o}:{code:JI(r,{jsescOption:{minimal:!0}}).code,elements:o}}function YI(e){return!e.findParent(t=>t.isJSXElement())}function ZI(e){return/(?:^|[=(:,?;\[{>&|\n\r]|return\s+)\s*<(?:[A-Za-z][\w.:-]*|>)(?:\s|>|\/)/m.test(e)}function qI(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 QI(e){return Ke.isJSXIdentifier(e)&&/^[a-z]/.test(e.name)}function Ts(e){return Ke.isJSXIdentifier(e)?e.name:Ke.isJSXMemberExpression(e)?$m(e):null}function ek(e,t){let n=new Set;for(let r of e.program.body)if(!(!Ke.isImportDeclaration(r)||!Fr(r.source.value,t)))for(let o of r.specifiers)n.add(o.local.name);return n}function tk(e,t){let n=e.split(".")[0]??e;return t.has(n)}function nk(e){let t=Ts(e);return!t||t==="Fragment"||t.endsWith(".Fragment")?!1:!zI.has(t)}function Bm(e,t){return e.attributes.some(n=>Ke.isJSXAttribute(n)&&Ke.isJSXIdentifier(n.name,{name:t}))}function rk(e,t,n){jm(e,Ke.jsxAttribute(Ke.jsxIdentifier(t),Ke.stringLiteral(n)))}function Fm(e,t){Bm(e,t)||jm(e,Ke.jsxAttribute(Ke.jsxIdentifier(t),null))}function jm(e,t){let n=e.attributes.findIndex(r=>Ke.isJSXSpreadAttribute(r));if(n>=0){e.attributes.splice(n,0,t);return}e.attributes.push(t)}function $m(e){return`${Ke.isJSXIdentifier(e.object)?e.object.name:$m(e.object)}.${e.property.name}`}function ok(e){let t=e;for(;t;){if(t.isFunctionDeclaration()||t.isClassDeclaration())return t.node.id?.name??null;if(t.isVariableDeclarator()&&Ke.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 ik(e){return e.some(t=>Ke.isJSXElement(t)||Ke.isJSXFragment(t))}var Lm=new WeakMap,As=new WeakMap,Dl=new WeakMap;function sk(e){let t=Lm.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=ak(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return Lm.set(e.node,o),o}function ak(e){let t=Ts(e.node.openingElement.name);return!t||t==="Fragment"||t.endsWith(".Fragment")?null:/^[A-Z]/.test(t)?`component:${t}#${Dm(e,t)}`:`${t}#${Dm(e,t)}`}function Dm(e,t){let n=Vm(e)??e.getFunctionParent();if(!n)return 0;let r=Dl.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=Dl.get(n.node);o||(o=new Map,Dl.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()?ws(n):ck(n);for(let c of a)if(Ts(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 ck(e){let t=As.get(e.node);if(t)return t;let n=[];return e.traverse({JSXElement(r){r.getFunctionParent()?.node===e.node&&!Vm(r)&&n.push(r)}}),As.set(e.node,n),n}function Vm(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 ws(e){let t=As.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(...ws(o));continue}o.isJSXExpressionContainer()&&n.push(...Lr(o.get("expression")))}return As.set(e.node,n),n}function Lr(e){if(e.isJSXElement())return[e];if(e.isJSXFragment())return ws(e);if(e.isParenthesizedExpression())return Lr(e.get("expression"));if(e.isLogicalExpression()&&e.node.operator==="&&")return Lr(e.get("right"));if(e.isConditionalExpression())return[...Lr(e.get("consequent")),...Lr(e.get("alternate"))];if(e.isCallExpression()&&uk(e.node)){let t=e.get("arguments")[0];return lk(t)}return[]}function lk(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return[t];if(t.isJSXFragment())return ws(t);if(t.isParenthesizedExpression())return Lr(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?Lr(r):[]}return[]}function uk(e){return Ke.isMemberExpression(e.callee)&&Ke.isIdentifier(e.callee.property)&&e.callee.property.name==="map"}import{SiteEditOperationRequestSchema as ND,SiteEditPatchPlanSchema as PD}from"@vcp-dev/contracts";function Dr(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 Os(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 Fs(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 Ls(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:dk(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 Ds(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:Dr(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 dk(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 BL,computeSiteEditCompositionKey as jL,getSiteEditSourceDeleteProtectionReason as $L,isSiteEditTextSourcePath as VL,parseSiteEditRepeatInstanceKey as UL,SITE_EDIT_SOURCE_DELETE_CAPABILITY as KL,stripSiteEditRepeatInstanceKeys as Lt}from"@vcp-dev/contracts";import zc from"node:path";import{parse as JL}from"yaml";import Vl from"node:path";import{TextDecoder as pk}from"node:util";import{SITE_EDIT_SOURCE_ALLOWED_APP_FILES as Km,SITE_EDIT_SOURCE_ALLOWED_DIRS as Jm,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as Xm,SiteEditCompositionContextSchema as mk,SiteEditSourceFileResponseSchema as Ml,SiteEditSourceLocationSchema as gk,SiteEditSourcePathSchema as Ms,SiteEditSourceTreeResponseSchema as hk,isSiteEditTextSourcePath as yk}from"@vcp-dev/contracts";import{createHash as fk}from"node:crypto";var ri=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 ve(e){return`sha256:${fk("sha256").update(e).digest("hex")}`}var xk=[...Xm,...Km,...Jm];function Ul(e){if(!e.composition)throw new Error("Composition unavailable for source access policy.");return mk.parse(e.composition)}var Bl=2e3,jl=12,$l=24*1024*1024,Um=512*1024,bk=new Set(["image/avif","image/gif","image/jpeg","image/png","image/webp","image/x-icon"]),Ek={".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"},Sk={".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"},vk=new pk("utf-8",{fatal:!0});async function Bs(e,t={}){let n=Ul(t),{files:r,truncated:o}=await _k(e,t),i=wk(r.map(s=>s.metadata));return hk.parse({composition:n,nodes:i,defaultPath:Ok(r.map(s=>s.metadata)),totalFiles:r.length,...o?{truncated:o}:{}})}async function js(e,t,n={}){let r=Ul(n),o=Ms.parse(t.path),i=await kk(e,o,n);if(!i)throw new Error(`Source file not found: ${o}`);if(Jl(o)){let a=Wm(o),c=await Ck(e,{path:o,sizeBytes:i.sizeBytes,mimeType:a});return Ml.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:i.sizeBytes,mimeType:a,readonly:!0,...c})}let s=await Kl(e,o);return s.ok?Ml.parse({composition:r,path:o,kind:"text",language:Gm(o),sizeBytes:s.sizeBytes,contentHash:ve(s.content),readonly:!1,content:s.content}):Ml.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:s.sizeBytes,mimeType:"application/octet-stream",readonly:!0,previewUnavailableReason:"unsupported-mime"})}async function Kl(e,t){if(e.readFileBytes){let o=await e.readFileBytes(t),i=Ik(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 Ik(e){if(e.includes(0))return null;try{return vk.decode(e)}catch{return null}}async function kk(e,t,n){if(!Nk(t,n))return null;let r=await Rk(e,t);return r?{path:t,sizeBytes:r.sizeBytes}:null}async function Rk(e,t){if(e.getFileInfo)return e.getFileInfo(t);if(e.listFiles){let o=zm(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(Jl(t))return{path:t,sizeBytes:0};let n=await e.readFile(t);return{path:t,sizeBytes:Buffer.byteLength(n,"utf8")}}async function Ck(e,t){if(!bk.has(t.mimeType))return{previewUnavailableReason:"unsupported-mime"};if(t.sizeBytes>Um)return{previewUnavailableReason:"too-large"};if(!e.readFileBytes)return{previewUnavailableReason:"bytes-unavailable"};let n=await e.readFileBytes(t.path);return n.byteLength>Um?{previewUnavailableReason:"too-large"}:{contentBase64:Buffer.from(n).toString("base64")}}function Nk(e,t){return Xm.some(n=>n===e)||Km.some(n=>n===e)||Jm.some(n=>e===n||e.startsWith(`${n}/`))?!0:!e.startsWith("app/")&&!e.startsWith("src/app/")?!1:(t.routeEntryFiles??[]).some(n=>{let r=Ms.safeParse(n);return r.success&&r.data===e})}function $s(e,t){if(!t.sourceLocator)throw new Error(`Source location not available for key: ${e.key}`);return gk.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 zm(e){return Array.isArray(e)?{files:e}:e}function Pk(e){return["max-files","max-depth","max-total-bytes"].filter(n=>e.includes(n))}async function _k(e,t){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let n=zm(await e.listFiles({roots:Ak(t),maxFiles:Bl+1,maxDepth:jl,maxTotalBytes:$l+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=Ms.safeParse(a.path);if(!c.success)continue;let l=c.data;if(l.split("/").length>jl){o.add("max-depth");continue}if(r.size>=Bl){o.add("max-files");break}if(i+a.sizeBytes>$l){o.add("max-total-bytes");break}r.set(l,{path:l,sizeBytes:a.sizeBytes,metadata:Tk(l,a.sizeBytes,Ul(t))}),i+=a.sizeBytes}return{files:[...r.values()].sort((a,c)=>a.path.localeCompare(c.path)),...o.size>0?{truncated:{reasons:Pk([...o]),maxFiles:Bl,maxDepth:jl,maxTotalBytes:$l}}:{}}}function Ak(e){let t=new Set(xk);for(let n of e.routeEntryFiles??[]){let r=Ms.safeParse(n);r.success&&(r.data.startsWith("app/")||r.data.startsWith("src/app/"))&&t.add(r.data)}return[...t]}function Tk(e,t,n){return Jl(e)?{composition:n,path:e,kind:"binary",language:null,sizeBytes:t,mimeType:Wm(e),readonly:!0}:{composition:n,path:e,kind:"text",language:Gm(e),sizeBytes:t,readonly:!1}}function wk(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 Hm(t)}function Hm(e){return e.map(t=>t.kind==="directory"?{...t,children:Hm(t.children)}:t).sort((t,n)=>t.kind!==n.kind?t.kind==="directory"?-1:1:t.name.localeCompare(n.name))}function Ok(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 Jl(e){return!yk(e)}function Wm(e){let t=Vl.posix.extname(e).toLowerCase();return!t&&Vl.posix.basename(e).toLowerCase()==="favicon"?"image/x-icon":Ek[t]??"application/octet-stream"}function Gm(e){let t=Vl.posix.extname(e).toLowerCase();return Sk[t]??"plaintext"}import*as Br from"@babel/types";import Xl from"@babel/traverse";import*as vn from"@babel/types";function ze(e){if(e.isJSXFragment())return!0;if(!e.isJSXElement())return!1;let t=e.node.openingElement.name;if(vn.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(vn.isIdentifier(s)&&s.name==="Fragment"||vn.isStringLiteral(s)&&s.value==="Fragment")&&Ym(i.parentPath)}if(!vn.isJSXMemberExpression(t)||!vn.isJSXIdentifier(t.property)||t.property.name!=="Fragment"||!vn.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())&&Ym(r.parentPath)}function Ym(e){return e?.isImportDeclaration()===!0&&e.node.source.value==="react"}var tr=typeof Xl=="function"?Xl:Xl.default,Vs=new WeakMap,Us=new WeakMap;function In(e,t){let n=Tl(e,t);if(!n.ok)return Al(e,n.diagnostic.code,n.diagnostic.message,t.kind);let r=Ee(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}}:Al(e,r.diagnostic.code,r.diagnostic.message,t.kind,r.diagnostic.details)}function Ee(e,t){return t.kind==="jsx-node"?eg(e,t):t.kind==="jsx-attribute"?jk(e,t):t.kind==="value"?$k(e,t):t.kind==="expression"?Vk(e,t):t.kind==="directive"?Uk(e,t):t.kind==="export"?Kk(e,t):{ok:!1,diagnostic:wr("unsupported-syntax",`Unsupported locator kind: ${t.kind}`)}}function eg(e,t){return t.strategy==="source-range"?Fk(e,t):Lk(e,t)}function Fk(e,t){let n=null;if(tr(e,{JSXElement(o){if(!Mr(o.node,t.sourceRange))return;let i=Qe("jsx-node",o);if(i){if(!n){n=i;return}i.end-i.start<n.end-n.start&&(n=i)}},JSXFragment(o){if(!Mr(o.node,t.sourceRange))return;let i=Qe("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXExpressionContainer(o){if(!Mr(o.node,t.sourceRange))return;let i=Qe("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXText(o){if(!Mr(o.node,t.sourceRange))return;let i=Qe("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)}}),!n)return ot("jsx-node","locator-miss","JSX node not found for source-range locator");let r=n;return t.expectedIdentity&&!tR(r.path,t.expectedIdentity)?ot("jsx-node","locator-miss","JSX node failed expected identity validation"):{ok:!0,match:r}}function Lk(e,t){if(t.structuralPath===""){let r=Mk(e,t.component);if(r){let o=Bk(r);if(o)return o}}let n=null;return tr(e,{JSXElement(r){if(ii(r)!==t.component||Hl(r)!==t.structuralPath)return;let i=Qe("jsx-node",r);i&&(n=i,r.stop())},JSXFragment(r){if(ii(r)!==t.component||Hl(r)!==t.structuralPath)return;let i=Qe("jsx-node",r);i&&(n=i,r.stop())}}),!n&&t.expectedRange&&(n=Dk(e,t.component,t.expectedRange)),n?{ok:!0,match:n}:ot("jsx-node","locator-miss","JSX node not found for structural-path locator")}function Dk(e,t,n){let r=null;return tr(e,{JSXElement(o){if(ii(o)!==t||!Mr(o.node,n))return;let i=Qe("jsx-node",o);i&&(r=i,o.stop())},JSXFragment(o){if(ii(o)!==t||!Mr(o.node,n))return;let i=Qe("jsx-node",o);i&&(r=i,o.stop())}}),r}function Mk(e,t){let n=null;return tr(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 Bk(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 ot("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}return null}return(t.isParenthesizedExpression()?t.get("expression"):t).isJSXFragment()?ot("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 ot("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}}}return null}function jk(e,t){let n=eg(e,t.element);if(!n.ok)return n;let s=n.match.path.get("openingElement").get("attributes").find(c=>nR(c,t.name));if(!s||!s.isJSXAttribute())return ot("jsx-attribute","locator-miss",`JSX attribute '${t.name}' not found`);let a=Qe("jsx-attribute",s);return a?{ok:!0,match:a}:ot("jsx-attribute","locator-miss",`JSX attribute '${t.name}' has no source range`)}function $k(e,t){let n=Jk(e,t);if(!n.ok)return n;let r=Xk(n.match.path,t.path??[]);return r.ok?t.expectedRange&&!jn(r.match.path.node.loc,t.expectedRange)?ot("value","locator-miss","Resolved value does not match expected range"):{ok:!0,match:r.match}:r}function Vk(e,t){let n=null;return tr(e,{Identifier(r){if(!Zk(r))return;let o=qm(r);if(!o||!Qm(o,t))return;let i=Qe("expression",r);i&&(t.expectedRange&&!jn(r.node.loc,t.expectedRange)||(n=i,r.stop()))},MemberExpression(r){let o=qm(r);if(!o||!Qm(o,t))return;let i=Qe("expression",r);i&&(t.expectedRange&&!jn(r.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:ot("expression","locator-miss","Expression not found")}function Uk(e,t){let n=null;return tr(e,{Program(r){let i=r.get("directives").find(a=>a.node.value.value===t.value);if(!i||t.expectedRange&&!jn(i.node.loc,t.expectedRange))return;let s=Qe("directive",i);s&&(n=s,r.stop())}}),n?{ok:!0,match:n}:ot("directive","locator-miss",`Directive '${t.value}' not found`)}function Kk(e,t){let n=null;return tr(e,{ExportNamedDeclaration(r){if(t.exportKind==="generate-metadata"){let c=r.get("declaration");if(c.isFunctionDeclaration()&&c.node.id?.name==="generateMetadata"){let f=Qe("export",c);if(!f||t.expectedRange&&!jn(c.node.loc,t.expectedRange))return;n=f,r.stop();return}if(!c.isVariableDeclaration())return;let l=Wl(c,"generateMetadata");if(!l||!l.isVariableDeclarator())return;let u=l.get("init");if(!u.node)return;let d=Qe("export",u);if(!d||t.expectedRange&&!jn(u.node.loc,t.expectedRange))return;n=d,r.stop();return}let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=Wl(o,t.exportKind==="named"?t.name:"metadata");if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node||t.expectedRange&&!jn(s.node.loc,t.expectedRange))return;let a=Qe("export",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(t.exportKind!=="default")return;let o=r.get("declaration"),i=Qe("export",o);i&&(t.expectedRange&&!jn(o.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:ot("export","export-not-found",`Export '${eR(t)}' not found`)}function Jk(e,t){let n=null;return tr(e,{Expression(r){if(n||t.root.kind!=="expression"||!Mr(r.node,t.root.sourceRange))return;let o=Qe("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=Qe("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=Qe("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=Wl(o,t.root.name);if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node)return;let a=Qe("value",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(n||t.root.kind!=="default-export")return;let o=r.get("declaration"),i=Qe("value",o);i&&(n=i,r.stop())}}),n?{ok:!0,match:n}:ot("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 Xk(e,t){let n=zl(e);for(let o of t){if(n=zl(n),o.kind==="property"){if(!n.isObjectExpression())return ot("value","unsupported-syntax","Property path requires object expression");let a=n.get("properties");if(a.some(l=>!l.isObjectProperty()))return ot("value","unsupported-syntax","Spread properties are not supported");let c=a.find(l=>rR(l,o.name));if(!c||!c.isObjectProperty())return ot("value","property-not-found",`Property '${o.name}' not found`);n=c.get("value");continue}if(!n.isArrayExpression())return ot("value","unsupported-syntax","Array index path requires array expression");let i=n.get("elements");if(i.some(a=>a.node?.type==="SpreadElement"))return ot("value","unsupported-syntax","Spread array elements are not supported");let s=i[o.index];if(!s?.node)return ot("value","array-index-out-of-range",`Array index ${o.index} is out of range`);n=s}n=zl(n);let r=Qe("value",n);return r?{ok:!0,match:r}:ot("value","locator-miss","Resolved value has no source range")}function zl(e){let t=e;for(;t.isTSAsExpression()||t.isTSSatisfiesExpression()||t.isTSNonNullExpression();)t=t.get("expression");return t}function Qe(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 Mr(e,t){return jn(e.loc,t)}function jn(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 Hl(e){let t=[],n=e,r=e.node;for(;n;){if(n.isJSXElement()){if(!ze(n)){let o=ng(n.node.openingElement);o&&(/^[A-Z]/.test(o)?t.unshift(`component:${o}#${Zm(n,o)}`):t.unshift(`${o}#${Zm(n,o)}`))}}else n.isJSXFragment()&&n.node===r&&t.unshift("fragment");if(!n.parentPath||Gk(n.parentPath)&&!Yk(n.parentPath))break;n=n.parentPath}return t.join("/")}function Zm(e,t){let n=tg(e)??e.getFunctionParent();if(!n)return 0;let r=Vs.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=0,i=Vs.get(n.node)?.get(t);if(!i){let a=Vs.get(n.node);a||(a=new Map,Vs.set(n.node,a)),i=new WeakMap,a.set(t,i)}let s=n.isJSXElement()||n.isJSXFragment()?oi(n):zk(n);for(let a of s)if(ng(a.node.openingElement)===t){if(i.set(a.node,o),a.node===e.node)return o;o++}return i.get(e.node)??0}function zk(e){let t=Us.get(e.node);if(t)return t;let n=[];return e.traverse({JSXElement(r){r.getFunctionParent()?.node===e.node&&!tg(r)&&n.push(r)}}),Us.set(e.node,n),n}function tg(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(ze(t)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function oi(e){let t=Us.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(ze(o)){n.push(...oi(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...oi(o));continue}o.isJSXExpressionContainer()&&n.push(...Bn(o.get("expression")))}return Us.set(e.node,n),n}function Bn(e){if(e.isJSXElement())return ze(e)?oi(e):[e];if(e.isJSXFragment())return oi(e);if(e.isParenthesizedExpression())return Bn(e.get("expression"));if(e.isLogicalExpression()&&Hk(e.node.operator))return Bn(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(...Bn(c))}if(s.isReturnStatement()){let a=s.get("argument");a.isExpression()&&i.push(...Bn(a));break}}return i}else if(o.node&&o.isExpression())return Bn(o)}}}}return e.isConditionalExpression()?[...Bn(e.get("consequent")),...Bn(e.get("alternate"))]:e.isArrayExpression()?e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:Bn(t)):[]}function Hk(e){return e==="&&"||e==="||"||e==="??"}function ng(e){return e.name.type==="JSXIdentifier"?e.name.name:e.name.type==="JSXMemberExpression"?Wk(e.name):null}function Wk(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 ii(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 Gk(e){return!!(e.isFunctionDeclaration()||e.isFunctionExpression()||e.isArrowFunctionExpression())}function Yk(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 Zk(e){return!(!e.isExpression()||e.parentPath?.isMemberExpression({property:e.node}))}function qm(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 Qm(e,t){return e.base===t.base&&qk(e.path,t.path??[])}function qk(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 Qk(e){return e.key.type==="Identifier"?e.key.name:e.key.type==="StringLiteral"?e.key.value:null}function eR(e){return e.exportKind==="named"?e.name:e.exportKind}function ot(e,t,n,r){return{ok:!1,diagnostic:wr(t,n,e,r)}}function tR(e,t){return ii(e)!==t.component?!1:Hl(e)===t.structuralPath}function nR(e,t){return!e.isJSXAttribute()||e.node.name.type!=="JSXIdentifier"?!1:e.node.name.name===t}function Wl(e,t){return e.get("declarations").find(n=>!n.isVariableDeclarator()||n.node.id.type!=="Identifier"?!1:n.node.id.name===t)}function rR(e,t){return e.isObjectProperty()?Qk(e.node)===t:!1}import*as og from"@babel/parser";import{arrayExpression as cR,booleanLiteral as lR,identifier as uR,jsxAttribute as dR,jsxExpressionContainer as fR,jsxIdentifier as pR,nullLiteral as mR,numericLiteral as gR,objectExpression as hR,objectProperty as yR,stringLiteral as Yl}from"@babel/types";import Gl from"@babel/generator";var oR=typeof Gl=="function"?Gl:Gl.default;function iR(e){let t=e.split(`
|
|
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 sR(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 aR(e,t){return e.split(`
|
|
3
|
+
`).map(r=>sR(r,t)).join(`
|
|
4
|
+
`)}function Ks(e){let{ast:t,source:n}=e;try{let r=iR(n),i=oR(t,{comments:!0,jsescOption:{minimal:!0,quotes:"single"}},n).code;return r!=="2"&&(i=aR(i,r)),{ok:!0,source:i}}catch(r){return Q(n,"printer-failed",`AST print failed: ${r instanceof Error?r.message:String(r)}`)}}function rg(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 si(e,t,n){return{ok:!0,source:t,operation:{type:n.kind,nodeId:n.target,kind:n.kind,target:n.target,beforeSourceHash:rg(e),afterSourceHash:rg(t),inverse:n.inverse}}}function we(e,t,n){let r=Ks({ast:e,source:t});return r.ok?si(t,r.source,n):r}function Je(e,t){let n=ti(e,t);return n.ok?{ok:!0,ast:n.ast}:{ok:!1,result:{ok:!1,source:e,diagnostic:n.diagnostic}}}function Js(e,t){return Ks({ast:e,source:t})}function xR(e,t,n){let r=Ee(e,t);return r.ok?{ok:!0,match:r.match}:{ok:!1,result:{ok:!1,source:n,diagnostic:r.diagnostic}}}function co(e,t,n){let r=xR(e,t,n);return r.ok?r.match.path.isJSXElement()?r:{ok:!1,result:Q(n,"unsupported-syntax","JSX locator must resolve to JSXElement","jsx-node")}:r}function nr(e){return typeof e=="string"?Yl(e):typeof e=="number"?gR(e):typeof e=="boolean"?lR(e):e===null?mR():Array.isArray(e)?cR(e.map(t=>nr(t))):hR(Object.entries(e).map(([t,n])=>{let r=yR(Zl(t),nr(n));return t==="__proto__"&&(r.computed=!0),r}))}function bR(e){return typeof e=="string"?Yl(e):fR(nr(e))}function ai(e,t){return dR(pR(e),bR(t))}function Xs(e,t){try{let r=og.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:Q(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:Q(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function Zl(e){return/^[$A-Z_][0-9A-Z_$]*$/i.test(e)?uR(e):Yl(e)}function zs(e){let{source:t,locator:n,segmentIndex:r,newText:o}=e,i=Je(t,"jsx-node");if(!i.ok)return i.result;let s=Ee(i.ast,n);if(!s.ok)return{ok:!1,source:t,diagnostic:s.diagnostic};let c=ER(s.match.path)[r];if(!c)return Q(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?[Br.jsxText(d)]:[],Br.jsxExpressionContainer(Br.stringLiteral("")),...f?[Br.jsxText(f)]:[]]);break}let u=SR(l,o);c.path.node.value=u,c.path.node.extra={rawValue:u,raw:u.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/{/g,"{").replace(/}/g,"}")};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 we(i.ast,t,{kind:"update-text",target:"jsx-node",inverse:"restore-text"})}function ER(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=vR(r.get("expression"));o.length>0&&t.push(...o)}}return t}function SR(e,t){let n=e.match(/^\s*/)?.[0]??"",r=e.match(/\s*$/)?.[0]??"";return`${n}${t.trim()}${r}`}function vR(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 ql}from"@babel/types";function jr(e){let{source:t,locator:n}=e,r=Je(t,"jsx-node");if(!r.ok)return r.result;let o=Ee(r.ast,n);return o.ok?(IR(o.match.path),we(r.ast,t,{kind:"remove-node",target:"jsx-node",inverse:"insert-child"})):{ok:!1,source:t,diagnostic:o.diagnostic}}function IR(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(ql());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(ql());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(ql());return}e.remove()}import{cloneNode as kR}from"@babel/types";function lo(e){let t=Je(e.source,"jsx-node");if(!t.ok)return t.result;let n=Ee(t.ast,e.locator);if(!n.ok)return{ok:!1,source:e.source,diagnostic:n.diagnostic};let r=Xs(e.source,e.node.jsx);return r.ok?(n.match.path.replaceWith(kR(r.node,!0)),we(t.ast,e.source,{kind:"replace-node",target:"jsx-node",inverse:"replace-node"})):r.result}import{cloneNode as LR}from"@babel/types";import Ql from"@babel/traverse";import*as fe from"@babel/types";function ci(e,t,n){return`${e}::${t}::${n}`}var B={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 RR=typeof Ql=="function"?Ql:Ql.default;function Yt(e,t,n,r){if(!e.ok)return e;let o=Gt(n,t);if(!o)return e;let i=CR(t,o,r);return i?{...e,selectionRef:i}:e}function CR(e,t,n){let r=NR(e,t);if(!r)return;let o=n.sourceLocator?ig(n.sourceLocator):void 0,i=n.targetParentLocator?ig(n.targetParentLocator):void 0,s=n.file??i?.file??o?.file,a=n.component??_R(r)??i?.component??o?.component;if(!(!s||!a))return{key:ci(s,a,AR(r))}}function ig(e){return e.strategy==="structural-path"?{file:e.file,component:e.component,structuralPath:e.structuralPath}:e.expectedIdentity}function NR(e,t){let n=dg(e,t);return!n||n.node.type!=="JSXElement"?null:n}function dg(e,t){let n=null;return RR(e,{JSXElement(r){r.node===t&&(n=r,r.stop())},JSXFragment(r){r.node===t&&(n=r,r.stop())}}),n}function Gt(e,t){if(!e)return null;if(fe.isJSXElement(e))return FR(t,e)?sg(e.children,t):e;if(fe.isJSXFragment(e))return sg(e.children,t);if(fe.isJSXExpressionContainer(e)||fe.isParenthesizedExpression(e)||fe.isTSAsExpression(e)||fe.isTSSatisfiesExpression(e)||fe.isTSTypeAssertion(e)||fe.isTSNonNullExpression(e))return Gt(e.expression,t);if(fe.isLogicalExpression(e))return Gt(e.right,t);if(fe.isConditionalExpression(e))return Gt(e.consequent,t)??Gt(e.alternate,t);if(fe.isCallExpression(e)||fe.isOptionalCallExpression(e))return fg(e)?PR(e.arguments[0],t):null;if(fe.isArrayExpression(e))for(let n of e.elements){if(!n)continue;let r=Gt(n,t);if(r)return r}return null}function sg(e,t){for(let n of e){let r=Gt(n,t);if(r)return r}return null}function PR(e,t){return!e||!fe.isArrowFunctionExpression(e)&&!fe.isFunctionExpression(e)?null:fe.isBlockStatement(e.body)?li(e.body.body,t):Gt(e.body,t)}function li(e,t){for(let n of e){if(fe.isReturnStatement(n)){let r=Gt(n.argument,t);if(r)return r;continue}if(fe.isBlockStatement(n)){let r=li(n.body,t);if(r)return r;continue}if(fe.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(fe.isSwitchStatement(n))for(let r of n.cases){let o=li(r.consequent,t);if(o)return o}}return null}function ag(e,t){return fe.isBlockStatement(e)?li(e.body,t):li([e],t)}function _R(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(fe.isFunctionDeclaration(n))return n.id?.name??"default"}if(t.isVariableDeclarator()&&fe.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 cg=new WeakMap,lg=new WeakMap,eu=new WeakMap;function AR(e){let t=cg.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=TR(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return cg.set(e.node,o),o}function TR(e){let t=pg(e.node.openingElement.name);return!t||ze(e)?null:/^[A-Z]/.test(t)?`component:${t}#${ug(e,t)}`:`${t}#${ug(e,t)}`}function ug(e,t){let n=wR(e);if(!n)return 0;let r=eu.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=eu.get(n.node);o||(o=new Map,eu.set(n.node,o));let i=o.get(t);i||(i=new WeakMap,o.set(t,i));let s=0;for(let a of $r(n))if(pg(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 wR(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(ze(t)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function $r(e){let t=lg.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(ze(o)){n.push(...$r(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...$r(o));continue}o.isJSXExpressionContainer()&&n.push(...kn(o.get("expression")))}return lg.set(e.node,n),n}function kn(e){if(e.isJSXElement())return ze(e)?$r(e):[e];if(e.isJSXFragment())return $r(e);if(e.isParenthesizedExpression())return kn(e.get("expression"));if(e.isLogicalExpression())return kn(e.get("right"));if(e.isConditionalExpression())return[...kn(e.get("consequent")),...kn(e.get("alternate"))];if(e.isArrayExpression())return e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:kn(t));if((e.isCallExpression()||e.isOptionalCallExpression())&&fg(e.node)){let t=e.get("arguments"),n=Array.isArray(t)?t[0]:void 0;return n?OR(n):[]}return[]}function OR(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return ze(t)?$r(t):[t];if(t.isJSXFragment())return $r(t);if(t.isParenthesizedExpression())return kn(t.get("expression"));if(t.isLogicalExpression()||t.isConditionalExpression())return kn(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(...kn(s))}if(!r.isReturnStatement())continue;let o=r.get("argument");return o.node&&n.push(...kn(o)),n}return n}function fg(e){let t=e.callee;return(fe.isMemberExpression(t)||fe.isOptionalMemberExpression(t))&&fe.isIdentifier(t.property)&&t.property.name==="map"&&!t.computed}function FR(e,t){let n=dg(e,t);return n?ze(n):!1}function pg(e){return fe.isJSXIdentifier(e)?e.name:fe.isJSXMemberExpression(e)?mg(e):fe.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function mg(e){return`${fe.isJSXIdentifier(e.object)?e.object.name:mg(e.object)}.${e.property.name}`}function rr(e,t){if(t.parentPath===e&&t.listKey==="children"&&tu(e))return e;if(!t.parentPath||t.listKey!=="children")return null;let n=t.parentPath;if(!tu(n))return null;let r=n;for(;r&&r!==e;){if(!tu(r)||!ze(r)||r.listKey!=="children")return null;r=r.parentPath}return r===e?n:null}function tu(e){return e.isJSXElement()||e.isJSXFragment()}function Zt(e){let{source:t,locator:n,node:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=Je(t,"jsx-node");if(!a.ok)return a.result;let c=Ee(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};if(!c.match.path.isJSXElement()&&!c.match.path.isJSXFragment())return Q(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 Q(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=Xs(t,r.jsx);if(!u.ok)return u.result;let d=LR(u.node,!0),f=l.node.children,g={...s,targetParentLocator:n},p=b=>s?Yt(b,a.ast,d,g):b;if(o==="append")return f.push(d),p(we(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return f.unshift(d),p(we(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(!i)return Q(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let m=Ee(a.ast,i);if(!m.ok)return{ok:!1,source:t,diagnostic:m.diagnostic};let y=rr(c.match.path,m.match.path);if(!y)return Q(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,E=x.findIndex(b=>b===m.match.path.node);return E===-1?Q(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(x.splice(o==="before"?E:E+1,0,d),p(we(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"})))}import*as gg from"@babel/parser";import{cloneNode as DR}from"@babel/types";function Hs(e){let{source:t,locator:n,expression:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=Je(t,"jsx-node");if(!a.ok)return a.result;let c=MR(t,r);if(!c.ok)return c.result;let l=Ee(a.ast,n);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return Q(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 Q(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=l.match.path,d=null;if(i){let x=Ee(a.ast,i);if(!x.ok)return{ok:!1,source:t,diagnostic:x.diagnostic};let E=rr(l.match.path,x.match.path);if(!E)return Q(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=E,d=x.match.path.node}else if(o==="before"||o==="after")return Q(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let f=DR(c.node,!0),g=u.node.children,p={...s,targetParentLocator:n},m=x=>s?Yt(x,a.ast,f,p):x;if(o==="append")return g.push(f),m(we(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return g.unshift(f),m(we(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));let y=g.findIndex(x=>x===d);return y===-1?Q(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(g.splice(o==="before"?y:y+1,0,f),m(we(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"})))}function MR(e,t){try{let r=gg.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:Q(e,"unsupported-syntax","Expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:Q(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}import{cloneNode as BR,nullLiteral as nu}from"@babel/types";import*as or from"@babel/types";import*as hg from"@babel/types";function ui(e,t){let n=e.parentPath;if(!n?.isConditionalExpression()||e.key!=="consequent"||!hg.isNullLiteral(n.node.alternate))return e;let r=n.parentPath;return!r?.isJSXExpressionContainer()||r.parentPath?.node!==t.node||r.listKey!=="children"?e:r}function Vr(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=Je(t,"jsx-node");if(!a.ok)return a.result;let c=Ee(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};let l=Ee(a.ast,r);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return Q(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 Q(t,"self-closing-element","Cannot move child into self-closing element","jsx-node")}let d=null;if(i){let b=Ee(a.ast,i);if(!b.ok)return{ok:!1,source:t,diagnostic:b.diagnostic};let S=b.match.path.isJSXElement()?ui(b.match.path,l.match.path):b.match.path,C=rr(l.match.path,S);if(!C)return Q(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=C,d=S}else if(o==="before"||o==="after")return Q(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let f=d&&typeof d.key=="number"?d.key:-1;if(d&&f===-1)return Q(t,"locator-miss","Anchor node does not exist in target parent","jsx-node");let g=c.match.path.isJSXElement()?ui(c.match.path,l.match.path):c.match.path,p=BR(g.node,!0);if(!or.isJSXElement(p)&&!or.isJSXExpressionContainer(p)&&!or.isJSXFragment(p)&&!or.isJSXText(p))return Q(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 Q(t,"invalid-parent-child-relation","Cannot move a node relative to itself","jsx-node");jR(g);let y=u.node.children,x={...s,sourceLocator:n,targetParentLocator:r};if(o==="append")return y.push(p),Yt(Js(a.ast,t),a.ast,p,x);if(o==="prepend")return y.unshift(p),Yt(Js(a.ast,t),a.ast,p,x);let E=f-(m!==-1&&m<f?1:0);return y.splice(o==="before"?E:E+1,0,p),Yt(Js(a.ast,t),a.ast,p,x)}function jR(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(nu());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(nu());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(nu());return}e.remove()}import*as yg from"@babel/parser";import{cloneNode as $R,nullLiteral as ru}from"@babel/types";function Ws(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,repeatExpression:s,selectionContext:a}=e,c=Je(t,"jsx-node");if(!c.ok)return c.result;let l=VR(t,s);if(!l.ok)return l.result;let u=Ee(c.ast,n);if(!u.ok)return{ok:!1,source:t,diagnostic:u.diagnostic};let d=Ee(c.ast,r);if(!d.ok)return{ok:!1,source:t,diagnostic:d.diagnostic};if(!d.match.path.isJSXElement()&&!d.match.path.isJSXFragment())return Q(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 Q(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=Ee(c.ast,i);if(!b.ok)return{ok:!1,source:t,diagnostic:b.diagnostic};let S=rr(d.match.path,b.match.path);if(!S)return Q(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");f=S,g=b.match.path.node}else if(o==="before"||o==="after")return Q(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");if(!u.match.path.isJSXElement())return Q(t,"unsupported-syntax","move-repeat-template-child source must be a JSXElement","jsx-node");let p=f.node,m=$R(l.node,!0);UR(u.match.path);let y={...a,sourceLocator:n,targetParentLocator:r},x=p.children;if(o==="append")return x.push(m),Yt(we(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),Yt(we(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,m,y);let E=x.findIndex(b=>b===g);return E===-1?Q(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(x.splice(o==="before"?E:E+1,0,m),Yt(we(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,m,y))}function VR(e,t){try{let r=yg.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:Q(e,"unsupported-syntax","Repeat expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:Q(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function UR(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(ru());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(ru());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(ru());return}e.remove()}import{SiteEditSetPropsParamsSchema as KR,classifySiteEditPropertyName as JR}from"@vcp-dev/contracts";import*as uo from"@babel/types";function Gs(e){let t=KR.safeParse({kind:"set-props",scope:"selection",changes:e.changes});if(!t.success)return Q(e.source,"unsupported-syntax","Invalid typed JSX property changes","jsx-node",{issues:t.error.issues});let n=Je(e.source,"jsx-node");if(!n.ok)return n.result;let r=co(n.ast,e.locator,e.source);if(!r.ok)return r.result;for(let a of t.data.changes){let c=JR(a.name);if(c.owner!=="generic")return Q(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(uo.isJSXAttribute),s=new Map;for(let a of i){let c=XR(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 Q(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=ai(a.name,a.value).value;c?c.value=l:o.attributes.push(ai(a.name,a.value))}return we(n.ast,e.source,{kind:"set-props",target:"jsx-node",inverse:"set-props"})}function XR(e){return uo.isJSXIdentifier(e.name)?e.name.name:uo.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:null}import{SiteEditOperationParamsSchema as zR}from"@vcp-dev/contracts";import*as ne from"@babel/types";var xg=["prefetch","replace","scroll","locale","onNavigate"],HR=/^on(?:Click|DoubleClick|AuxClick|MouseDown|MouseUp|PointerDown|PointerUp|TouchStart|TouchEnd|KeyDown|KeyUp|ContextMenu)(?:Capture)?$/;function WR(e){let t=e;for(;t;){if(t.isJSXElement()&&t.node.openingElement.attributes.some(n=>ne.isJSXAttribute(n)&&ne.isJSXIdentifier(n.name)&&HR.test(n.name.name)))return!0;t=t.parentPath}return!1}function Ys(e){let t=Je(e.source,"jsx-node");if(!t.ok)return t.result;let n=co(t.ast,e.locator,e.source);if(!n.ok)return n.result;let r=zR.safeParse({kind:"set-link-target",scope:"selection",link:e.link,changes:e.changes});if(!r.success||r.data.kind!=="set-link-target")return $n(e.source,"Invalid typed link-target changes");let o=n.match.path,i=o.node,s=i.openingElement,a=tC(s.name);if(!a)return $n(e.source,"Unsupported JSX link tag");if(s.attributes.some(ne.isJSXSpreadAttribute))return $n(e.source,"Link elements with spread props cannot be transformed safely");let c=new Map;for(let p of s.attributes){if(!ne.isJSXAttribute(p))continue;let m=iu(p);if(!m)return $n(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 $n(e.source,"Duplicate JSX attributes cannot be transformed safely");let l=c.get("href")?.[0];if(l&&!eC(l))return $n(e.source,"Dynamic link href cannot be transformed safely");let u=a==="a",d=u?null:ZR(o,s.name);if(!u&&!d)return $n(e.source,"Only native anchors and imported next/link components are supported");if(e.link.kind==="none"&&WR(o))return $n(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=qR(t.ast,o);if(!p.ok)return $n(e.source,p.reason);f=p.localName}if(d&&e.link.kind!=="internal-route"){let p=ne.jsxIdentifier("a");s.name=p,i.closingElement&&(i.closingElement.name=ne.jsxIdentifier("a")),QR(t.ast,d,o)}else f&&u&&(s.name=ne.jsxIdentifier(f),i.closingElement&&(i.closingElement.name=ne.jsxIdentifier(f)));let g=new Set;return e.link.kind==="none"?(g.add("href"),g.add("target"),g.add("rel"),xg.forEach(p=>g.add(p))):(g.add("href"),e.link.kind==="native-link"&&xg.forEach(p=>g.add(p))),s.attributes=s.attributes.filter(p=>{if(!ne.isJSXAttribute(p))return!0;let m=iu(p);return!m||!g.has(m)}),e.link.kind!=="none"&&s.attributes.push(ne.jsxAttribute(ne.jsxIdentifier("href"),ne.stringLiteral(e.link.href))),GR(s,e.changes),we(t.ast,e.source,{kind:"set-link-target",target:"jsx-node",inverse:"set-link-target"})}function GR(e,t){for(let n of t){let r=e.attributes.find(s=>ne.isJSXAttribute(s)&&iu(s)===n.name);if(n.operation==="remove"){e.attributes=e.attributes.filter(s=>s!==r);continue}let o=typeof n.value=="string"?ne.stringLiteral(n.value):ne.jsxExpressionContainer(ou(n.value)),i=ne.jsxAttribute(ne.jsxIdentifier(n.name),o);r&&ne.isJSXAttribute(r)?r.value=i.value:e.attributes.push(i)}}function ou(e){return e===null?ne.nullLiteral():typeof e=="string"?ne.stringLiteral(e):typeof e=="number"?ne.numericLiteral(e):typeof e=="boolean"?ne.booleanLiteral(e):Array.isArray(e)?ne.arrayExpression(e.map(t=>ou(t))):typeof e=="object"?ne.objectExpression(Object.entries(e).map(([t,n])=>ne.objectProperty(ne.isValidIdentifier(t)?ne.identifier(t):ne.stringLiteral(t),ou(n)))):ne.nullLiteral()}function YR(e){return ne.isImportDefaultSpecifier(e)||ne.isImportSpecifier(e)&&e.importKind!=="type"&&(ne.isIdentifier(e.imported,{name:"default"})||ne.isStringLiteral(e.imported,{value:"default"}))}function bg(e){return!e.parentPath?.isImportDeclaration()||e.parentPath.node.importKind==="type"?!1:e.isImportDefaultSpecifier()||e.isImportSpecifier()&&e.node.importKind!=="type"&&(ne.isIdentifier(e.node.imported,{name:"default"})||ne.isStringLiteral(e.node.imported,{value:"default"}))}function ZR(e,t){if(!ne.isJSXIdentifier(t))return null;let n=e.scope.getBinding(t.name);if(!n||!bg(n.path))return null;let r=n.path.parentPath;return!r?.isImportDeclaration()||r.node.source.value!=="next/link"?null:t.name}function qR(e,t){let n=e.program.body.filter(c=>ne.isImportDeclaration(c)&&c.source.value==="next/link"&&c.importKind!=="type"),r=n[0],o=n.flatMap(c=>c.specifiers).find(YR);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=ne.importDefaultSpecifier(ne.identifier(s));if(r)r.specifiers.unshift(a);else{let c=ne.importDeclaration([a],ne.stringLiteral("next/link")),l=0;for(;l<e.program.body.length&&ne.isImportDeclaration(e.program.body[l]);)l+=1;e.program.body.splice(l,0,c)}return{ok:!0,localName:s}}function QR(e,t,n){let r=n.scope.getProgramParent();r.crawl();let o=r.getBinding(t);if(!o||!bg(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 eC(e){return!e.value||ne.isStringLiteral(e.value)}function tC(e){return ne.isJSXIdentifier(e)?e.name:null}function iu(e){return ne.isJSXIdentifier(e.name)?e.name.name:null}function $n(e,t){return Q(e,"unsupported-syntax",t,"jsx-node")}import*as ut from"@babel/types";import{classifySiteEditPropertyName as Eg}from"@vcp-dev/contracts";function Zs(e){let t=Eg(e.name),n=Eg(e.property);if(t.owner!=="generic"||n.owner!=="generic")return Q(e.source,"unsupported-syntax","Property binding is only available for generic properties","jsx-node");if(!Sg(e.object))return Q(e.source,"unsupported-syntax","Property binding object must be a single identifier","jsx-node");if(e.property.length===0)return Q(e.source,"unsupported-syntax","Property binding requires a non-empty property name","jsx-node");let r=Je(e.source,"jsx-node");if(!r.ok)return r.result;let o=co(r.ast,e.locator,e.source);if(!o.ok)return o.result;let i=o.match.path.node.openingElement,s=i.attributes.filter(l=>ut.isJSXAttribute(l)&&rC(l)===e.name);if(s.length>1)return Q(e.source,"unsupported-syntax",`JSX attribute '${e.name}' has multiple sources`,"jsx-node");let a=nC(e.object,e.property),c=s[0];if(c)c.value=ut.jsxExpressionContainer(a);else{let l=ai(e.name,"");l.value=ut.jsxExpressionContainer(a),i.attributes.push(l)}return we(r.ast,e.source,{kind:"set-property-binding",target:"jsx-node",inverse:"restore-property-binding"})}function nC(e,t){return Sg(t)?ut.memberExpression(ut.identifier(e),ut.identifier(t)):ut.memberExpression(ut.identifier(e),ut.stringLiteral(t),!0)}function Sg(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(e)}function rC(e){return ut.isJSXIdentifier(e.name)?e.name.name:ut.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:null}import{getBindingIdentifiers as iC,identifier as di,importDeclaration as sC,importDefaultSpecifier as aC,importNamespaceSpecifier as cC,importSpecifier as lC,isImportDefaultSpecifier as vg,isImportNamespaceSpecifier as Ig,isImportSpecifier as kg,stringLiteral as uC}from"@babel/types";function qt(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(y=>!bC(y));if(o!==-1){let y=r[o],x=y&&typeof y=="object"&&"kind"in y?y.kind:void 0;return Q(t,"unsupported-syntax",`Unsupported import spec kind: ${String(x)}`)}let i=hC(r);if(!i.ok)return Q(t,"unsupported-syntax",i.message);let s=Je(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 E=EC(y,x);return E?[E]:[]}))),d=i.imports.filter(y=>!u.has(Ag(y)));if(d.length===0)return si(t,t,{kind:"add-import",target:"import",inverse:"remove-import"});let f=yC(c.body),g=d.find(y=>f.has(su(y)));if(g)return Q(t,"unsupported-syntax",`Import local binding already exists: ${su(g)}`);let p=gC(d);if(p.reduce((y,x)=>y+x.length,0)!==d.length)return Q(t,"unsupported-syntax","Unsupported import specifier grouping");for(let y of p){if(!Pg(Cg(y)))return Q(t,"unsupported-syntax","Unsupported import specifier combination");let x=l.find(E=>dC(E,y));if(x)fC(x,y);else{let E=sC(Rg(y),uC(n));xC(c.body,E),l.push(E)}}return we(a,t,{kind:"add-import",target:"import",inverse:"remove-import"})}function dC(e,t){return e.importKind==="type"?!1:Pg(mC(pC(e),Cg(t)))}function fC(e,t){let n=!1,r=new Set(e.specifiers.map(o=>au(o)));for(let o of Rg(t)){let i=au(o);r.has(i)||(e.specifiers.push(o),r.add(i),n=!0)}return _g(e.specifiers),{changed:n}}function Rg(e){let t=e.map(n=>{switch(n.kind){case"named":return lC(n.local?di(n.local):di(n.imported),di(n.imported));case"default":return aC(di(n.local));case"namespace":return cC(di(n.local));default:return n}});return _g(t),t}function Cg(e){let t=Ng();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 pC(e){let t=Ng();for(let n of e.specifiers)vg(n)?t.defaultLocals.add(n.local.name):Ig(n)?t.namespaceLocals.add(n.local.name):t.hasNamed=!0;return t}function Ng(){return{defaultLocals:new Set,hasNamed:!1,namespaceLocals:new Set}}function mC(e,t){return{defaultLocals:new Set([...e.defaultLocals,...t.defaultLocals]),hasNamed:e.hasNamed||t.hasNamed,namespaceLocals:new Set([...e.namespaceLocals,...t.namespaceLocals])}}function Pg(e){return e.defaultLocals.size>1||e.namespaceLocals.size>1?!1:!(e.hasNamed&&e.namespaceLocals.size>0)}function _g(e){let t=[...e.filter(n=>vg(n)),...e.filter(n=>Ig(n)),...e.filter(n=>kg(n))];e.splice(0,e.length,...t)}function gC(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 hC(e){let t=new Map,n=new Map;for(let r of e){let o=Ag(r);if(t.has(o))continue;let i=su(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 yC(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(iC(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 xC(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 bC(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 Ag(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 su(e){return e.kind==="named"?e.local??e.imported:e.local}function EC(e,t){return e.importKind==="type"||kg(t)&&t.importKind==="type"?null:au(t)}function au(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 fo(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(u=>!vC(u));if(o!==-1){let u=r[o],d=u&&typeof u=="object"&&"kind"in u?u.kind:void 0;return Q(t,"unsupported-syntax",`Unsupported remove import spec kind: ${String(d)}`)}let i=Je(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 si(t,t,{kind:"remove-import",target:"import",inverse:"add-import"});let l=a.body[c];return r.length===0?(a.body.splice(c,1),we(s,t,{kind:"remove-import",target:"import",inverse:"add-import"})):(l.specifiers=l.specifiers.filter(u=>!r.some(d=>SC(u,d))),l.specifiers.length===0&&a.body.splice(c,1),we(s,t,{kind:"remove-import",target:"import",inverse:"add-import"}))}function SC(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 vC(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 fi(e){let{source:t,locator:n,next:r}=e,o=ta(t,n);return o.ok?(o.path.replaceWith(nr(r)),we(o.ast,t,{kind:"update-value",target:"value",inverse:"restore-value"})):o.result}function qs(e){let{source:t,locator:n,index:r,value:o}=e,i=ta(t,n);return i.ok?i.path.isArrayExpression()?i.path.node.elements.some(s=>s?.type==="SpreadElement")?Q(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>i.path.node.elements.length?Q(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(i.path.node.elements.splice(r,0,nr(o)),we(i.ast,t,{kind:"insert-array-element",target:"value",inverse:"remove-array-element"})):Q(t,"unsupported-syntax","Array operations require array expression target","value"):i.result}function Qs(e){let{source:t,locator:n,index:r}=e,o=ta(t,n);return o.ok?o.path.isArrayExpression()?o.path.node.elements.some(i=>i?.type==="SpreadElement")?Q(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>=o.path.node.elements.length?Q(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(o.path.node.elements.splice(r,1),we(o.ast,t,{kind:"remove-array-element",target:"value",inverse:"insert-array-element"})):Q(t,"unsupported-syntax","Array operations require array expression target","value"):o.result}function ea(e){let{source:t,locator:n,fromIndex:r,toIndex:o}=e,i=ta(t,n);if(!i.ok)return i.result;if(!i.path.isArrayExpression())return Q(t,"unsupported-syntax","Array operations require array expression target","value");if(i.path.node.elements.some(c=>c?.type==="SpreadElement"))return Q(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 Q(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),we(i.ast,t,{kind:"move-array-element",target:"value",inverse:"move-array-element-back"})}function ta(e,t){let n=Je(e,"value");if(!n.ok)return{ok:!1,result:n.result};let r=Ee(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 ht from"@babel/types";function na(e){let t=Je(e.source,"value");if(!t.ok)return t.result;let n=Ee(t.ast,e.objectLocator);if(!n.ok)return{ok:!1,source:e.source,diagnostic:n.diagnostic};if(!n.match.path.isObjectExpression())return Q(e.source,"unsupported-syntax","Object property upsert requires an ObjectExpression parent","value");let r=n.match.path.node;if(r.properties.some(a=>ht.isSpreadElement(a)||ht.isObjectProperty(a)&&a.computed))return Q(e.source,"unsupported-syntax","Object property upsert does not support spreads or computed keys","value");let o=r.properties.filter(a=>ht.isObjectProperty(a)&&IC(a.key)===e.name);if(o.length>1)return Q(e.source,"unsupported-syntax",`Object property '${e.name}' has multiple sources`,"value");let i=e.value.kind==="undefined"?ht.unaryExpression("void",ht.numericLiteral(0)):nr(e.value.value),s=o[0];if(s)s.value=i,s.shorthand=!1;else{let a=ht.objectProperty(Zl(e.name),i);e.name==="__proto__"&&(a.computed=!0),r.properties.push(a)}return we(t.ast,e.source,{kind:"upsert-object-property",target:"value",inverse:"restore-object-property"})}function IC(e){return ht.isIdentifier(e)?e.name:ht.isStringLiteral(e)?e.value:ht.isNumericLiteral(e)?String(e.value):null}import{isSiteEditRuntimeContainerTag as kC,isSiteEditRuntimeVoidElementTag as RC}from"@vcp-dev/contracts/site-edit-runtime-capability";function po(e){if(!e.composition)throw new Error("Composition unavailable for render source graph.");return e.composition}function CC(e,t,n){let r=po(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(S=>({kind:S.kind,message:S.reason})),a=i.isOpaque,l=o.parentKey===null&&i.componentName==="Page",u=i.tag.toLowerCase(),d=i.tag!==u,f=!d&&RC(u),g=d||kC(u),p=d&&i.childKeys.length>0&&!i.isPublicUiComponent,m=i.textSegments.length>0&&i.textSegments.some(S=>S.editable);f&&!s.some(S=>S.kind==="void-element")&&s.push({kind:"void-element",message:`Element '${i.tag}' is void: children cannot be inserted`}),!f&&!g&&!s.some(S=>S.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 ra(e,t){let n=new Map;for(let r of e.nodes.keys())n.set(r,CC(r,e,t));return n}function cu(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:ve(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Key not found: ${e.key}`}]};let n=NC(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:ve(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:wg(r),version:{documentVersion:e.route.graph.version,contentHash:ve(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()?PC(l.get("expression")):void 0;return{...i,sourceKind:a,attrRaw:Tg(e.route.source,o),valueRaw:s?Tg(e.route.source,s):null,...u===void 0?{}:{resolvedClassName:u},attrRange:wg(o),diagnostics:[]}}function Og(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 NC(e,t){let n=Sn({source:e,profile:Or({filePath:t.sourceFile,source:e})});if(!n.ok)return null;let r=Ee(n.ast,{kind:"jsx-node",strategy:"structural-path",file:t.identity.file,component:t.identity.component,structuralPath:t.identity.structuralPath,expectedRange:_C(t.sourceRange)});return!r.ok||!r.match.path.isJSXElement()?null:r.match.path}function PC(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 Fg(e){let t=Sn({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 Tg(e,t){return t.start==null||t.end==null?"":e.slice(t.start,t.end)}function wg(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 _C(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function Lg(){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 AC}from"node:crypto";import oa from"node:fs/promises";import lu from"node:path";import{setTimeout as TC}from"node:timers/promises";var wC={async mkdir(e,t){await oa.mkdir(e,t)},async writeFile(e,t,n){await oa.writeFile(e,t,n)},async rename(e,t){await oa.rename(e,t)},async rm(e,t){await oa.rm(e,t)}},OC=new Set(["EACCES","EBUSY","EPERM"]),FC=[10,20,40,80,160];async function LC(e,t,n){for(let r of FC)try{await e.rename(t,n);return}catch(o){if(!DC(o))throw o;await TC(r)}await e.rename(t,n)}function DC(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&OC.has(e.code)}async function ia(e,t,n=wC){let r=lu.dirname(e),o=lu.basename(e),i=lu.join(r,`.${o}.${process.pid}.${AC()}.tmp`),s=!1;try{await n.mkdir(r,{recursive:!0}),await n.writeFile(i,t,"utf8"),await LC(n,i,e),s=!0}finally{if(!s)try{await n.rm(i,{force:!0})}catch{}}}import uu from"@babel/traverse";import*as N from"@babel/types";import*as _e from"@babel/types";function Rn(e,t={}){if(_e.isTSAsExpression(e)||_e.isTSSatisfiesExpression(e)||_e.isTSNonNullExpression(e)||_e.isTypeCastExpression(e)||_e.isParenthesizedExpression(e))return Rn(e.expression,t);if(_e.isStringLiteral(e))return{status:"resolved",value:e.value};if(_e.isNumericLiteral(e))return Number.isFinite(e.value)?{status:"resolved",value:e.value}:{status:"unresolved"};if(_e.isBooleanLiteral(e))return{status:"resolved",value:e.value};if(_e.isNullLiteral(e))return{status:"resolved",value:null};if(_e.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(_e.isIdentifier(e))return e.name==="undefined"&&!t.resolveIdentifier?{status:"undefined"}:t.resolveIdentifier?.(e.name)??{status:"unresolved"};if(_e.isUnaryExpression(e)&&e.operator==="void"&&_e.isNumericLiteral(e.argument)&&e.argument.value===0)return{status:"undefined"};if(_e.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||_e.isSpreadElement(r))return{status:"unresolved"};let o=Rn(r,t);if(o.status!=="resolved")return{status:"unresolved"};n.push(o.value)}return{status:"resolved",value:n}}if(_e.isObjectExpression(e)){let n=Object.create(null);for(let r of e.properties){if(!_e.isObjectProperty(r)||r.computed||!_e.isExpression(r.value))return{status:"unresolved"};let o=MC(r.key);if(o===null)return{status:"unresolved"};let i=Rn(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 _e.isMemberExpression(e)||_e.isOptionalMemberExpression(e)?t.resolveMember?.(e)??{status:"unresolved"}:{status:"unresolved"}}function MC(e){return _e.isIdentifier(e)?e.name:_e.isStringLiteral(e)?e.value:_e.isNumericLiteral(e)?String(e.value):null}var BC=typeof uu=="function"?uu:uu.default;function It(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 jC(e){return/^[A-Z]/.test(e)}function gu(e){let t=e.openingElement;return N.isJSXIdentifier(t.name)?t.name.name==="Fragment":N.isJSXMemberExpression(t.name)?t.name.property.name==="Fragment":!1}function go(e){return N.isJSXFragment(e)}function Mg(e){return N.isJSXIdentifier(e.name)?e.name.name:N.isJSXMemberExpression(e.name)?Bg(e.name):N.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:"unknown"}function Bg(e){return N.isJSXIdentifier(e.object)?`${e.object.name}.${e.property.name}`:N.isJSXMemberExpression(e.object)?`${Bg(e.object)}.${e.property.name}`:e.property.name}function $C(e){return e.split(".")[0]??e}function VC(e){let t=e;for(;t;){let n=t.node;if(N.isFunctionDeclaration(n)&&n.id||N.isVariableDeclarator(n)&&N.isIdentifier(n.id))return n.id.name;if(N.isExportDefaultDeclaration(n)){let r=n.declaration;if(N.isFunctionDeclaration(r)&&r.id)return r.id.name;if(N.isFunctionDeclaration(r)&&!r.id)return"default"}t=t.parentPath}return null}function UC(){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 KC(e){let t=new Map;for(let n of e.program.body){if(!N.isImportDeclaration(n))continue;let r=n.source.value;for(let o of n.specifiers)if(N.isImportDefaultSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"default"});else if(N.isImportNamespaceSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"*"});else if(N.isImportSpecifier(o)){let i=N.isIdentifier(o.imported)?o.imported.name:o.imported.value;t.set(o.local.name,{specifier:r,exportName:i})}}return t}function Vn(e,t=[]){if(N.isIdentifier(e))return t.push(e.name),t;if(N.isObjectPattern(e)){for(let n of e.properties)N.isObjectProperty(n)?Vn(n.value,t):N.isRestElement(n)&&Vn(n.argument,t);return t}if(N.isArrayPattern(e)){for(let n of e.elements)n&&(N.isRestElement(n)?Vn(n.argument,t):Vn(n,t));return t}return N.isAssignmentPattern(e)?(Vn(e.left,t),t):(N.isRestElement(e)&&Vn(e.argument,t),t)}function cn(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function pi(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 JC(e,t,n){e.set(t,{resolved:!0,value:n})}function hu(e,t){e.set(t,{resolved:!1})}function jg(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 at(e,t,n){if(N.isTSAsExpression(e)||N.isTSSatisfiesExpression(e)||N.isTSNonNullExpression(e)||N.isTypeCastExpression(e)||N.isParenthesizedExpression(e))return at(e.expression,t,n);if(N.isLogicalExpression(e))return sa([at(e.left,t,n),at(e.right,t,n)]);if(N.isBinaryExpression(e))return sa([N.isExpression(e.left)?at(e.left,t,n):null,N.isExpression(e.right)?at(e.right,t,n):null]);if(N.isConditionalExpression(e))return sa([at(e.consequent,t,n),at(e.alternate,t,n)]);if(N.isTemplateLiteral(e))return sa(e.expressions.filter(N.isExpression).map(i=>at(i,t,n)));if(N.isIdentifier(e))return{kind:"identifier",expression:e.name,base:e.name,path:[]};if(!N.isMemberExpression(e)&&!N.isOptionalMemberExpression(e))return null;let r=[],o=e;for(;N.isMemberExpression(o)||N.isOptionalMemberExpression(o);){if(o.computed)if(N.isNumericLiteral(o.property))r.unshift({kind:"index",index:o.property.value});else if(N.isStringLiteral(o.property))r.unshift({kind:"property",name:o.property.value});else if(n&&N.isExpression(o.property)){let i=ir(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(!N.isIdentifier(o.property))return null;r.unshift({kind:"property",name:o.property.name})}o=o.object}return N.isIdentifier(o)?{kind:r.some(i=>i.kind==="index")?"index-expression":"member-expression",expression:cn(e,t),base:o.name,path:r}:null}function sa(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 yu(e,t,n){if(N.isArrayExpression(e)){let r=e.elements[0];return e.elements.length===1&&N.isExpression(r)?at(r,t,n):null}return N.isCallExpression(e)&&N.isMemberExpression(e.callee)&&!e.callee.computed&&N.isIdentifier(e.callee.property)&&["filter","slice","sort","toSorted","reverse","toReversed"].includes(e.callee.property.name)&&N.isExpression(e.callee.object)?yu(e.callee.object,t,n):at(e,t,n)}function ir(e,t){if(N.isStringLiteral(e)||N.isNumericLiteral(e)||N.isBooleanLiteral(e))return e.value;if(N.isNullLiteral(e))return null;if(N.isTemplateLiteral(e))return e.expressions.length===0&&e.quasis.length===1?e.quasis[0].value.cooked??e.quasis[0].value.raw:void 0;if(N.isIdentifier(e)){let n=pi(e.name,t.valueScopes);return n.kind==="resolved"?n.value:void 0}if(N.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||N.isSpreadElement(r))return;let o=ir(r,t);if(o===void 0)return;n.push(o)}return n}if(N.isObjectExpression(e)){let n={};for(let r of e.properties){if(!N.isObjectProperty(r)||r.computed||!N.isExpression(r.value))return;let o=null;if(N.isIdentifier(r.key)?o=r.key.name:N.isStringLiteral(r.key)&&(o=r.key.value),!o)return;let i;if(r.shorthand){if(!N.isIdentifier(r.value))return;let s=pi(r.value.name,t.valueScopes);if(s.kind!=="resolved")return;i=s.value}else i=ir(r.value,t);if(i===void 0)return;n[o]=i}return n}if(N.isMemberExpression(e)){let n=at(e,"",t);if(!n)return;let r=pi(n.base,t.valueScopes);if(r.kind!=="resolved")return;let o=jg(r.value,n.path);return o.kind==="resolved"?o.value:void 0}if(N.isCallExpression(e))return Vg(e,t)??void 0}function $g(e,t,n){let r=at(e,n,t);if(!r)return N.isMemberExpression(e)||N.isBinaryExpression(e)||N.isLogicalExpression(e)||N.isConditionalExpression(e)||N.isCallExpression(e)?{value:cn(e,n),source:null}:null;let o=pi(r.base,t.valueScopes),i=r.kind==="identifier"?o:o.kind==="resolved"?jg(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 du(e,t,n,r,o,i){return{file:e,componentName:t,elements:n,regions:r,ordinalTracker:UC(),parentStack:[],valueScopes:i,importMap:o}}function pu(e,t,n){for(let r of e)for(let o of r.declarations){for(let s of Vn(o.id))hu(n,s);if(!N.isIdentifier(o.id)||!o.init||!N.isExpression(o.init))continue;let i=ir(o.init,t);i!==void 0&&JC(n,o.id.name,i)}}function XC(e){let t=[];for(let n of e){if(N.isVariableDeclaration(n)){t.push(n);continue}N.isExportNamedDeclaration(n)&&n.declaration&&N.isVariableDeclaration(n.declaration)&&t.push(n.declaration)}return t}function zC(e,t,n){let r=[],o=0;for(let i of e)if(N.isJSXText(i)){let s=i.value.trim();s&&r.push({index:o++,value:s,sourceRange:It(i),editable:!0,source:null})}else if(N.isJSXExpressionContainer(i)&&N.isStringLiteral(i.expression))r.push({index:o++,value:i.expression.value,sourceRange:It(i),editable:!0,source:null});else if(N.isJSXExpressionContainer(i)&&N.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:It(i),editable:!0,source:null}):r.push({index:o++,value:cn(s,n),sourceRange:It(i),editable:!0,source:at(s,n,t)})}else if(N.isJSXExpressionContainer(i)&&N.isExpression(i.expression)){let s=$g(i.expression,t,n);s&&r.push({index:o++,value:s.value,sourceRange:It(i),editable:!0,source:s.source})}return r}function HC(e,t,n){let r=[];for(let[o,i]of e.attributes.entries()){if(!N.isJSXAttribute(i))continue;let s=GC(i.name);if(!s)continue;let a=cn(i,n);if(N.isStringLiteral(i.value)){r.push({name:s,value:i.value.value,sourceRange:It(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:It(i),source:null,syntaxKind:"boolean-shorthand",raw:a,order:o,resolution:{status:"resolved",value:!0},resolvedValue:!0});continue}if(N.isJSXExpressionContainer(i.value)&&N.isExpression(i.value.expression)){let c=ir(i.value.expression,t);if(s==="className"){let g=typeof c=="string"?c:c===void 0?Vg(i.value.expression,t):null;if(g){r.push({name:s,value:g,sourceRange:It(i),source:null,resolvedValue:g,syntaxKind:"expression",raw:a,order:o,resolution:{status:"resolved",value:g}});continue}}let l=$g(i.value.expression,t,n);if(c!==void 0){r.push({name:s,value:nN(c),sourceRange:It(i),source:at(i.value.expression,n,t),resolvedValue:c,syntaxKind:"expression",raw:a,order:o,resolution:{status:"resolved",value:c}});continue}let u=YC(i.value.expression,t),d=at(i.value.expression,n,t),f=l?.value??cn(i.value.expression,n);r.push({name:s,value:u.status==="undefined"?"undefined":f,sourceRange:It(i),source:l?.source??d,syntaxKind:"expression",raw:a,order:o,resolution:u})}}return r}function WC(e,t,n){return e.attributes.flatMap((r,o)=>!N.isJSXSpreadAttribute(r)||!N.isExpression(r.argument)?[]:[{raw:cn(r.argument,n),sourceRange:It(r),order:o,source:at(r.argument,n,t)}])}function GC(e){return N.isJSXIdentifier(e)?e.name:N.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function YC(e,t){return Rn(e,{resolveIdentifier(n){let r=pi(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=ir(n,t);return r===void 0?{status:"unresolved"}:{status:"resolved",value:r}}})}function Vg(e,t){let n=mo(e,t);return n&&n.map(o=>o.trim()).filter(Boolean).join(" ")||null}function mo(e,t){if(N.isStringLiteral(e))return[e.value];if(N.isTemplateLiteral(e))return e.expressions.length>0?null:[e.quasis.map(n=>n.value.cooked??"").join("")];if(N.isNullLiteral(e))return[];if(N.isBooleanLiteral(e))return e.value?null:[];if(N.isIdentifier(e)||N.isMemberExpression(e)){if(N.isIdentifier(e)&&e.name==="undefined")return[];let n=ir(e,t);return typeof n=="string"?[n]:null}if(N.isConditionalExpression(e)){let n=mo(e.consequent,t),r=mo(e.alternate,t);return!n||!r?null:[...n,...r]}if(N.isLogicalExpression(e)){if(e.operator!=="&&")return null;let n=ir(e.left,t);return n===!1||n===null?[]:mo(e.right,t)}if(N.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||N.isSpreadElement(r))return null;let o=mo(r,t);if(!o)return null;n.push(...o)}return n}if(N.isObjectExpression(e)){let n=[];for(let r of e.properties){if(!N.isObjectProperty(r))return null;let o=qC(r.key);if(!o)return null;n.push(o)}return n}if(N.isCallExpression(e)){let n=ZC(e.callee);if(!n||!["cn","clsx","twMerge"].includes(n))return null;let r=[];for(let o of e.arguments){if(!N.isExpression(o))return null;let i=mo(o,t);if(!i)return null;r.push(...i)}return r}return null}function ZC(e){return N.isIdentifier(e)?e.name:N.isMemberExpression(e)&&N.isIdentifier(e.property)?e.property.name:null}function qC(e){return N.isIdentifier(e)?e.name:N.isStringLiteral(e)?e.value:null}function QC(e,t){let n=e.attributes.find(r=>N.isJSXAttribute(r)&&N.isJSXIdentifier(r.name)&&r.name.name===t);return!n||!N.isJSXAttribute(n)||!N.isJSXExpressionContainer(n.value)?null:n.value.expression}function eN(e,t){for(let n of t){let r=QC(e,n);if(r)return r}return null}function tN(e){return N.isJSXIdentifier(e.name)?e.name.name:null}function nN(e){return e===null?"null":typeof e=="boolean"?e?"true":"false":JSON.stringify(e)}function rN(e){if(!N.isCallExpression(e)&&!N.isOptionalCallExpression(e))return null;let t=e.callee;return!N.isMemberExpression(t)&&!N.isOptionalMemberExpression(t)||!N.isIdentifier(t.property)||t.property.name!=="map"||t.computed||!N.isExpression(t.object)?null:{call:e,collection:t.object,callback:e.arguments[0]}}function fu(e){return N.isArrowFunctionExpression(e)||N.isFunctionExpression(e)}function oN(e){return e==="render"||e==="itemRender"||e==="rowRender"||e==="children"}function iN(e){return e==="empty"||e==="emptyRender"||e==="loading"||e==="loadingRender"||e==="error"||e==="errorRender"||e==="fallback"||e==="headerRender"||e==="footerRender"}function Dg(e,t,n,r){if(!e||!N.isExpression(e))return null;let o={kind:"repeat-template",collectionExpression:cn(e,n),collectionSource:yu(e,n,r)};if(t){let i=t.params[0],s=t.params[1];N.isIdentifier(i)&&(o.itemParamName=i.name),N.isIdentifier(s)&&(o.indexParamName=s.name)}return o}function Un(e,t,n){if(!e)return[];if(N.isJSXElement(e)){if(gu(e))return da(e.children,t,n);let r=la(e,t,n);return r?[r]:[]}return go(e)?ua(e,t,n):N.isParenthesizedExpression(e)?Un(e.expression,t,n):N.isExpression(e)?fa(e,t,n):[]}function aa(e,t,n){let r=new Map;for(let o of e.params)for(let i of Vn(o))hu(r,i);t.valueScopes.push(r);try{if(!N.isBlockStatement(e.body))return Un(e.body,t,n);let o=new Map;t.valueScopes.push(o);try{return Ug(e.body.body,t,n)}finally{t.valueScopes.pop()}}finally{t.valueScopes.pop()}}function Ug(e,t,n){let r=[];for(let o of e){if(N.isVariableDeclaration(o)){let i=t.valueScopes[t.valueScopes.length-1];if(i){pu([o],t,i);for(let s of o.declarations)N.isIdentifier(s.id)&&(N.isJSXElement(s.init)||N.isJSXFragment(s.init))&&r.push(...Un(s.init,t,n))}continue}r.push(...mu(o,t,n))}return r}function mu(e,t,n){if(N.isReturnStatement(e))return e.argument?Un(e.argument,t,n):[];if(N.isBlockStatement(e))return Ur(e.body,t,n);if(N.isIfStatement(e)){let r=N.isBlockStatement(e.consequent)?Ur(e.consequent.body,t,n):mu(e.consequent,t,n),o=e.alternate?N.isBlockStatement(e.alternate)?Ur(e.alternate.body,t,n):mu(e.alternate,t,n):[];return[...r,...o]}if(N.isSwitchStatement(e))return Ur(e.cases.flatMap(r=>r.consequent),t,n);if(N.isTryStatement(e)){let r=Ur(e.block.body,t,n);return e.handler&&r.push(...Ur(e.handler.body.body,t,n)),e.finalizer&&r.push(...Ur(e.finalizer.body,t,n)),r}return[]}function Ur(e,t,n){let r=new Map;t.valueScopes.push(r);try{return Ug(e,t,n)}finally{t.valueScopes.pop()}}function ca(e,t,n,r,o,i){o.length!==0&&e.regions.push({kind:t,ownerKey:n,childKeys:o,sourceRange:It(r),sourceCandidates:i&&i.length>0?i:void 0})}function sN(e,t,n,r){let o=eN(e.openingElement,["items","dataSource","data"]),i={key:t,tag:Mg(e.openingElement)};n.parentStack.push(i);try{for(let s of e.openingElement.attributes){if(!N.isJSXAttribute(s))continue;let a=tN(s);if(!a||!N.isJSXExpressionContainer(s.value))continue;let c=s.value.expression;if(!N.isJSXEmptyExpression(c)){if(oN(a)&&fu(c)){let l=aa(c,n,r),u=Dg(o,c,r,n);ca(n,"repeat-region",t,s,l,u?[u]:void 0);continue}if(iN(a)){let l=fu(c)?aa(c,n,r):Un(c,n,r);ca(n,"conditional-region",t,s,l)}}}if(o)for(let s of e.children){if(!N.isJSXExpressionContainer(s)||!fu(s.expression))continue;let a=aa(s.expression,n,r),c=Dg(o,s.expression,r,n);ca(n,"repeat-region",t,s,a,c?[c]:void 0)}}finally{n.parentStack.pop()}}function la(e,t,n){let r=Mg(e.openingElement);if(r==="Fragment"||gu(e))return da(e.children,t,n),null;let o=t.parentStack[t.parentStack.length-1]??null,i=o?.key??null,s=jC(r),a;if(s){let S=t.ordinalTracker.getOrdinal(i,r);a=`component:${r}#${S}`}else{let S=t.ordinalTracker.getOrdinal(i,r);a=`${r}#${S}`}let c=o?t.elements.get(o.key)?.identity.structuralPath:void 0,l=c?`${c}/${a}`:a,u=ci(t.file,t.componentName,l),d={file:t.file,component:t.componentName,structuralPath:l,key:u},f=s?"component-boundary":null,g=zC(e.children,t,n),p=HC(e.openingElement,t,n),m=WC(e.openingElement,t,n),y,x,E=!1;if(s){let S=t.importMap.get(r)??t.importMap.get($C(r));S&&(y=S.specifier,x=S.exportName,E=Fr(S.specifier,t.file))}let b={identity:d,tag:r,componentName:t.componentName,sourceFile:t.file,sourceRange:It(e),parentKey:i,childKeys:[],textSegments:g,attributes:p.length>0?p:void 0,attributeSpreads:m.length>0?m:void 0,boundaryKind:f,isOpaque:s,...E?{isPublicUiComponent:!0}:{},importedFrom:y,exportName:x};return t.elements.set(u,b),i&&t.elements.has(i)&&t.elements.get(i).childKeys.push(u),sN(e,u,t,n),(!s||e.children.length>0)&&(t.parentStack.push({key:u,tag:r}),aN(e.children,t,n),t.parentStack.pop()),u}function ua(e,t,n){return da(e.children,t,n)}function da(e,t,n){let r=[];for(let o of e)if(N.isJSXElement(o))if(gu(o))r.push(...da(o.children,t,n));else{let i=la(o,t,n);i&&r.push(i)}else go(o)?r.push(...ua(o,t,n)):N.isJSXExpressionContainer(o)&&r.push(...fa(o.expression,t,n));return r}function aN(e,t,n){for(let r of e)N.isJSXElement(r)?la(r,t,n):go(r)?ua(r,t,n):N.isJSXExpressionContainer(r)&&fa(r.expression,t,n)}function cN(e){return e==="&&"||e==="||"||e==="??"}function fa(e,t,n){if(N.isJSXEmptyExpression(e))return[];let r=rN(e);if(r){let o=r.call,i=t.parentStack[t.parentStack.length-1]??null,s=[],a=r.callback,c={kind:"repeat-template",collectionExpression:cn(r.collection,n),collectionSource:yu(r.collection,n,t)};if(N.isArrowFunctionExpression(a)||N.isFunctionExpression(a)){let u=a.params[0],d=a.params[1];N.isIdentifier(u)&&(c.itemParamName=u.name),N.isIdentifier(d)&&(c.indexParamName=d.name)}s.push(c);let l={kind:"repeat-region",ownerKey:i?.key??"",childKeys:[],sourceRange:It(o),sourceCandidates:s.length>0?s:void 0};return t.regions.push(l),(N.isArrowFunctionExpression(a)||N.isFunctionExpression(a))&&l.childKeys.push(...aa(a,t,n)),l.childKeys}if(N.isConditionalExpression(e)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:cn(e.test,n),conditionSource:at(e.test,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:It(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...Un(e.consequent,t,n)),s.childKeys.push(...Un(e.alternate,t,n)),s.childKeys}if(N.isLogicalExpression(e)&&cN(e.operator)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:cn(e.left,n),conditionSource:at(e.left,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:It(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...Un(e.right,t,n)),s.childKeys}if(N.isParenthesizedExpression(e))return fa(e.expression,t,n);if(N.isJSXElement(e)){let o=la(e,t,n);return o?[o]:[]}return go(e)?ua(e,t,n):[]}function lN(e){let t=e.argument;return t&&(N.isExpression(t)||go(t))?t:null}function mi(e,t){let n=[];for(let r of e){if(N.isReturnStatement(r)){let o=lN(r);o&&n.push({argument:o,statement:r,condition:t});continue}if(N.isIfStatement(r)){let o=N.isBlockStatement(r.consequent)?r.consequent.body:[r.consequent];if(n.push(...mi(o,r.test)),r.alternate){let i=N.isBlockStatement(r.alternate)?r.alternate.body:[r.alternate];n.push(...mi(i,r.test))}continue}if(N.isSwitchStatement(r))for(let o of r.cases){let i=o.test?N.binaryExpression("===",r.discriminant,o.test):r.discriminant;n.push(...mi(o.consequent,i))}}return n}function pa(e){return{routeId:e,rootKeys:[],elements:new Map,regions:[],fileIndex:new Map,version:1,diagnostics:[]}}function Kg(e){let{file:t,source:n,ast:r}=e,o=e.imports.map(f=>f.specifier);if(!N.traverseFast(r,f=>{if(N.isJSXElement(f)||N.isJSXFragment(f))return N.traverseFast.stop}))return{graph:pa(t),localImports:o};let s=new Map,a=[],c=[],l=new Map,u=KC(r);BC(r,{"FunctionDeclaration|FunctionExpression|ArrowFunctionExpression"(f){let g=VC(f);if(!g)return;let p=f.node,m=[];if(N.isArrowFunctionExpression(p))N.isExpression(p.body)||go(p.body)?m=[{argument:p.body,statement:N.returnStatement(N.isExpression(p.body)?p.body:null)}]:N.isBlockStatement(p.body)&&(m=mi(p.body.body));else{let C=p.body;N.isBlockStatement(C)&&(m=mi(C.body))}if(m.length===0){f.skip();return}let y=new Map;pu(XC(r.program.body),du(t,g,s,a,u,[y]),y);let x=new Map;for(let C of p.params)for(let T of Vn(C))hu(x,T);let E=N.isBlockStatement(p.body)?p.body.body:[],b=m[0]?.statement??null;for(let C of E){if(b&&C===b)break;N.isVariableDeclaration(C)&&pu([C],du(t,g,s,a,u,[y,x]),x)}let S=du(t,g,s,a,u,[y,x]);for(let C of m){let T=Un(C.argument,S,n);for(let R of T)c.includes(R)||c.push(R);if(C.condition){let R={kind:"conditional-branch",conditionExpression:cn(C.condition,n),conditionSource:at(C.condition,n,S)};ca(S,"conditional-region","",C.statement,T,[R])}}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 xu(e,t,n,r){return[...e.map(o=>({...o})),{fromFile:t,specifier:n,targetPath:r}]}function ma(e,t,n){return{...e,details:{...e.details??{},entryFile:t,importStack:n.map(r=>({...r}))}}}async function Jg(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 ga(e,t,n,r,o={}){let i=o.maxDepth??10,s=o.version??1,a=o.parseModule??Ue,c=new Map,l=new Map,u=new Map,d=[],f=new Set,g=x=>{let E=`${x.path}\0${x.code}\0${x.message}\0${JSON.stringify(x.details??{})}`;f.has(E)||(f.add(E),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:E,source:b,depth:S,diagnosticEntryFile:C,importStack:T}=x;if(m.has(E))continue;m.add(E),c.set(E,b);let R=o.validationOnly&&S<i?o.validatedImports?.(E,b):void 0,_,A;if(R)_=pa(E),A=R;else{let V=a(E,b);if(!V.ok){g(ma(V.diagnostic,C,T));continue}u.set(E,V.module);let Y=o.validationOnly&&S<i?{graph:pa(E),localImports:V.module.imports.map(ue=>ue.specifier)}:Kg(V.module);_=Y.graph,A=Y.localImports}let w=[...new Set([..._.elements.values()].map(V=>V.importedFrom).filter(V=>typeof V=="string"&>(V)))],D=w.length?await Jg(w,V=>Ps(E,V,r)):[],U=new Map(w.map((V,Y)=>[V,D[Y]]));for(let V of _.elements.values())if(V.importedFrom&>(V.importedFrom)){let Y=V.importedFrom,ue=U.get(Y);ue.ok?(V.importedFrom=ue.path,Mn(ue.path)&&(V.isPublicUiComponent=!0)):Fr(Y,E)||g(ma(ue.diagnostic,C,xu(T,E,Y,ue.diagnostic.path)))}if(l.set(E,_),S>=i)continue;let z=await Jg(A,async V=>{if(km(V))return null;let Y=U.get(V)??await Ps(E,V,r);if(!Y.ok)return Fr(V,E)?null:{diagnostic:ma(Y.diagnostic,C,xu(T,E,V,Y.diagnostic.path))};let ue=Y.path;if(m.has(ue)||Mn(ue))return null;let st=xu(T,E,V,ue);try{let pt=await n(ue);return{entry:{file:ue,source:pt,depth:S+1,diagnosticEntryFile:C,importStack:st}}}catch(pt){return{diagnostic:ma({path:ue,code:"import-read-failed",message:`Failed to read imported file: ${ue}`,details:{fromFile:E,specifier:V,reason:pt instanceof Error?pt.message:String(pt)}},C,st)}}});for(let V of z)V&&"entry"in V?p.push(V.entry):V&&g(V.diagnostic)}let y=uN(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 uN(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 Xg(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 jN}from"@vcp-dev/contracts";import{createHash as dN,randomUUID as Pu}from"node:crypto";import Ye from"node:fs/promises";import qe from"node:path";var th=new WeakMap;function ho(e){return th.get(e)?.()??e.readIndex()}var Qt=1,Eu=1,fN=2,pN="index.json",mN="recovery.json",gN="transaction-journal.json",hN="document-version.json",xa={maxEntries:100,maxSessionBytes:512*1024*1024,maxEntryBytes:128*1024*1024},me={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"},he=class extends Error{constructor(t,n,r){super(n),this.name="FileHistoryStoreError",this.code=t,r?.cause!==void 0&&(this.cause=r.cause)}};function Kn(){return{entries:new Map,blobSizes:new Map}}function ha(e,t){let n={entries:new Map,blobs:new Map,objectBytes:0};for(let r of e)nh(n,r,t);return n}function nh(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 rh(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 oh(e,t={}){let n=ON(e),r=MN(t.limits),o=bu(n),i=FN(n),s=await Tt(i),a=await Tt(o)||s;a||(await RN(n),await CN(n)),a||await BN(n);let c=Kn(),l=await Ea(n,c),u=new Set(a?(await Ra(n)).map(E=>E.stageId):[]);a||await Yg(n,l.entryIds,c);let d=l.digest,f=ha(l.entryIds,c),g=async E=>{let{index:b,sizeBytes:S}=await bi(n);if(dh(b,E),b.digest!==d){let C=Kn();await ch(n,b.entryIds,C,S),f=ha(b.entryIds,C),d=b.digest}return{...Ca(b),totalBytes:f.objectBytes+S}},p=async E=>{_u(E),await g(),await Wg(n,f,[E.entryId],E.blobIds,E.stageId),await ba(n,E.stageId)},m=async(E,b)=>{let S=await g(b);sh(E,S.entryIds.length);let C=Kn();for(let T of S.entryIds.slice(Math.min(S.cursor,E)+1,Math.max(S.cursor,E)+1))await hi(n,T,C);return S},y=async()=>{if(await Tt(o)||s)throw new he(me.RECOVERY_PENDING,"history store requires explicit recovery before accepting writes")},x={rootDir:n,recoveryRequired:a,async readDocumentVersion(){return Qg(n)},async writeDocumentVersion(E){if(await y(),!Number.isInteger(E)||E<0)throw new he(me.INVALID_SCHEMA,"document version must be a non-negative integer");let b=await Qg(n);E<=b||await gi(gh(n),{schemaVersion:1,version:Math.max(b,E)})},async stageAppend(E,b={}){await y();let S=await bN(E,r),C={schemaVersion:Eu,stageId:Pu(),entryId:S.entryId,blobIds:S.blobs.map(T=>T.digest)};try{await EN(n,S),await vN(n,C,b.durableManifest!==!1)}catch(T){try{await p(C)}catch(R){throw new he(me.INDEX_CORRUPT,"staged history cleanup failed after preparation error",{cause:R})}throw T}return{stageId:C.stageId,entryId:C.entryId,blobIds:C.blobIds}},async discardStage(E){await y(),Iu(E);let b=await Su(n,E);b&&await p(b)},async previewStagedAppend(E,b){await y();let S=await g(b);return(await zg(n,r,E,S,f)).transition},async previewCursor(E,b){await y();let S=await m(E,b);return ih(S,S.entryIds,E)},async publishStagedAppend(E,b,S){if(await y(),va(E,"entryId"),S){Iu(S);let A=await Su(n,S);if(!A||A.entryId!==E)throw new he(me.INVALID_SCHEMA,"history stage does not match the published entry")}let C=await g(b),T=f,R=await zg(n,r,E,C,T),_=await qg({rootDir:n,previousDigest:R.current.digest,entryIds:R.entryIds,cursor:R.cursor,readback:async()=>Zg(n,R.usage),afterWrite:async()=>{S?await ba(n,S):await kN(n,E),await Wg(n,R.usage,[...T.entries.keys()].filter(A=>!R.usage.entries.has(A)),[...T.blobs.keys()].filter(A=>!R.usage.blobs.has(A)))}});return f=R.usage,d=_.digest,_},async append(E){await y();let b=await g(),S=await x.stageAppend(E);try{return await x.publishStagedAppend(S.entryId,b.digest,S.stageId)}catch(C){throw await x.discardStage(S.stageId),C}},async readEntry(E){return va(E,"entryId"),hi(n,E)},async readBlob(E){va(E,"blobId");let b=await yh(n,E),S=await yi(b,me.NOT_FOUND,"blob");return mh(S,E,b),S},async readIndex(){let E=Kn(),b=await Ea(n,E);return f=ha(b.entryIds,E),d=b.digest,b},async readStatus(){let E=await Sa(n);return{canUndo:E.undoIds.length>0,canRedo:E.redoIds.length>0,undoDepth:E.undoIds.length,redoDepth:E.redoIds.length,cursor:E.cursor,recoveryRequired:await Tt(o)||await Tt(i)}},async readUndoRedoIds(){let E=await Sa(n);return{undoIds:E.undoIds,redoIds:E.redoIds,currentId:E.currentId}},async setCursor(E,b){await y();let S=await m(E,b),C=await qg({rootDir:n,previousDigest:S.digest,entryIds:S.entryIds,cursor:E,readback:async()=>Zg(n,f)});return d=C.digest,C},async markRecoveryRequired(E){await Tt(o)||await gi(bu(n),{schemaVersion:Qt,reason:LN(E),createdAt:new Date().toISOString()})},async clearRecoveryRequired(){await Ye.rm(bu(n),{force:!0})},async readTransactionJournal(){return await Tt(i)?ya(i):null},async writeTransactionJournal(E){await y(),hh(E);try{await gi(i,E)}catch(S){let C=await ya(i).catch(()=>null);if(C&&Buffer.from(wt(C)).equals(Buffer.from(wt(E))))return;throw C?new he(me.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous",{cause:S}):S}let b=await ya(i);if(!Buffer.from(wt(b)).equals(Buffer.from(wt(E))))throw new he(me.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous")},async clearTransactionJournal(E){let b=await Tt(i)?await ya(i):null;if(b&&b.transactionId!==E)throw new he(me.INVALID_SCHEMA,"transaction journal changed concurrently");try{await Ye.rm(i,{force:!0})}catch(S){if(!await Tt(i))return;throw S}if(await Tt(i))throw new he(me.INDEX_CORRUPT,"transaction journal clear outcome is ambiguous");s=!1},async cleanupTmp(){await y();for(let S of u)await ba(n,S),u.delete(S);await NN(n);let E=Kn(),b=await Ea(n,E);await Yg(n,b.entryIds,E),f=ha(b.entryIds,E),d=b.digest}};return th.set(x,()=>Sa(n)),x}async function zg(e,t,n,r,o){va(n,"entryId");let i=Kn(),s=await hi(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))rh(a,u);nh(a,s.id,i),c.push(s.id);let l=SN(c,t,a);return{current:r,entryIds:l.entryIds,cursor:l.cursor,usage:a,transition:ih(r,l.entryIds,l.cursor)}}function ih(e,t,n){return sh(n,t.length),{expectedIndexDigest:e.digest,publishedIndexDigest:yN(t,n),publishedCursor:n,publishedCurrentId:t[n]??null}}function yN(e,t){return sr(wt({schemaVersion:Qt,entryIds:e,cursor:t}))}function sh(e,t){if(!Number.isInteger(e)||e<-1||e>=t)throw new he(me.INVALID_SCHEMA,`history cursor is out of bounds: ${e}`)}function xN(e){if(!ln(e))return!1;let t=e.publishedCursor,n=e.publishedCurrentId;return!Mt(e.expectedIndexDigest)||!Mt(e.publishedIndexDigest)||!Number.isInteger(t)||t<-1||n!==null&&!Mt(n)?!1:t===-1?n===null:Mt(n)}async function bN(e,t){if(!e.kind.trim())throw new he(me.INVALID_JSON,"history entry kind must not be empty");let n=[],r=[];for(let c of e.blobs??[]){if(!c.name.trim())throw new he(me.INVALID_JSON,"history blob name must not be empty");let l=wN(c.data),u=sr(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:Qt,kind:e.kind,manifest:e.manifest,blobs:r},i=wt({...o}),s=sr(i),a=i.byteLength+n.reduce((c,l)=>c+l.sizeBytes,0);if(a>t.maxEntryBytes)throw new he(me.CAPACITY_EXCEEDED,`history entry exceeds maxEntryBytes (${a} > ${t.maxEntryBytes})`);return{entryBody:o,entryId:s,blobs:n}}async function EN(e,t){let n=Ou(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=>Hg(Fu(e,c.digest),c.bytes,{kind:"blob",digest:c.digest},Du(e,c.digest))),Hg(n,wt(r),{kind:"entry",digest:t.entryId},Lu(e,t.entryId))],a=(await Promise.allSettled(i)).find(c=>c.status==="rejected");if(a)throw a.reason}async function Hg(e,t,n,r){let o=await Cu(e)??(r?await Cu(r):null);if(o!==null){if(Buffer.compare(o,t)!==0)throw new he(n.kind==="blob"?me.BLOB_CORRUPT:me.ENTRY_CORRUPT,`${n.kind} content mismatch for ${n.digest}`);return}await fh(e,t)}function SN(e,t,n){let r=[...e],o=r.length-1;for(;;){if(n.objectBytes+wt(uh(r,o)).byteLength<=t.maxSessionBytes&&r.length<=t.maxEntries)return{entryIds:r,cursor:o};if(o<=0||r.length===0)throw new he(me.CAPACITY_EXCEEDED,"history store exceeds capacity limits and the current entry cannot be trimmed");rh(n,r.shift()),o-=1}}async function vN(e,t,n){_u(t);let r=wu(e,t.stageId);if(n){await gi(r,t);return}await TN(r,t)}async function Su(e,t){let n=await Cu(wu(e,t));if(n===null)return null;let r=Ei(Buffer.from(n).toString("utf8"),`history stage ${t}`),o=_u(r);if(o.stageId!==t)throw new he(me.INVALID_SCHEMA,`history stage id mismatch: ${t}`);return o}async function Ra(e){let t=[];for(let n of await ka(Tu(e))){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);Iu(r);let o=await Su(e,r);o&&t.push(o)}return t}async function Wg(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 Ra(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 Gg(Ou(e,a),Lu(e,a));for(let a of new Set(r))!t.blobs.has(a)&&!s.has(a)&&await Gg(Fu(e,a),Du(e,a));await Nu(Si(e)),await Nu(vi(e))}async function ba(e,t){await vu(wu(e,t)),await IN(e)}async function IN(e){try{await Ye.rmdir(Tu(e))}catch(t){if(Ii(t)||ln(t)&&t.code==="ENOTEMPTY")return;throw t}}async function kN(e,t){for(let n of await Ra(e))n.entryId===t&&await ba(e,n.stageId)}async function vu(e){if(await Ye.rm(e,{force:!0}),await Tt(e))throw new he(me.INDEX_CORRUPT,`unable to remove staged history object: ${e}`)}async function Gg(e,t){await vu(e),await vu(t)}function _u(e){if(!ln(e)||e.schemaVersion!==Eu||typeof e.stageId!="string"||!ah(e.stageId)||!Mt(e.entryId))throw new he(me.INVALID_SCHEMA,"history stage schema is invalid");let t=ph(e.blobIds,"history stage blobIds");return{schemaVersion:Eu,stageId:e.stageId,entryId:e.entryId,blobIds:t}}function Iu(e){if(!ah(e))throw new he(me.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 Yg(e,t,n=Kn()){let r=new Set(t),o=new Set;for(let l of t){let u=await hi(e,l,n);for(let d of u.blobs)o.add(d.digest)}for(let l of await Ra(e)){r.add(l.entryId);for(let u of l.blobIds)o.add(u)}let i=Si(e),s=await ka(i);for(let l of s){if(!l.endsWith(".json"))continue;let u=eh(l.slice(0,-5));u&&!r.has(u)&&await Ia(qe.join(i,l))}let a=vi(e),c=await ka(a);for(let l of c){let u=eh(l);u&&!o.has(u)&&await Ia(qe.join(a,l))}}async function Ea(e,t=Kn()){let{index:n,sizeBytes:r}=await bi(e),{totalBytes:o}=await ch(e,n.entryIds,t,r);return{...Ca(n),totalBytes:o}}async function Zg(e,t){let{index:n,sizeBytes:r}=await bi(e);return{...Ca(n),totalBytes:t.objectBytes+r}}async function bi(e){let t=Au(e),n=await yi(t,me.NOT_FOUND,"index"),r=Ei(Buffer.from(n).toString("utf8"),"index");return{index:PN(r),sizeBytes:n.byteLength}}async function Sa(e){return Ca((await bi(e)).index)}function Ca(e){let t=[...e.entryIds],n=t.slice(0,e.cursor+1).reverse(),r=t.slice(e.cursor+1);return{schemaVersion:Qt,digest:e.digest,entryIds:t,cursor:e.cursor,currentId:t[e.cursor]??null,undoIds:n,redoIds:r}}async function ch(e,t,n,r){let o=0,i=new Set;o+=r??(await bi(e)).sizeBytes;for(let s of new Set(t)){let a=await hi(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 hi(e,t,n=Kn()){let r=n.entries.get(t);if(r)return r.entry;let o=await DN(e,t),i=await yi(o,me.NOT_FOUND,"entry"),s=Ei(Buffer.from(i).toString("utf8"),`entry ${t}`),a=_N(s);if(a.id!==t)throw new he(me.ENTRY_CORRUPT,`entry id mismatch for ${t}`);if(sr(wt({schemaVersion:a.schemaVersion,kind:a.kind,manifest:a.manifest,blobs:a.blobs}))!==t)throw new he(me.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 yh(e,d),g=await yi(f,me.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(E){f.push({index:x,error:E})}}}),m=await Promise.allSettled(p),y=f.sort((x,E)=>x.index-E.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 lh(e,t,n){await gi(Au(e),uh(t,n))}function uh(e,t){return{schemaVersion:Qt,digest:sr(wt({schemaVersion:Qt,entryIds:e,cursor:t})),entryIds:e,cursor:t}}function dh(e,t){if(t!==void 0&&e.digest!==t)throw new he(me.INVALID_SCHEMA,`history index changed concurrently (expected ${t}, current ${e.digest})`)}async function qg(e){dh(await Sa(e.rootDir),e.previousDigest);let t=sr(wt({schemaVersion:Qt,entryIds:e.entryIds,cursor:e.cursor}));try{await lh(e.rootDir,e.entryIds,e.cursor),await e.afterWrite?.();let n=await e.readback();if(n.digest!==t)throw new he(me.INDEX_CORRUPT,"history index readback did not match the published transition");return n}catch(n){let r=await Ea(e.rootDir).catch(()=>null);if(r?.digest===t)return r;throw r?.digest===e.previousDigest?n:new he(me.INDEX_CORRUPT,"history index publish outcome is ambiguous",{cause:n})}}async function RN(e){await Ye.mkdir(e,{recursive:!0}),await Ye.mkdir(Si(e),{recursive:!0}),await Ye.mkdir(vi(e),{recursive:!0}),await Ye.mkdir(xi(e),{recursive:!0})}async function CN(e){await Ye.rm(xi(e),{recursive:!0,force:!0}),await Ye.mkdir(xi(e),{recursive:!0})}async function NN(e){let t=xi(e);await Ye.mkdir(t,{recursive:!0});for(let n of await ka(t))n!=="stages"&&await Ye.rm(qe.join(t,n),{recursive:!0,force:!0})}function PN(e){if(!ln(e))throw new he(me.INDEX_CORRUPT,"index.json must be an object");if(e.schemaVersion!==Qt)throw new he(me.INVALID_SCHEMA,`unsupported index schemaVersion: ${String(e.schemaVersion)}`);let t=ph(e.entryIds,"index.entryIds"),n=e.cursor;if(!Number.isInteger(n)||n<-1||n>=t.length)throw new he(me.INDEX_CORRUPT,"index cursor is out of bounds");let r=n,o=e.digest;if(!Mt(o))throw new he(me.INDEX_CORRUPT,"index digest is invalid");let i=sr(wt({schemaVersion:Qt,entryIds:t,cursor:r}));if(o!==i)throw new he(me.INDEX_CORRUPT,"index digest mismatch");return{schemaVersion:Qt,digest:o,entryIds:t,cursor:r}}function _N(e){if(!ln(e))throw new he(me.ENTRY_CORRUPT,"entry must be an object");if(e.schemaVersion!==Qt)throw new he(me.INVALID_SCHEMA,`unsupported entry schemaVersion: ${String(e.schemaVersion)}`);let t=e.id;if(!Mt(t))throw new he(me.ENTRY_CORRUPT,"entry id is invalid");let n=e.kind;if(typeof n!="string"||n.trim().length===0)throw new he(me.ENTRY_CORRUPT,"entry kind is invalid");let r=Ru(e.manifest,"entry.manifest"),o=AN(e.blobs);return{id:t,schemaVersion:Qt,kind:n,manifest:r,blobs:o}}function AN(e){if(!Array.isArray(e))throw new he(me.ENTRY_CORRUPT,"entry blobs must be an array");return e.map((t,n)=>{if(!ln(t))throw new he(me.ENTRY_CORRUPT,`entry blob ref ${n} must be an object`);let r=t.name;if(typeof r!="string"||r.trim().length===0)throw new he(me.ENTRY_CORRUPT,`entry blob ref ${n} name is invalid`);let o=t.digest;if(!Mt(o))throw new he(me.ENTRY_CORRUPT,`entry blob ref ${n} digest is invalid`);let i=t.sizeBytes;if(!Number.isInteger(i)||i<0)throw new he(me.ENTRY_CORRUPT,`entry blob ref ${n} sizeBytes is invalid`);return{name:r,digest:o,sizeBytes:i}})}async function gi(e,t){await fh(e,wt(t))}async function TN(e,t){let n=qe.dirname(e),r=qe.basename(e),o=qe.join(n,`.${r}.${process.pid}.${Pu()}.tmp`);await Ye.mkdir(n,{recursive:!0});try{await Ye.writeFile(o,wt(t),{flag:"wx"}),await Ye.rename(o,e)}finally{await Ia(o)}}async function fh(e,t){let n=qe.dirname(e),r=qe.basename(e),o=qe.join(n,`.${r}.${process.pid}.${Pu()}.tmp`);await Ye.mkdir(n,{recursive:!0});try{let i=await Ye.open(o,"wx");try{await i.writeFile(t),await i.sync()}finally{await i.close()}await Ye.rename(o,e),await Nu(n)}finally{await Ia(o)}}function wt(e){return Buffer.from(JSON.stringify(ku(e)),"utf8")}function ku(e){if(Array.isArray(e))return e.map(t=>ku(t));if(ln(e)){let t={};for(let n of Object.keys(e).sort())t[n]=ku(e[n]);return t}return e}function Ei(e,t){try{return JSON.parse(e)}catch(n){throw new he(me.INVALID_JSON,`${t} is not valid JSON`,{cause:n})}}function Ru(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=>Ru(n,t));if(ln(e)){let n={};for(let[r,o]of Object.entries(e))n[r]=Ru(o,t);return n}break}throw new he(me.INVALID_JSON,`${t} must be JSON-serializable`)}function ph(e,t){if(!Array.isArray(e))throw new he(me.INDEX_CORRUPT,`${t} must be an array`);return e.map((n,r)=>{if(!Mt(n))throw new he(me.INDEX_CORRUPT,`${t}[${r}] is invalid`);return n})}function va(e,t){if(!Mt(e))throw new he(me.INVALID_PATH,`${t} must be a sha256 digest`)}function Mt(e){return typeof e=="string"&&/^sha256:[a-f0-9]{64}$/u.test(e)}function sr(e){return`sha256:${dN("sha256").update(e).digest("hex")}`}function wN(e){return typeof e=="string"?Buffer.from(e,"utf8"):Buffer.from(e)}async function yi(e,t,n){try{return await Ye.readFile(e)}catch(r){throw new he(t,`${n} not found: ${e}`,{cause:r})}}async function Cu(e){try{return await Ye.readFile(e)}catch(t){if(Ii(t))return null;throw t}}function mh(e,t,n){if(sr(e)!==t)throw new he(me.BLOB_CORRUPT,`blob hash mismatch for ${n}`)}async function Tt(e){try{return await Ye.access(e),!0}catch(t){if(Ii(t))return!1;throw t}}async function Ia(e){try{await Ye.rm(e,{force:!0,recursive:!0})}catch{}}async function Nu(e){try{let t=await Ye.open(e,"r");try{await t.sync()}finally{await t.close()}}catch{}}async function ka(e){try{return await Ye.readdir(e)}catch(t){if(Ii(t))return[];throw t}}function ON(e){if(typeof e!="string"||e.trim().length===0)throw new he(me.INVALID_ROOT,"history store rootDir must be a non-empty string");return qe.resolve(e)}function Au(e){return qe.join(e,pN)}function bu(e){return qe.join(e,mN)}function FN(e){return qe.join(e,gN)}function gh(e){return qe.join(e,hN)}async function Qg(e){try{let t=await Ye.readFile(gh(e),"utf8"),n=Ei(t,"document version");if(!ln(n)||n.schemaVersion!==1||!Number.isInteger(n.version)||n.version<0)throw new he(me.INVALID_SCHEMA,"document version schema is invalid");return n.version}catch(t){if(Ii(t))return 0;throw t}}async function ya(e){let t=await yi(e,me.RECOVERY_PENDING,"transaction journal"),n=Ei(Buffer.from(t).toString("utf8"),"transaction journal");return hh(n),n}function hh(e){if(!ln(e)||e.schemaVersion!==fN||typeof e.transactionId!="string"||e.transactionId.length===0||typeof e.operationId!="string"||e.operationId.length===0||!["prepared","files-written","history-published"].includes(e.phase)||!xN(e.historyTransition)||!Array.isArray(e.files))throw new he(me.INVALID_SCHEMA,"transaction journal schema is invalid");for(let t of e.files)if(!ln(t)||typeof t.path!="string"||t.path.length===0||t.preDigest!==null&&!Mt(t.preDigest)||t.postDigest!==null&&!Mt(t.postDigest))throw new he(me.INVALID_SCHEMA,"transaction journal file digest is invalid")}function LN(e){return e.replace(/[\r\n]+/g," ").slice(0,512)}function Si(e){return qe.join(e,"entries")}function vi(e){return qe.join(e,"blobs")}function xi(e){return qe.join(e,"tmp")}function Tu(e){return qe.join(xi(e),"stages")}function wu(e,t){return qe.join(Tu(e),`${t}.json`)}function Ou(e,t){return qe.join(Si(e),`${bh(t)}.json`)}function Fu(e,t){return qe.join(vi(e),bh(t))}function Lu(e,t){return qe.join(Si(e),`${t}.json`)}function Du(e,t){return qe.join(vi(e),t)}async function DN(e,t){return xh(Ou(e,t),Lu(e,t))}async function yh(e,t){return xh(Fu(e,t),Du(e,t))}async function xh(e,t){return await Tt(e)?e:await Tt(t)?t:e}function bh(e){return e.slice(7)}function eh(e){let t=e.startsWith("sha256:")?e:`sha256:${e}`;return Mt(t)?t:null}function ln(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ii(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function MN(e){return{maxEntries:e?.maxEntries??xa.maxEntries,maxSessionBytes:e?.maxSessionBytes??xa.maxSessionBytes,maxEntryBytes:e?.maxEntryBytes??xa.maxEntryBytes}}async function BN(e){let t=Au(e);await Tt(t)||await lh(e,[],-1)}var $N={affectedCompositions:[]};function kh(e){let t=null,n=new WeakMap;async function r(){return t??=VN(e),t}async function o(i){if(!i)return null;let s=Mu(i);return s?UN(e,s):i}return{async prepareAppend(i){let s=await ho(e),a=await e.stageAppend(vh(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 ho(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 ho(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);Eh(c,i.historyTransition),i.entry.historyId=s.entryId,Object.assign(a,yo(c))}else{if(s.cursor===void 0)throw new Error("prepared cursor is missing");let c=i.kind==="undo"?a.undo:a.redo;if(Mu(c.at(-1))!==Mu(i.entry))throw new Error("history state changed before publish");let l=await e.setCursor(s.cursor,s.expectedDigest);Eh(l,i.historyTransition),Object.assign(a,yo(l))}n.delete(i)},async discardPrepared(i){let s=n.get(i);if(!s)return;let a=i.historyTransition;if(a){let c=await ho(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,yo(d));return}catch(d){throw s.redo.push(i),d}}let c=await e.append(vh(i)),l=c.currentId;if(!l)throw new Error("history store did not publish an entry");i.historyId=l,Object.assign(s,yo(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,yo(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 Eh(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 Mu(e){return typeof e=="string"?e:e?.historyId}async function VN(e){let t=await ho(e);return yo(t)}function yo(e){return{undo:[...e.undoIds].reverse(),redo:[...e.redoIds].reverse(),entryIds:[...e.entryIds],cursor:e.cursor}}async function UN(e,t){let n=await e.readEntry(t),r=KN(n),o=r.provenance??$N;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 Sh(e,n,r.preSnapshots),postSnapshots:await Sh(e,n,r.postSnapshots)}}async function Sh(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(zN(r,o.blobName))).toString("utf8"):"";return{file:o.file,content:i,version:o.version,exists:o.exists,...o.sha256?{sha256:o.sha256}:{}}}))}function vh(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=JN(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 KN(e){if(!Ch(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:Rh(t.provenance)}:{},preSnapshots:Ih(t.preSnapshots,"preSnapshots"),postSnapshots:Ih(t.postSnapshots,"postSnapshots")}}function JN(e){if(e.provenance!==void 0)return Rh(e.provenance);if(e.composition)return{initiatingComposition:e.composition,affectedCompositions:[]}}function Rh(e){let t=jN.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 Ih(e,t){return e.map((n,r)=>{if(!Ch(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&&!XN(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 XN(e){return/^sha256:[0-9a-f]{64}$/.test(e)}function zN(e,t){let n=e.get(t);if(!n)throw new Error(`durable history blob is missing: ${t}`);return n}function Ch(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{GeneratedSiteCapabilitiesSchema as HN}from"@vcp-dev/contracts";var Nh={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 Bu(){let e=HN.safeParse(Nh);return e.success?e.data:null}import{randomBytes as WN}from"node:crypto";import Na from"node:path";import{parse as Fh}from"@babel/parser";import GN from"@babel/traverse";import*as Lh from"@babel/types";import{COMPONENT_I18N_FILE_SUFFIX as $u,PageResourceArtifactSchema as YN,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as ZN,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as qN,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as QN,parseComponentI18nResourcesJson as eP}from"@vcp-dev/contracts";var Vu="{{$INSTANCE}}",tP=/\{\{\$PAGE_ROUTE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,nP=/\{\{\$PAGE_TITLE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,Uu="components/site/generated",rP=/\.(?:tsx?|json)$/,oP=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,iP=["react","react/","next","next/","lucide-react","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],sP=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),ju=GN,aP=typeof ju=="function"?ju:ju.default;async function Ku(e){let t=YN.safeParse(e.artifact);if(!t.success)return Ze("Page resource artifact failed contract validation.");let n=t.data,r=e.randomHex??(()=>WN(4).toString("hex")),o=Math.max(1,Math.min(e.maxAttempts??5,5)),i=hP(r());if(!i)return Ze("Random instance suffix must be 8 lowercase hex chars.");let s=`${yP(n.resource_id)}-${i}`,a=new Map,c=new Map,l=[];for(let b of n.pages){let S=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/${S}/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(S=>S.component_id)));for(let b of n.components){if(!y.has(b.component_id))continue;let S=Ph({materialization:b.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c});if(!S.ok)return S;for(let C of S.files){let T=Ah(C,d,u);if(T)return T}f.add(S.entry),p.set(S.entry,S.entryExport),g.set(b.component_id,S.entry)}for(let[b,S]of n.pages.entries()){let C=l[b],T=Ph({materialization:S.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c,pageEntryTarget:C.route_file_path,pageTitle:C.title});if(!T.ok)return T;for(let R of T.files){let _=Ah(R,d,u);if(_)return _}f.add(T.entry),p.set(T.entry,T.entryExport),m.push({entry:T.entry,declaredComponentIds:new Set(S.components.map(R=>R.component_id))})}let x=lP(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?Ku({...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 E=uP(u);return E||(u.sort((b,S)=>b.file.localeCompare(S.file)),{ok:!0,packageInstanceId:s,pages:l,files:u})}function Ph(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:_h(o.pathTemplate,e.packageInstanceId);if(!s)return Ze("Materialization path cannot be mapped into the package namespace.",o.pathTemplate);let a=cP(o.content,e.packageInstanceId,e.routeByPage,e.titleByPage);if(!a.ok)return a;let c=i&&e.pageTitle!==void 0?fP(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??_h(t,e.packageInstanceId);return!r||!n.some(o=>o.file===r)?Ze("Materialization entry must match one controlled source file.",t):{ok:!0,files:n,entry:r,entryExport:e.materialization.entry.export}}function cP(e,t,n,r){let o,i=e.replace(tP,(c,l)=>{let u=n.get(l);return u||(o=l,c)});if(o)return Ze(`Page route placeholder references unknown template page: ${o}`);let s=i.replace(nP,(c,l)=>{let u=r.get(l);return u?JSON.stringify(u):(o=l,c)});if(o)return Ze(`Page title placeholder references unknown template page: ${o}`);let a=s.replaceAll(Vu,t);return a.includes("{{$PAGE_ROUTE:")||a.includes("{{$PAGE_TITLE:")||a.includes("{{$INSTANCE}}")?Ze("Materialization contains an unresolved placeholder."):{ok:!0,data:a}}function _h(e,t){let n=`${Uu}/${t}`;if(e.split(Vu).length>2)return null;let o=e.replace(Vu,t),i=`${Uu}/${t}/`,s=o.startsWith(i)?o:`${n}/${o}`,a=Na.posix.normalize(s);return a!==s||!a.startsWith(`${n}/`)||!rP.test(a)||oP.test(a)?null:a}function Ah(e,t,n){return t.has(e.file)?Ze(`Page resource materializations resolve duplicate target: ${e.file}`,e.file):(t.add(e.file),n.push(e),null)}function lP(e,t,n,r,o,i){let s=new Set(e.map(g=>g.file)),a=`${Uu}/${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 Ze("Materialization JSON file must contain valid JSON.",g.file)}if(g.file.endsWith($u)&&!eP(g.content).success)return Ze("Materialization component i18n resources are invalid.",g.file);continue}try{let p=Fh(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,E=mP(g.file,x,s,a);if(!E.allowed)return Ze(`Materialization import is outside the controlled package: ${x}`,g.file);E.internalPath&&c.get(g.file).add(E.internalPath)}let m;if(aP(p,{Identifier(y){y.isReferencedIdentifier()&&sP.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 Ze(`Materialization source uses forbidden capability: ${m}`,g.file)}catch{return Ze("Materialization source must parse as TS/TSX.",g.file)}}if([...t].some(g=>!s.has(g)))return Ze("Materialization entry is outside the controlled package.");for(let g of t)if(g.endsWith(".json"))return Ze("Materialization JSON files cannot be package entries.");for(let[g,p]of i){let m=l.get(g);if(!m||!dP(m,p))return Ze("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=Oh(g.entry,c);for(let m of g.declaredComponentIds){let y=r.get(m);if(!y||!p.has(y))return Ze(`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 Ze(`Page entry imports undeclared component: ${y}`,g.entry)}}let d=new Set;for(let g of t)for(let p of Oh(g,c))d.add(p);if(d.size!==e.length)return Ze("Every materialization file must be reachable from a package entry.");let f=gP(e,l,c);return f||{ok:!0}}function uP(e){if(e.length>ZN)return Ze("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>qN)return Ze("Page resource file exceeds the content byte limit.",n.file);t+=r}return t>QN?Ze("Page resource exceeds the aggregate content byte limit."):null}function dP(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 fP(e,t,n){let r;try{r=Fh(e,{sourceType:"module",sourceFilename:n,plugins:["jsx","typescript"]})}catch{return Ze("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=Th(s.init);if(a?.type!=="ObjectExpression")return{ok:!0,data:e};let c=a.properties.find(u=>u.type==="ObjectProperty"&&!u.computed&&pP(u.key));if(!c||c.type!=="ObjectProperty")return{ok:!0,data:e};let l=Th(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 Th(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression"||t?.type==="TSNonNullExpression";)t=t.expression;return t&&Lh.isExpression(t)?t:null}function pP(e){return e.type==="Identifier"&&e.name==="title"||e.type==="StringLiteral"&&e.value==="title"}function mP(e,t,n,r){if(t.startsWith(`@/${r}/`)){let s=t.slice(2),a=wh(s,n);return a?{allowed:!0,internalPath:a}:{allowed:!1}}if(!t.startsWith("."))return{allowed:iP.some(s=>s.endsWith("/")?t.startsWith(s):t===s)};if(t.includes("\\")||t.includes("\0"))return{allowed:!1};let o=Na.posix.normalize(Na.posix.join(Na.posix.dirname(e),t)),i=wh(o,n);return i&&(i.startsWith(`${r}/`)||i.startsWith("app/"))?{allowed:!0,internalPath:i}:{allowed:!1}}function wh(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 gP(e,t,n){let r=new Set(e.map(o=>o.file));for(let o of e){if(!o.file.endsWith($u))continue;let i=o.file.slice(0,-$u.length),s=[`${i}.tsx`,`${i}.ts`].find(u=>r.has(u));if(!s)return Ze("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 Ze("Component i18n resources must have exactly one same-name Client Component static importer.",s)}return null}function Oh(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 hP(e){return/^[a-f0-9]{8}$/.test(e)?e:null}function yP(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"page-resource"}function Ze(e,t){return{ok:!1,code:"MATERIALIZATION_REJECTED",message:e,...t?{path:t}:{}}}import{randomBytes as KP}from"node:crypto";import Xn from"node:path";import{parse as JP}from"@babel/parser";import XP from"@babel/traverse";import{COMPONENT_I18N_FILE_SUFFIX as _a,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as Uh,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as zP,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as HP,SiteEditMaterializationSchema as WP,parseComponentI18nResourcesJson as GP}from"@vcp-dev/contracts";import{parse as OP}from"@babel/parser";import FP from"@babel/traverse";import{GeneratedSiteCapabilitiesSchema as LP,FormDefinitionIdSchema as DP}from"@vcp-dev/contracts";var Mh={colorMixPolicy:"always",includeExtendedColorFunctions:!0},Bh=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\(/i,jh=/\b(?:bg-black|bg-white|text-white|text-black)(?:\b|\/)/g,xP=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke)-\[#(?:[0-9a-fA-F]{3,8})\](?:\/\d+)?/g,bP=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*#[0-9a-fA-F]{3,8}[^'"]*['"]/g,EP=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*rgba?\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,SP=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,vP=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,IP=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*(?:oklch|lab|lch|hsla?)\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,kP=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*(?:oklch|lab|lch|hsla?)\([^)]+\)[^'"]*['"]/gi,RP=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*color-mix\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,CP=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*color-mix\([^'"]*['"]/gi,NP=/\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,PP=/var\(\s*--(?:_|private-|vcp-)[^)]+\)/gi,_P=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\([^)]*\)/gi;function Ju(e,t){let n=Pa([...en(e,xP),...en(e,bP),...en(e,EP),...en(e,t.includeRgbBackgroundImage?SP:vP),...t.includeExtendedColorFunctions?[...en(e,IP),...en(e,kP)]:[]]),r=Pa([...en(e,RP),...en(e,CP)]).filter(o=>t.colorMixPolicy==="always"||Bh.test(o));return n.push(...r.filter(o=>!n.includes(o))),t.rejectTailwindPalette&&n.push(...en(e,NP).filter(o=>!n.includes(o))),t.rejectAnyRawColorLiteral&&n.push(...en(e,_P).filter(o=>!n.includes(o))),{hardCodedSurfaceHits:Pa(en(e,jh)),hardCodedSurfaceOccurrences:wP(e),rawColorHits:n,privateTokenHits:t.rejectPrivateTokens?AP(e):[]}}function AP(e){return Pa(en(e,PP))}function en(e,t){return e.match(new RegExp(t.source,t.flags))??[]}var Dh=160,TP=/((?:[a-z][a-z0-9-]*(?:\[[^\]]*\])?:)+)$/;function wP(e){let t=new RegExp(jh.source,"g"),n=[0];for(let s=0;s<e.length;s+=1)e[s]===`
|
|
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=TP.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>Dh?`${g.slice(0,Dh-1)}\u2026`:g})}return o}function Pa(e){return[...new Set(e)]}var MP=["@/components/site/","@/lib/generated/","@/lib/cms","@/lib/cms/"],BP=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),$h=new Set(["require","module","exports","__dirname","__filename"]),Xu=FP,jP=typeof Xu=="function"?Xu:Xu.default;function Hu(e,t={}){let n=[],r=$P(t.hostCapabilities),o=Ju(e,t.style??Mh),i;try{i=OP(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"&&UP(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 jP(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(zu(u.node))},OptionalMemberExpression(u){l(zu(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)&&DP.safeParse(/^@\/components\/site\/generated\/forms\/form-([^/]+)$/u.exec(u)?.[1]).success)&&!(u.startsWith("./")||u.startsWith("../"))){if(t.allowSiteOwnedImports&&MP.some(d=>d.endsWith("/")?u.startsWith(d):u===d)){c(u);return}r?VP(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||!BP.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:$h.has(u)?"commonjs-forbidden":"browser-global-forbidden",message:$h.has(u)?`Generated source cannot depend on the CommonJS global ${u}.`:`Generated source cannot depend on the restricted global ${u}.`,name:u})}}}function $P(e){if(e==null)return null;let t=LP.safeParse(e);return t.success?t.data:null}function VP(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)):Vh(n)===Vh(o)})}function Vh(e){return e.replace(/\.(?:jsx?|tsx?|json)$/i,"")}function UP(e){return e.hardCodedSurfaceHits.length>0||e.rawColorHits.length>0||e.privateTokenHits.length>0}function zu(e){return e.type==="Identifier"?e.name:e.type==="MemberExpression"||e.type==="OptionalMemberExpression"?zu(e.object):null}var Wh="components/site/generated",Kh="{{$INSTANCE}}",Aa=5,YP=/^[a-z][a-z0-9-]{0,48}$/,ZP=/^[a-f0-9]{8}$/,Jh=/\.tsx?$/,qP=/\.json$/,QP=/\.(?:tsx?|json)$/,e_=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,Wu=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),Gu=XP,t_=typeof Gu=="function"?Gu:Gu.default;function n_(e){let t=Array.isArray(e.manifest.files)?e.manifest.files:[];if(t.length>Uh)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file count exceeds the reusable limit."}};let n=y_(t);if(n)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Static prefab resolves duplicate target path: ${n}`,path:n}};let r=WP.safeParse(e.manifest);if(!r.success)return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab manifest failed schema validation."}};let o=m_(e.generatedRoot);if(!o)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Generated root must be ${Wh}.`,path:e.generatedRoot}};if(!Gh(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=zh(r.data.files),s=zh(e.controlledFiles);if(!x_(i,s))return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Controlled file list must exactly match the manifest file templates."}};if(i.size>Uh)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>zP)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>HP?{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 r_(e){let t=n_(e);if(!t.ok)return t;let n=t.data.generatedRoot,r=Gh(e.manifest.instanceBaseName),o=Math.max(1,Math.min(Aa,e.maxAttempts??Aa));for(let i=0;i<o;i+=1){let s=g_(e.instanceNameGenerator?.()??KP(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=Zh(n,a),l=o_({manifest:e.manifest,generatedRoot:n,instanceName:a,instanceRoot:c,hostCapabilities:e.hostCapabilities??null,availableHostDependencies:e.availableHostDependencies});if(!l.ok)return l;if(!await s_(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 Yu(e){let t=Math.max(1,Math.min(Aa,e.maxAttempts??Aa));for(let n=0;n<t;n+=1){let r=await r_({...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 o_(e){let t=i_(e);if(t)return{ok:!1,error:t};let n=[],r=new Set;for(let s of e.manifest.files){let a=ki({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=ki({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=Zu({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 i_(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 s_(e,t,n){if(await e(t))return!0;for(let r of n)if(await e(r.path))return!0;return!1}function ki(e){if(e.pathTemplate.split(Kh).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(Kh,e.instanceName),n=h_(t);return n?Zh(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||!QP.test(n)||e_.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 Zu(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(qP.test(g.path)){if(g.path.endsWith(_a)){let x=GP(g.content);if(!x.success)return Jn("MATERIALIZATION_DATA_UNSUPPORTED",x.error.message,g.path);u.set(g.path,new Set)}else try{JSON.parse(g.content)}catch{return Jn("MATERIALIZATION_DATA_UNSUPPORTED","Static prefab JSON file must contain valid JSON.",g.path)}continue}let p;try{p=JP(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=Hu(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=c_(m.violations,g.path);if(y)return{ok:!1,error:y};c.set(g.path,p)}for(let g of t){if(!Jh.test(g.path))continue;let p=c.get(g.path),m=null;if(t_(p,{ImportDeclaration(y){let x=Xh({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&&!l_(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 E=d_({importer:g.path,imported:x.internalPath,source:y.node.source.value,ast:p});E.ok?u.get(x.internalPath).add(g.path):(m??=E.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=Xh({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=Hh(y.node);x&&Wu.has(x)&&(m??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${x}.`,file:g.path},y.stop())},OptionalMemberExpression(y){let x=Hh(y.node);x&&Wu.has(x)&&(m??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${x}.`,file:g.path},y.stop())},Identifier(y){y.isReferencedIdentifier()&&Wu.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"||a_(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&&Ta(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&&Ta(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 Jn("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 Jn("MATERIALIZATION_PATH_INVALID",`Static prefab contains duplicate source entries: ${g.path}`,g.path);if(d.add(g.path),!Jh.test(g.path))return Jn("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must be a .ts/.tsx source module.",g.path);let p=c.get(g.path);if(!p)return Jn("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must resolve to a controlled source file.",g.path);if(!f_(p,g.export))return Jn("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 Jn("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 p_(g.path,l))f.add(p);return f.size!==t.length?Jn("MATERIALIZATION_ENTRY_INVALID","Every controlled source file must be reachable from the entry module.",r[0]?.path):{ok:!0}}function Ta(e){return/(?:url|expression)\s*\(|@import|javascript:|-moz-binding|\\/iu.test(e)}function a_(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"||Ta(n))return!1;let r=t.value;return r.type==="StringLiteral"&&!Ta(r.value)||r.type==="NumericLiteral"||r.type==="NullLiteral"||r.type==="UnaryExpression"&&["-","+"].includes(r.operator)&&r.argument.type==="NumericLiteral"})}function c_(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 Xh(e){if(!e.source.startsWith("./")&&!e.source.startsWith("../"))return{allowed:!0};if(e.source.includes("\\")||e.source.includes("\0"))return{allowed:!1};let t=Xn.posix.normalize(Xn.posix.join(Xn.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 l_(e,t,n){if(n===null)return!0;let r=u_(e);return r===null||t.has(r)&&n.has(r)}function u_(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 d_(e){let t=Xn.posix.dirname(e.importer),n=Xn.posix.dirname(e.imported),r=Xn.posix.basename(e.importer).replace(/\.tsx?$/,""),o=Xn.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 f_(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 p_(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 Jn(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{file:n}:{}}}}function m_(e){let t=Yh(e);return t===Wh?t:null}function g_(e){let t=e.trim().toLowerCase();return ZP.test(t)?t:null}function Gh(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 YP.test(t)?t:null}function Yh(e){if(!e||e.startsWith("/")||e.includes("\\"))return null;let t=Xn.posix.normalize(e);return t==="."||t.startsWith("../")||t.includes("/../")||t.includes("//")?null:t}function h_(e){let t=Yh(e);return!t||t!==e?null:t}function Zh(...e){return Xn.posix.join(...e)}function zh(e){return new Set(e.map(t=>t.pathTemplate))}function y_(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 x_(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function Hh(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 kd}from"node:crypto";import yd from"@babel/traverse";function qu(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 wa(e){if(e.node.alternate||!b_(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 b_(e){let t=qh(e);return e.traverse({enter(n){qh(n)||(t=!1,n.stop())}}),t}function qh(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 K_}from"node:crypto";import ly from"node:path";import*as Eo from"@babel/parser";import ad from"@babel/traverse";import cd from"@babel/generator";import*as ce from"@babel/types";import rd from"@babel/generator";import{parse as A_}from"@babel/parser";import od from"@babel/traverse";import*as Re from"@babel/types";import{PortableInvocationBindingSchema as T_}from"@vcp-dev/contracts";import Qu from"@babel/traverse";import*as Ce from"@babel/types";var Qh=typeof Qu=="function"?Qu:Qu.default;function un(e){let t=ty(e.module,e.exportName,e.parsedModules??new Map([[e.module.file,e.module]]),new Set);return t?ey(t,e.allowNonRenderingGuards):ar("component-export-unresolved","The requested local component export is not a statically resolvable function.",e.module.file)}function cr(e){let t=E_(e.module,e.componentName,e.callSourceRange);return t.kind==="local"?ey(t.definition):t.kind==="imported"?!e.imported?.module&&!gt(t.specifier)?ar("component-external-module-opaque","External package components are opaque to the local source graph.",t.specifier):e.imported?e.imported.module?un({module:e.imported.module,exportName:e.imported.exportName,parsedModules:e.imported.parsedModules}):ar("component-module-unavailable","The component source module is unavailable in the parsed graph.",e.imported.file):ar("component-local-binding-unresolved","The JSX call does not resolve to a statically declared local component function.",e.module.file):ar("component-local-binding-unresolved","The JSX call does not resolve to a statically declared local component function.",e.module.file)}function ey(e,t=!1){let n=R_(e.module.ast,e.node);if(!n)return ar("component-function-unresolved","The component function has no source AST path.",e.module.file);let r=ny(n,t);if(!r){let s=N_(n);return s?{ok:!0,componentName:e.name,sourceFile:e.module.file,metadataOnly:!1,roots:[s[0]],returnAlternatives:s}:ar("component-control-flow-unsupported","Component roots require an expression body or one direct return.",e.module.file)}let o=[],i=ry(r);return Fa(r,o)?{ok:!0,componentName:e.name,sourceFile:e.module.file,metadataOnly:i,roots:o}:ar("component-root-dynamic","Component return contains an unsupported dynamic or spread root.",e.module.file)}function E_(e,t,n){let r={kind:"unresolved"};return Qh(e.ast,{JSXElement(o){if(!I_(o.node.loc,n))return;let i=o.node.openingElement.name;if(!Ce.isJSXIdentifier(i)||i.name!==t)return;let s=o.scope.getBinding(t);if(!s||s.constantViolations.length>0){o.stop();return}if(S_(s.path)){let c=s.path.parentPath;c?.isImportDeclaration()&&(r={kind:"imported",specifier:c.node.source.value}),o.stop();return}let a=v_(s.path);a&&(r={kind:"local",definition:{node:a,name:t,module:e}}),o.stop()}}),r}function S_(e){return e.isImportSpecifier()||e.isImportDefaultSpecifier()||e.isImportNamespaceSpecifier()}function v_(e){if(e.isFunctionDeclaration())return e.node;if(!e.isVariableDeclarator())return null;let t=e.get("init");return!Array.isArray(t)&&nd(t.node)?t.node:null}function I_(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 ty(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=Qn(e.file,u,n),g=f?n.get(f):void 0;return g?ty(g,d,n,i):null},a=u=>{let d=k_(e,u);if(d)return{...d,module:e};for(let f of e.ast.program.body)if(!(!Ce.isImportDeclaration(f)||f.importKind==="type")){for(let g of f.specifiers)if(g.local.name===u){if(Ce.isImportDefaultSpecifier(g))return s(f.source.value,"default");if(Ce.isImportSpecifier(g)&&g.importKind!=="type")return s(f.source.value,Oa(g.imported))}}return null};for(let u of e.ast.program.body){if(Ce.isExportDefaultDeclaration(u)&&t==="default"){let d=u.declaration;if(nd(d))return{node:d,name:__(d)??"default",module:e};if(Ce.isIdentifier(d))return a(d.name)}if(!(!Ce.isExportNamedDeclaration(u)||u.exportKind==="type")){if(u.declaration){let d=P_(u.declaration,t);if(d)return a(d)}for(let d of u.specifiers)if(Ce.isExportSpecifier(d)&&d.exportKind!=="type"&&Oa(d.exported)===t)return u.source?s(u.source.value,Oa(d.local)):a(Oa(d.local))}}let c=e.ast.program.body.flatMap(u=>{if(!Ce.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 k_(e,t){for(let n of e.ast.program.body){let r=Ce.isExportNamedDeclaration(n)?n.declaration:n;if(Ce.isFunctionDeclaration(r)&&r.id?.name===t)return{node:r,name:t};if(Ce.isVariableDeclaration(r)){for(let o of r.declarations)if(Ce.isIdentifier(o.id)&&o.id.name===t&&nd(o.init))return{node:o.init,name:t}}}return null}function R_(e,t){let n=null;return Qh(e,{Function(r){r.node===t&&(n=r,r.stop())}}),n}function ny(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()||C_(i)||t&&i.isIfStatement()&&wa(i))?null:o.get("argument")}function C_(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(!Ce.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 N_(e){let t=e.get("body");if(!t.isBlockStatement())return null;let n=ed(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(!Ce.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=>!Ce.isJSXText(c)||c.value.trim()!=="")||i.node.openingElement.attributes.some(c=>Ce.isJSXSpreadAttribute(c)||Ce.isJSXAttribute(c)&&Ce.isJSXIdentifier(c.name,{name:"children"}))))return null;r.push(i)}return r}function ed(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=>ed(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:ed(e.slice(t+1));return o&&s?[...o,...s]:null}return null}function Fa(e,t){if(ry(e))return!0;if(e.isJSXFragment()||e.isJSXElement()&&ze(e)){let n=e.get("children");for(let r of Array.isArray(n)?n:[n])if(!r.isJSXText()&&(r.isJSXSpreadChild()||!Fa(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()||Fa(n,t)}return e.isParenthesizedExpression()||e.isTSAsExpression()||e.isTSTypeAssertion()||e.isTSNonNullExpression()||e.isTypeCastExpression()?Fa(e.get("expression"),t):e.isNullLiteral()||e.isStringLiteral()||e.isNumericLiteral()||e.isBooleanLiteral()}function td(e){return["base","link","meta","script","style","title"].includes(e)}function ry(e){let t=!1,n=r=>{if(r.isJSXElement()){let o=r.node.openingElement.name;return Ce.isJSXIdentifier(o)&&td(o.name)?(t=!0,!0):ze(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||!Ce.isIdentifier(o.node.property,{name:"map"})||i.length!==1)return!1;let s=i[0];if(!s.isArrowFunctionExpression()&&!s.isFunctionExpression())return!1;let a=ny(s);return a!==null&&n(a)}return!1};return n(e)&&t}function P_(e,t){return Ce.isFunctionDeclaration(e)?e.id?.name===t?t:null:Ce.isVariableDeclaration(e)&&e.declarations.some(n=>Ce.isIdentifier(n.id)&&n.id.name===t)?t:null}function nd(e){return Ce.isFunctionDeclaration(e)||Ce.isFunctionExpression(e)||Ce.isArrowFunctionExpression(e)}function __(e){return"id"in e&&e.id&&Ce.isIdentifier(e.id)?e.id.name:null}function Oa(e){return Ce.isIdentifier(e)?e.name:e.value}function ar(e,t,n){return{ok:!1,diagnostic:{code:e,message:t,file:n}}}var id=typeof rd=="function"?rd:rd.default,oy=typeof od=="function"?od:od.default,sy=new Set(["sourceBlockId","source_block_id","originalBlockId","original_block_id"]),w_=new Set(["sourceOrder","source_order","originalOrder","original_order"]),O_=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"]),F_=/^[A-Za-z_$][A-Za-z0-9_$]*$/u,L_=/^[A-Za-z_$][A-Za-z0-9_$]*(?:\.[A-Za-z_$][A-Za-z0-9_$]*)*$/u;function ur(e){if(!cy(e)||!Array.isArray(e.bindings))return lr("INVOCATION_INPUT_INVALID","bindings must be an array in a portable invocation.","bindings");let t=j_(e);if(!t||!L_.test(t))return lr("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=$_(e.targetOrder);if(!r.ok)return r;let o=e.searchParamsIdentifier??"searchParams";if(!F_.test(o))return lr("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=T_.safeParse(f);if(!g.success)return lr("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 lr("INVOCATION_DUPLICATE_PROP",`Portable invocation contains duplicate prop ${p.propName}.`,`bindings.${d}.propName`);if(a.add(p.propName),w_.has(p.propName))return lr("INVOCATION_SOURCE_METADATA","Source block order cannot be copied or rebound as a component prop.",`bindings.${d}`);if(sy.has(p.propName)&&p.value.kind!=="target-block-id")return lr("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 lr("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(M_(p.value,n.value,o))))}let u=Re.jsxElement(Re.jsxOpeningElement(B_(t),i,!0),null,[],!0);return{ok:!0,plan:{kind:"portable-invocation",component:t,jsx:id(u,{jsescOption:{minimal:!0}}).code,bindings:s,targetBlockId:n.value,targetOrder:r.value,requiresRouteSearchParams:c,searchParamsIdentifier:c?o:null}}}function D_(e){if(!cy(e)||e.jsx===void 0==(e.source===void 0))return xo("BLOCK_METADATA_INPUT_INVALID","Provide exactly one JSX expression or full source module.","input");let t=ay(e.targetBlockId);if(!t.ok)return xo("BLOCK_METADATA_TARGET_INVALID",t.error.message,"targetBlockId");if(!Number.isSafeInteger(e.targetOrder)||e.targetOrder<0)return xo("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=Ue("portable-entry.tsx",e.source);if(!g.ok)throw new Error(g.diagnostic.message);o=g.module,r=o.ast}else r=A_(n?e.jsx:e.source,{sourceType:"module",plugins:["jsx","typescript"]})}catch(g){return xo("BLOCK_METADATA_PARSE_FAILED",g instanceof Error?g.message:String(g),n?"jsx":"source")}let i=[],s;if(o&&e.entryExport){let g=un({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 oy(r,{JSXElement(g){iy(g)||i.push(g.node)},JSXFragment(g){iy(g)||i.push(g.node)}});if(i.length!==1)return xo("BLOCK_METADATA_ROOT_AMBIGUOUS","Portable block metadata requires exactly one JSX root.",n?"jsx":"source");let a=i[0],c=V_(a);if(!c)return xo("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=U_(g.node.name);!p||!O_.has(p)||(p==="data-site-block-id"||p==="data-vcp-block-id"||sy.has(p)?l+=1:u+=1,g.remove())};s?s.traverse({JSXAttribute:d}):oy(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?id(a,{jsescOption:{minimal:!0}}).code:id(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 M_(e,t,n){return e.kind==="route-search-params"?Re.identifier(n):e.kind==="target-block-id"?Re.stringLiteral(t):sd(e.value)}function sd(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=>sd(t))):Re.objectExpression(Object.entries(e).map(([t,n])=>Re.objectProperty(Re.stringLiteral(t),sd(n))))}function B_(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 j_(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 $_(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 V_(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 iy(e){let t=e.parentPath;for(;t;){if(t.isJSXElement()||t.isJSXFragment())return!0;t=t.parentPath}return!1}function U_(e){return Re.isJSXIdentifier(e)?e.name:null}function cy(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function lr(e,t,n){return{ok:!1,error:{code:e,path:n,message:t}}}function xo(e,t,n){return{ok:!1,error:{code:e,path:n,message:t}}}var ud=typeof cd=="function"?cd:cd.default,J_=typeof ad=="function"?ad:ad.default;function Pi(e){let t=gy(e);if(t)return{ok:!1,error:t};let n=e.projection,r=hd(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=H_(n,o),s=rA(e);if(!s.ok)return s;let a={jsx:s.invocation?.jsx??`<${e.component.localName} />`},c=X_(e);if(i){let p=dd(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??(La(l,n.container.sourceRange)?n.container.sourceHash:null);if(!l||!u)return Ri("Route page composition does not expose a verifiable container boundary.");let d=Ni(l),f=dy(e.source,d,u,"Route page composition container");if(!f.ok)return f.result;let g=o.anchorSourceRange?Ni(o.anchorSourceRange):void 0;if(g){if(!o.anchorSourceHash)return Ri("Route page composition placement does not expose a verifiable anchor boundary.");let p=dy(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 md(e){let t=Ue(e.entryFile,e.source);if(!t.ok)return dr("PORTABLE_ROUTE_SOURCE_INVALID",t.diagnostic.message);let n=dn({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 dr("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&&La(l.anchorSourceRange,e.anchor.sourceRange)?[{placement:l,matchCount:1}]:[];let u=l.members.reduce((d,f)=>d+py(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 dr("PORTABLE_ROUTE_ANCHOR_MISSING","Portable route anchor was not found in the canonical page composition.");if(o!==1||r.length!==1)return dr("PORTABLE_ROUTE_ANCHOR_AMBIGUOUS","Portable route anchor does not identify exactly one page-composition gap.");let i=Pi({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=_i({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 dr("PORTABLE_ROUTE_PATCH_FAILED",l.diagnostic.message);s=l.source}else{let l=Zt({source:s,locator:a.parentLocator,node:a.node,placement:a.placement,...a.anchorLocator?{anchorLocator:a.anchorLocator}:{}});if(!l.ok)return dr("PORTABLE_ROUTE_PATCH_FAILED",l.diagnostic.message);s=l.source}if(i.plan.serverParamsStep){let l=hy({source:s,step:i.plan.serverParamsStep});if(!l.ok)return dr("PORTABLE_ROUTE_PATCH_FAILED",l.diagnostic.message);s=l.source}let c=qt({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}}:dr("PORTABLE_ROUTE_PATCH_FAILED",c.diagnostic.message)}function py(e,t){return(e.label===t?1:0)+e.children.reduce((n,r)=>n+py(r,t),0)}function dr(e,t,n=[]){return{ok:!1,error:{code:e,message:t,diagnostics:n}}}function X_(e){let t=Z_(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 _i(e){if(e.locator.root.kind!=="expression"||e.locator.path?.length)return Kr(e.source,"Root expression rewrite requires an exact expression locator.");let t=ti(e.source,"value");if(!t.ok)return Kr(e.source,t.diagnostic.message);let n=Ee(t.ast,e.locator);if(!n.ok)return Kr(e.source,n.diagnostic.message);let r=n.match.path;if(!r.isExpression())return Kr(e.source,"Resolved value locator does not point to an expression.");let o=bo(e.source,r.node.start??null,r.node.end??null);if(!o||o!==e.expectedSourceHash)return Kr(e.source,"Root expression hash no longer matches the current source.");if(e.action.kind==="remove")return r.replaceWith(ce.nullLiteral()),{ok:!0,source:ud(t.ast,{}).code};let i;try{i=Eo.parseExpression(e.action.jsx,{plugins:["jsx","typescript"]})}catch(s){return Kr(e.source,s instanceof Error?s.message:String(s))}return!ce.isJSXElement(i)&&!ce.isJSXFragment(i)?Kr(e.source,"Root expression rewrite requires a JSX insertion expression."):(e.action.kind==="replace"?r.replaceWith(i):r.replaceWith(z_(r.node,i,e.action.placement,e.action.replaceOriginal)),{ok:!0,source:ud(t.ast,{}).code})}function z_(e,t,n,r){if(ce.isNullLiteral(e)||r)return t;let o=ce.isJSXFragment(e)?[...e.children]:[ce.isJSXElement(e)?e:ce.jsxExpressionContainer(e)],s=n==="before"||n==="prepend"?[t,...o]:[...o,t];return ce.jsxFragment(ce.jsxOpeningFragment(),ce.jsxClosingFragment(),s)}function Kr(e,t){return{ok:!1,source:e,diagnostic:{message:t}}}function gd(e){let t=gy(e);if(t)return{ok:!1,error:t};let n=e.projection,r=vy(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(W_(n,o)){let m=dd(e);return m.ok?e.operation==="remove-node"&&!uy(n,o.placementUnitKey)?Ri("The last editable page unit cannot be deleted."):e.operation==="move-node"?Ri("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=Ni(o.sourceRange),a=In(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?[]:[Ci(a.diagnostic)]}};if(bo(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=dd(e);return m.ok?uy(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}}}:Ri("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||!Y_(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=hd(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=Ni(d),g=In(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?[]:[Ci(g.diagnostic)]}};if(bo(e.source,g.match.node.start??null,g.match.node.end??null)!==u.containerSourceHash)return fy("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=Ni(m),E=In(e.source,x);return!E.ok||!E.match.node?{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:E.ok===!1?E.diagnostic.message:"Route page composition target anchor could not be resolved.",diagnostics:E.ok?[]:[Ci(E.diagnostic)]}}:bo(e.source,E.match.node.start??null,E.match.node.end??null)!==y?fy("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 uy(e,t){for(let n of e.placementUnitByKey.values())if(n.placementUnitKey!==t&&n.members.length>0)return!0;return!1}function H_(e,t){let n=e.placementUnitByKey.get(t.placementUnitKey);return n&&e.container.kind!=="jsx-container"&&La(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 W_(e,t){return e.container.kind!=="jsx-container"&&La(t.sourceRange,e.mutationTarget.sourceRange)&&t.sourceHash===e.mutationTarget.sourceHash}function dd(e){let t=e.projection.mutationTarget,n={kind:"value",root:{kind:"expression",sourceRange:t.sourceRange}},r=In(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?[]:[Ci(r.diagnostic)]}}}:bo(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 dy(e,t,n,r){let o=In(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?[]:[Ci(o.diagnostic)]}}}:bo(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 Ri(e){return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:e,diagnostics:[]}}}function fy(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function Ci(e){return{code:"UNSUPPORTED_PAGE_SHAPE",message:e.message,details:{astCode:e.code}}}function gy(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&&!G_(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 G_(e,t){return e.routeId===t.routeId&&e.effectiveTemplateId===t.effectiveTemplateId}function Y_(e,t){return e.routeId===t.routeId&&e.templateId===t.effectiveTemplateId}function Z_(e,t){let n=ly.posix.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=ly.posix.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function Ni(e){return{kind:"jsx-node",strategy:"source-range",sourceRange:e}}function bo(e,t,n){return t==null||n==null?null:`sha256:${K_("sha256").update(e.slice(t,n)).digest("hex")}`}function La(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 hy(e){let t;try{t=Eo.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=q_(t,e.step);return n.ok?{ok:!0,source:ud(t,{}).code}:{ok:!1,source:e.source,diagnostic:{message:n.message}}}function q_(e,t){let n=Ey(e);if(!n)return{ok:!1,message:"Route default function could not be resolved for searchParams wiring."};let r=pd(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."}:xy(r)!==t.identifier?{ok:!1,message:"Existing route searchParams binding no longer matches the plan."}:{ok:!0};let o=yy(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?fd():Q_()),{ok:!0};let i=n.node.params[0],s=pd(i);return s?(eA(s,t.typescript),{ok:!0}):{ok:!1,message:"Route page parameter is not a supported object pattern."}}function Q_(){return ce.objectPattern([ce.objectProperty(ce.identifier("searchParams"),ce.identifier("searchParams"),!1,!0)])}function fd(){let t=Eo.parse("function __PortablePage({ searchParams }: { searchParams?: Promise<Record<string, string | string[] | undefined>> }) {}",{sourceType:"module",plugins:["typescript"]}).program.body[0];if(!ce.isFunctionDeclaration(t))throw new Error("Failed to construct the canonical searchParams type.");let n=t.params[0];if(!ce.isObjectPattern(n))throw new Error("Failed to construct the canonical searchParams pattern.");return ce.cloneNode(n,!0)}function eA(e,t){let n=ce.objectProperty(ce.identifier("searchParams"),ce.identifier("searchParams"),!1,!0),r=e.properties.findIndex(ce.isRestElement);if(r<0?e.properties.push(n):e.properties.splice(r,0,n),!t)return;let o=by(e);if(!o){e.typeAnnotation=fd().typeAnnotation;return}if(!ce.isTSTypeLiteral(o.typeAnnotation))return;let i=fd().typeAnnotation;if(!i||!ce.isTSTypeAnnotation(i)||!ce.isTSTypeLiteral(i.typeAnnotation))return;let s=i.typeAnnotation.members[0];s&&!tA(o.typeAnnotation)&&o.typeAnnotation.members.push(ce.cloneNode(s,!0))}function tA(e){return e.members.some(t=>!("key"in t)||!t.key?!1:Sy(t.key)==="searchParams")}function nA(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 rA(e){if(!e.invocation)return{ok:!0};let t=ur({component:e.component.localName,bindings:e.invocation.bindings,targetBlockId:e.invocation.targetBlockId,targetOrder:e.invocation.targetOrder});if(!t.ok)return ld(t.error.message);let n;if(t.plan.requiresRouteSearchParams){let r=oA(e.source,e.entryFile);if(!r.ok)return ld(r.message,"UNSUPPORTED_ROUTE_PARAMS");if(n=r.step,r.step.identifier!==t.plan.searchParamsIdentifier&&(t=ur({component:e.component.localName,bindings:e.invocation.bindings,targetBlockId:e.invocation.targetBlockId,targetOrder:e.invocation.targetOrder,searchParamsIdentifier:r.step.identifier}),!t.ok))return ld(t.error.message)}return{ok:!0,invocation:t.plan,...n?{serverParamsStep:n}:{}}}function ld(e,t="PORTABLE_INVOCATION_INVALID"){return{ok:!1,error:{code:t,message:e,diagnostics:[]}}}function oA(e,t){let n;try{n=Eo.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=Ey(n);if(!r)return{ok:!1,message:"Portable route searchParams wiring requires a default server function."};let o=/\.(?:ts|tsx)$/iu.test(t),i=yy(r.node.params,o);return i.ok?{ok:!0,step:{kind:"ensure-search-params",action:i.action,identifier:i.identifier,typescript:o}}:i}function yy(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=pd(e[0]);if(!n)return{ok:!1,message:"Portable route searchParams wiring requires an object page parameter or an empty signature."};let r=xy(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&&!iA(n)?{ok:!1,message:"Portable route searchParams wiring cannot safely extend this typed page signature."}:{ok:!0,action:"add",identifier:"searchParams"}}function pd(e){return!e||ce.isTSParameterProperty(e)?null:ce.isObjectPattern(e)?e:ce.isAssignmentPattern(e)&&ce.isObjectPattern(e.left)?e.left:null}function xy(e){for(let t of e.properties)if(!(!ce.isObjectProperty(t)||t.computed||Sy(t.key)!=="searchParams"))return ce.isIdentifier(t.value)?t.value.name:ce.isAssignmentPattern(t.value)&&ce.isIdentifier(t.value.left)?t.value.left.name:"unsupported";return null}function iA(e){let t=by(e);return t?ce.isTSTypeLiteral(t.typeAnnotation):e.properties.length===0}function by(e){return e.typeAnnotation&&ce.isTSTypeAnnotation(e.typeAnnotation)?e.typeAnnotation:null}function Ey(e){let t=null;return J_(e,{ExportDefaultDeclaration(n){if(t)return;let r=nA(n,n.get("declaration"));r&&(t=r)}}),t}function Sy(e){return ce.isIdentifier(e)?e.name:ce.isStringLiteral(e)?e.value:null}var sA=typeof yd=="function"?yd:yd.default;function dn(e){if(!e.ast)return fn(e,[ct("UNSUPPORTED_PAGE_SHAPE","SourceGraph entry AST is required",{reason:"parsed-ast-required"})]);let t=mA(e.ast);if(!t)return fn(e,[ct("UNSUPPORTED_PAGE_SHAPE","Route default export must resolve to a local function component",{reason:"default-export-unresolved"})]);let n=hA(t);if(!n.ok)return fn(e,[n.diagnostic]);let r=n.expression;if(r.isIdentifier()){let o=xA(r,t);if(o.status==="resolved")r=o.expression;else if(o.status==="invalid")return fn(e,[ct("UNSUPPORTED_PAGE_SHAPE","Route default export local binding is not a supported JSX root")])}if(EA(r,t))return fn(e,[ct("INDIRECT_RETURN_ONLY","Route default export only returns through an indirect function boundary")]);if(r.isNullLiteral())return bd(e,t,"virtual-route-root",r);if(bA(r)){let o=kA({input:e,source:e.source,expression:r});return xd(e,t,o,{kind:"virtual-route-root",sourceKind:"atomic-expression"},r)}if(r.isConditionalExpression())return fn(e,[ct("UNSUPPORTED_PAGE_SHAPE","Route conditional root contains an unsupported branch shape",{reason:"ambiguous-placement"})]);if(r.isJSXElement()&&!ze(r)&&!Ti(r)){let o=vd(r),i=Ry({input:e,containerKind:"virtual-route-root",sourceKind:"jsx-element",source:e.source,containerPath:r,members:[o]});return xd(e,t,i,{kind:"virtual-route-root",sourceKind:"jsx-element"},r)}if(r.isJSXElement()||r.isJSXFragment()){let o=vA(r);if(!o.ok)return fn(e,[o.diagnostic]);let i=So(o.path);if(i.unsupported)return fn(e,[ct("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);if(SA(e.source,r,i.members))return bd(e,t,"starter-placeholder",r);let s=r.isJSXFragment()||ze(r);if(i.members.length===0&&s)return bd(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=Ry({input:e,containerKind:a,sourceKind:c,source:e.source,containerPath:o.path,members:i.members});return xd(e,t,l,{kind:a,sourceKind:c},r)}return fn(e,[ct("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")])}function hd(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:ct("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:ct("PLACEMENT_KEY_NOT_FOUND","Placement key was not found in the projected page composition",{placementKey:t})}}function vy(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:ct("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:ct("PLACEMENT_KEY_NOT_FOUND","Placement unit key was not found in the projected page composition",{placementUnitKey:t})}}function Cy(e){return e.ok?aA(e.projection):cA(e.projection)}function aA(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)=>Ny(e,u,m,y,e.container.placementKey)),f=d.filter(({member:m})=>m.isBusinessMember).map(({sourceMember:m})=>uA(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:lA(e,a),sourceMembers:i,businessMembers:s,placementUnits:n,placements:c}}function cA(e){let t=e.diagnostics.map(dA);return{status:"unsupported",version:e.version,composition:e.composition,reason:fA(e.diagnostics),diagnostics:t}}function lA(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 Ny(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)=>Ny(e,t,a,c,i))]}function uA(e,t,n){return{key:`business:${e}:${t.key}`,sourceMemberKey:t.key,containerKey:e,label:t.label,isIndependent:n}}function dA(e){return{code:pA(e),message:e.message}}function fA(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 pA(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 mA(e){let t=null;return sA(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=gA(o.path);i&&(t=i,n.stop())}}),t}function gA(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 hA(e){let t=e.get("body");if(!t.isBlockStatement()){let s=Ai(t);return s?{ok:!0,expression:s}:{ok:!1,diagnostic:ct("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:ct("ROUTE_RETURN_NOT_FOUND","Route default export does not contain a proven return boundary")};if(!r.isReturnStatement())return{ok:!1,diagnostic:ct("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(!yA(s)&&!wa(s))return{ok:!1,diagnostic:ct("UNSUPPORTED_PAGE_SHAPE","Route guard return shape is not statically safe",{reason:"guard-shape"})};continue}if(Py(s)||_y(s))return{ok:!1,diagnostic:ct("UNSUPPORTED_PAGE_SHAPE","Route default export contains unsupported control flow before the terminal return",{reason:"control-flow-return"})}}let o=r.get("argument"),i=Ai(o);return i?{ok:!0,expression:i}:{ok:!1,diagnostic:ct("ROUTE_RETURN_NOT_FOUND","Route default export returns without a boundary expression",{reason:"bare-return"})}}function yA(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(Py(o)||_y(o))return null;return r}function Py(e){return e.isForStatement()||e.isForInStatement()||e.isForOfStatement()||e.isWhileStatement()||e.isDoWhileStatement()||e.isSwitchStatement()||e.isTryStatement()||e.isWithStatement()}function _y(e){let t=!1;return e.traverse({Function(n){n.skip()},ReturnStatement(){t=!0}}),t}function xA(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=Ai(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 bA(e){return e.isConditionalExpression()?Iy(Ai(e.get("consequent")))&&Iy(Ai(e.get("alternate"))):!1}function Iy(e){return!!(e&&(e.isJSXElement()||e.isJSXFragment()||e.isNullLiteral()))}function Ai(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 EA(e,t){if(e.isIdentifier())return ky(e.node.name,t);if(e.isCallExpression()){let n=e.get("callee");if(n.isIdentifier())return ky(n.node.name,t)}return!1}function ky(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 SA(e,t,n){return e.includes("DESIGN_PLAN_REPLACE_ME")&&t.isJSXElement()&&n.length>0&&Sd(t)}function Sd(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(!Sd(t))return!1;continue}if(t.isJSXElement()&&!Sd(t))return!1}return!0}function vA(e){return{ok:!0,path:e}}function So(e){let t=[],n=!1;for(let r of e.get("children")){if(r.isJSXText()){if(!r.node.value.trim())continue;t.push({memberKey:Id(r.node.type,r.node.start,r.node.end),kind:"text",nodeType:r.node.type,sourceRange:tn(r.node.loc),businessMemberCount:0,parentSourceRange:tn(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=So(o);n||=i.unsupported,t.push(...i.members);continue}if(o.isJSXElement()){let i=Ti(o)?So(o):null;n||=i?.unsupported??!1,t.push({...vd(o,i?.members),sourceRange:tn(r.node.loc),parentSourceRange:tn(e.node.loc)});continue}if(o.isJSXSpreadChild()){n=!0;continue}t.push({memberKey:Id(o.node.type,o.node.start,o.node.end),kind:"atomic-expression",nodeType:o.node.type,sourceRange:tn(r.node.loc),businessMemberCount:1,parentSourceRange:tn(e.node.loc),children:[],isBusinessMember:!0,label:"atomic-expression"});continue}if(r.isJSXFragment()||r.isJSXElement()&&ze(r)){let o=So(r);n||=o.unsupported,t.push(...o.members);continue}if(r.isJSXElement()){let o=Ti(r)?So(r):null;n||=o?.unsupported??!1,t.push({...vd(r,o?.members),parentSourceRange:tn(e.node.loc)})}}return{members:t,unsupported:n}}function vd(e,t){let n=e.isJSXElement()&&Ti(e)?t??So(e).members:[],r=e.isJSXElement()&&!Ti(e)&&!ze(e);return{memberKey:Id(e.node.type,e.node.start,e.node.end),kind:"jsx-element",nodeType:e.node.type,sourceRange:tn(e.node.loc),businessMemberCount:r?1:Ay(n),parentSourceRange:tn(e.parentPath?.node.loc),children:n,isBusinessMember:r,label:IA(e)}}function Ti(e){let t=e.node.openingElement.name;return t.type==="JSXIdentifier"&&t.name[0]===t.name[0]?.toLowerCase()}function IA(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 Ay(e){return e.reduce((t,n)=>t+n.businessMemberCount,0)}function Da(e){return e.length===0?0:Math.max(1,Ay(e))}function Ry(e){let t=tn(e.containerPath.node.loc),n=Rd(e.source,e.containerPath.node.start,e.containerPath.node.end),r=nn(e.input,e.containerKind,e.sourceKind,t),o=nn(e.input,e.containerKind,"placement-unit",t);return{placementKey:r,placementUnitKey:o,version:e.input.version,containerKey:r,independent:Da(e.members)<=1,memberCount:Da(e.members),sourceRange:t,sourceHash:n,relation:"append",containerSourceRange:t,containerSourceHash:n,anchorSourceRange:null,anchorSourceHash:null,members:e.members}}function kA(e){let t=tn(e.expression.node.loc),n=Rd(e.source,e.expression.node.start,e.expression.node.end),r=nn(e.input,"virtual-route-root","atomic-expression",t),o=nn(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:nn(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 Ty(e,t){let n=tn(t.node.loc),r=Rd(e.source,t.node.start,t.node.end);return!n||!r?null:{kind:"expression",documentVersion:e.version,sourceRange:n,sourceHash:r}}function xd(e,t,n,r,o){let i=Ty(e,o);if(!i)return fn(e,[ct("UNSUPPORTED_PAGE_SHAPE","Route default export does not provide an exact mutation target",{reason:"mutation-target-unavailable"})]);let s=n.containerSourceRange??n.sourceRange,a=RA(e,n,s),c=qu(a),l={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:Oy(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 RA(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:Da(p)<=1,memberCount:Da(p),sourceRange:f,sourceHash:f?Ed(e.source,f):null,relation:l,containerSourceRange:m,containerSourceHash:m?Ed(e.source,m):null,anchorSourceRange:g,anchorSourceHash:g?Ed(e.source,g):null,members:p}),i=t.placementKey,s=t.members.map(l=>nn(e,i,"placement-unit",l.sourceRange)),a=s[0]??t.placementUnitKey,c=s.at(-1)??t.placementUnitKey;r.push(o("prepend",nn(e,i,"prepend",n),a,n,null,[]));for(let l of t.members){let u=l.parentSourceRange??n,d=nn(e,i,"placement-unit",l.sourceRange);r.push(o("before",nn(e,d,"before",l.sourceRange),d,l.sourceRange,l.sourceRange,[l],u)),r.push(o("after",nn(e,d,"after",l.sourceRange),d,l.sourceRange,l.sourceRange,[l],u))}return r.push(o("append",i,c,n,null,[])),r}function bd(e,t,n,r){let o=Ty(e,r);if(!o)return fn(e,[ct("UNSUPPORTED_PAGE_SHAPE","Route default export does not provide an exact mutation target",{reason:"mutation-target-unavailable"})]);let i=nn(e,n,"empty-container",void 0),s=nn(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=qu([a]),l={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:Oy(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 fn(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 ct(e,t,n){return n===void 0?{code:e,message:t}:{code:e,message:t,details:n}}function nn(e,t,n,r){return wy([e.route,e.entryFile,String(e.version),t,n,r?`${r.startLine}:${r.startColumn}-${r.endLine}:${r.endColumn}`:"no-range"])}function Id(e,t,n){return wy(["member",e,String(t??-1),String(n??-1)])}function wy(e){return`pc_${kd("sha256").update(e.join("\0")).digest("hex").slice(0,24)}`}function Rd(e,t,n){return t==null||n==null?null:`sha256:${kd("sha256").update(e.slice(t,n)).digest("hex")}`}function Ed(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:${kd("sha256").update(e.slice(r+t.startColumn,o+t.endColumn)).digest("hex")}`}function tn(e){return e?{startLine:e.start.line,startColumn:e.start.column,endLine:e.end.line,endColumn:e.end.column}:null}function Oy(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 MA}from"node:crypto";import*as pn from"@babel/types";function Fy(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 Cd from"@babel/traverse";import*as vo from"@babel/types";var NA=typeof Cd=="function"?Cd:Cd.default,PA=32;function wi(e,t,n,r=new Set){if(r.has(e.ast)||r.size>=PA)return null;let o=new Set(r).add(e.ast),i;if(NA(e.ast,{Program(d){i=d,d.stop()}}),!i)return null;let s=(d,f)=>{let g=Qn(e.file,d,n),p=g?n.get(g):void 0;return p?wi(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,Ma(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(vo.getBindingIdentifiers(f.node),t)&&c.push(a(t));for(let g of d.node.specifiers)vo.isExportSpecifier(g)&&g.exportKind!=="type"&&Ma(g.exported)===t&&c.push(d.node.source?s(d.node.source.value,Ma(g.local)):a(Ma(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 Ma(e){return vo.isIdentifier(e)?e.name:e.value}import*as ye from"@babel/types";var _A=32;function Bt(e,t=new Map,n=new Set){if(n.has(e.node)||n.size>=_A)return null;let r=new Set(n).add(e.node),o=t.get(e.node);if(o)return Oi(o,t,r);if(e.isTSAsExpression()||e.isTSTypeAssertion()||e.isTSNonNullExpression()||e.isTSSatisfiesExpression()||e.isParenthesizedExpression())return Bt(e.get("expression"),t,r);if(e.isIdentifier()){let i=e.scope.getBinding(e.node.name);return!i||i.constantViolations.length?null:Pd(i,t,r)}if(e.isMemberExpression()||e.isOptionalMemberExpression()){let i=jt(e.node.property,e.node.computed),s=e.get("object"),a=Bt(s,t,r);return i!==null&&a?$a(a,i,t,r):null}if(e.isConditionalExpression())return Oi([e.get("consequent"),e.get("alternate")],t,r);if(e.isLogicalExpression())return Oi([e.get("left"),e.get("right")],t,r);if(e.isSequenceExpression()){let i=e.get("expressions").at(-1);return i?Bt(i,t,r):null}if(e.isCallExpression()&&ye.isIdentifier(e.node.callee)){let i=e.scope.getBinding(e.node.callee.name);if(!i||!Io(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=Bt(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?Bt(f,c,r):null}return[e]}function Pd(e,t=new Map,n=new Set){if(e.constantViolations.length)return null;let r=t.get(e.identifier);if(r)return Oi(r,t,n);if(!e.path.isVariableDeclarator())return null;let o=e.path.get("init");if(!o.node)return null;let i=Bt(o,t,n);if(!i)return null;let s=Nd(e.path.node.id,e.identifier.name);return s?s.reduce((a,c)=>a&&$a(a,c,t,n),i):null}function Ba(e){if(!e.params.every(n=>ye.isIdentifier(n)||ye.isAssignmentPattern(n)&&ye.isIdentifier(n.left)&&Jr(n.right)))return!1;if(!ye.isBlockStatement(e.body))return Jr(e.body);if(e.body.body.length!==1)return!1;let t=e.body.body[0];return ye.isReturnStatement(t)&&!!t.argument&&Jr(t.argument)}function Io(e){if(e.constantViolations.length>0)return!1;if(e.path.isFunctionDeclaration())return Ba(e.path.node);let t=e.path.isVariableDeclarator()?e.path:e.path.findParent(r=>r.isVariableDeclarator()),n=t?.isVariableDeclarator()?t.node.init:null;return ye.isArrowFunctionExpression(n)||ye.isFunctionExpression(n)?Ba(n):!1}function Jr(e){let t=!0;return ye.traverseFast(e,n=>{(ye.isCallExpression(n)&&!ja(n)||ye.isOptionalCallExpression(n)||ye.isNewExpression(n)||ye.isAwaitExpression(n)||ye.isAssignmentExpression(n)||ye.isUpdateExpression(n)||ye.isUnaryExpression(n,{operator:"delete"})||ye.isYieldExpression(n)||ye.isTaggedTemplateExpression(n))&&(t=!1)}),t}function ja(e){return ye.isIdentifier(e.callee,{name:"useTranslations"})&&e.arguments.length===1&&ye.isStringLiteral(e.arguments[0])}function Oi(e,t,n){let r=[];for(let o of e){let i=Bt(o,t,n);if(!i)return null;r.push(...i)}return r.length?r:null}function $a(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=>ye.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 Oi(o,n,r)}function _d(e,t){let n=Bt(e,t);return!!(n?.length&&n.every(r=>ye.isLiteral(r.node)&&!r.isRegExpLiteral()||r.isTemplateLiteral()||r.isBinaryExpression()||r.isUnaryExpression()))}function jt(e,t){return!t&&ye.isIdentifier(e)?e.name:ye.isStringLiteral(e)||ye.isNumericLiteral(e)?String(e.value):null}function Nd(e,t){if(ye.isIdentifier(e))return e.name===t?[]:null;if(ye.isObjectPattern(e))for(let n of e.properties){if(!ye.isObjectProperty(n)||n.computed)continue;let r=jt(n.key,!1),o=Nd(n.value,t);if(r!==null&&o)return[r,...o]}if(ye.isArrayPattern(e))for(let[n,r]of e.elements.entries()){if(!r)continue;let o=Nd(r,t);if(o)return[String(n),...o]}return null}function Ly(e,t=new Set,n){return Dy(e.get("callee"),t,n)}function Dy(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&&Qn(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"?wi(g,p,n):null;return m?ko(m,o,n):{kind:"guard"}}let s=r.path.isVariableDeclarator()?r.path.get("init"):r.path;if(!s.node)return{kind:"unknown"};let a=ko(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=ko(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=Bt(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=ko(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 ko(e,new Set(t).add(e.node),n)}function ko(e,t,n){if(e.isIdentifier())return Dy(e,t,n);if(e.isTSAsExpression()||e.isTSTypeAssertion()||e.isTSNonNullExpression()||e.isParenthesizedExpression())return ko(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 Ua(e,t){return JSON.stringify([t,e])}var TA=new Set;function Vy(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)=>!$y(m)&&[...t].some(y=>e.graph.elements.get(y)?.sourceFile===p);function c(p,m,y,x,E,b=TA){if(p.isIdentifier())return x&&Va(p,x)?x.children.some(C=>c(C.path,C.file,y,C.substitution,E,b)):u({path:p,file:m,active:y,substitution:x,unknownIsRelevant:E,aliases:b});if(p.isCallExpression()||p.isOptionalCallExpression()){let C=p,T=Ly(C,b,e.parsedModules);return T.kind==="guard"||T.kind==="sources"&&T.sources.some(R=>c(R,[...e.parsedModules.values()].find(_=>_.ast.program===R.scope.getProgramParent().path.node)?.file??m,y,x,E,T.aliases))?!0:C.get("arguments").some(R=>c(R,m,y,x,E,b))||T.kind==="unknown"&&E}if(p.isJSXElement()){if(ze(p))return p.get("children").some(D=>c(D,m,y,x,E,b));let C=o.get(i(m,p.node));if(C){if(t.has(C.identity.key))return!0;if(C.boundaryKind==="component-boundary"&&!C.isPublicUiComponent){let D=e.parsedModules.get(C.sourceFile);if(!D)return!1;let U=cr({module:D,componentName:C.tag,callSourceRange:C.sourceRange,...C.importedFrom?{imported:{file:C.importedFrom,module:e.parsedModules.get(C.importedFrom),exportName:C.exportName??C.tag,parsedModules:e.parsedModules}}:{}});return U.ok?U.metadataOnly?!1:l(U,p,C.sourceFile,y,x,b):U.diagnostic.code==="component-external-module-opaque"?Fi(p).some(z=>c(z,m,y,x,!1,b)):a(D.file,U.diagnostic.code)}return p.get("children").some(D=>c(D,m,y,x,E,b))}let T=p.node.openingElement.name;if(!pn.isJSXIdentifier(T))return!1;if(/^[a-z]/.test(T.name))return p.get("children").some(D=>c(D,m,y,x,E,b));let R=e.parsedModules.get(m),_=p.node.loc;if(!R||!_)return!1;let A=DA({path:p,file:m,componentName:T.name,parsedModules:e.parsedModules}),w=cr({module:R,componentName:T.name,callSourceRange:{startLine:_.start.line,startColumn:_.start.column,endLine:_.end.line,endColumn:_.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"?Fi(p).some(D=>c(D,m,y,x,!1,b)):a(R.file,w.diagnostic.code)}if(p.isJSXFragment())return p.get("children").some(C=>c(C,m,y,x,E,b));if(p.isJSXExpressionContainer()||p.isParenthesizedExpression()||p.isTSAsExpression()||p.isTSNonNullExpression()||p.isTSTypeAssertion())return c(p.get("expression"),m,y,x,E,b);let S=!1;return p.traverse({"CallExpression|OptionalCallExpression"(C){c(C,m,y,x,E,b)&&(S=!0),C.skip(),S&&C.stop()},ReferencedIdentifier(C){c(C,m,y,x,E,b)&&(S=!0),S&&C.stop()},JSXElement(C){c(C,m,y,x,E,b)&&(S=!0),C.skip(),S&&C.stop()},JSXFragment(C){c(C,m,y,x,E,b)&&(S=!0),C.skip(),S&&C.stop()}}),S?!0:E&&!Xr(p)}function l(p,m,y,x,E,b){let S=`${p.sourceFile}#${p.componentName}`;if(x.has(S))return!1;let C=new Set(x).add(S);return p.returnAlternatives?.some(T=>Fi(T).some(R=>c(R,p.sourceFile,C,null,!1,b)))||p.roots.some(T=>c(T,p.sourceFile,C,null,!1,b))?!0:My(p.roots).kind==="none"?!1:jy(m).some(T=>c(T,y,C,E,!0,b))}function u(p){if(!p.path.isIdentifier())return p.unknownIsRelevant;let m=Fy({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:Ad(m.initializer).isIdentifier()?!1:p.unknownIsRelevant&&!Xr(m.initializer)}let d=(p,m,y,x,E,b)=>{if(p.isIdentifier()){c(p,m,x,b,!1)&&s(m);return}if(p.isJSXElement()){if(ze(p)){for(let T of p.get("children"))d(T,m,y,x,E,b);return}let S=o.get(i(m,p.node));if(!S)return;let C=S.identity.key;if(t.has(C)){E||s(m);let T=n.get(C)??[];T.push(Ua(C,y)),n.set(C,T)}if(S.boundaryKind==="component-boundary"&&!S.isPublicUiComponent){let T=e.parsedModules.get(S.sourceFile);if(!T)return;let R=cr({module:T,componentName:S.tag,callSourceRange:S.sourceRange,...S.importedFrom?{imported:{file:S.importedFrom,module:e.parsedModules.get(S.importedFrom),exportName:S.exportName??S.tag,parsedModules:e.parsedModules}}:{}});if(!R.ok){if(R.diagnostic.code==="component-external-module-opaque"){Fi(p).some(z=>c(z,m,x,b,!1))&&s(m);return}[...t].some(z=>e.graph.elements.get(z)?.sourceFile===T.file)&&!$y(R.diagnostic.code)&&s(T.file);return}if(R.metadataOnly)return;let _=`${R.sourceFile}#${R.componentName}`;if(x.has(_)){s(T.file);return}let A=new Set(x).add(_);R.returnAlternatives?.some(z=>Fi(z).some(V=>c(V,R.sourceFile,A,b,!1)))&&s(R.sourceFile);let w=My(R.roots),D=LA(p);if(w.kind==="unproven"||w.kind==="supported"&&D){for(let z of jy(p))if(c(z,m,A,b,!0)){s(m);break}}let U=w.kind==="supported"&&!D?{bindingNode:w.bindingNode,children:p.get("children").map(z=>({path:z,file:m,substitution:b}))}:null;for(let z of R.roots)d(z,R.sourceFile,[...y,C],A,E,U);return}for(let T of p.get("children"))d(T,m,y,x,E,b);return}if(p.isJSXFragment()){for(let S of p.get("children"))d(S,m,y,x,E,b);return}if(p.isJSXExpressionContainer()){let S=p.get("expression");if(b&&!S.isJSXEmptyExpression()){let C=Ad(S);if(Va(C,b)){for(let T of b.children)d(T.path,T.file,y,x,E,T.substitution);return}if(wA(S,b))for(let T of b.children)d(T.path,T.file,y,x,!1,T.substitution)}d(S,m,y,x,E,b);return}if(p.isParenthesizedExpression()||p.isTSAsExpression()||p.isTSNonNullExpression()||p.isTSTypeAssertion()){d(p.get("expression"),m,y,x,E,b);return}c(p,m,x,b,!1)&&s(m),p.traverse({JSXElement(S){d(S,m,y,x,!1,b),S.skip()}})},f=e.parsedModules.get(e.entryFile);if(!f)return{occurrences:n,diagnostics:r};let g=un({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 Ad(e){let t=e;for(;t.isParenthesizedExpression()||t.isTSAsExpression()||t.isTSNonNullExpression()||t.isTSTypeAssertion();)t=t.get("expression");return t}function Xr(e){let t=Ad(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||Xr(n)):t.isConditionalExpression()?Xr(t.get("consequent"))&&Xr(t.get("alternate")):t.isLogicalExpression()?Xr(t.get("left"))&&Xr(t.get("right")):!1}function Va(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 wA(e,t){if(Va(e,t))return!0;let n=!1;return e.traverse({Identifier(r){Va(r,t)&&(n=!0,r.stop())}}),n}function My(e){let t=e[0]?.getFunctionParent();if(!t)return{kind:"none"};let n=t.get("params")[0];return n?n.isAssignmentPattern()?By(n.get("left"),!0):By(n,!1):{kind:"none"}}function By(e,t){if(e.isObjectPattern()){let n=[],r=!1;for(let i of e.get("properties")){if(i.isObjectProperty()){if(i.node.computed){Cn(i.get("value"))&&(r=!0);continue}let s=i.node.key;(pn.isIdentifier(s)?s.name:pn.isStringLiteral(s)?s.value:null)==="children"&&n.push(i);continue}i.isRestElement()&&Cn(i.get("argument"))&&(r=!0)}if(n.length>1)return r||n.some(i=>Cn(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=>OA(s))?t?{kind:"unproven"}:{kind:"supported",bindingNode:o.node}:{kind:"unproven"}}return Cn(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=>FA(r))?{kind:"none"}:{kind:"unproven"}}return Cn(e)?{kind:"unproven"}:{kind:"none"}}function Cn(e){if(e.isIdentifier()){let t=e.scope.getBinding(e.node.name);return!!(t&&t.referencePaths.length>0)}return e.isAssignmentPattern()?Cn(e.get("left")):e.isRestElement()?Cn(e.get("argument")):e.isObjectPattern()?e.get("properties").some(t=>t.isObjectProperty()?Cn(t.get("value")):t.isRestElement()?Cn(t.get("argument")):!0):e.isArrayPattern()?e.get("elements").some(t=>t.node?Cn(t):!1):!0}function OA(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 FA(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?pn.isStringLiteral(n)&&n.value!=="children":pn.isIdentifier(n)&&n.name!=="children"}function LA(e){for(let t of e.get("openingElement").get("attributes")){if(t.isJSXAttribute()){let n=t.node.name;if(pn.isJSXIdentifier(n)&&n.name==="children")return!0;continue}if(t.isJSXSpreadAttribute()&&Uy(t.get("argument")))return!0}return!1}function jy(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(!pn.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");Uy(r)&&t.push(r)}}return t}function Fi(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 Uy(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 DA(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=Qn(e.file,r.node.source.value,e.parsedModules);if(!o)return;let i=n.isImportDefaultSpecifier()?"default":pn.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 $y(e){return e==="component-export-unresolved"||e==="component-local-binding-unresolved"}function Xy(e){let t=[],n=[];return zy(e.element,e,[],e.ownerNode,e.element,[],new Set,t,n),{roots:t,diagnostics:n}}function zy(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(td(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=cr({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(E=>({key:E.identity.key,structuralPath:E.identity.structuralPath,sourceRange:E.sourceRange}))}:{}}],m=d.roots.length>1?{kind:"component-definition",key:g}:r,y=new Set(s);y.add(g);let x=[];for(let E of d.returnAlternatives??[]){let b=Jy(E),S=b?Ky(t.graph,f,b):[];if(S.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(S[0])}for(let E of d.roots){let b=Jy(E),S=b?Ky(t.graph,f,b):[];if(S.length!==1){c.push({code:S.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}zy(S[0],t,p,m,d.roots.length>1?S[0]:o,d.roots.length>1?p:i,y,a,c,x)}}function Ky(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 Jy(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 Ka(e){let t=[],n=[];if(e.projection.entryFile!==e.entryFile||!Wy(e.projection.composition,e.composition)||e.graph.composition&&!Wy(e.graph.composition,e.composition))return{roots:[],diagnostics:[Li("composition-mismatch",e.entryFile)]};if(!e.parsedModules.has(e.entryFile))return{roots:[],diagnostics:[Li("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(Li("route-member-not-addressable",e.entryFile));continue}let s=jA(e.graph,e.entryFile,i.sourceRange);if(s.length!==1){t.push(Li(s.length?"route-root-ambiguous":"route-root-unresolved",e.entryFile));continue}let a=s[0],c=Xy({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=Vy(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=Ua(s,i.callChain.map(c=>c.callLocator.key));o.occurrences.get(s)?.filter(c=>c===a).length!==1&&t.push(Li("render-occurrence-unproven",i.element.sourceFile))}return{roots:BA(n,e.composition,o.occurrences),diagnostics:t}}function BA(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:MA("sha256").update(JSON.stringify([t,c,s.identity.key])).digest("hex"),rootRef:{key:s.identity.key,...a.length>1?{instanceIndex:a.indexOf(Ua(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=Hy(i);o.set(s,[...o.get(s)??[],i])}return r.map(i=>{let s=o.get(Hy(i))??[i];return{...i,siblingIndex:s.indexOf(i),siblingRootKeys:s.filter(a=>a!==i).map(a=>a.rootKey)}})}function Hy(e){return JSON.stringify([e.ownerNode.kind,e.ownerNode.key,e.parentStructuralPath,e.ownerCallKeys])}function jA(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 Wy(e,t){return e.routeId===t.routeId&&e.effectiveTemplateId===t.effectiveTemplateId}function Li(e,t){return{code:e,message:"Page block roots could not be proven from the current source graph.",file:t}}import{SiteEditPageBlockDirectorySchema as $A,SiteEditPageBlockDescriptorSchema as VA,SiteEditSourcePathSchema as Yy}from"@vcp-dev/contracts";function Ja(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}),Gy(i,r,o,t,e)}}return{nodes:t,rootKeys:[...e.rootKeys]}}function Gy(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}),Gy(s,t,n,r,o))}}function Di(e){let t=[],n={...e.graph,composition:e.composition},r=ra(Ja(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=JA(a,e.graph),f=d?e.parsedModules.get(d):void 0;if(!c||!l||l.sourceFile!==d||!u||!Yy.safeParse(a.sourceFile).success||!d||!f||!Yy.safeParse(d).success){t.push(Td("root-source-unavailable",a.sourceFile));continue}if(i.has(a.rootKey)){t.push(Td("block-key-ambiguous",a.sourceFile));continue}let g=ve(u.source),p=VA.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:XA(a,e),capabilities:UA(c,r),...KA(c,r)});if(!p.success){t.push(Td("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:ve(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=$A.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 UA(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 KA(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 JA(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 XA(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 Td(e,t){return{code:e,message:"The page block source binding could not be proven.",file:t}}import wd from"@babel/traverse";import{BlockRenderRefSchema as zA,SiteEditPageBlockPositionSchema as HA,SiteEditPageBlockTargetSchema as WA}from"@vcp-dev/contracts";var GA=typeof wd=="function"?wd:wd.default;function Ro(e,t,n,r){if(!WA.safeParse(t).success)return Ot("INVALID_PARAMS","Invalid page block target.");if(n!==e.documentVersion)return Ot("VERSION_STALE","The page block index is stale.");if(t.composition.routeId!==e.composition.routeId||t.composition.templateId!==e.composition.effectiveTemplateId)return Ot("INVALID_TARGET","The target belongs to another composition.");let o=e.bindings.get(t.blockKey);return o?r&&(!zA.safeParse(r).success||r.key!==o.descriptor.rootRef.key||r.instanceIndex!==o.descriptor.rootRef.instanceIndex||r.instanceCount!==o.descriptor.rootRef.instanceCount)?Ot("INVALID_TARGET","The render occurrence does not match the target."):{ok:!0,binding:o}:Ot("INVALID_TARGET","The page block target was not found.")}function Xa(e,t){if(!HA.safeParse(t).success)return Ot("INVALID_PARAMS","Invalid page block boundary.");if(t.documentVersion!==e.documentVersion)return Ot("VERSION_STALE","The page block boundary is stale.");if(t.composition.routeId!==e.composition.routeId||t.composition.templateId!==e.composition.effectiveTemplateId)return Ot("INVALID_TARGET","The boundary belongs to another composition.");let n=e.bindings.get(t.anchorBlockKey);if(!n)return Ot("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 Ot("INVALID_TARGET","A verified sibling binding is unavailable.");let o=r.sort((u,d)=>u.root.siblingIndex-d.root.siblingIndex),i=Zy(n);if(!i)return Ot("INVALID_TARGET","The operation owner call site is unavailable.");let s=qy(n,i);if(s===void 0)return Ot("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||!YA(qy(u,Zy(u)),s))return Ot("INVALID_TARGET","Siblings do not share one proven source boundary.");let a=o.findIndex(u=>u.blockKey===n.blockKey);if(a<0)return Ot("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 Zy(e){return e.ownerLocator.file===e.ownerFile?e.ownerLocator:null}function qy(e,t){if(!t)return;let n=Ue(t.file,e.ownerSourceContent);if(!n.ok)return;let r=[];if(GA(n.module.ast,{JSXElement(i){let s=Od(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=Od(o.node);return i?{kind:"jsx-fragment",file:t.file,sourceRange:i}:void 0}if(o.isJSXElement()){let i=Od(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 YA(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 Od(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 Ot(e,t){return{ok:!1,code:e,message:t}}import tx from"node:path";import{SiteEditSourcePathSchema as aT}from"@vcp-dev/contracts";import za from"node:path";import Fd from"@babel/traverse";import*as fr from"@babel/types";import{SiteEditSourcePathSchema as Qy,SiteEditPageBlockTargetSchema as ZA}from"@vcp-dev/contracts";var qA=typeof Fd=="function"?Fd:Fd.default;function ex(e){if(!e.operationId)return et("INVALID_PARAMS","An operationId is required.");if(!ZA.safeParse(e.target).success)return et("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 et("INVALID_TARGET","The request target does not match its resolved block binding.");if(e.documentVersion!==e.binding.documentVersion)return et("VERSION_STALE","The resolved block belongs to a stale document version.");if(e.operation==="move-node"||e.operation==="remove-node")return et("UNSUPPORTED_OPERATION","Move and remove are planned by the structural operation task.");if(!e.node)return et("INVALID_PARAMS","An insert/replacement node is required.");let t=e.operation==="insert-child"?e.boundary?.ownerFile:e.binding.ownerFile;if(!t||!Qy.safeParse(t).success)return et("INVALID_TARGET","The exact owner source file is unavailable.");let n=e.files.get(t);if(n===void 0)return et("INVALID_TARGET","The exact owner source is absent from the fixed file map.");if(ve(n)!==e.binding.ownerSourceHash)return et("VERSION_STALE","The owner source hash changed after target resolution.");let r=e.files.get(e.binding.descriptor.source.file);if(r===void 0||ve(r)!==e.binding.descriptor.source.contentHash)return et("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 et("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 et("INVALID_TARGET","The boundary anchor is not a verified same-owner sibling.");if(!o.parentLocator)return et("UNSUPPORTED_OPERATION","A root without a source parent has no safe sibling insertion boundary.")}let i=eT(e.node,t,n,e.files);if(!i.ok)return i;let s=e.operation==="replace-node"?lo({source:n,locator:QA(e.binding),node:{jsx:i.value.jsx}}):Zt({source:n,locator:Ld(o.parentLocator),anchorLocator:Ld(o.anchorLocator),placement:o.placement,node:{jsx:i.value.jsx}});if(!s.ok)return et("UNSUPPORTED_OPERATION",s.diagnostic.message);let a=s.source;if(i.value.import){let l=qt({source:a,moduleSpecifier:i.value.import.moduleSpecifier,imports:i.value.import.specifiers});if(!l.ok)return et("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 QA(e){return Ld(e.ownerLocator)}function Ld(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 eT(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}>`}}:et("INVALID_PARAMS","The native JSX tag is invalid.");if(!e.component)return et("UNSUPPORTED_OPERATION","A materialized component entry is resolved by the materialization task.");let o=tT(t,e.component.source,r);if(!o)return et("INVALID_TARGET","The component source is not in the safe fixed file map.");let i=Ue(t,n);if(!i.ok)return et("UNSUPPORTED_OPERATION",i.diagnostic.message);let s=nT(i.module.ast.program.body,e.component.source,e.component.exportName),a=s??oT(iT(e.component.exportName,o),rT(i.module.ast)),c=sT(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 tT(e,t,n){let r=t.startsWith("@/")?t.slice(2):t.startsWith("./")||t.startsWith("../")?za.posix.normalize(za.posix.join(za.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=>Qy.safeParse(i).success&&n.has(i))??null:null}function nT(e,t,n){for(let r of e)if(!(!fr.isImportDeclaration(r)||r.source.value!==t)){for(let o of r.specifiers)if(n==="default"&&fr.isImportDefaultSpecifier(o)||n!=="default"&&fr.isImportSpecifier(o)&&(fr.isIdentifier(o.imported)?o.imported.name:o.imported.value)===n)return o.local.name}return null}function rT(e){let t=new Set;return qA(e,{Program(n){n.scope.crawl(),t=new Set(Object.keys(n.scope.bindings)),n.stop()}}),t}function oT(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n+=1;return`${e}${n}`}function iT(e,t){let r=(e==="default"?za.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 sT(e){let t=[];for(let[n,r]of Object.entries(e)){if(!/^[A-Za-z_][A-Za-z0-9_:.-]*$/.test(n))return et("INVALID_PARAMS","A component prop name is invalid.");let o;try{o=JSON.stringify(r)}catch{return et("INVALID_PARAMS","Component props must be JSON serializable.")}if(o===void 0)return et("INVALID_PARAMS","Component props must be JSON serializable.");t.push(`${n}={${o}}`)}return{ok:!0,value:t.join(" ")}}function et(e,t){return{ok:!1,code:e,message:t}}function nx(e){if(e.materialization.kind!=="static-prefab-materialization"||!e.materialization.files.some(i=>i.path===e.materialization.entry.path))return Ha("MATERIALIZATION_ENTRY_INVALID","The materialization entry must identify one controlled create-only file.");if(!e.materialization.files.every(i=>i.kind==="create-only"&&aT.safeParse(i.path).success))return Ha("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 Ha("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 Ha("INVALID_TARGET","The exact page-block owner source is missing from the fixed file map.");let n=lT(t,e.materialization.entry.path),r=ex({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:cT(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 cT(e,t){let n=new Map(e);for(let r of t.files)n.set(r.path,r.content);return n}function lT(e,t){let n=tx.posix.relative(tx.posix.dirname(e),t);return n.startsWith(".")?n:`./${n}`}function Ha(e,t){return{ok:!1,code:e,message:t}}import{PageTemplateIdSchema as ET}from"@vcp-dev/contracts";import CJ from"node:fs";import PJ from"node:path";var uT=/^page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function Mi(e){let t=e.map(r=>bT(r.path)),n=dT(t);return n?t.filter(r=>pT(n,r)).map(r=>({routeId:mT(n,r),entryFile:r})).sort((r,o)=>r.routeId.localeCompare(o.routeId)):[]}function Dd(e,t=""){let r=((e??"/").trim()||"/").split(/[?#]/,1)[0]||"/",o=r.startsWith("/")?r:`/${r}`,i=xT(t),s=i&&(o===i||o.startsWith(`${i}/`))?o.slice(i.length)||"/":o,a=s.startsWith("/")?s:`/${s}`;return a==="/"?"/":a.replace(/\/+$/,"")}function dT(e){return e.some(r=>r.startsWith("app/")&&!fT(r))?"app":e.some(r=>r.startsWith("src/app/"))?"src/app":null}function fT(e){return/^(?:src\/)?app\/(?:_vcp|\.vcp)/.test(e)}function pT(e,t){if(!t.startsWith(`${e}/`))return!1;let n=t.slice(t.lastIndexOf("/")+1);return uT.test(n)?t.slice(e.length+1,-n.length-1).split("/").filter(Boolean).every(r=>!r.startsWith("_")&&!r.startsWith(".")):!1}function mT(e,t){let n=t.slice(e.length+1).split("/").slice(0,-1).map(hT).filter(r=>!!r);return n.length===0?"/":`/${n.join("/")}`}function gT(e){return e.startsWith("(")&&e.endsWith(")")}function hT(e){return!e||e.startsWith("@")||e.startsWith("_")||gT(e)?null:yT(e)}function yT(e){return e.replace(/^\((?:\.|\.\.|\.\.\.)\)/,"")}function xT(e){let t=e.trim();return!t||t==="/"?"":(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"")}function bT(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}var Bi=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="PageTemplateManagedSourceError"}};function Ft(e,t={}){throw new Bi("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Invalid page-template source (${e}): ${t.path??t.routeId??t.templateId??""}`,{reason:e,...t})}function Md(e){return ET.safeParse(e).success||Ft("invalid-template-id",{templateId:e}),Buffer.from(e,"utf8").toString("base64url")}function rx(e){/^[A-Za-z0-9_-]{1,255}$/.test(e)||Ft("invalid-template-key",{path:e});let t;try{t=new TextDecoder("utf-8",{fatal:!0}).decode(Buffer.from(e,"base64url"))}catch{return Ft("invalid-template-key",{path:e})}return Md(t)!==e&&Ft("noncanonical-template-key",{path:e}),t}function ST(e){let t=Dd(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("(")||vT(r)&&!ox(r)))&&Ft("invalid-public-route",{routeId:e}),t}function vT(e){return e.includes("[")||e.includes("]")}function ox(e){return/^\[\[\.\.\.[^\[\]]+\]\]$|^\[[^\[\]]+\]$/.test(e)}function ix(e){return e.some(ox)}function sx(e,t,n="app"){n!=="app"&&n!=="src/app"&&Ft("invalid-app-root");let r=ST(e),o=Md(t),i=ix(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))&&Ft("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 cx(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===".")&&Ft("invalid-file-path",{path:i}),n.has(i)&&Ft("duplicate-file-path",{path:i}),n.set(i,o)}return n}function Ga(e){let t=cx(e.files),n=Mi([...t.keys()].map(i=>({path:i}))),r=new Map;for(let i of n){if(r.has(i.routeId))throw new Bi("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||Ft("candidate-must-be-single-page",{path:i});let a=s[1],c=s[2].split("/"),l=ix(c),u=l?c[0]:c.pop(),d=l?c.slice(1):c,f=rx(u),g=d.length?`/${d.join("/")}`:"/";sx(g,f,a).templateEntryFile!==i&&Ft("candidate-path-mismatch",{path:i,routeId:g});let m=r.get(g);(!m||!m.startsWith(`${a}/`))&&Ft("canonical-entry-missing",{path:i,routeId:g}),o.push({routeId:g,templateId:f,entryFile:i,canonicalEntryFile:m,appRoot:a})}return o.sort((i,s)=>Wa(i.routeId,s.routeId)||Wa(i.templateId,s.templateId))}function Ya(e){let t=cx(e.files),n=Ga({files:t}),r=Mi([...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)=>Wa(o.context.routeId,i.context.routeId)||(o.context.effectiveTemplateId===void 0?-1:i.context.effectiveTemplateId===void 0?1:Wa(o.context.effectiveTemplateId,i.context.effectiveTemplateId)))}function IT(e){let t=Dd(e.selector.routeId),n=Ya({files:e.files}),r=n.find(i=>i.context.routeId===t&&i.context.effectiveTemplateId===void 0);(!r||r.entryFile!==e.canonicalEntryFile)&&Ft("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||Ft("template-selection-not-found",{routeId:t,templateId:e.selector.templateId}),{...o,mode:e.selector.templateId===void 0?"direct":"candidate",effectiveEntryFile:o.entryFile}}function Wa(e,t){return e<t?-1:e>t?1:0}import{HOME_PAGE_URL_PATH as XT}from"@vcp-dev/contracts";import{parse as MT}from"@babel/parser";import{parse as JJ}from"@babel/parser";import{FormBlockIdSchema as zJ,FormSpecV1Schema as HJ}from"@vcp-dev/contracts";import{posix as MJ}from"node:path";import kT from"@babel/traverse";var Bd=kT,jJ=typeof Bd=="function"?Bd:Bd.default,$J=Symbol("unknown-member");var ji="components/site/generated/forms",GJ=`${ji}/vcp-form-runtime.tsx`,Za="[A-Za-z0-9][A-Za-z0-9_-]{0,127}",YJ=new RegExp(`^${ji}/form-(${Za})\\.spec\\.ts$`),ZJ=new RegExp(`^${ji}/form-(${Za})\\.tsx$`),qJ=new RegExp(`^@/${ji}/form-(${Za})$`),QJ=new RegExp(`(?:^|/)${ji}/form-(${Za})(?:\\.tsx?)?$`);var e1=Symbol("invalid-literal");import{createHash as r1}from"node:crypto";import{posix as i1}from"node:path";import{parse as a1}from"@babel/parser";import{FormSpecV1Schema as l1}from"@vcp-dev/contracts";var u1=Symbol("dynamic");import{parse as RT}from"@babel/parser";function qa(e){return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&typeof t.type=="string"):[]}var CT=/^(?:src\/)?app\/(.*)page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function lx(e){let t=CT.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 NT(e){let t=e;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function ux(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function PT(e){let t=e;for(;t&&(t.type==="TSAsExpression"||t.type==="TSSatisfiesExpression"||t.type==="ParenthesizedExpression");)t=t.expression??null;return t}function jd(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(jd);if(t?.type==="ObjectExpression"){let n={};for(let r of qa(t.properties)){if(r.type!=="ObjectProperty"||r.computed)throw new Error("dynamic object property");let o=ux(r.key);if(!o)throw new Error("unsupported object key");n[o]=jd(r.value)}return n}throw new Error(`unsupported static value: ${t?.type??"unknown"}`)}function $d(e,t){let n=[],r=lx(t);if(r===null)return{found:!1,seo:null,diagnostics:n};let o;try{o=RT(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 qa(o.program.body)){let u=l.type==="ExportNamedDeclaration"?l.declaration:l;if(u?.type==="VariableDeclaration")for(let d of qa(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=PT(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 qa(s.properties)){if(l.type!=="ObjectProperty"||l.computed)continue;let u=ux(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=NT(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=jd(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 _T}from"@babel/parser";var dx=["page","anchor","external","email","phone","group","file"],AT=["link","cta"],px=["description","badge","iconKey"],Vd=["label","targetType","href","role","openInNewTab","nofollow","children",...px],TT=new Set(Vd);function Vi(e){return Array.isArray(e)?e:[]}function $i(e){let t=e;return t?.type==="StringLiteral"&&typeof t.value=="string"?t.value:void 0}function wT(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function fx(e){let t=e;return t?.type==="BooleanLiteral"&&typeof t.value=="boolean"?t.value:void 0}function Ud(e){let t=[],n;try{n=_T(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 Vi(n.program.body)){let s=i.type==="ExportNamedDeclaration"?i.declaration:i;if(s?.type==="VariableDeclaration")for(let a of Vi(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 Vi(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 Vi(e.properties)){if(l.type!=="ObjectProperty"||l.computed)continue;let u=wT(l.key);u&&(r[u]=l.value)}let o=$i(r.label),i=$i(r.targetType);if(!o)return n.push({severity:"fatal",path:`${t}.label`,message:"label must be a static string"}),null;if(!i||!dx.includes(i))return n.push({severity:"fatal",path:`${t}.targetType`,message:`targetType must be one of ${dx.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 px){if(r[l]===void 0)continue;let u=$i(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))TT.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 ${Vd.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=[];Vi(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=$i(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=$i(r.role);if(c!==void 0&&(AT.includes(c)?s.role=c:n.push({severity:"warning",path:`${t}.role`,message:"role ignored: not link/cta"})),r.openInNewTab!==void 0){let l=fx(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=fx(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 OT}from"@babel/parser";function Ui(e){return Array.isArray(e)?e:[]}function gx(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression";)t=t.expression;return t?.type==="ArrayExpression"?t:void 0}function FT(e){let t;try{t=OT(e,{sourceType:"module",plugins:["typescript","jsx"],tokens:!0})}catch{return{status:"unsupported"}}let n=[];for(let o of Ui(t.program.body)){let i=o.type==="ExportNamedDeclaration"?o.declaration:o;if(i?.type==="VariableDeclaration")for(let s of Ui(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=gx(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 Kd(e,t){let n=hx(t);if(!n)return{status:"unsupported",source:e};let r=FT(e);if(r.status!=="ok")return{status:r.status,source:e};let o=r.array;if(Ud(e).diagnostics.some(({severity:l})=>l==="fatal"))return{status:"unsupported",source:e};let s=[],a=l=>{let u=Ui(l.elements);for(let[d,f]of u.entries()){if(DT(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 E=/^\s*,/.exec(e.slice(x));s.push({start:y,end:E?x+E[0].length:x})}continue}let g=LT(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 LT(e){if(e.type==="ObjectExpression")for(let t of Ui(e.properties)){if(t.type!=="ObjectProperty")continue;let n=t.key;if((n?.name??n?.value)==="children")return gx(t.value)}}function hx(e){let t=e.trim();return t.startsWith("/")?t==="/"?t:t.replace(/\/+$/,""):null}function DT(e,t){if(e.type!=="ObjectExpression")return!1;let n,r;for(let o of Ui(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"&&hx(n??"")===t}import{estimateNavLabelWidth as E1}from"@vcp-dev/contracts";import{parse as I1}from"@babel/parser";function zn(e,t){let n;try{n=MT(e,{sourceType:"module",sourceFilename:t.filePath,plugins:["jsx","typescript"]})}catch(_){let A=_.loc;return{form_codes:[],components:[],uncertain_components:[],rendered_component_openings:[],renders_native_form:!1,diagnostics:[{code:"rendered-module.parse-failed",message:_ instanceof Error?_.message:"Rendered module failed Babel parsing.",file_path:t.filePath??"",line:A?.line??1}]}}let r=n.program,o=$t(r?.body),i=new Map,s=new Map,a=new Map,c=new Map,l=_=>{if(_?.type==="FunctionDeclaration"){let A=_.id;A?.type==="Identifier"&&typeof A.name=="string"&&s.set(A.name,_);return}if(_?.type==="VariableDeclaration")for(let A of $t(_.declarations)){let w=A.id,D=A.init;w?.type==="Identifier"&&typeof w.name=="string"&&D&&(pr(D)?s.set(w.name,D):D.type==="Identifier"&&typeof D.name=="string"&&a.set(w.name,D.name))}};for(let _ of o){if(_.type==="ImportDeclaration"){let A=_.source?.value;if(typeof A!="string")continue;for(let w of $t(_.specifiers)){let D=w.local;if(!(D?.type!=="Identifier"||typeof D.name!="string")){if(w.type==="ImportDefaultSpecifier")i.set(D.name,{source:A,exportName:"default"});else if(w.type==="ImportNamespaceSpecifier")i.set(D.name,{source:A,exportName:"*"});else if(w.type==="ImportSpecifier"){let U=w.imported,z=U?.type==="Identifier"&&typeof U.name=="string"?U.name:U?.type==="StringLiteral"&&typeof U.value=="string"?U.value:"";z&&i.set(D.name,{source:A,exportName:z})}}}continue}_.type==="ExportNamedDeclaration"?l(_.declaration):l(_)}for(let _ of o){if(_.type==="ExportDefaultDeclaration"){let D=_.declaration;D&&pr(D)?c.set("default",D):D?.type==="Identifier"&&typeof D.name=="string"&&c.set("default",D.name);continue}if(_.type!=="ExportNamedDeclaration")continue;let A=_.declaration;if(A?.type==="FunctionDeclaration"){let D=A.id;D?.type==="Identifier"&&typeof D.name=="string"&&c.set(D.name,D.name)}else if(A?.type==="VariableDeclaration")for(let D of $t(A.declarations)){let U=D.id;U?.type==="Identifier"&&typeof U.name=="string"&&c.set(U.name,U.name)}let w=_.source?.value;for(let D of $t(_.specifiers)){let U=bx(D.local),z=bx(D.exported);if(!(!U||!z))if(typeof w=="string"){let V=`#re-export:${z}`;i.set(V,{source:w,exportName:U}),c.set(z,V)}else c.set(z,U)}}let u=new Set,d=[],f=new Set,g=[],p=new Set,m=[],y=new Map,x=!1,E=[],b=new Map,S=new Map,C=(_,A="rendered")=>{let w=xx(_,i);if(!w)return!1;let D=`${w.source}\0${w.exportName}`;if(A==="uncertain")return!f.has(D)&&!p.has(D)&&(p.add(D),g.push({source:w.source,export_name:w.exportName})),!0;if(!f.has(D)&&(f.add(D),d.push({source:w.source,export_name:w.exportName}),p.delete(D))){let U=g.findIndex(z=>z.source===w.source&&z.export_name===w.exportName);U>=0&&g.splice(U,1)}return!0},T=(_,A="rendered",w=[])=>{let D=`${A}\0${Xd(w)}`,U=b.get(_)??new Set,z=S.get(_)??new Set;if(U.has(D)||z.has(A))return;U.add(D),b.set(_,U),z.add(A),S.set(_,z);let V=new Map(s),Y=new Map,ue=[],st=(xe,rt=!1)=>{if(Qa(xe)){if(!rt&&pr(xe)){if(xe.type==="FunctionDeclaration"){let Te=xe.id;Te?.type==="Identifier"&&typeof Te.name=="string"&&V.set(Te.name,xe)}return}if(xe.type==="VariableDeclarator"){let Te=xe.id,de=xe.init;Te?.type==="Identifier"&&typeof Te.name=="string"&&de&&(pr(de)?V.set(Te.name,de):Y.set(Te.name,de))}else if(xe.type==="ReturnStatement"){let Te=xe.argument;Te&&ue.push(Te)}if(xe.type==="CallExpression"){let Te=xe.callee;if(Te?.type==="Import"&&E.push({code:"rendered-module.dynamic-import",message:"Rendered component graph must use static imports.",file_path:t.filePath??"",line:xe.loc?.start.line??1}),Ki(Te)==="cms.forms.getConfig"){let de=$t(xe.arguments)[0];de?.type==="StringLiteral"&&typeof de.value=="string"&&de.value.trim()?A==="rendered"?u.add(de.value.trim()):E.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:xe.loc?.start.line??1}):E.push({code:"rendered-module.dynamic-form-code",message:"Rendered cms.forms.getConfig() requires a non-empty string literal.",file_path:t.filePath??"",line:xe.loc?.start.line??1})}}for(let[Te,de]of Object.entries(xe))if(Te!=="loc")if(Array.isArray(de))for(let Le of de)st(Le);else st(de)}};st(_,!0);let pt=new Set,qo=new Set,sn=(xe,rt=A,Te=w)=>{if(!(!Qa(xe)||pr(xe))){if(xe.type==="Identifier"&&typeof xe.name=="string"){let de=Y.get(xe.name),Le=`${rt}\0${xe.name}\0${Xd(Te)}`;de&&!pt.has(Le)&&!qo.has(xe.name)?(pt.add(Le),qo.add(xe.name),sn(de,rt,Te),qo.delete(xe.name)):C(xe.name,rt);return}if(xe.type==="CallExpression"){let de=xe.callee,Le=$t(xe.arguments),Et=Ki(de),an=de?.type==="Identifier"&&typeof de.name=="string"?i.get(de.name):void 0;if(rt==="rendered"&&(Et==="createElement"||Et.endsWith(".createElement")||an?.source==="react"&&an.exportName==="createElement")&&Le[0]?.type==="StringLiteral"&&Le[0].value==="form"&&(x=!0),de?.type==="Identifier"&&typeof de.name=="string"){let St=V.get(de.name);if(St){T(St,rt,Te);return}}if(de&&pr(de)){T(de,rt,Te);return}if($T(de)){for(let St of Le)if(pr(St))T(St,rt,Te);else if(St.type==="Identifier"&&typeof St.name=="string"){let Is=V.get(St.name);Is&&T(Is,rt,Te)}return}for(let St of Le)VT(St)&&E.push({code:"rendered-module.unresolved-export",message:"Unable to prove whether a JSX-producing call argument is rendered.",file_path:t.filePath??"",line:St.loc?.start.line??1});return}if(xe.type==="JSXElement"){let de=xe.openingElement,Le=de?yx(Te,BT(de)):Te;sn(de,rt,Le);for(let Et of $t(xe.children))sn(Et,rt,Le);return}if(xe.type==="JSXOpeningElement"){let de=ec(xe.name);rt==="rendered"&&de==="form"&&(x=!0);let Le=de?xx(de,i):void 0;if(rt==="rendered"&&Le&&typeof xe.start=="number"){let Et=`${Le.source}\0${Le.exportName}\0${xe.start}`,an=y.get(Et);if(!an){let St=UT(xe).get("formBlockId");an={source:Le.source,export_name:Le.exportName,start_offset:xe.start,...typeof St=="string"?{static_form_block_id:St}:{}},y.set(Et,an),m.push(an)}Te.length>0&&(an.static_render_blockers=yx(an.static_render_blockers??[],Te))}if(de&&!C(de,rt)){let Et=V.get(de);Et?T(Et,rt,Te):Y.has(de)?sn(Y.get(de),rt,Te):jT(de)||/^[A-Z]/.test(de)&&E.push({code:"rendered-module.dynamic-import",message:`Unable to resolve rendered component ${de} from a static import.`,file_path:t.filePath??"",line:xe.loc?.start.line??1})}for(let Et of $t(xe.attributes))sn(Et,"uncertain",Te);return}if(xe.type==="JSXAttribute"){let de=xe.value,Le=de?.type==="JSXExpressionContainer"?de.expression:de;Le&&pr(Le)?T(Le,"uncertain",Te):sn(Le,"uncertain",Te);return}for(let[de,Le]of Object.entries(xe))if(!(de==="loc"||de==="closingElement"))if(Array.isArray(Le))for(let Et of Le)sn(Et,rt,Te);else sn(Le,rt,Te)}},Qo=_.body;Qo&&Qo.type!=="BlockStatement"&&ue.push(Qo);for(let xe of ue)sn(xe);z.delete(A)},R=c.get(t.exportName);if(typeof R=="string"){let _=R,A=new Set;for(;a.has(_)&&!A.has(_);)A.add(_),_=a.get(_);if(!C(_)){let w=s.get(_);w?T(w):E.push(Ex(t))}}else R?T(R):E.push(Ex(t));return{form_codes:[...u],components:d,uncertain_components:g,rendered_component_openings:m,renders_native_form:x,diagnostics:E}}function Xd(e){return e.map(t=>`${t.start_offset}:${t.reason}`).join("|")}function yx(e,t){return[...new Map([...e,...t].map(r=>[Xd([r]),r])).values()]}function BT(e){let t=new Map;for(let a of $t(e.attributes)){if(a.type==="JSXSpreadAttribute"){t.clear();continue}let c=Sx(a.name);if(!c)continue;let l=a.value;t.set(c,l?.type==="JSXExpressionContainer"?l.expression:l)}let n=ec(e.name)??"unknown",r=[],o=a=>{r.push({element_name:n,line:e.loc?.start.line??1,start_offset:JT(e.start),reason:a})};for(let a of["hidden","inert","aria-hidden","disabled"]){if(!t.has(a)||a==="disabled"&&n!=="fieldset")continue;let c=Jd(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 $t(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,Jd(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=Jd(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 Jd(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"&&$t(e.expressions).length===0)return $t(e.quasis)[0]?.value?.cooked}}function xx(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 jT(e){return e.endsWith(".Provider")||e.endsWith(".Consumer")}function pr(e){return e?.type==="FunctionDeclaration"||e?.type==="FunctionExpression"||e?.type==="ArrowFunctionExpression"}function $T(e){let t=Ki(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 VT(e){let t=!1;return zd(e,n=>{if(!t){if(n.type==="JSXOpeningElement"){t=!0;return}n.type==="CallExpression"&&Ki(n.callee)==="cms.forms.getConfig"&&(t=!0)}}),t}function bx(e){return e?.type==="Identifier"&&typeof e.name=="string"?e.name:e?.type==="StringLiteral"&&typeof e.value=="string"?e.value:""}function Ex(e){return{code:"rendered-module.unresolved-export",message:`Unable to resolve rendered export ${e.exportName}.`,file_path:e.filePath??"",line:1}}function Ki(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=Ki(e.object),n=e.property;return!t||n?.type!=="Identifier"||typeof n.name!="string"?"":`${t}.${n.name}`}function UT(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=Sx(o.name);i&&t.set(i,KT(o.value))}return t}function KT(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 Sx(e){let t=e;if(t?.type==="JSXIdentifier")return typeof t.name=="string"?t.name:void 0}function JT(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function zd(e,t){if(Qa(e)){t(e);for(let[n,r]of Object.entries(e))if(n!=="loc"){if(Array.isArray(r)){for(let o of r)zd(o,t);continue}zd(r,t)}}}function Qa(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}function ec(e){let t=e;if(!t)return"";if(t.type==="JSXIdentifier")return typeof t.name=="string"?t.name:"";if(t.type==="JSXMemberExpression"){let n=ec(t.object),r=ec(t.property);return n&&r?`${n}.${r}`:r||n}return""}function $t(e){return Array.isArray(e)?e.filter(t=>Qa(t)):[]}var zT="components/site/generated/",Ji=[".tsx",".ts",".jsx",".js"];function vx(e){if(e.expectedUrlPath===XT)return{ok:!1,code:"HOME_PAGE_LOCKED",message:"The homepage source is protected from deletion."};let t=new Set(Mi(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 E=$d(y,x);return E.found&&E.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=Ga({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=HT(e.files);if(!i.ok)return i.error;let s=i.graph,a=ZT(o,s),c=qT(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=Kd(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 HT(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")||!WT(r))continue;let s=Ue(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(GT(c))continue;let l=En(r,c),u=YT(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 WT(e){let t=e.toLowerCase();return Ji.some(n=>t.endsWith(n))}function GT(e){return!!(/\.([a-z0-9]+)$/i.exec(e)&&!Ji.some(n=>e.endsWith(n)))}function YT(e,t){let n=e.replace(/\\/g,"/");return(Ji.some(o=>n.endsWith(o))?[n]:[...Ji.map(o=>`${n}${o}`),...Ji.map(o=>`${n}/index${o}`)]).find(o=>t.has(o))??null}function ZT(e,t){let n=new Set,r=[...e].flatMap(o=>[...t.get(o)??[]]);for(;r.length>0;){let o=r.pop();!o.startsWith(zT)||n.has(o)||(n.add(o),r.push(...t.get(o)??[]))}return n}function qT(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 Ib from"@babel/parser";import*as Ae from"@babel/types";import*as xc from"node:path";import*as Me from"@babel/types";function Ix(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 Nn(e){if(e.path.isObjectPattern()||e.path.isArrayPattern())return zr(e.path.node,e.identifier.name);if(e.path.isVariableDeclarator()){let n=e.path.node.id;if(Me.isObjectPattern(n)||Me.isArrayPattern(n))return zr(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(ew(e.path,n))return!0}if(t.isFunction()||t.isVariableDeclarator())return!1;t=t.parentPath}return!1}function zr(e,t,n=!1){return Me.isIdentifier(e)?e.name===t&&n:Me.isObjectPattern(e)?e.properties.some(r=>Me.isObjectProperty(r)?zr(r.value,t,n):zr(r.argument,t,n)):Me.isArrayPattern(e)?e.elements.some(r=>{if(!r)return!1;let o=Me.isRestElement(r)?r.argument:r;return zr(o,t,n)}):Me.isAssignmentPattern(e)?zr(e.left,t,!0):Me.isRestElement(e)?zr(e.argument,t,n):!1}function Co(e,t){if(e.path.isObjectPattern()){if(t){let r=mn(e.path.node,t.base),[o,...i]=r??[];if(o?.kind==="property")return{propName:o.name,remainingPath:[...i,...t.path],hasDefault:Nn(e)}}return t?{propName:t.base,remainingPath:t.path,hasDefault:Nn(e)}:null}if(e.path.isVariableDeclarator()){let r=e.path.get("init");if(r?.isExpression()){let o=kx(r),i=!1,s=o?o.initBinding&&Hd(o.initBinding)?(i=Nn(o.initBinding),[...o.initPathPrefix]):o.initBinding?(()=>{let c=Co(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=mn(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||Nn(e)}}}}let n=rw(e);if(n){let r=QT(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||Nn(e)}}if(n.findParent(s=>s.isVariableDeclarator()))return null;let o=tw(e);if(o){let[s,...a]=o;return!s||s.kind!=="property"?null:{propName:s.name,remainingPath:[...a,...t?.path??[]],hasDefault:Nn(e)}}let i=Xi(n.node);return i?{propName:i,remainingPath:t?.path??[],hasDefault:Nn(e)}:null}if(Hd(e)){let[r,...o]=t?.path??[];return!r||r.kind!=="property"?null:{propName:r.name,remainingPath:o,hasDefault:Nn(e)}}return null}function QT(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=kx(r);if(!o)return null;let{initBinding:i,initPathPrefix:s}=o;if(!i)return null;let a=!1,c=Hd(i)?(a=Nn(i),[...s]):(()=>{let u=Co(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=mn(n.node.id,t.identifier.name);return l?{path:[...c,...l],hasDefault:a||Nn(t)}:null}function kx(e){if(e.isIdentifier())return{initBinding:e.scope.getBinding(e.node.name),initPathPrefix:[]};if(!e.isMemberExpression())return null;let t=ow(e.node);return t?{initBinding:e.scope.getBinding(t.base),initPathPrefix:t.path}:null}function Hd(e){return e.path.isIdentifier()&&e.path.key===0&&Array.isArray(e.path.container)&&e.path.parentPath?.isFunction()===!0}function ew(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function tw(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=mn(i.node,t);if(a)return a}return null}function Rx(e,t,n){if(e.path.isVariableDeclarator()){let a=e.path.get("id");if(!Array.isArray(a)&&(a.isObjectPattern()||a.isArrayPattern())){let c=tc(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=Xi(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=nw(e);if(!r)return null;let o=r.parentPath;if(!o?.isObjectProperty())return null;let i=Xi(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 tc(e,t){if(e.isObjectPattern()){for(let n of e.get("properties"))if(n.isObjectProperty()){let r=Xi(n.node),o=n.get("value");if(o.isAssignmentPattern()){let i=o.get("left"),s=o.get("right");if(r&&!Array.isArray(i)&&mn(i.node,t)&&!Array.isArray(s)&&s.isExpression())return{propName:r,expressionPath:s}}if(!Array.isArray(o)&&(o.isObjectPattern()||o.isArrayPattern())){let i=tc(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=tc(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=tc(r,t);if(o)return o}}return null}function mn(e,t,n=[]){if(Me.isIdentifier(e))return e.name===t?n:null;if(Me.isObjectPattern(e)){for(let r of e.properties)if(Me.isObjectProperty(r)){let o=Xi(r);if(!o)continue;let i=mn(r.value,t,[...n,{kind:"property",name:o}]);if(i)return i}else if(Me.isRestElement(r)){let o=mn(r.argument,t,n);if(o)return o}}if(Me.isArrayPattern(e))for(let r=0;r<e.elements.length;r+=1){let o=e.elements[r];if(!o)continue;let i=Me.isRestElement(o)?o.argument:o,s=mn(i,t,[...n,{kind:"index",index:r}]);if(s)return s}return Me.isAssignmentPattern(e)?mn(e.left,t,n):null}function nw(e){if(!e.path.isIdentifier())return null;let t=e.path.parentPath;return t?.isAssignmentPattern()&&t.node.left===e.path.node?t:null}function rw(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 Xi(e){return e.computed?null:Me.isIdentifier(e.key)?e.key.name:Me.isStringLiteral(e.key)?e.key.value:null}function ow(e){let t=[],n=e;for(;Me.isMemberExpression(n);){if(n.computed)if(Me.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(Me.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(Me.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return Me.isIdentifier(n)?{base:n.name,path:t}:null}import*as Tx from"@babel/parser";import Yd from"@babel/traverse";import*as No from"@babel/types";import*as Ie from"@babel/types";var Cx=new WeakMap;function oc(e,t=[]){if(e.isIdentifier()){let n=e.scope.getBinding(e.node.name);return n?nc(n,t):null}if(e.isMemberExpression()){let n=uw(e.node),r=iw(e.node);if(!n||r===null)return null;let o=e.scope.getBinding(n);return o?nc(o,[...r,...t]):null}return e.isAwaitExpression()||Gd(e.node)?mr(fw(e.node),t,"awaited or fetched expression"):null}function iw(e){let t=[],n=e;for(;Ie.isMemberExpression(n);){if(n.computed)if(Ie.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(Ie.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(Ie.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return Ie.isIdentifier(n)?t:null}function nc(e,t=[],n){let r=sw(e,t);if(r)return r;let o=aw(e,t,n);if(o)return o;let i=cw(e,t,n);return i||null}function Hi(e){return e?.kind==="api-source"}function sw(e,t){if(e.path.isVariableDeclarator()&&Ie.isIdentifier(e.path.node.id)){let s=e.path.get("init");if(s?.isCallExpression()&&Wd(s.node)&&t[0]?.kind==="property"&&t[0].name==="data")return mr(e.identifier.name,t,"query hook result.data binding")}if(e.path.isVariableDeclarator()&&Ie.isObjectPattern(e.path.node.id)){let s=e.path.node.id.properties.find(c=>Ie.isObjectProperty(c)&&_x(c)==="data"&&zi(c.value,e.identifier.name)),a=e.path.get("init");if(s&&a?.isCallExpression()&&Wd(a.node))return mr(e.identifier.name,t,"query hook data binding")}let n=lw(e);if(!n||_x(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()||!Wd(i.node)?null:mr(e.identifier.name,t,"query hook data binding")}function aw(e,t,n){if(e.path.isVariableDeclarator()&&Ie.isArrayPattern(e.path.node.id)){let c=e.path.get("init");if(!c?.isCallExpression()||!Px(c.node))return null;let[l,u]=e.path.node.id.elements;return!Ie.isIdentifier(l)||l.name!==e.identifier.name||!Ie.isIdentifier(u)?null:Nx(e,u.name,n)?mr(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()||!Px(i.node)||r.node.elements.findIndex(c=>c===e.path.node)!==0)return null;let a=r.node.elements[1];return Ie.isIdentifier(a)&&Nx(e,a.name,n)?mr(e.identifier.name,t,"state setter is updated by API data"):null}function cw(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()?mr(e.identifier.name,t,"awaited binding result"):Gd(o.node,n)?mr(e.identifier.name,t,"fetch-backed binding result"):null:null}function lw(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 zi(e,t){return Ie.isIdentifier(e)?e.name===t:Ie.isAssignmentPattern(e)?zi(e.left,t):Ie.isObjectPattern(e)?e.properties.some(n=>Ie.isObjectProperty(n)?zi(n.value,t):zi(n.argument,t)):Ie.isArrayPattern(e)?e.elements.some(n=>!!n&&zi(Ie.isRestElement(n)?n.argument:n,t)):!1}function Nx(e,t,n){let r=!1,o=!1,i=e.scope.path,s;if(n){let c=Cx.get(n);c||(c=new WeakMap,Cx.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){Gd(c.node)&&(r=!0),(dw(c.node.callee,t)||c.node.arguments.some(l=>Ie.isIdentifier(l)&&l.name===t))&&(o=!0)}});let a=r&&o;return s?.set(t,a),a}function Wd(e){let t=ic(e.callee);return t==="useQuery"||t==="useSWR"||t==="useSuspenseQuery"}function Px(e){return ic(e.callee)==="useState"}function Gd(e,t){let n=t?.get(e);if(n!==void 0)return n;let r=rc(e,o=>Ie.isCallExpression(o)&&ic(o.callee)==="fetch");return t?.set(e,r),r}function uw(e){let t=e;for(;Ie.isMemberExpression(t);)t=t.object;return Ie.isIdentifier(t)?t.name:null}function _x(e){return e.computed?null:Ie.isIdentifier(e.key)?e.key.name:Ie.isStringLiteral(e.key)?e.key.value:null}function ic(e){return Ie.isIdentifier(e)?e.name:Ie.isMemberExpression(e)&&Ie.isIdentifier(e.property)?e.property.name:null}function dw(e,t){return rc(e,n=>Ie.isIdentifier(n)&&n.name===t)}function rc(e,t){if(t(e))return!0;let n=Ie.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(Ie.isNode(i)&&rc(i,t))return!0;continue}if(Ie.isNode(o)&&rc(o,t))return!0}return!1}function fw(e){return Ie.isIdentifier(e)?e.name:Ie.isCallExpression(e)?ic(e.callee)??"api":Ie.isAwaitExpression(e)?"awaited-api":"api"}function mr(e,t,n){return{kind:"api-source",readonly:!0,sourceId:e,displayPath:pw(e,t),reason:n}}function pw(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}var wx=typeof Yd=="function"?Yd:Yd.default;function Ox(e,t){let n=Lx(e);if(!n)return{allowed:!0};let r=!1;return wx(n,{CallExpression(o){if(!Dx(o.node,t.sourceRange)||!mw(o.node))return;let i=o.get("callee");if(!i.isMemberExpression())return;let s=i.get("object");Array.isArray(s)||!s.isExpression()||Hi(oc(s))&&(r=!0,o.stop())}}),r?{allowed:!1,reason:"Cannot add data-backed items to a dynamic API list"}:{allowed:!0}}function Fx(e,t){let n=Lx(e);if(!n)return{allowed:!0};let r=!1;return wx(n,{JSXExpressionContainer(o){Dx(o.node,t.sourceRange)&&(No.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 Lx(e){try{return Tx.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function mw(e){let t=e.callee;return No.isMemberExpression(t)&&No.isIdentifier(t.property)&&t.property.name==="map"}function Dx(e,t){let n=e.loc;return n?Ax({line:n.start.line,column:n.start.column},{line:t.startLine,column:t.startColumn})>=0&&Ax({line:n.end.line,column:n.end.column},{line:t.endLine,column:t.endColumn})<=0:!1}function Ax(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 ee from"@babel/types";import*as Mx from"@babel/parser";import Zd from"@babel/traverse";import*as We from"@babel/types";import*as Po from"node:path";var gn=typeof Zd=="function"?Zd:Zd.default;function dt(e){try{return Mx.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function qd(e){return e.computed?We.isStringLiteral(e.key)||We.isNumericLiteral(e.key)?String(e.key.value):null:gw(e.key)}function gw(e){return We.isIdentifier(e)?e.name:We.isStringLiteral(e)||We.isNumericLiteral(e)?String(e.value):null}function Hr(e){return We.isParenthesizedExpression(e)||We.isTSAsExpression(e)||We.isTSSatisfiesExpression(e)||We.isTSNonNullExpression(e)||We.isTSTypeAssertion(e)?Hr(e.expression):We.isExpression(e)?e:null}function Qd(e){if(We.isIdentifier(e))return[e.name];if((We.isMemberExpression(e)||We.isOptionalMemberExpression(e))&&!e.computed&&We.isIdentifier(e.property)){let t=Hr(e.object),n=t?Qd(t):null;return n?[...n,e.property.name]:null}return null}function Wr(e,t){return t.startsWith("@/")?t.slice(2).replace(/\\/g,"/"):t.startsWith(".")?Po.normalize(Po.join(Po.dirname(e),t)).replace(/\\/g,"/"):t}function Vt(e,t){return sc(e)===sc(t)}function sc(e){let t=_o(e);return t.endsWith("/index")?t.slice(0,-6):t}function _o(e){return e.replace(/\.(tsx|ts|jsx|js)$/,"")}function $x(e,t,n){let r=Jx(e,t);if(Xx(e,r),zx(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 gn(e,{JSXElement(s){Yx(s,r)&&o.push(s)}}),o.length!==1?{ok:!1,reason:"Cannot move prop-backed repeat child without a single unambiguous component call site"}:ac(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 Vx(e,t){let n=new Map,r=i=>{let s=Ao(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 hw(i,n))o=r(s)||o}return[...n.values()]}function hw(e,t){let n=[],r=yw(e,t);for(let o of e.ast.program.body){if(ee.isExportDefaultDeclaration(o)&&ee.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=Wi(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(ee.isExportNamedDeclaration(o)&&o.source&&typeof o.source.value=="string"){let i=Wr(e.file,o.source.value);for(let s of o.specifiers){if(ee.isExportNamespaceSpecifier(s)){let l=gr(s.exported);for(let u of t.values())Vt(u.file,i)&&n.push({file:e.file,namespace:ef(l,u.namespace),exportName:u.exportName});continue}if(!ee.isExportSpecifier(s))continue;let a=gr(s.local),c=[...t.values()].filter(l=>Vt(l.file,i)&&Gr(l.namespace,a));if(c.length>0){let l=gr(s.exported);for(let u of c){let d=Wi(u.namespace,a,l);d&&n.push({file:e.file,namespace:d,exportName:u.exportName})}continue}t.has(Ao({file:i,exportName:a}))&&n.push({file:e.file,exportName:gr(s.exported)})}continue}if(ee.isExportNamedDeclaration(o)&&!o.source){for(let i of o.specifiers){if(!ee.isExportSpecifier(i))continue;let s=gr(i.local),a=r.get(s)??[];if(a.length>0){let c=gr(i.exported);n.push({file:e.file,exportName:c});for(let l of a){let u=Wi(l.namespace,s,c);u&&n.push({file:e.file,namespace:u,exportName:l.exportName})}}}continue}if(ee.isExportAllDeclaration(o)&&typeof o.source.value=="string"){let i=Wr(e.file,o.source.value),s=o.exported;if(s){let a=gr(s);for(let c of t.values())Vt(c.file,i)&&n.push({file:e.file,namespace:ef(a,c.namespace),exportName:c.exportName});continue}for(let a of t.values())Vt(a.file,i)&&(a.namespace||a.exportName!=="default")&&n.push({file:e.file,namespace:a.namespace,exportName:a.exportName})}}return n}function ef(e,t){return t?`${e}.${t}`:e}function Gr(e,t){return e===t||e?.startsWith(`${t}.`)===!0}function Wi(e,t,n){return!Gr(e,t)||!e?null:e===t?n:`${n}${e.slice(t.length)}`}function yw(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(!ee.isImportDeclaration(i)||typeof i.source.value!="string")continue;let s=Wr(e.file,i.source.value);for(let a of i.specifiers){if(ee.isImportDefaultSpecifier(a)){let c=t.get(Ao({file:s,exportName:"default"}));c&&r(a.local.name,c);let l=[...t.values()].filter(u=>Vt(u.file,s)&&Gr(u.namespace,"default"));for(let u of l){let d=Wi(u.namespace,"default",a.local.name);d&&r(a.local.name,{...u,namespace:d})}continue}if(ee.isImportSpecifier(a)){let c=gr(a.imported),l=[...t.values()].filter(d=>Vt(d.file,s)&&Gr(d.namespace,c));for(let d of l)r(a.local.name,d);let u=t.get(Ao({file:s,exportName:c}));u&&r(a.local.name,u);continue}if(ee.isImportNamespaceSpecifier(a))for(let c of t.values())Vt(c.file,s)&&r(a.local.name,{...c,namespace:ef(a.local.name,c.namespace)})}}let o=!0;for(;o;){o=!1;for(let i of e.ast.program.body)if(ee.isVariableDeclaration(i))for(let s of i.declarations){if(!ee.isIdentifier(s.id)||!s.init)continue;let a=Hr(s.init);if(!a||!ee.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(Ao));for(let d of c){let f=Wi(d.namespace,a.name,s.id.name),g=f?{...d,namespace:f}:d,p=Ao(g);u.has(p)||(r(s.id.name,g),u.add(p),o=!0)}}}return n}function Ao(e){let t=e.namespace?`${e.namespace}.${e.exportName}`:e.exportName;return`${sc(e.file)}#${t}`}function gr(e){return ee.isIdentifier(e)?e.name:e.value}function Ux(e,t){for(let n of e.program.body){if(ee.isExportDefaultDeclaration(n)){let o=n.declaration;if((ee.isFunctionDeclaration(o)||ee.isClassDeclaration(o))&&o.id?.name===t)return{exportName:"default"};if(ee.isIdentifier(o)&&o.name===t)return{exportName:"default"}}if(!ee.isExportNamedDeclaration(n))continue;let r=n.declaration;if((ee.isFunctionDeclaration(r)||ee.isClassDeclaration(r))&&r.id?.name===t)return{exportName:t};if(ee.isVariableDeclaration(r)){for(let o of r.declarations)if(ee.isIdentifier(o.id,{name:t}))return{exportName:t}}for(let o of n.specifiers){if(!ee.isExportSpecifier(o)||o.local.name!==t)continue;return{exportName:ee.isIdentifier(o.exported)?o.exported.name:o.exported.value}}}return null}function nf(e){let t=xw(e),n=[],r=zx(e.ast,t);return gn(e.ast,{JSXElement(o){Vt(e.file,e.sourceFile)&&ac(o)===e.sourceComponent||Yx(o,t)&&n.push({file:e.file,path:o})}}),{callSites:n,hasUnsafeReference:r}}function Kx(){return{localBindings:new Set,namespaceMembers:new Map,hasUnsupportedAlias:!1}}function Jx(e,t){let n=Kx();return gn(e,{Program(r){let o=r.scope.getBinding(t);o&&n.localBindings.add(o),r.stop()}}),n}function xw(e){let t=Kx();return Vt(e.file,e.sourceFile)&&bw(t,Jx(e.ast,e.sourceComponent)),gn(e.ast,{ImportDeclaration(n){let r=n.node,o=r.source.value;if(typeof o!="string")return;let i=Wr(e.file,o),s=e.componentIdentities.filter(a=>Vt(a.file,i));if(s.length!==0)for(let a of r.specifiers){let c=n.scope.getBinding(a.local.name);if(c){if(ee.isImportDefaultSpecifier(a)&&s.some(l=>l.exportName==="default")&&t.localBindings.add(c),ee.isImportDefaultSpecifier(a)){let l=s.filter(u=>Gr(u.namespace,"default"));if(l.length>0){let u=t.namespaceMembers.get(c)??new Set;for(let d of l){let f=jx(d,"default");f&&u.add(f)}t.namespaceMembers.set(c,u)}continue}if(ee.isImportSpecifier(a)){let l=ee.isIdentifier(a.imported)?a.imported.name:a.imported.value,u=s.filter(d=>Gr(d.namespace,l));if(u.length>0){let d=t.namespaceMembers.get(c)??new Set;for(let f of u){let g=jx(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(ee.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)}}}}}),Xx(e.ast,t),t}function bw(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 Xx(e,t){gn(e,{VariableDeclarator(n){if(!n.node.init)return;let r=Hr(n.node.init);if(r){if(ee.isIdentifier(n.node.id)){let o=Yr(r,t,n),i=n.scope.getBinding(n.node.id.name);o&&i&&tf(t,i,o);return}if(ee.isObjectPattern(n.node.id)){let o=Yr(r,t,n);o?.unsupported||o?.local?t.hasUnsupportedAlias=!0:o&&o.namespaceMembers.size>0&&Gx(n.node.id,o.namespaceMembers,t,n)}}}})}function zx(e,t){if(t.hasUnsupportedAlias)return!0;let n=!1;return gn(e,{ReferencedIdentifier(r){if(n){r.stop();return}Ew(r)||!r.isIdentifier()||!Hx(r,t)||Sw(r,t)||vw(r)||(n=!0,r.stop())}}),n}function Ew(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 Hx(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)&&Yr(r.node,t,r)?r:null}function Sw(e,t){let n=e.findParent(c=>c.isVariableDeclarator());if(!n?.isVariableDeclarator())return!1;let r=n.get("init");if(!r?.isExpression()||!Bx(e,r))return!1;let o=Hx(e,t);if(!o)return!1;if(Hr(r.node)===o.node)return!!Yr(r.node,t,r);let s=e.findParent(c=>c.isObjectProperty());if(!s?.isObjectProperty())return!1;let a=s.get("value");return a.isExpression()&&Bx(e,a)&&!!Yr(a.node,t,a)}function vw(e){let t=e.parentPath;return t?.isExportDefaultDeclaration()&&t.node.declaration===e.node?!0:!!(t?.isExportSpecifier()&&t.node.local===e.node)}function Bx(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function Yr(e,t,n){let r=Hr(e);if(!r)return null;if(ee.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(ee.isObjectExpression(r))return Iw(r,t,n);let o=Qd(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?Wx(s,o.slice(1).join(".")):null}function Iw(e,t,n){let r=new Set,o=!1;for(let i of e.properties){if(!ee.isObjectProperty(i))continue;let s=qd(i);if(!s||!ee.isExpression(i.value)){ee.isExpression(i.value)&&(o||=Yr(i.value,t,n)!==null);continue}let a=Yr(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 Wx(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 tf(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 Gx(e,t,n,r){for(let o of e.properties){if(ee.isRestElement(o)){if(ee.isIdentifier(o.argument)){let c=r.scope.getBinding(o.argument.name);c&&tf(n,c,{local:!1,namespaceMembers:new Set(t),unsupported:!1})}else n.hasUnsupportedAlias=!0;continue}if(!ee.isObjectProperty(o))continue;let i=qd(o);if(!i){n.hasUnsupportedAlias=!0;continue}let s=Wx(t,i);if(!s)continue;n.hasUnsupportedAlias||=s.unsupported;let a=ee.isAssignmentPattern(o.value)?o.value.left:o.value;if(ee.isIdentifier(a)){let c=r.scope.getBinding(a.name);c&&tf(n,c,s);continue}if(ee.isObjectPattern(a)&&s.namespaceMembers.size>0){Gx(a,s.namespaceMembers,n,r);continue}n.hasUnsupportedAlias=!0}}function jx(e,t){if(!Gr(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 Yx(e,t){let n=e.node.openingElement.name;if(ee.isJSXIdentifier(n)){let o=e.scope.getBinding(n.name);return!!(o&&t.localBindings.has(o))}let r=Zx(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 Zx(e){if(ee.isJSXIdentifier(e))return[e.name];if(ee.isJSXMemberExpression(e)){let t=Zx(e.object);return t?[...t,e.property.name]:null}return null}function ac(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()&&ee.isIdentifier(n.node.id))return n.node.id.name}return null}function qx(e,t){let n=dt(e);if(!n||!t.tag||!t.importedFrom||!t.exportName)return Number.POSITIVE_INFINITY;let r=nf({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 De(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 Oe(e){return typeof e.start=="number"&&typeof e.end=="number"?{start:e.start,end:e.end}:null}function Pn(e,t){let n=Oe(e);return!!(n&&Ut(t,n))}function Ut(e,t){return t.start>=e.start&&t.end<=e.end}function rn(e,t){let n=Ee(e,De(t));return n.ok&&n.match.path.isJSXElement()?n.match.path:cc(e,t)}function To(e,t){let n=Oe(t);return n?e.slice(n.start,n.end):""}function Qx(e,t){return e.start===t.start&&e.end===t.end}function cc(e,t){let n=null;return gn(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 lc(e,t){return rf(e,t).length>0}function uc(e,t){let n=Oe(e.node),r=Oe(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()&&!kw(o,n,r)))return!0;o=o.parentPath}return!1}function kw(e,t,n){let r=Oe(e.node.consequent);if(r&&Ut(r,t)&&!Ut(r,n))return!1;let o=e.node.alternate?Oe(e.node.alternate):null;return!(o&&Ut(o,t)&&!Ut(o,n))}function rf(e,t){let n=Oe(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=Oe(o.node.consequent),a=Oe(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()&&of(o.node.operator)){let s=Oe(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 of(e){return e==="&&"||e==="||"||e==="??"}function eb(e,t){let n=Oe(e.consequent);if(n&&Ut(n,t))return n;let r=Oe(e.alternate);return r&&Ut(r,t)?r:null}function tb(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=>_o(a.file)));if(!t.has(_o(e.sourceFile))||!t.has(_o(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(_o(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=Ux(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=dt(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=Vx(r,{file:e.sourceFile,exportName:n.exportName}),i=[];for(let a of r){let c=nf({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!Vt(s.file,e.targetFile)||ac(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 Aw}from"@vcp-dev/contracts";function dc(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 Gi();let a=s.target,c=a.locator;if(a.sourceKind==="repeat-template"){let l=o?.instanceIndex;if(l===void 0)return Gi();let u=Rw(a,l,o?.instanceCount);if(!u)return Gi();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"?Gi():{ok:!0,target:{kind:"jsx-attribute"}}}function Gi(){return{ok:!1,code:"unsupported-binding",reason:"Property does not have a safe typed binding write target for this scope and operation"}}function Rw(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 _n from"@babel/types";import{SiteEditSetPropsParamsSchema as Cw}from"@vcp-dev/contracts";function nb(e){let t=e.changes??(e.change?[e.change]:[]);if(!Cw.safeParse({kind:"set-props",scope:"selection",changes:t}).success)return Yi("invalid-change","Repeat property changes are invalid");if(t.length!==1||t[0].name!==e.target.propertyName)return Yi("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=Je(e.source,"value");if(!o.ok)return Yi("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=Ee(o.ast,a);if(!c.ok||!c.match.path.isObjectExpression())return Yi("unsupported-object",`Repeat item ${s} is not a writable object expression`);let l=s===e.target.sourceItemIndex?Nw(r):Pw(c.match.path.node,r.name);if(!l)return Yi("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 Nw(e){return e.operation==="set"?{kind:"value",value:e.value}:{kind:"undefined"}}function Pw(e,t){let n=e.properties.filter(i=>_n.isObjectProperty(i)&&_w(i.key)===t);if(n.length>1)return null;let r=n[0];if(!r)return{kind:"undefined"};if(!_n.isExpression(r.value))return null;let o=Rn(r.value);return o.status==="undefined"?{kind:"undefined"}:o.status!=="resolved"?null:{kind:"value",value:o.value}}function _w(e){return _n.isIdentifier(e)?e.name:_n.isStringLiteral(e)?e.value:_n.isNumericLiteral(e)?String(e.value):null}function Yi(e,t){return{ok:!1,errorCode:e,reason:t}}function rb(e){if(e.change.name!=="className"&&e.change.name!=="class")return Zi("unsupported-owner",`No specialized property owner is available for '${e.change.name}'`);let t=e.classNameSource;if(!t||t.filePath!==e.node.file)return Zi("owner-source-unavailable","className source details are unavailable for the selected node");if(e.change.name==="class"&&t.sourceKind==="missing")return Zi("owner-source-unavailable","The class alias requires an existing className source");if(t.sourceKind==="expression")return Zi("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 Zi("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 Zi(e,t){return{ok:!1,errorCode:e,reason:t}}async function ib(e){let t=Aw.safeParse({kind:"set-props",scope:e.scope,changes:e.changes});if(!t.success)return hr("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 hr("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 Tw(e,r);if(o){if(!o.ok)return hr("owner-plan-failed",o.reason);ob(n,o.steps);continue}let i=await e.getPropertyState(e.node.key,r.name,e.selectionRef);if(!i)return hr("missing-property-state",`No authoritative property state is available for '${r.name}'`);if(i.status==="blocked")return hr("readonly-property",i.diagnostic?.message??`Property '${r.name}' is not writable`);if(Fw(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=dc({state:i,scope:e.scope,operation:r.operation,selectionRef:e.selectionRef,repeatTarget:s});if(!a.ok)return hr(a.code,a.reason);let c=a.target;if(c.kind==="value-binding"&&r.operation==="set"){sf(n,{type:"update-value",order:n.length,file:c.file,locator:c.locator,value:r.value});continue}if(c.kind==="repeat-property"){let l=nb({source:e.getFileContent(c.target.sourceFile),target:c.target,changes:[r]});if(!l.ok)return hr("repeat-target-failed",l.reason);ob(n,l.steps);continue}sf(n,{type:"set-property-changes",order:n.length,file:e.node.file,locator:ww(e.node),scope:e.scope,changes:[r]})}return n.forEach((r,o)=>{r.order=o}),Ow(n)?hr("step-conflict","Property changes resolve to conflicting write steps"):{ok:!0,steps:n}}async function Tw(e,t){return t.name!=="className"&&t.name!=="class"?null:rb({node:e.node,change:t,classNameSource:e.classNameSource})}function ww(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 Ow(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 ob(e,t){for(let n of t)sf(e,{...n,order:e.length})}function sf(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 Fw(e,t){if(t.operation!=="set"||e.status!=="direct")return!1;let n=e.attribute?.resolution;return n?.status==="resolved"?af(n.value,t.value):e.attribute?.source===null&&e.attribute.value===t.value}function af(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)=>af(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=>af(n[i],r[i]))}return!1}function hr(e,t){return{ok:!1,errorCode:e,reason:t}}import*as Oo from"@babel/types";import*as ie from"@babel/types";function cf(e,t,n){let r=rn(t,n);return r?An(e,r):null}function An(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(!ie.isIdentifier(l)||l.name!=="map"||c.computed)return null;let u=a.get("object"),d=To(e,u.node),f=r.node.params.map(m=>To(e,m)),g=Oe(i.node),p=Oe(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:ie.isOptionalMemberExpression(c)&&c.optional?"?.map":".map",collectionNeedsParens:fc(u.node),callbackPath:r,collectionPath:u}}function qi(e,t){return!!(e&&t&&e.callStart===t.callStart&&e.callEnd===t.callEnd&&e.callbackStart===t.callbackStart&&e.callbackEnd===t.callbackEnd)}function Lw(e,t){let n=Oe(e.node);return n?Dw(t).some(r=>{let o=Oe(r);return r===e.node||!!(o&&o.start===n.start&&o.end===n.end)}):!1}function Dw(e){let t=e.callbackPath.node.body;return ie.isBlockStatement(t)?yr(t.body):xr(t)}function yr(e){let t=[];for(let n of e){if(ie.isReturnStatement(n)){n.argument&&t.push(...xr(n.argument));continue}if(ie.isBlockStatement(n)){t.push(...yr(n.body));continue}if(ie.isIfStatement(n)){let r=ie.isBlockStatement(n.consequent)?n.consequent.body:[n.consequent];if(t.push(...yr(r)),n.alternate){let o=ie.isBlockStatement(n.alternate)?n.alternate.body:[n.alternate];t.push(...yr(o))}continue}if(ie.isSwitchStatement(n)){for(let r of n.cases)t.push(...yr(r.consequent));continue}ie.isTryStatement(n)&&(t.push(...yr(n.block.body)),n.handler&&t.push(...yr(n.handler.body.body)),n.finalizer&&t.push(...yr(n.finalizer.body)))}return t}function xr(e){return ie.isJSXElement(e)?Mw(e)?sb(e.children):[e]:ie.isJSXFragment(e)?sb(e.children):ie.isParenthesizedExpression(e)||ie.isTSAsExpression(e)||ie.isTSSatisfiesExpression(e)||ie.isTSNonNullExpression(e)||ie.isTSTypeAssertion(e)?xr(e.expression):ie.isConditionalExpression(e)?[...xr(e.consequent),...xr(e.alternate)]:ie.isLogicalExpression(e)&&of(e.operator)?xr(e.right):[]}function sb(e){return e.flatMap(t=>ie.isJSXElement(t)||ie.isJSXFragment(t)?xr(t):ie.isJSXExpressionContainer(t)&&(ie.isJSXElement(t.expression)||ie.isJSXFragment(t.expression)||ie.isConditionalExpression(t.expression)||ie.isLogicalExpression(t.expression))?xr(t.expression):[])}function Mw(e){let t=e.openingElement.name;return ie.isJSXIdentifier(t)?t.name==="Fragment":ie.isJSXMemberExpression(t)&&t.property.name==="Fragment"}function ab(e,t){return!!(e&&t&&e.callbackStart<t.callbackStart&&e.callbackEnd>t.callbackEnd)}function fc(e){return!(ie.isIdentifier(e)||ie.isThisExpression(e)||ie.isMemberExpression(e)||ie.isOptionalMemberExpression(e)||ie.isCallExpression(e)||ie.isOptionalCallExpression(e))}function cb(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(ie.isMemberExpression(n)||ie.isOptionalMemberExpression(n))&&ie.isIdentifier(n.property)&&n.property.name==="map"&&!n.computed}function wo(e,t){let n=dt(e);if(!n)return t.isRepeatItemRoot===!0;let r=Ee(n,De(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:cc(n,t);if(!o)return t.isRepeatItemRoot===!0;let i=An(e,o);return i?Lw(o,i):t.isRepeatItemRoot===!0}function lb(e,t){let n=dt(e);if(!n)return!1;let r=Ee(n,De(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:cc(n,t);return o?!!o.findParent(i=>{if(!i.isCallExpression()&&!i.isOptionalCallExpression())return!1;let s=i.node.callee;return(ie.isMemberExpression(s)||ie.isOptionalMemberExpression(s))&&ie.isIdentifier(s.property)&&s.property.name==="map"}):!1}import*as $e from"@babel/types";function lf(e){if($e.isJSXIdentifier(e))return/^[A-Z]/.test(e.name)?e.name:null;if($e.isJSXMemberExpression(e)){let t=e;for(;$e.isJSXMemberExpression(t);)t=t.object;return t.name}return null}function Bw(e,t){let n=Oe(e.node);if(!n)return[];let r=new Set,o=(i,s)=>{let a=s.scope.getBinding(i);!a||Pn(a.path.node,n)||br(a,i,t)||r.add(i)};return e.traverse({ReferencedIdentifier(i){o(i.node.name,i)},JSXOpeningElement(i){let s=lf(i.node.name);s&&o(s,i)}}),[...r].sort()}function uf(e,t,n){let r=dt(e);if(!r)return{ok:!0};let o=Ee(r,De(t));if(!o.ok||!o.match.path.isJSXElement())return{ok:!0};let i=Ee(r,De(n));if(!i.ok||!i.match.path.isJSXElement())return{ok:!0};let s=ui(o.match.path,i.match.path);if(lc(s,i.match.path))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let a=Bw(s,i.match.path);return a.length>0?{ok:!1,bindingNames:a}:{ok:!0}}function db(e){let t=e;for(;$e.isTSQualifiedName(t);)t=t.left;return $e.isIdentifier(t)?t.name:null}function Qi(e,t){e.isIdentifier()&&e.isReferencedIdentifier()&&t(e),e.traverse({ReferencedIdentifier(n){n.isIdentifier()&&t(n)}})}function pc(e){let t=[],n=r=>{if(r){if($e.isIdentifier(r)){t.push(r.name);return}if($e.isObjectPattern(r)){for(let o of r.properties){if($e.isRestElement(o)){n(o.argument);continue}$e.isObjectProperty(o)&&n(o.value)}return}if($e.isArrayPattern(r)){for(let o of r.elements)n(o);return}if($e.isAssignmentPattern(r)){n(r.left);return}if($e.isRestElement(r)){n(r.argument);return}$e.isTSParameterProperty(r)&&n(r.parameter)}};return n(e),t}function df(e,t){let n=Oe(e.node),r=Oe(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=ub(e),i=ub(t);if(!o||!i||!Qx(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=eb(s.node,n);if(a&&!Ut(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=Oe(s.node.right);if(a&&Ut(a,n)&&!Ut(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())&&cb(s)){let a=Oe(s.node.body)??Oe(s.node);if(a&&!Ut(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 ub(e){let t=e;for(;t;){if(t.isReturnStatement())return t.node.argument?Oe(t.node.argument):null;if(t.isArrowFunctionExpression()&&($e.isJSXElement(t.node.body)||$e.isJSXFragment(t.node.body)||$e.isConditionalExpression(t.node.body)||$e.isLogicalExpression(t.node.body)))return Oe(t.node.body);t=t.parentPath}return null}function br(e,t,n){return n.scope.getBinding(t)===e}function ff(e,t,n,r={}){if(!r.preserveConditionalBoundary&&lc(e,t))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let o=Oe(e.node);if(!o)return{ok:!0};let i=new Set(n.callbackPath.node.params.flatMap(c=>pc(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||Pn(u.path.node,o)||i.has(u.path.node)||br(u,c,t)||s.add(c)};return e.traverse({ReferencedIdentifier(c){a(c.node.name,c)},JSXOpeningElement(c){let l=lf(c.node.name);l&&a(l,c)}}),s.size>0?{ok:!1,bindingNames:[...s].sort()}:{ok:!0}}function pf(e,t,n){let r=Oe(e.node);if(!r)return{ok:!0};let o=new Set(n.callbackPath.node.params.flatMap(s=>pc(s)).map(s=>n.callbackPath.scope.getBinding(s)?.path.node).filter(Boolean)),i=new Set;return Qi(e,s=>{let a=s.scope.getBinding(s.node.name);!a||Pn(a.path.node,r)||o.has(a.path.node)||br(a,s.node.name,t)||i.add(s.node.name)}),i.size>0?{ok:!1,bindingNames:[...i].sort()}:{ok:!0}}function fb(e,t){let n=new Set(e.callbackPath.node.params.flatMap(a=>pc(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)||br(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(Oo.isIdentifier(l))o(l.name,c);else{let u=db(l);u&&o(u,c)}}});return r.size>0?{ok:!1,bindingNames:[...r].sort()}:{ok:!0}}function mf(e,t){let n=Oe(e.node),r=new Set;return Qi(e,o=>{let i=o.scope.getBinding(o.node.name);i&&(n&&Pn(i.path.node,n)||br(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 pb(e){let t=[];for(let n of e.callbackPath.node.params){if(Oo.isIdentifier(n)){t.push(n.name);continue}if(Oo.isRestElement(n)&&Oo.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 gf(e,t){return`${e.collectionNeedsParens?`(${e.collectionExpression})`:e.collectionExpression}${e.mapOperator}((${e.callbackParams.join(", ")}) => ${t})`}function es(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 gb(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 Zr(e){return{file:e.file,component:e.component}}function jw(e){return e.target.kind==="node"?e.target.key:null}function $w(e){return"kind"in e&&e.kind==="page-composition"}function hc(e){return typeof e=="object"&&e!==null&&"kind"in e&&e.kind==="block-boundary"}function mc(e){return!$w(e)&&!hc(e)}function Ef(e,t){let n=xc.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=xc.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function hf(e,t){let n=e.getFileContent(t.file);if(!n)return;let r=In(n,De(t));if(r.ok)return n.slice(r.match.start,r.match.end)}function vf(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 Vw(e){if(e.isNumericLiteral())return!0;if(!e.isUnaryExpression({operator:"-"}))return!1;let t=e.get("argument");return!Array.isArray(t)&&t.isNumericLiteral()}function Uw(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 yf(e){return e==="Cannot edit repeat-backed child node structure with a generic node operation"}function Kw(e){let t=$x(e.ast,e.sourceNode.component,e.targetParent.component);if(!t.ok)return{ok:!1,reason:t.reason};let n=df(t.path,e.targetParentPath);if(!n.ok)return{ok:!1,reason:n.reason};let r=Jw({source:e.source,sourceContext:e.sourceContext,callSitePath:t.path,targetParentPath:e.targetParentPath});if(!r.ok)return r;let o=kb(r.collectionExpression);return{ok:!0,context:{...e.sourceContext,collectionExpression:r.collectionExpression,collectionNeedsParens:o?fc(o):!0}}}function Jw(e){let t=Oe(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||Pn(a.path.node,t))return;let c=Hw(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=Gw(e.callSitePath,c.propName,e.source);if(!l.ok){o=l.reason;return}let u=Xw(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=mf(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}br(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:Yw(e.source,t,[...n.values()])}}function Xw(e,t){if(t.length===0)return e;let n=kb(e);if(!n)return null;let r=fc(n)?`(${e})`:e;for(let o of t){if(o.kind==="property"){r=zw(o.name)?`${r}.${o.name}`:`${r}[${JSON.stringify(o.name)}]`;continue}r=`${r}[${o.index}]`}return r}function zw(e){return/^[$A-Z_a-z][$\w]*$/.test(e)}function Hw(e,t,n){let r=Ww(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=Co(t,o);if(!i)return null;let s=r?.range??Oe(e.node);return s?{propName:i.propName,remainingPath:i.remainingPath,hasDefault:i.hasDefault,range:s}:null}function Ww(e,t){let n=e.parentPath;if(!n||!n.isMemberExpression()&&!n.isOptionalMemberExpression()||n.node.object!==e.node||!Pn(n.node,t)||n.node.computed||!Ae.isIdentifier(n.node.property))return null;let r=Oe(n.node);return r?{propertyName:n.node.property.name,range:r}:null}function Gw(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()&&Ae.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=To(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 Yw(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 kb(e){try{let n=Ib.parse(`const __VD_EXPR__ = (${e});`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0],r=Ae.isVariableDeclaration(n)?n.declarations[0]?.init:null;return r&&Ae.isExpression(r)?r:null}catch{return null}}function Zw(e){let t=Oe(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||Pn(s.path.node,t))return;let a=hb(s,e.sourceFile,e.targetFile);if(a){let c=e.targetParentPath.scope.getBinding(a.localName);if(c){let u=hb(c,e.targetFile,e.targetFile);(!u||u.moduleFile!==a.moduleFile||!qw(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 Qi(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 qw(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 hb(e,t,n){let r=Qw(e),o=r?.parentPath;if(!r||!o?.isImportDeclaration())return null;let i=o.node.source.value;if(typeof i!="string")return null;let s=Wr(t,i),a=i.startsWith(".")?Ef(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=Ae.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 Qw(e){let t=e.path;for(;t&&!t.isImportDeclaration();){if(t.isImportSpecifier()||t.isImportDefaultSpecifier()||t.isImportNamespaceSpecifier())return t;t=t.parentPath}return null}function yb(e,t,n,r){let o=rf(t,n);if(o.length===0)return{sourceJsx:r,conditionPaths:[]};let i=r,s=[];for(let a of o){let c=To(e,a.conditionPath.node);if(!c)return{sourceJsx:r,conditionPaths:[]};let l=eO(a.conditionPath,c);if(s.push(a.conditionPath),a.kind==="logical"){i=`${l} ${a.operator} ${nO(i)}`;continue}i=a.branch==="consequent"?`${l} ? ${i} : null`:`${l} ? null : ${i}`}return{sourceJsx:i,conditionPaths:s}}function eO(e,t){return tO(e.node)?t:`(${t})`}function tO(e){return Ae.isIdentifier(e)||Ae.isThisExpression(e)||Ae.isSuper(e)||Ae.isMemberExpression(e)||Ae.isOptionalMemberExpression(e)||Ae.isCallExpression(e)||Ae.isOptionalCallExpression(e)||Ae.isBooleanLiteral(e)||Ae.isNumericLiteral(e)||Ae.isStringLiteral(e)||Ae.isNullLiteral(e)||Ae.isUnaryExpression(e)}function nO(e){return e.trim().startsWith("<")?e:`(${e})`}var rO={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 gc(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=rO[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 oO(e,t){for(let n of e.program.body){if(!Ae.isImportDeclaration(n)||n.source.value!==t)continue;let r=n.specifiers.find(o=>Ae.isImportDefaultSpecifier(o));if(r&&Ae.isImportDefaultSpecifier(r))return r.local.name}return null}function iO(e,t,n){for(let r of e.program.body){if(!Ae.isImportDeclaration(r)||r.source.value!==t)continue;let o=r.specifiers.find(i=>Ae.isImportSpecifier(i)&&(Ae.isIdentifier(i.imported)?i.imported.name:i.imported.value)===n);if(o&&Ae.isImportSpecifier(o))return o.local.name}return null}function xb(e){let t=new Set;return gn(e,{Program(n){for(let r of Object.keys(n.scope.bindings))t.add(r);n.stop()}}),t}function bb(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n+=1;return`${e}${n}`}function sO(e,t){if(!e.component)return{localName:"Component"};let n=e.component,r=vf(e),o=dt(t);if(n.exportName!=="default"){let a=o?iO(o,n.source,n.exportName):null;if(a)return{localName:a};let c=o?bb(r,xb(o)):r;return{localName:c,importStep:xf(e,c)}}if(!o)return{localName:r,importStep:xf(e,r)};let i=oO(o,n.source);if(i)return{localName:i};let s=bb(r,xb(o));return{localName:s,importStep:xf(e,s)}}function aO(e,t){if(e.kind==="native-tag")return e.text?`<${e.tag}>${e.text}</${e.tag}>`:`<${e.tag} />`;let n=t??vf(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 cO(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?lO(e.props):void 0;return{kind:e.kind,component:{source:e.component.source,exportName:e.component.exportName},...t?{props:t}:{}}}function lO(e){return Object.fromEntries(Object.entries(e).filter(t=>Sf(t[1])))}function Sf(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(Sf):typeof e=="object"?Object.values(e).every(Sf):!1}function xf(e,t=vf(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 Eb(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 uO(e,t,n){let r=e;for(;r;){if(r===t)return!0;r=n.getNode(r)?.parentKey}return!1}function Fo(e,t){return`Operation kind '${e}' does not match params.kind '${t}'`}function If(e,t=e.path){return{kind:"value",root:e.root,path:t&&t.length>0?t:void 0,expectedRange:e.expectedRange}}function ts(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:If(e,t.slice(0,n)),index:r.index}}return null}function bf(e,t){return e.locator?e.collectionPathMap?.[t]?If(e.locator,e.collectionPathMap[t]):ts(e.locator)?fO(e.locator,pO(t,e.collectionIndexMap)):null:null}function dO(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:Rb(o,t)}function Rb(e,t){let[n,...r]=e;if(!n)return t;if(n.kind!=="property")return;let o=Rb(r,t);return o===void 0?void 0:{[n.name]:o}}function fO(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},If(e,i)}return null}function pO(e,t){return t?.[e]??e}function Sb(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 mO(e,t){return gO(e.root,t.root)&&yO(e.path??[],t.path??[])}function gO(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&&hO(e.sourceRange,t.sourceRange)}}function hO(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function yO(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 yc=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:Fo(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:Fo(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:Fo(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:Fo(t.kind,t.params.kind)};let r=t;if(hc(r.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page-block boundaries require the page-block resolver"};if(!mc(r.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};let o=Eb(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:Fo(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:Fo(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=jw(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):vb(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 vb(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:De(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?ib({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=bf(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:De(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=bf(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:De(t),segmentIndex:n,newText:r}]}}coerceTextValueForValueTarget(t,n,r,o="update-text"){let i=this.graph.getFileContent(t),s=dt(i);if(!s)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not inspect the value source`};let a=Ee(s,n);if(!a.ok)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not resolve the value source`};if(!Vw(a.match.path))return{ok:!0,value:r};let c=Uw(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=bf(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=dt(this.graph.getFileContent(t));if(!o)return!1;let i=Ee(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=ts(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=es(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:De(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||qx(n,t)>1)return null;let r=Ef(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(!mc(n.params.position))return hc(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=es(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=Ox(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=gc(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"?sO(n.params.node,this.graph.getFileContent(r.file)):void 0,E=x?.importStep;return E&&m.push({order:y++,file:r.file,type:"add-import",moduleSpecifier:E.moduleSpecifier,imports:E.imports}),m.push({order:y++,file:r.file,type:"insert-child",parentLocator:De(r),node:{jsx:aO(n.params.node,x?.localName)},placement:n.params.position.relation,anchorLocator:i?De(i):void 0}),this.buildPlan(t,n,m,o)}async planExternalBackedInsertChild(t,n,r,o,i,s){if(!mc(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:cO(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(!mc(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=ts(a.locator);if(!c)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child requires an array-backed target"};let l=dO(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"?Sb(0,a.collectionIndexMap):Sb(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=es(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 wo(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:")||lb(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&&wo(this.graph.getFileContent(r.file),r)||r.file!==o.file)return null;let c=this.graph.getFileContent(r.file),l=dt(c);if(!l)return null;let u=rn(l,r),d=rn(l,o);if(!u||!d)return null;let f=An(c,u),g=An(c,d);if(!qi(f,g))return null;if(a&&(s==="before"||s==="after")){let m=rn(l,a),y=m?An(c,m):null;if(!qi(f,y))return null}if(uc(u,d))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child across statement-level conditional branches"};let p=uf(c,r,o);return p.ok?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:De(r),targetParentLocator:De(o),placement:s,anchorLocator:a?De(a):void 0,selectionContext:Zr(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&&wo(this.graph.getFileContent(r.file),r)||r.file!==o.file)return null;let c=this.graph.getFileContent(r.file),l=dt(c);if(!l)return null;let u=rn(l,r),d=rn(l,o);if(!u||!d)return null;let f=An(c,u);if(!f)return null;let g=An(c,d);if(qi(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=cf(c,l,a);if(g&&!qi(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=gc(o,{kind:"native-tag",tag:r.tag});if(b)return{ok:!1,errorCode:"unsupported-operation",reason:b}}let p=hf(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(uc(u,d))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let m=yb(c,u,d,p);for(let b of m.conditionPaths){let S=pf(b,d,f);if(!S.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its condition depends on bindings outside the target scope: ${S.bindingNames.join(", ")}`}}let y=ff(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=fb(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 E=f;if(r.component!==o.component){let b=Kw({source:c,ast:l,sourceContext:f,sourceNode:r,targetParent:o,targetParentPath:d});if(!b.ok)return{ok:!1,errorCode:"unsupported-operation",reason:b.reason};E=b.context}else{let b=mf(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:De(r),targetParentLocator:De(o),placement:s,anchorLocator:a?De(a):void 0,repeatExpression:gf(E,m.sourceJsx),selectionContext:Zr(o)}],i)}planCrossFileRepeatTemplateHoistMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&wo(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=dt(c),d=dt(l);if(!u||!d)return null;let f=tb({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=rn(u,r),p=rn(d,o);if(!g||!p)return null;let m=df(f.callSitePath,p);if(!m.ok)return{ok:!1,errorCode:"unsupported-operation",reason:m.reason};let y=An(c,g);if(!y)return null;if(An(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")&&cf(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=gc(o,{kind:"native-tag",tag:r.tag});if(A)return{ok:!1,errorCode:"unsupported-operation",reason:A}}let E=hf(this.graph,r);if(!E)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(uc(g,p))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let b=yb(c,g,p,E);for(let A of b.conditionPaths){let w=pf(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 S=ff(g,p,y,{preserveConditionalBoundary:b.conditionPaths.length>0});if(!S.ok)return{ok:!1,errorCode:"unsupported-operation",reason:S.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${S.bindingNames.join(", ")}`};let C=Zw({sourceFile:r.file,targetFile:o.file,sourceContext:y,targetParentPath:p});if(!C.ok)return{ok:!1,errorCode:"unsupported-operation",reason:C.reason};let T=pb(y);if(!T.ok)return{ok:!1,errorCode:"unsupported-operation",reason:T.reason};let R=mb(y,T.callbackParams),_=[{order:0,file:r.file,type:"remove-node",locator:De(r),removeWhitespace:!0}];for(let A of C.imports)_.push({order:_.length,file:o.file,type:"add-import",moduleSpecifier:A.moduleSpecifier,imports:A.imports});return _.push({order:_.length,file:o.file,type:"insert-jsx-expression-child",parentLocator:De(o),expression:gf(R,b.sourceJsx),placement:s,anchorLocator:a?De(a):void 0,selectionContext:Zr(o)}),this.buildPlan(t,n,_,i)}async planMoveNode(t,n,r,o){if(!o.canMove)return{ok:!1,errorCode:"capability-denied",reason:"Cannot move this node"};if(hc(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,S=this.graph.getNode(b.anchorKey);if(!S||r.file!==S.file||r.component!==S.component)return{ok:!1,errorCode:"locator-miss",reason:"Source sibling move requires a sibling in the same component file"};let C=this.graph.getFileVersion(r.file);if(n.documentVersion!==C)return{ok:!1,errorCode:"stale-version",reason:`Document version ${n.documentVersion} is stale or otherwise does not match source sibling file version (current: ${C})`};let T=this.graph.getFileContent(r.file),R=dt(T),_=R?rn(R,r):null,A=R?rn(R,S):null,w=_?.parentPath,D=A?.parentPath;if(!_||!A||!w||!D||w.node!==D.node||!w.isJSXFragment()&&!(w.isJSXElement()&&ze(w)))return{ok:!1,errorCode:"unsupported-operation",reason:"Source sibling move requires two direct children of the same transparent Fragment"};let U=w.node.loc;return U?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:De(r),targetParentLocator:{kind:"jsx-node",strategy:"source-range",sourceRange:{startLine:U.start.line,startColumn:U.start.column,endLine:U.end.line,endColumn:U.end.column}},placement:b.relation,anchorLocator:De(S),selectionContext:Zr(r)}],o):{ok:!1,errorCode:"locator-miss",reason:"Source Fragment has no stable source range"}}let i=Eb(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(uO(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,S=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:S?.kind==="external-entry"?S.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=es(r,c,f);if(g&&!yf(g)&&!gb(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,S=await this.graph.getTextWriteTarget(d.key,0);if(b?.kind==="value-binding"&&S?.kind==="value-binding"&&b.locator&&S.locator){let C=ts(b.locator),T=ts(S.locator);if(C&&T&&b.file===S.file&&mO(C.locator,T.locator)){let R=C.index,_=T.index,A=u==="before"?_-(R<_?1:0):_+(R<_?0:1);return this.buildPlan(t,n,[{order:0,file:b.file,type:"move-array-item",locator:C.locator,fromIndex:R,toIndex:A}],o)}}}if(r.isRepeatItemRoot&&wo(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=yf(g)?g:p;if(m&&yf(m)){let b=this.planRepeatTemplateInternalMove(t,n,r,s,o,u,d);if(b)return b;let S=this.planRepeatTemplateHoistMove(t,n,r,s,o,u,d);if(S)return S;let C=this.planCrossFileRepeatTemplateHoistMove(t,n,r,s,o,u,d);return C||{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=gc(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=uf(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 E=[{order:0,file:r.file,type:"move-node",locator:De(r),targetParentLocator:De(s),placement:u,anchorLocator:d?De(d):void 0,selectionContext:Zr(s)}];return this.buildPlan(t,n,E,o)}planCrossFileMove(t,n,r,o,i,s,a){let c=[],l=0,u=this.graph.getFileContent(r.file),d=hf(this.graph,r)??`<${r.component} />`,f=Fx(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:De(r),removeWhitespace:!0}),r.importedFrom&&r.exportName){let p=r.tag??r.component,y={moduleSpecifier:Ef(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:De(o),node:{jsx:d},placement:s,anchorLocator:a?De(a):void 0,selectionContext:Zr(o)})}else c.push({order:l++,file:o.file,type:"insert-child",parentLocator:De(o),node:{jsx:d},placement:s,anchorLocator:a?De(a):void 0,selectionContext:Zr(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:ve(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 vb(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 _f from"@babel/generator";import{parse as TO,parseExpression as wO}from"@babel/parser";import*as v from"@babel/types";import*as Tn from"@babel/types";import kf from"@babel/generator";import*as Be from"@babel/types";var xO=typeof kf=="function"?kf:kf.default,bO=/(?:token|secret|key|password|authorization|cookie|signature|credential)/i,EO=/^((?:https?:)?\/\/)[^/@\s]+@/i,SO=/(\/(?:token|secret|api[-_]?key|password|credential|signature)\/)[^/?#]+/gi;function Nb(e,t){let n=Kt(e.callee);if(!n)return null;if(n==="fetch")return Rf(e.arguments[0],"GET",t,["fetch call"]);if(n.startsWith("axios.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(Cb(r))return Rf(e.arguments[0],r,t,["axios client contract"])}if(n.startsWith("ky.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(Cb(r))return Rf(e.arguments[0],r,t,["ky client contract"])}return null}function Rf(e,t,n,r){if(!e||Be.isSpreadElement(e)||Be.isJSXNamespacedName(e))return RO(t,n,r,"missing url argument");let o=ns(e);return{sourceKind:kO(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 ns(e){if(Be.isStringLiteral(e))return qr(e.value);if(Be.isTemplateLiteral(e))return qr(vO(e));if(Be.isBinaryExpression(e)&&e.operator==="+"){let t=ns(e.left),n=ns(e.right);return!t&&!n?void 0:qr(`${t??Cf(e.left)}${n??Cf(e.right)}`)}if(Be.isMemberExpression(e)){let t=Pb(e);if(t)return`env:${t}`}if(!(Be.isCallExpression(e)&&Kt(e.callee)==="new URL")){if(Be.isNewExpression(e)&&Be.isIdentifier(e.callee,{name:"URL"})){let[t,n]=e.arguments,r=t&&!Be.isSpreadElement(t)?ns(t):void 0,o=n&&!Be.isSpreadElement(n)?ns(n):void 0;return o&&r?qr(`${o} + ${r}`):r??o}if(Be.isIdentifier(e))return`:${e.name}`}}function vO(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+=Cf(r))}return t}function Cf(e){if(Be.isIdentifier(e))return`:${e.name}`;if(Be.isMemberExpression(e)){let t=Pb(e);if(t)return`env:${t}`}return`:${IO(e)}`}function IO(e){return xO(e,{comments:!1}).code.replace(/[^a-zA-Z0-9_$]+/g,"_").replace(/^_+|_+$/g,"")||"param"}function qr(e){let[t]=e.split("#"),[n,r]=t.split("?"),o=n.replace(EO,"$1<redacted>@").replace(SO,"$1<redacted>");if(!r)return o;let i=r.split("&").map(s=>{let[a]=s.split("=");return a?bO.test(a)?`${a}=<redacted>`:`${a}=:${a}`:""}).filter(Boolean).join("&");return i?`${o}?${i}`:o}function kO(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 RO(e,t,n,r){return{sourceKind:"unknown-api",method:e,confidence:"partial",evidence:[{file:t.file,reason:[...n,r].join("; ")}]}}function Cb(e){return["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(e)}function Pb(e){return!Be.isMemberExpression(e.object)||!Be.isIdentifier(e.object.object,{name:"process"})||!CO(e.object.property,"env")?null:Be.isIdentifier(e.property)?e.property.name:Be.isStringLiteral(e.property)?e.property.value:null}function CO(e,t){return Be.isIdentifier(e)&&e.name===t}function Kt(e){if(Be.isIdentifier(e))return e.name;if(Be.isMemberExpression(e)){let t=Kt(e.object),n=Be.isIdentifier(e.property)?e.property.name:Be.isStringLiteral(e.property)?e.property.value:null;if(t&&n)return`${t}.${n}`}return null}var NO=new Set(["list","listStrict","get","getStrict","getByUrl","getByUrlStrict","schema","categories"]),PO=new Set(["getConfig","submit"]);function _b(e,t){let n=Ab(Kt(e.callee),t);if(!n)return null;let r="cms.collections.";if(n.startsWith(r)){let i=n.slice(r.length);if(!NO.has(i))return null;let s=Nf(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(!PO.has(i))return null;let s=Nf(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=Nf(e,0)??_O(e,0,"path")??"/cms/:path",s=AO(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 Ab(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 Tb(e,t){let n=Kt(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 bc(e,t){let n=Kt(e.callee),r=t?Ab(n,t):n;return typeof r=="string"&&r.startsWith("cms.field.")}function Nf(e,t){let n=e.arguments[t];return Tn.isStringLiteral(n)?n.value:null}function _O(e,t,n){let r=e.arguments[t];if(!Tn.isObjectExpression(r))return null;for(let o of r.properties)if(Tn.isObjectProperty(o)&&!o.computed&&(Tn.isIdentifier(o.key)&&o.key.name===n||Tn.isStringLiteral(o.key)&&o.key.value===n)&&Tn.isStringLiteral(o.value))return o.value.value;return null}function AO(e){let t=/^\/collections\/([^/]+)(?:\/|$)/.exec(e)?.[1];return t&&/^[a-z0-9][a-z0-9_-]*$/i.test(t)?t:null}function wb(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 kt from"@babel/types";import{posix as Pf}from"node:path";function Lo(e,t,n=new Set){if(n.has(e))return;let r=new Set(n).add(e);if(kt.isBooleanLiteral(e))return e.value;if(kt.isUnaryExpression(e,{operator:"!"})){let l=Lo(e.argument,t,r);return l===void 0?void 0:!l}if(kt.isLogicalExpression(e)){let l=Lo(e.left,t,r),u=Lo(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(!kt.isCallExpression(e)||!kt.isIdentifier(e.callee))return;let o=t.imports.get(e.callee.name),i=o?.source.startsWith(".")&&t.file?Pf.normalize(Pf.join(Pf.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=kt.isExpression(s.body)?s.body:s.body.body.length===1&&kt.isReturnStatement(s.body.body[0])?s.body.body[0].argument:null;if(!a||!kt.isExpression(a))return;let c=s.params.flatMap(l=>kt.isIdentifier(l)?[l.name]:[]);return Lo(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 Cz=typeof _f=="function"?_f:_f.default,Ub=new WeakMap;function Kb(e){let t=new Map;return Ub.set(t,new Map([...e].map(n=>[n.file,n]))),t}var OO={maxFunctionDepth:8,maxImportDepth:6},FO=new Set(["src","href","alt","poster","content","title","aria-label"]),Ob=new WeakMap;function LO(e,t,n){let r=Ob.get(t.fileCache);r||(r=new WeakMap,Ob.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 Jb(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")&&Lb(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=Mf(e.file,e.source,t),r={file:e.file,analysis:n,readFile:e.readFile,exists:e.exists,fileCache:t,options:{...OO,...e.options},variableCache:new Map,functionDepth:0,importDepth:0,paramSources:new Map,paramArguments:new Map,resolvingVariables:new Set,resolvingComponentProps:new Set,scopeVariables:iE(n,e.element.componentName),scopeFunction:Bf(n,e.element.componentName)};await Xb(e.element.componentName,e.graph,r);let o=[];o.push(...await jO(e.element,e.graph,r),...await $O(e.element,e.graph,r));for(let s of e.element.textSegments){let a=await VO(s,e.element,e.graph,r);a&&o.push(Nc(a,"text","children"))}for(let s of e.element.attributes??[]){let a=Lb(s,e.element);if(!a)continue;let c=await Wb(s.source,e.element,e.graph,r);if(!c&&s.syntaxKind==="expression"&&!(s.source&&eo(s.source.base,e.element,e.graph))){let u=n.jsxElementsByRange.get(_c(e.element.sourceRange))?.openingElement.attributes.find(d=>v.isJSXAttribute(d)&&v.isJSXIdentifier(d.name,{name:s.name}));v.isJSXExpressionContainer(u?.value)&&v.isExpression(u.value.expression)&&!Yb(u.value.expression,e.element,e.graph)&&(c=await He(u.value.expression,r))}c&&o.push(Nc(c,a,s.name))}let i=QO(o).sort(rE);return{hasDynamicData:i.length>0,bindings:i}}async function Xb(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 LO(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 DO(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 Hb(l.sourceFile,n);if(!d)continue;let f=Ir(d,n,{importDepth:n.importDepth+1});f.paramSources.clear(),f.scopeVariables=iE(d,l.componentName),f.scopeFunction=Bf(d,l.componentName),f.lexicalContext=void 0,await Xb(l.componentName,t,f);let g=await MO(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=Df(u);d.length===1&&c.set(l,d[0])}BO(o,c,n)}var Fb=new WeakMap;function DO(e,t,n,r){let o=Fb.get(r.fileCache);return o||(o=wb(),Fb.set(r.fileCache,o)),o.resolve({fromFile:e,exportName:t,targetFile:n,maxImportDepth:r.options.maxImportDepth},()=>zb(e,t,n,r))}async function zb(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 Hb(e,r))?.imports.get(t);if(!s||!gt(s.source))return!1;let a=await $f(e,s.source,r.exists);return a?a===n?!0:zb(a,s.importedName,n,r,o):!1}async function MO(e,t,n){let r=new Map,o=n.analysis.jsxElementsByRange.get(_c(e.sourceRange));if(o)for(let s of o.openingElement.attributes)!v.isJSXAttribute(s)||!v.isJSXIdentifier(s.name)||!v.isJSXExpressionContainer(s.value)||!v.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?eo(c.base,e,t):null)?await Ac(c,e,t,n):Yb(a,e,t)?null:await He(a,n);u&&i.set(s,u)}return i}function _c(e){return`${e.startLine}:${e.startColumn}:${e.endLine}:${e.endColumn}`}async function Hb(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 Mf(e,r,t.fileCache)}function BO(e,t,n){if(v.isIdentifier(e)){t.size>0&&n.paramSources.set(e.name,Cc(Object.fromEntries(t),n.file));return}if(v.isObjectPattern(e))for(let r of e.properties){if(!v.isObjectProperty(r)||r.computed||!v.isIdentifier(r.key))continue;let o=t.get(r.key.name);if(!o)continue;let i=v.isAssignmentPattern(r.value)?r.value.left:r.value;v.isIdentifier(i)&&n.paramSources.set(i.name,yt(o))}}function Lb(e,t){return e.name==="dangerouslySetInnerHTML"?"richtext":FO.has(e.name)?"attribute":t.importedFrom||/^[A-Z]/.test(t.tag)?"component-prop":null}async function jO(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 Tc(i.collectionSource,n);s&&r.push(Nc(Er(s),"repeat-region",i.collectionExpression))}return r}async function $O(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 Tc(i.conditionSource,n);s&&r.push(Nc(Er(s),"conditional-region",i.conditionExpression))}return r}async function VO(e,t,n,r){if(!e.source){let i=r.analysis.jsxElementsByRange.get(_c(t.sourceRange))?.children.find(s=>v.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 v.isJSXExpressionContainer(i)&&v.isCallExpression(i.expression)&&bc(i.expression)?Gb(i.expression,t,n,r):null}return Wb(e.source,t,n,r)}async function Wb(e,t,n,r){return e&&eo(e.base,t,n)?Ac(e,t,n,r):Tc(e,r)}async function Ac(e,t,n,r,o){if(!e)return null;let i=eo(e.base,t,n,o);if(!i||i.candidate.itemParamName!==e.base)return null;let s=i.candidate.collectionSource,c=(s?eo(s.base,t,n,i.region):null)?await Ac(s,t,n,r,i.region):s?await Tc(s,r):await UO(i.candidate.collectionExpression,t,n,r,i.region);return c?rs(c,e.path,!0):null}async function UO(e,t,n,r,o){let i;try{i=wO(e,{plugins:["typescript","jsx"]})}catch{return null}return Gb(i,t,n,r,o)}async function Gb(e,t,n,r,o){let i=Ir(r.analysis,r),s=new Set;v.traverseFast(e,a=>{v.isIdentifier(a)&&s.add(a.name)});for(let a of s){let c=eo(a,t,n,o);if(!c)continue;if(c.candidate.itemParamName!==a)return null;let l=await Ac({kind:"identifier",expression:a,base:a,path:[]},t,n,r,o);if(!l)return null;i.paramSources.set(a,l)}return He(e,i)}function eo(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&&!Db(s.sourceRange,r.sourceRange))continue;let a=s.sourceCandidates?.find(c=>c.kind==="repeat-template"&&(c.itemParamName===e||c.indexParamName===e));a&&(!i||Db(i.region.sourceRange,s.sourceRange))&&(i={candidate:a,region:s})}o=n.elements.get(o)?.parentKey??null}return i}function Db(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 Yb(e,t,n){let r=!1;return v.traverseFast(e,o=>{!r&&v.isIdentifier(o)&&eo(o.name,t,n)&&(r=!0)}),r}async function Tc(e,t){if(!e)return null;let n=await Ff(e.base,t);return n?rs(n,e.path,!1):null}async function Ff(e,t){let n=t.paramSources.get(e);if(n)return yt(n);if(t.variableCache.has(e))return eF(t.variableCache.get(e)??null);let r=vr(e,t);if(r&&r!==t)return Ff(e,r);if(t.resolvingVariables.has(e))return null;t.resolvingVariables.add(e);let o=await JO(e,t);if(o)return t.variableCache.set(e,yt(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=v.isArrayExpression(s)&&s.elements.length===0?await KO(e,t):await He(s,t);return t.variableCache.set(e,c?yt(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 jf(a,t);if(c){let l=Ir(c,t,{importDepth:t.importDepth+1}),u=sE(a,c);if(u){let g=(await Qr(u,[],l)).returnSource;return t.variableCache.set(e,g?yt(g):null),t.resolvingVariables.delete(e),g}let d=c.variables.get(a.importedName);if(d){let f=await He(d,l);return t.variableCache.set(e,f?yt(f):null),t.resolvingVariables.delete(e),f}}}return t.variableCache.set(e,null),t.resolvingVariables.delete(e),null}function vr(e,t){return t.scopeVariables?.has(e)||t.scopeFunction?.params.some(n=>Sr(n).includes(e))?t:t.lexicalContext?vr(e,t.lexicalContext):void 0}function Ec(e,t,n=new Set){if(v.isIdentifier(e)){let s=vr(e.name,t);if(s&&s!==t)return Ec(e,s,n)}if(n.has(e))return null;if(n.add(e),v.isStringLiteral(e))return e.value;if(!v.isIdentifier(e))return null;let r=vr(e.name,t),o=t.paramArguments.get(e.name);if(o)return Ec(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?Ec(i,t,n):null}function wn(e,t,n=new Set){if(n.has(e))return null;let r=new Set(n).add(e);if(v.isStringLiteral(e))return e.value;if(v.isNumericLiteral(e))return String(e.value);if(v.isIdentifier(e)){if(/token|secret|password|authorization|cookie|credential/i.test(e.name))return":redacted";let o=vr(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?wn(s.expression,s.context,r):a?wn(a,i,r):null)??`:${e.name}`}if(v.isBinaryExpression(e,{operator:"+"})){let o=wn(e.left,t,r),i=wn(e.right,t,r);return o!==null&&i!==null?o+i:null}if(v.isTemplateLiteral(e)){let o=e.quasis[0]?.value.cooked??"";for(let[i,s]of e.expressions.entries()){if(!v.isExpression(s))return null;o+=(wn(s,t,r)??":param")+(e.quasis[i+1]?.value.cooked??"")}return o}if(v.isCallExpression(e)&&v.isIdentifier(e.callee)&&["encodeURIComponent","decodeURIComponent"].includes(e.callee.name)&&v.isExpression(e.arguments[0])){let o=wn(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 v.isTSAsExpression(e)||v.isTSNonNullExpression(e)||v.isParenthesizedExpression(e)?wn(e.expression,t,r):null}async function KO(e,t){let n=t.scopeFunction;if(!n)return null;let r=[],o=!1,i=0,s=u=>{let d=!1;return v.traverseFast(u,f=>{v.isIdentifier(f,{name:e})&&(d=!0)}),d},a=u=>{let d=u;for(;v.isMemberExpression(d);)d=d.object;return v.isIdentifier(d,{name:e})},c=async(u,d)=>{if(!o){if(v.isFunction(u)){s(u)&&(o=!0);return}if(v.isVariableDeclarator(u)&&(Sr(u.id).includes(e)&&i++,u.init&&s(u.init)&&(o=!0)),(v.isAssignmentExpression(u)||v.isUpdateExpression(u))&&a(v.isAssignmentExpression(u)?u.left:u.argument)){o=!0;return}if(v.isUnaryExpression(u,{operator:"delete"})&&a(u.argument)){o=!0;return}if(v.isCallExpression(u)){if(v.isMemberExpression(u.callee)&&v.isIdentifier(u.callee.object,{name:e})){if(!v.isIdentifier(u.callee.property,{name:"push"})||u.callee.computed||!u.arguments.length){o=!0;return}for(let f of u.arguments){let g=v.isSpreadElement(f)?f.argument:f,p=v.isExpression(g)?await He(g,d):null;p?r.push(Of(p)):o=!0}return}if(u.arguments.some(f=>s(f))){o=!0;return}}if(v.isForOfStatement(u)){let f=await He(u.right,d),g=Ir(d.analysis,d),p=v.isVariableDeclaration(u.left)?u.left.declarations[0]?.id:u.left;f&&p&&kc(p,Of(f),g),await c(u.body,g);return}for(let f of v.VISITOR_KEYS[u.type]??[]){let g=u[f];for(let p of Array.isArray(g)?g:[g])v.isNode(p)&&await c(p,d)}}};await c(n.body,t);let l=Df(r);return!o&&i===1&&l.length===1?Er(l[0]):null}async function JO(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 He(o,t);if(i)return i}return null}async function He(e,t){if(v.isIdentifier(e))return Ff(e.name,t);if(v.isMemberExpression(e)||v.isOptionalMemberExpression(e)){let n=v.isMemberExpression(e)?Tb(e,{file:t.file}):null;if(n)return tE(n);let r=await XO(e,t);if(!r)return null;let o=qO(e);return rs(r,o,!1)}if(v.isAwaitExpression(e))return v.isExpression(e.argument)?He(e.argument,t):null;if((v.isCallExpression(e)||v.isOptionalCallExpression(e))&&(v.isMemberExpression(e.callee)||v.isOptionalMemberExpression(e.callee))&&!e.callee.computed&&v.isIdentifier(e.callee.property)&&["trim","trimStart","trimEnd"].includes(e.callee.property.name)&&e.arguments.length===0&&v.isExpression(e.callee.object))return Mo(await He(e.callee.object,t));if(v.isCallExpression(e))return qb(e,t);if(v.isObjectExpression(e)){let n=await eE(e,t);return Object.keys(n).length>0?Cc(n,t.file):null}if(v.isArrayExpression(e)){let n={};for(let[r,o]of e.elements.entries()){if(!v.isExpression(o))continue;let i=await He(o,t);i&&(n[String(r)]=i)}return Object.keys(n).length?Cc(n,t.file):null}if(v.isConditionalExpression(e)){let n=await He(e.consequent,t),r=await He(e.alternate,t);return Mo(jb(n,r))}if(v.isLogicalExpression(e)){let n=await He(e.left,t),r=await He(e.right,t);return Mo(jb(n,r))}return v.isTSAsExpression(e)||v.isTSSatisfiesExpression(e)||v.isTSNonNullExpression(e)||v.isTypeCastExpression(e)||v.isParenthesizedExpression(e)?He(e.expression,t):null}async function XO(e,t){let n=e;for(;v.isMemberExpression(n)||v.isOptionalMemberExpression(n);)n=n.object;return v.isExpression(n)?He(n,t):null}var Af=new WeakMap;function wf(e,t){let n=Af.get(e)?.get(t);if(n!==void 0)return n;let r=new Set([t]),o=l=>{let u=l;for(;v.isMemberExpression(u)||v.isOptionalMemberExpression(u);)u=u.object;return v.isIdentifier(u)?u.name:null},i=!0;for(;i;)i=!1,v.traverseFast(e,l=>{if(!v.isVariableDeclarator(l)||!l.init)return;let u=o(l.init);if(!(!u||!r.has(u)))for(let d of Object.keys(v.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(v.getBindingIdentifiers(l)).some(d=>r.has(d))},a=!1;v.traverseFast(e,l=>{(v.isAssignmentExpression(l)&&s(l.left)||v.isUpdateExpression(l)&&s(l.argument)||v.isUnaryExpression(l,{operator:"delete"})&&s(l.argument))&&(a=!0)});let c=Af.get(e)??new Map;return c.set(t,a),Af.set(e,c),a}async function Zb(e,t,n=0){if(n>=t.options.maxFunctionDepth)return null;let r=vr(e,t);if(r){if(r.scopeFunction&&wf(r.scopeFunction,e))return null;let s=r.paramArguments.get(e);return s&&v.isIdentifier(s.expression)?Zb(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)||wf(t.analysis.ast,e))return null;let i=await $f(t.file,o.source,t.exists);return i?{...o,source:i}:null}async function qb(e,t){let n=e.arguments[0],r=v.isExpression(n)?Ec(n,t):null,i=Kt(e.callee)?.split(".")[0],s=i?await Zb(i,t):null,a=r!==null&&!v.isStringLiteral(n)?{...e,arguments:[v.stringLiteral(r),...e.arguments.slice(1)]}:e;if(s&&["cmsFetch","cmsFetchResult","cmsFetchEnvelope"].includes(s.importedName)&&v.isObjectExpression(n)){let x=Qb(n,"path"),E=x&&wn(x,t);E?.startsWith("/")&&(a={...e,arguments:[{...n,properties:n.properties.map(b=>v.isObjectProperty(b)&&jo(b)==="path"?{...b,value:v.stringLiteral(qr(E))}:b)},...e.arguments.slice(1)]})}let c=_b(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"&&v.isObjectExpression(n)){let x=Mb(n,"query"),E=v.isObjectExpression(x)?Mb(x,"path"):null,S=(E&&wn(E,t))?.match(/^\/([a-z0-9][a-z0-9_-]*)\/[^/?#]+(?:[?#].*)?$/i)?.[1];S&&(c.collection=S,c.evidence.push({file:t.file,reason:"CMS collection namespace from the actual content request path"}))}if(v.isMemberExpression(e.callee)){let x=await Hn(e.callee,t);if(x&&!Sc(x.node))return null;if(x&&Sc(x.node)){let E=await Tf(e,t,{node:x.node,context:x.context});return E&&{...E,...E.sourceKind===c.sourceKind?{operation:c.operation}:{}}}}if((c.operation==="getByUrl"||c.operation==="getByUrlStrict")&&v.isExpression(n)){let x=wn(n,t);x?.startsWith("/")&&(c.endpointPattern=qr(x))}return tE(c)}if(Kt(e.callee)==="Promise.all"&&v.isArrayExpression(n))return He(n,t);if(bc(e)){if(!bc(e,{file:t.file,imports:i&&s?new Map([[i,s]]):new Map})||!v.isExpression(e.callee))return null;let x=await Hn(e.callee,t);if(x)return Sc(x.node)?Tf(e,t,{node:x.node,context:x.context}):null;let E=e.arguments[0];if(E&&v.isExpression(E))return Mo(await He(E,t))}let l=await zO(e,t);if(l)return l;let u=Nb(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 WO(e,t);if(d)return d;let f=await GO(e,t);if(f)return f;let g=await YO(e,t);if(g)return g;let p=await Tf(e,t);if(p)return p;let m=[];for(let x of e.arguments)if(v.isExpression(x)){let E=await He(x,t);E&&m.push(E)}let y=Df(m);return y.length===1?Mo(y[0]):null}async function zO(e,t){let n=Kt(e.callee);if(n!=="useQuery"&&n!=="useSuspenseQuery"&&n!=="useInfiniteQuery"&&n!=="useSWR")return null;if(n==="useSWR"){let i=HO(e.arguments[0],t.file,"SWR key"),s=e.arguments[1];if(v.isIdentifier(s)){let a=await Bo(s.name,t);if(a)return(await Qr(a.node,i?[i]:[],a.context)).returnSource??i}return i}let r=e.arguments[0];if(!v.isObjectExpression(r))return vc(t.file,`${n} without static options`);let o=Qb(r,"queryFn");if(!o)return vc(t.file,`${n} without queryFn`);if(v.isIdentifier(o)){let i=await Bo(o.name,t);return i?(await Qr(i.node,[],i.context)).returnSource:vc(t.file,`${n} queryFn unresolved`)}return v.isArrowFunctionExpression(o)||v.isFunctionExpression(o)?(await Qr(o,[],t)).returnSource:v.isCallExpression(o)?qb(o,t):null}function Qb(e,t){for(let n of e.properties){if(!v.isObjectProperty(n)||!v.isExpression(n.value))continue;if(jo(n)===t)return n.value}return null}function Mb(e,t){let n=new Set;for(let i of e.properties){if(!v.isObjectProperty(i)||i.computed)return null;let s=jo(i);if(!s||n.has(s))return null;n.add(s)}let r=e.properties.filter(i=>v.isObjectProperty(i)&&jo(i)===t);if(r.length!==1)return null;let o=r[0];return v.isObjectProperty(o)&&v.isExpression(o.value)?o.value:null}function HO(e,t,n){return v.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 WO(e,t){if(!v.isMemberExpression(e.callee)||!v.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=v.isExpression(e.callee.object)?await He(e.callee.object,t):null;if(!r)return null;if(n!=="map")return Er(r);let o=e.arguments[0];if(v.isIdentifier(o)){let i=await Bo(o.name,t);if(!i)return Er(r);let s=await Qr(i.node,[r],i.context);return{...Er(r),...s.objectReturnMap??s.returnSource?.fieldMap?{fieldMap:s.objectReturnMap??s.returnSource.fieldMap}:{}}}if(v.isArrowFunctionExpression(o)||v.isFunctionExpression(o)){let i=await Qr(o,[r],t);return{...Er(r),...i.objectReturnMap??i.returnSource?.fieldMap?{fieldMap:i.objectReturnMap??i.returnSource.fieldMap}:{}}}return Er(r)}async function GO(e,t){return!v.isMemberExpression(e.callee)||!v.isIdentifier(e.callee.property,{name:"json"})||!v.isExpression(e.callee.object)?null:He(e.callee.object,t)}async function YO(e,t){return!v.isMemberExpression(e.callee)||!v.isIdentifier(e.callee.property,{name:"then"})||!v.isExpression(e.callee.object)?null:Mo(await He(e.callee.object,t))}async function Tf(e,t,n){let r=n;if(!r&&v.isIdentifier(e.callee))r=await Bo(e.callee.name,t)??void 0;else if(!r&&v.isMemberExpression(e.callee)){let s=await Hn(e.callee,t);s&&Sc(s.node)&&(r={node:s.node,context:s.context})}if(!r)return null;let o=[];for(let s of e.arguments){if(!v.isExpression(s)){o.push(vc(t.file,`unsupported argument for ${Kt(e.callee)??"call"}`));continue}let a=await He(s,t);o.push(a)}return(await Qr(r.node,o,r.context,{arguments:e.arguments,context:t})).returnSource}function Sc(e){return v.isFunctionDeclaration(e)||Pc(e)||v.isObjectMethod(e)&&e.kind==="method"}async function Hn(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(v.isTSAsExpression(e)||v.isTSSatisfiesExpression(e)||v.isTSNonNullExpression(e))return Hn(e.expression,t,o);if(v.isIdentifier(e)){let i=vr(e.name,t),s=i??t;if(wf(i?.scopeFunction??t.analysis.ast,e.name))return r;let a=s.paramArguments.get(e.name);if(a)return Hn(a.expression,a.context,o);let c=i?i.scopeVariables?.get(e.name):s.analysis.variables.get(e.name);if(c)return Hn(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 jf(u,s);return d?Hn(v.identifier(u.importedName),Ir(d,s,{importDepth:s.importDepth+1}),o):null}if(v.isMemberExpression(e)&&v.isExpression(e.object)){let i=e.computed?v.isStringLiteral(e.property)?e.property.value:null:v.isIdentifier(e.property)?e.property.name:null;if(!i)return null;let s=await Hn(e.object,t,o);if(!s)return null;if(!v.isObjectExpression(s.node))return{node:null,context:s.context};if(s.node.properties.some(l=>v.isSpreadElement(l)||l.computed))return{node:null,context:s.context};let a=s.node.properties.filter(l=>(v.isObjectMethod(l)||v.isObjectProperty(l))&&(v.isIdentifier(l.key)?l.key.name:v.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 v.isObjectMethod(c)?c.kind==="method"?{node:c,context:s.context}:null:v.isObjectProperty(c)&&v.isExpression(c.value)?Hn(c.value,s.context,o):null}return{node:e,context:t}}async function Bo(e,t,n=new Set){let r=t.paramArguments.get(e);if(r&&!n.has(r.expression)){if(n.add(r.expression),Pc(r.expression))return{node:r.expression,context:r.context};if(v.isIdentifier(r.expression))return Bo(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 jf(i,t);if(!s)return null;let a=Ir(s,t,{importDepth:t.importDepth+1}),c=sE(i,s);return c?{node:c,context:a}:Bo(i.importedName,a)}async function Qr(e,t,n,r){if(n.functionDepth>=n.options.maxFunctionDepth)return{returnSource:null};let o=Ir(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 Sr(d))o.paramSources.delete(y),o.paramArguments.delete(y);let g=v.isAssignmentPattern(d)?d.left:d,p=r?.arguments[f];v.isIdentifier(g)&&v.isExpression(p)&&r&&o.paramArguments.set(g.name,{expression:p,context:r.context});let m=t[f];m&&kc(d,Of(m),o)});let a=ZO(e,o),c=null,l,u=!1;for(let d of a){let f=Ir(n.analysis,o);if(v.isObjectExpression(d)){l={...l??{},...await eE(d,f)},c=c??Cc(l,n.file);continue}let g=await He(d,f);if(g){if(!c){c=g;continue}let p=Lf(c,g);if(!p){u=!0,c=null;continue}c=p}}return{returnSource:u?null:c,...l?{objectReturnMap:l}:{}}}function kc(e,t,n){if(v.isIdentifier(e)){n.paramSources.set(e.name,yt(t));return}if(v.isAssignmentPattern(e)){kc(e.left,t,n);return}if(v.isObjectPattern(e))for(let r of e.properties){if(!v.isObjectProperty(r)||r.computed||!v.isIdentifier(r.key))continue;let o=rs(t,[{kind:"property",name:r.key.name}],!0),i=v.isAssignmentPattern(r.value)?r.value.left:r.value;o&&kc(i,o,n)}}function ZO(e,t){if(v.isArrowFunctionExpression(e)&&v.isExpression(e.body))return[e.body];let n=[],r=e.body;if(!v.isBlockStatement(r))return n;let o=i=>{if(v.isFunction(i)&&i!==e)return;if(v.isReturnStatement(i)){i.argument&&v.isExpression(i.argument)&&n.push(i.argument);return}if(v.isIfStatement(i)){let a=Lo(i.test,{file:t.file,imports:new Map([...t.analysis.imports].filter(([c])=>!vr(c,t))),functions:t.analysis.functions});if(a!==void 0){a?o(i.consequent):i.alternate&&o(i.alternate);return}}let s=v.VISITOR_KEYS[i.type];for(let a of s??[]){let c=i[a];if(Array.isArray(c))for(let l of c)v.isNode(l)&&o(l);else v.isNode(c)&&o(c)}};return o(r),n}async function eE(e,t){let n={};for(let r of e.properties){if(!v.isObjectProperty(r))continue;let o=jo(r);if(!o||!v.isExpression(r.value))continue;let i=await He(r.value,t);i&&(n[o]=i)}return n}function jo(e){return v.isIdentifier(e.key)&&!e.computed?e.key.name:v.isStringLiteral(e.key)?e.key.value:null}function qO(e){let t=[],n=e;for(;v.isMemberExpression(n)||v.isOptionalMemberExpression(n);){let r=n.property;n.computed?v.isStringLiteral(r)?t.unshift({kind:"property",name:r.value}):v.isNumericLiteral(r)&&t.unshift({kind:"index",index:r.value}):v.isIdentifier(r)&&t.unshift({kind:"property",name:r.name}),n=n.object}return v.isIdentifier(n),t}function rs(e,t,n){if(t.length===0)return yt(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?rs(s,t.slice(1),n):null}let i=yt(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=Do(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=Do(i.valuePath,"data")),i.fieldPath=Do(i.fieldPath,s.slice(a+1).join(".")),i.cmsFieldRoot=!0,i):i.cmsFieldRoot||n||i.fieldMap?(i.fieldPath=Do(i.fieldPath,s.join(".")),i):(i.valuePath=Do(i.valuePath,Bb(t)),i)}return i.valuePath=Do(i.valuePath,Bb(t)),i}function Bb(e){return e.map(t=>t.kind==="property"?t.name:`[${t.index}]`).join(".").replace(/\.\[/g,"[")}function Do(e,t){return t?e?t.startsWith("[")?`${e}${t}`:`${e}.${t}`:t:e}function tE(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 Er(e){let t=yt(e);return t.sourceType==="cms-field"&&!t.valuePath&&(t.valuePath="items[]"),t}function Of(e){let t=yt(e);return t.valuePath=void 0,t.sourceType==="cms-field"&&!t.fieldPath&&(t.cmsFieldRoot=!1),t}function Mo(e){return e?{...yt(e),confidence:e.confidence==="unknown"?"unknown":"safe-derived",evidence:[...e.evidence,{file:e.evidence[0]?.file??"unknown",reason:"safe derived expression"}]}:null}function jb(e,t){return e?t?Lf(e,t):yt(e):t?yt(t):null}function Lf(e,t){if(Rc(e)!==Rc(t))return null;let n=oE(e.confidence,t.confidence)<=0?e.confidence:t.confidence;return{...e,confidence:n,evidence:[...e.evidence,...t.evidence]}}function Df(e){let t=new Map;for(let n of e){let r=Rc(n),o=t.get(r);t.set(r,o?Lf(o,n):yt(n))}return[...t.values()]}function Rc(e){let t=e.fieldMap?Object.fromEntries(Object.entries(e.fieldMap).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>[n,Rc(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 Cc(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 vc(e,t){return{sourceKind:"unknown-api",sourceType:"api-field",confidence:"unknown",readonly:!0,evidence:[{file:e,reason:t}]}}function Nc(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 nE(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 QO(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 $b(e.targetKind)-$b(t.targetKind)||oE(e.confidence,t.confidence)||Vb(e.sourceKind)-Vb(t.sourceKind)||e.targetName.localeCompare(t.targetName)}function $b(e){return{"repeat-region":0,"conditional-region":1,text:2,richtext:3,attribute:4,"component-prop":5}[e]}function Vb(e){return e.startsWith("vcp-cms-")?0:e==="site-api-route"?1:e==="external-api"?2:3}function oE(e,t){let n={exact:0,"safe-derived":1,partial:2,unknown:3};return n[e]-n[t]}function Mf(e,t,n){let r=n.get(e);if(r?.source===t)return r;let o=Ub.get(n)?.get(e),i=o?.source===t?o.ast:TO(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=[];v.traverse(i,{enter(d){switch(v.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=_c({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)v.isImportSpecifier(g)&&v.isIdentifier(g.local)?s.imports.set(g.local.name,{source:f,importedName:v.isIdentifier(g.imported)?g.imported.name:g.imported.value,localName:g.local.name,isDefault:!1}):v.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&&(v.isFunctionDeclaration(f)||v.isFunctionExpression(f)||v.isArrowFunctionExpression(f)||v.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 Ic(d.id,v.isExpression(d.init)?d.init:null))p.set(m,y);if(v.isArrayPattern(d.id)&&v.isCallExpression(d.init)&&Kt(d.init.callee)==="useState"){let[m,y]=d.id.elements;v.isIdentifier(m)&&v.isIdentifier(y)&&s.stateSetters.set(m.name,y.name)}v.isIdentifier(d.id)&&Pc(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(!v.isExportSpecifier(p))continue;let m=v.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(v.isFunctionDeclaration(f)&&f.id?.name&&s.functions.set(f.id.name,f),v.isVariableDeclaration(f))for(let p of f.declarations)v.isIdentifier(p.id)&&Pc(p.init)&&s.functions.set(p.id.name,p.init);break}case"ExportDefaultDeclaration":{let f=d.declaration;if((v.isFunctionDeclaration(f)||v.isFunctionExpression(f)||v.isArrowFunctionExpression(f))&&s.functions.set("default",f),v.isIdentifier(f)){let g=s.functions.get(f.name);g&&s.functions.set("default",g)}break}}},exit(d){v.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=v.isIdentifier(d.callee)?d.callee.name:null;f&&l.has(f)&&v.isExpression(d.arguments[0])&&u(f,d.arguments[0]);let g=new Set;for(let p of d.arguments)v.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 Ic(e,t){return v.isIdentifier(e)?[[e.name,t]]:v.isAssignmentPattern(e)?Ic(e.left,t):v.isArrayPattern(e)?e.elements.flatMap((n,r)=>n&&!v.isRestElement(n)?Ic(n,t?v.memberExpression(t,v.numericLiteral(r),!0):null):[]):v.isObjectPattern(e)?e.properties.flatMap(n=>{if(!v.isObjectProperty(n)||n.computed)return[];let r=jo(n);return r?Ic(n.value,t?v.memberExpression(t,v.stringLiteral(r),!0):null):[]}):[]}function Sr(e){return!e||v.isVoidPattern(e)?[]:v.isIdentifier(e)?[e.name]:v.isObjectPattern(e)?e.properties.flatMap(t=>v.isObjectProperty(t)?Sr(t.value):Sr(t.argument)):v.isArrayPattern(e)?e.elements.flatMap(t=>t?Sr(v.isRestElement(t)?t.argument:t):[]):v.isAssignmentPattern(e)?Sr(e.left):v.isRestElement(e)?Sr(e.argument):[]}function Pc(e){return v.isFunctionExpression(e)||v.isArrowFunctionExpression(e)}function iE(e,t){let n=Bf(e,t);return n?e.functionVariables.get(n):void 0}function Bf(e,t){return e.functions.get(t)??e.functions.get("default")}async function jf(e,t){let n=await $f(t.file,e.source,t.exists);if(!n)return null;let r=await t.readFile(n);return Mf(n,r,t.fileCache)}function sE(e,t){return e.isDefault?t.functions.get("default")??t.functions.get(e.localName)??null:t.functions.get(e.importedName)??null}async function $f(e,t,n){return gt(t)?Tr(e,t,n):null}function Ir(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 eF(e){return e?yt(e):null}function yt(e){return{...e,evidence:e.evidence.map(t=>({...t})),...e.fieldMap?{fieldMap:Object.fromEntries(Object.entries(e.fieldMap).map(([t,n])=>[t,yt(n)]))}:{}}}import*as Uf from"@babel/parser";import Vf from"@babel/traverse";import*as se from"@babel/types";import{classifySiteEditPropertyName as tF}from"@vcp-dev/contracts";var Kf=typeof Vf=="function"?Vf:Vf.default;function Jf(e){let t=tF(e.propertyName);if(t.owner!=="generic")return Jt("invalid-property",t.diagnostic?.message??`Property '${e.propertyName}' is not a generic property`);let n=e.selectionRef;if(!n)return Jt("missing-selection-ref","A repeat property target requires a complete selection reference");if(n.key!==e.element.identity.key)return Jt("selection-mismatch","Selection reference does not identify the requested element");if(n.instanceIndex===void 0)return Jt("missing-instance-index","A repeat property target requires an instance index");let r;try{r=Uf.parse(e.source,{sourceType:"module",plugins:["typescript","jsx"]})}catch(y){return Jt("repeat-not-found",`Unable to parse repeat source: ${y instanceof Error?y.message:String(y)}`)}let o=nF(r,e.element.sourceRange);if(!o)return Jt("repeat-not-found","The selected element is not inside a supported map repeat");if(!se.isIdentifier(o.callback.params[0]))return Jt("unsupported-callback","Repeat property materialization requires an identifier callback item");let i=rF(r,o.collection,e.file,e.sources);if(!i)return Jt("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||!se.isObjectExpression(x)||!fE(x))return Jt("unsafe-collection","Repeat materialization requires an array of local static objects without spreads");let E=[{kind:"index",index:y}];l.push(E),u.push({kind:"value",root:a.root,path:E})}let d=u.length;if(n.instanceCount!==void 0&&n.instanceCount!==d)return Jt("count-mismatch",`Selection reports ${n.instanceCount} instances but the source collection has ${d}`);let f=n.instanceIndex;if(f>=d)return Jt("index-out-of-range",`Selected repeat instance ${f} is outside the source collection`);let g=s.elements[f];if(!g||!se.isObjectExpression(g))return Jt("unsafe-collection","Selected repeat item is not an object");let p=lF(e.element,e.propertyName),m=aF(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:cF(g,e.propertyName),...p?{property:p}:{},selectionRef:n}:Jt("unsafe-property-source",`Property '${e.propertyName}' has a dynamic or unsupported source in the repeat item`)}function nF(e,t){let n=[];return Kf(e,{CallExpression(r){let o=aE(r.node);o&&lE(o.callback,t)&&n.push({...o,span:cE(r.node)})},OptionalCallExpression(r){let o=aE(r.node);o&&lE(o.callback,t)&&n.push({...o,span:cE(r.node)})}}),n.sort((r,o)=>r.span-o.span),n[0]??null}function aE(e){let t=e.callee;if(!se.isMemberExpression(t)&&!se.isOptionalMemberExpression(t)||t.computed||!se.isIdentifier(t.property)||t.property.name!=="map"||!se.isExpression(t.object))return null;let n=e.arguments[0];return!n||!se.isExpression(n)||!se.isArrowFunctionExpression(n)&&!se.isFunctionExpression(n)?null:{collection:t.object,callback:n}}function rF(e,t,n,r){let o=os(t);if(o&&se.isArrayExpression(o))return{array:o,locator:{kind:"value",root:{kind:"expression",sourceRange:mE(o)}},sourceFile:n};if(!se.isIdentifier(t))return null;let i=[];if(Kf(e,{VariableDeclarator(s){se.isIdentifier(s.node.id)&&s.node.id.name===t.name&&s.node.init&&i.push(s.node)}}),i.length===1){let s=os(i[0].init);return!s||!se.isArrayExpression(s)?null:{array:s,locator:{kind:"value",root:{kind:"binding",name:t.name}},sourceFile:n}}return oF(e,t.name,n,r)}function oF(e,t,n,r){if(!r)return null;for(let o of e.program.body){if(!se.isImportDeclaration(o))continue;let i=o.specifiers.find(f=>f.local.name===t);if(!i||!se.isStringLiteral(o.source)||!se.isImportSpecifier(i))continue;let s=sF(n,o.source.value,r);if(!s)return null;let a=se.isIdentifier(i.imported)?i.imported.name:i.imported.value,c=r.get(s);if(c===void 0)return null;let l;try{l=Uf.parse(c,{sourceType:"module",plugins:["typescript","jsx"]})}catch{return null}let u=iF(l,a),d=u?os(u):null;return!d||!se.isArrayExpression(d)?null:{array:d,locator:{kind:"value",root:{kind:"binding",name:a}},sourceFile:s}}return null}function iF(e,t){let n=null;return Kf(e,{VariableDeclarator(r){n||!se.isIdentifier(r.node.id)||r.node.id.name!==t||!r.node.init||!se.isExpression(r.node.init)||(n=r.node.init)}}),n}function sF(e,t,n){let r=En(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 os(e){return se.isParenthesizedExpression(e)?os(e.expression):se.isTSAsExpression(e)?dE(e.typeAnnotation)?os(e.expression):null:se.isTSSatisfiesExpression(e)?null:e}function dE(e){return se.isTSTypeReference(e)&&se.isIdentifier(e.typeName)&&e.typeName.name==="const"}function fE(e){return e.properties.every(t=>!se.isObjectProperty(t)||t.computed||!se.isExpression(t.value)?!1:wc(t.value))}function wc(e){if(se.isTSAsExpression(e)&&dE(e.typeAnnotation))return wc(e.expression);if(se.isTSSatisfiesExpression(e))return!1;if(se.isArrayExpression(e))return e.elements.every(n=>!n||se.isSpreadElement(n)||!se.isExpression(n)?!1:wc(n));if(se.isObjectExpression(e))return fE(e);let t=Rn(e);return t.status==="resolved"||t.status==="undefined"}function aF(e,t){let n=e.properties.filter(o=>se.isObjectProperty(o)&&pE(o.key)===t);if(n.length>1)return null;let r=n[0];return r?se.isExpression(r.value)?wc(r.value)?"static":se.isIdentifier(r.value)||se.isMemberExpression(r.value)?"binding":null:null:"missing"}function cF(e,t){let n=e.properties.filter(o=>se.isObjectProperty(o)&&pE(o.key)===t);if(n.length>1)return{status:"unresolved"};let r=n[0];return!r||!se.isExpression(r.value)?{status:"undefined"}:Rn(r.value)}function lF(e,t){let n=e.attributes?.filter(r=>r.name===t)??[];return n.length===1?n[0]:void 0}function pE(e){return se.isIdentifier(e)?e.name:se.isStringLiteral(e)?e.value:se.isNumericLiteral(e)?String(e.value):null}function mE(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 cE(e){return e.start==null||e.end==null?Number.MAX_SAFE_INTEGER:e.end-e.start}function lE(e,t){let n=mE(e);return uE(n.startLine,n.startColumn,t.startLine,t.startColumn)<=0&&uE(n.endLine,n.endColumn,t.endLine,t.endColumn)>=0}function uE(e,t,n,r){return e===n?t-r:e-n}function Jt(e,t){return{ok:!1,errorCode:e,reason:t}}import{classifySiteEditPropertyName as HF}from"@vcp-dev/contracts";import*as le from"@babel/types";import ls from"node:path";import*as G from"@babel/types";import*as EE from"@babel/parser";import Xf from"@babel/traverse";import*as ge from"@babel/types";function Fc(e,t){let n=[],r=e;for(;ge.isMemberExpression(r);){if(r.computed)if(ge.isNumericLiteral(r.property))n.unshift({kind:"index",index:r.property.value});else if(ge.isStringLiteral(r.property))n.unshift({kind:"property",name:r.property.value});else return null;else{if(!ge.isIdentifier(r.property))return null;n.unshift({kind:"property",name:r.property.name})}r=r.object}return!ge.isIdentifier(r)||r.name!==t?null:n}function gE(e){if(ge.isIdentifier(e))return{base:e.name,path:[]};if(!ge.isMemberExpression(e))return null;let t=[],n=e;for(;ge.isMemberExpression(n);){if(n.computed)if(ge.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(ge.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else{if(!ge.isIdentifier(n.property))return null;t.unshift({kind:"property",name:n.property.name})}n=n.object}return ge.isIdentifier(n)?{base:n.name,path:t}:null}function Rt(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 On=Symbol("not-closed-literal");function Oc(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:On;case"TSAsExpression":case"TSSatisfiesExpression":case"TSNonNullExpression":return Oc(e.expression);case"ArrayExpression":{let t=[];for(let n of e.elements){if(!n||ge.isSpreadElement(n))return On;let r=Oc(n);if(r===On)return On;t.push(r)}return t}case"ObjectExpression":{let t={};for(let n of e.properties){if(!ge.isObjectProperty(n)||n.computed||n.shorthand||!ge.isExpression(n.value))return On;let r=ge.isIdentifier(n.key)?n.key.name:ge.isStringLiteral(n.key)?n.key.value:null;if(!r)return On;let o=Oc(n.value);if(o===On)return On;t[r]=o}return t}default:return On}}function hE(e){let{resolveBindingTarget:t}=e;async function n(i,s,a,c,l,u,d){let f=Oc(i);if(f!==On)return f;if(!ge.isTemplateLiteral(i)){if(ge.isTSAsExpression(i)||ge.isTSSatisfiesExpression(i)||ge.isTSNonNullExpression(i))return await n(i.expression,s,a,c,l,u,d);if(ge.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(ge.isArrayExpression(i)){let g=[];for(let p of i.elements){if(!p||ge.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(ge.isObjectExpression(i)){let g={};for(let p of i.properties){if(!ge.isObjectProperty(p)||p.computed)return;let m=null;if(ge.isIdentifier(p.key)?m=p.key.name:ge.isStringLiteral(p.key)&&(m=p.key.value),!m)return;if(p.shorthand){if(!ge.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(!ge.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(ge.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:Rt(m.value,g.path)}}}async function r(i,s,a,c,l,u,d){if(!ge.isSpreadElement(i))return await n(i,s,a,c,l,u,d)}async function o(i,s,a,c,l,u,d){if(ge.isIdentifier(i))return{base:i.name,path:[]};if(!ge.isMemberExpression(i))return null;let f=[],g=i;for(;ge.isMemberExpression(g);){if(g.computed){let p=g.property;if(ge.isNumericLiteral(p))f.unshift({kind:"index",index:p.value});else if(ge.isStringLiteral(p))f.unshift({kind:"property",name:p.value});else{let m=ge.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(!ge.isIdentifier(g.property))return null;f.unshift({kind:"property",name:g.property.name})}g=g.object}return ge.isIdentifier(g)?{base:g.name,path:f}:null}return{normalizeExpressionWithScope:o,evaluateStaticExpression:n}}var SE=typeof Xf=="function"?Xf:Xf.default,yE=new WeakMap;function vE(e){try{return EE.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function Lc(e,t,n){let r=e.get(t);if(r?.source===n)return r.ast;let o=vE(n);return e.set(t,{source:n,ast:o}),o}function Dc(e,t){return zf(is(e).expressionRanges,t,!1)}function IE(e,t){return is(e).exactExpressions.get(kE(t))??null}function Mc(e,t){return zf(is(e).jsxRanges,t,!0)}function is(e){let t=yE.get(e);if(t)return t;let n={expressions:[],expressionRanges:[],jsxRanges:[],exactExpressions:new Map};return SE(e,{Expression(r){let o=r;n.expressions.push(o);let i=xE(o,n.expressions.length-1);if(!i)return;n.expressionRanges.push(i);let s=kE(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=xE(r,n.jsxRanges.length);o&&n.jsxRanges.push(o)}}),n.expressionRanges.sort(bE),n.jsxRanges.sort(bE),yE.set(e,n),n}function xE(e,t){let n=ss(e.node);return n?{path:e,range:n,traversalIndex:t,span:(e.node.end??0)-(e.node.start??0)}:null}function kE(e){return`${e.startLine}:${e.startColumn}:${e.endLine}:${e.endColumn}`}function bE(e,t){return e.range.startLine-t.range.startLine||e.range.startColumn-t.range.startColumn||e.traversalIndex-t.traversalIndex}function zf(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 ss(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 $o(e,t){if(t)return Hf(e,t);let n=gE(e);return n?n.path.reduce((r,o)=>o.kind==="property"?`${r}.${o.name}`:`${r}[${o.index}]`,n.base):""}function Hf(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function as(e,t,n){let r=null,o=Number.POSITIVE_INFINITY;for(let i of is(e).expressions){if(Hf(i.node,t)!==n)continue;let s=(i.node.end??0)-(i.node.start??0);s<=o&&(r=i,o=s)}return r}function RE(e,t,n,r){return zf(is(e).expressionRanges,r,!0,o=>Hf(o.node,t)===n)}function Vo(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}function cs(e){let t=null;if(SE(e,{Program(n){t=n.scope,n.stop()}}),!t)throw new Error("Unable to determine program scope");return t}async function hn(e,t,n){let r=n.get(e);if(r)return r;let o=await t(e),i=vE(o),s={source:o,ast:i};return n.set(e,s),s}function uF(e){return G.isIdentifier(e.callee)&&(e.callee.name==="useState"||e.callee.name==="useReducer")?e.callee.name:G.isMemberExpression(e.callee)&&G.isIdentifier(e.callee.property)&&(e.callee.property.name==="useState"||e.callee.property.name==="useReducer")?e.callee.property.name:null}function dF(e){if(!G.isNewExpression(e)||!G.isIdentifier(e.callee,{name:"Proxy"})||e.arguments.length!==2||!G.isIdentifier(e.arguments[0])||!G.isObjectExpression(e.arguments[1])||e.arguments[1].properties.length!==1)return null;let[t]=e.arguments[1].properties;if(!G.isObjectMethod(t)||t.kind!=="method"||t.computed||t.async||t.generator||!G.isIdentifier(t.key,{name:"get"})||t.params.length!==3||!t.params.every(G.isIdentifier)||t.body.body.length!==2)return null;let[n,r,o]=t.params,[i,s]=t.body.body;if(G.isIfStatement(i)&&G.isBlockStatement(i.consequent)&&i.consequent.body.length!==1)return null;let a=G.isIfStatement(i)?i.test:null,c=a&&G.isLogicalExpression(a,{operator:"&&"})?a.right:null,l=G.isIfStatement(i)?G.isBlockStatement(i.consequent)?i.consequent.body[0]:i.consequent:null,u=G.isReturnStatement(s)?s.argument:null;return!a||!G.isLogicalExpression(a,{operator:"&&"})||!G.isBinaryExpression(a.left,{operator:"==="})||!G.isUnaryExpression(a.left.left,{operator:"typeof"})||!G.isIdentifier(a.left.left.argument,{name:r.name})||!G.isStringLiteral(a.left.right,{value:"string"})||!G.isUnaryExpression(c,{operator:"!"})||!G.isBinaryExpression(c.argument,{operator:"in"})||!G.isIdentifier(c.argument.left,{name:r.name})||!G.isIdentifier(c.argument.right,{name:n.name})||!G.isReturnStatement(l)||!G.isIfStatement(i)||i.alternate||!G.isCallExpression(u)||!G.isMemberExpression(u.callee)||!G.isIdentifier(u.callee.object,{name:"Reflect"})||!G.isIdentifier(u.callee.property,{name:"get"})||u.arguments.length!==3||!G.isIdentifier(u.arguments[0],{name:n.name})||!G.isIdentifier(u.arguments[1],{name:r.name})||!G.isIdentifier(u.arguments[2],{name:o.name})?null:e.arguments[0].name}function fF(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()||!G.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 CE(e,t){let n=fF(e.path);if(!n)return null;let r=Co(e,t);return r?{...n,...r}:null}function NE(e,t,n,r){return e.importedFrom===t?r?e.exportName===r:!0:e.sourceFile===t&&e.tag===n}function Wf(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 Gf(e,t){for(let n of e.program.body){if(t==="default"&&G.isExportDefaultDeclaration(n))return G.isExpression(n.declaration)?{kind:"default-expression",expression:n.declaration}:(G.isFunctionDeclaration(n.declaration)||G.isClassDeclaration(n.declaration))&&n.declaration.id?{kind:"default-binding",name:n.declaration.id.name}:null;if(G.isExportNamedDeclaration(n)){if(n.declaration){if(G.isVariableDeclaration(n.declaration)){for(let r of n.declaration.declarations)if(G.isIdentifier(r.id)&&r.id.name===t)return{kind:"local-binding",name:r.id.name}}if((G.isFunctionDeclaration(n.declaration)||G.isClassDeclaration(n.declaration))&&n.declaration.id&&n.declaration.id.name===t)return{kind:"local-binding",name:t}}for(let r of n.specifiers)if((G.isIdentifier(r.exported)?r.exported.name:r.exported.value)===t&&G.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 PE(e){let{resolveExternalExpression:t,resolveCollectionCallTarget:n,evaluateStaticExpression:r,resolveSourceInfoProvenance:o,buildExpressionSourceInfo:i}=e;async function s(m){let{currentFile:y,binding:x,readFile:E,exists:b,fileCache:S,visited:C}=m,T=`${y}::${x.kind}::${x.identifier.name}`;if(C.has(T))return null;C.add(T);try{let R=await a({currentFile:y,binding:x,readFile:E,exists:b,fileCache:S,visited:C});if(R)return R;if(x.path.isImportSpecifier()||x.path.isImportDefaultSpecifier())return await g({currentFile:y,binding:x,readFile:E,exists:b,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,fileCache:S,visited:C});if(x.kind==="param")return null;if(x.path.isVariableDeclarator()){let _=x.path.node.init;if(!_||!G.isExpression(_))return null;let A=dF(_);if(A&&!x.path.scope.getBinding("Proxy")&&!x.path.scope.getBinding("Reflect")){let U=x.path.scope.getBinding(A),z=U?await s({...m,binding:U}):null;if(z?.kind==="static"&&z.value!==null&&!Array.isArray(z.value)&&typeof z.value=="object")return z}let w=x.path.get("init");if(w&&!Array.isArray(w)&&w.isExpression()){let U=await t({currentFile:y,expressionPath:w,readFile:E,exists:b,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:S,visited:C});if(U)return U;if(w.isCallExpression()){let z=await n({currentFile:y,callPath:w,readFile:E,exists:b,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:S,visited:C});if(z)return z}}let D=await r(_,x.path.scope,y,E,b,S,C);return D===void 0?null:{kind:"static",file:y,root:{kind:"binding",name:x.identifier.name},value:D,sourceKind:"binding"}}if(x.path.isIdentifier()&&x.path.parentPath?.isExportDefaultDeclaration()){let _=x.path.parentPath.node.declaration;if(!G.isExpression(_))return null;let A=await r(_,x.path.scope,y,E,b,S,C);return A===void 0?null:{kind:"static",file:y,root:{kind:"binding",name:x.identifier.name},value:A,sourceKind:"binding"}}return null}finally{C.delete(T)}}async function a(m){let{currentFile:y,binding:x,readFile:E,exists:b,fileCache:S,visited:C}=m;if(!x.path.isVariableDeclarator()||!x.path.get("id").isArrayPattern())return null;let T=x.path,R=T.node.init;if(!R||!G.isCallExpression(R))return null;let _=uF(R);if(!_||!G.isArrayPattern(T.node.id)||T.node.id.elements.findIndex(z=>G.isIdentifier(z)&&z.name===x.identifier.name)!==0)return null;let w=_==="useReducer"?1:0,D=R.arguments[w];if(!D||!G.isExpression(D))return null;let U=await r(D,T.scope,y,E,b,S,C);return U===void 0?null:{kind:"static",file:y,root:{kind:"hook-state",name:x.identifier.name,hook:_},value:U,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=CE(y,m.sourceInfo);if(!x)return null;let E=[...m.graph.elements.values()].filter(S=>NE(S,m.currentFile,x.componentName,x.exportName));if(!E.length)return null;let b=[];for(let S of E){if(S.sourceFile!==E[0].sourceFile||S.componentName!==E[0].componentName||S.attributeSpreads?.length)return null;let C=await hn(S.sourceFile,m.readFile,m.fileCache),T=C.ast?Mc(C.ast,S.sourceRange):null;if(!T)return null;let R=T.parentPath;for(;R&&!R.isFunction();){if(R.isJSXElement()){let V=R.node.openingElement.name;if(!G.isJSXIdentifier(V)||!/^[a-z]/.test(V.name))return null}else if(!R.isJSXFragment()&&!R.isReturnStatement()&&!R.isBlockStatement())return null;R=R.parentPath}if(!R)return null;let _=T.get("openingElement").get("attributes").filter(V=>V.isJSXAttribute()&&G.isJSXIdentifier(V.node.name,{name:x.propName}));if(_.length!==1)return null;let A=_[0];if(!A?.isJSXAttribute())return null;let w=A.get("value"),D=w.isJSXExpressionContainer()?w.get("expression"):w;if(!D.isExpression())return null;let U=await r(D.node,D.scope,S.sourceFile,m.readFile,m.exists,m.fileCache,m.visited),z=U===void 0?void 0:Rt(U,x.remainingPath);if(z===void 0)return null;b.push(z)}return b}async function l(m){let y=CE(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 E=[...x.elements.values()].filter(A=>NE(A,m.currentFile,y.componentName,y.exportName));if(E.length!==1)return null;let b=E[0],S=b.attributes?.find(A=>A.name===y.propName);if(S&&!S.source){let A=await d({caller:b,propName:y.propName,remainingPath:y.remainingPath,readFile:m.readFile,fileCache:m.fileCache});if(A)return Wf(A,{componentName:y.componentName,propName:y.propName,file:b.sourceFile})}if(!S?.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 Wf(A,{componentName:y.componentName,propName:y.propName,file:b.sourceFile});let w=Rx(m.binding,y.componentName,y.propName);if(!w||w.propName!==y.propName)return null;let D=await r(w.expressionPath.node,w.expressionPath.scope,m.currentFile,m.readFile,m.exists,m.fileCache,m.visited);if(D===void 0)return null;let U=y.remainingPath;return U.length>0&&Rt(D,U)===void 0?null:{kind:"value",file:m.currentFile,root:{kind:"binding",name:y.propName},path:U,sourceKind:"binding",semanticKind:"component-prop",displayExpression:w.displayPath,chainPrefix:[{kind:"component-prop",file:m.currentFile,displayName:w.displayPath,canEditHere:!0}],editMode:"upstream",diagnostics:[]}}let C=await hn(b.sourceFile,m.readFile,m.fileCache);if(!C.ast)return null;let T=RE(C.ast,C.source,S.source.expression,S.sourceRange)??as(C.ast,C.source,S.source.expression);if(!T)return null;let R={...S.source,expression:Vo(S.source.expression,y.remainingPath),path:[...S.source.path,...y.remainingPath]},_=await o({currentFile:b.sourceFile,expressionPath:T,sourceInfo:R,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 _?Wf(_.kind==="external"?_:{..._,displayExpression:R.expression},{componentName:y.componentName,propName:y.propName,file:b.sourceFile}):null}async function d(m){let y=await hn(m.caller.sourceFile,m.readFile,m.fileCache);if(!y.ast)return null;let x=Mc(y.ast,m.caller.sourceRange);if(!x)return null;let E=x.get("openingElement").get("attributes").find(T=>T.isJSXAttribute()&&T.node.name.type==="JSXIdentifier"&&T.node.name.name===m.propName);if(!E?.isJSXAttribute())return null;let b=E.get("value"),S=b.isStringLiteral()?b:b.isJSXExpressionContainer()?b.get("expression"):null;if(!S?.isExpression())return null;let C=ss(S.node);return C?{kind:"value",file:m.caller.sourceFile,root:{kind:"expression",sourceRange:C},path:m.remainingPath,sourceKind:"binding",semanticKind:"component-prop",displayExpression:m.propName,editMode:"upstream",diagnostics:[]}:null}async function f(m){let y=await hn(m.caller.sourceFile,m.readFile,m.fileCache);if(!y.ast)return null;let x=Mc(y.ast,m.caller.sourceRange);if(!x)return null;let E=x.get("openingElement");for(let b of E.get("attributes")){if(!b.isJSXSpreadAttribute())continue;let S=b.get("argument");if(!S.isExpression())continue;let C=await i({expression:S.node,scope:S.scope,source:y.source,currentFile:m.caller.sourceFile,readFile:m.readFile,exists:m.exists,fileCache:m.fileCache,visited:m.visited});if(!C)continue;let T=[{kind:"property",name:m.propName},...m.remainingPath],R={...C,expression:Vo(C.expression,T),path:[...C.path,...T]},_=await o({currentFile:m.caller.sourceFile,expressionPath:S,sourceInfo:R,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(_)return _.kind==="external"?_:{..._,displayExpression:R.expression}}return null}async function g(m){let{currentFile:y,binding:x,readFile:E,exists:b,fileCache:S,visited:C}=m,T=x.path.parentPath;if(!T||!T.isImportDeclaration())return null;let R=T.node.source.value;if(typeof R!="string")return null;let _=await Tr(y,R,b);if(!_)return null;if(x.path.isImportDefaultSpecifier()){let V=await hn(_,E,S),Y=V.ast?Gf(V.ast,"default"):null,ue=await p({file:_,exportName:"default",readFile:E,exists:b,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:S,visited:C});return!ue||ue.kind!=="static"?null:{kind:"static",file:Y?.kind==="default-expression"?ue.file:_,root:Y?.kind==="default-expression"?ue.root:{kind:"default-export"},value:ue.value,sourceKind:"imported-binding"}}if(!x.path.isImportSpecifier())return null;let A=x.path.node.imported,w=G.isIdentifier(A)?A.name:A.value,D=await hn(_,E,S),U=D.ast?Gf(D.ast,w):null,z=await p({file:_,exportName:w,readFile:E,exists:b,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:S,visited:C});return z?z.kind==="external"?z:{kind:"static",file:U?.kind==="re-export"?z.file:_,root:U?.kind==="re-export"||z.root.kind==="binding"&&z.root.name!==U?.name?z.root:{kind:"named-export",name:w},value:z.value,sourceKind:"imported-binding"}:null}async function p(m){let{file:y,exportName:x,readFile:E,exists:b,fileCache:S,visited:C}=m,T=`export::${y}::${x}`;if(!C.has(T)){C.add(T);try{let R=await hn(y,E,S);if(!R.ast)return;let _=Gf(R.ast,x);if(!_)return;if(_.kind==="default-expression"){let U=_.expression;if(!U||!G.isIdentifier(U))return;let z=cs(R.ast).getBinding(U.name);return z?await s({currentFile:y,binding:z,readFile:E,exists:b,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:S,visited:C})??void 0:void 0}if(_.kind==="re-export"){if(!_.source||!_.name)return;let U=await Tr(y,_.source,b);return U?p({...m,file:U,exportName:_.name}):void 0}let A=_.name;if(!A)return;let w=cs(R.ast).getBinding(A);return w?await s({currentFile:y,binding:w,readFile:E,exists:b,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:S,visited:C})??void 0:void 0}finally{C.delete(T)}}}return{resolveExportValue:p,resolveComponentPropBinding:l,resolveComponentPropValues:c,resolveBindingTarget:s}}import*as oe from"@babel/types";function Zf(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=mn(o,t);if(!i)return null;let s=r.parentPath;return!s||!s.isCallExpression()||!pF(s,r)?null:{callPath:s,basePath:i}}function pF(e,t){let n=e.node.callee;return!oe.isMemberExpression(n)||!oe.isIdentifier(n.property)||n.property.name!=="map"?!1:e.node.arguments.some(r=>r===t.node)}function wE(e,t){let n=e.get("callee");if(!n.isMemberExpression())return null;let r=n.get("object");return Array.isArray(r)||!r.isExpression()?null:oc(r,t)}function _E(e,t){return e?oe.isNumericLiteral(e)&&Number.isInteger(e.value)?e.value:null:t}function AE(e,t,n,r,o){let i=oe.isExpression(e.body)?e.body:e.body.body.find(a=>oe.isReturnStatement(a))?.argument;if(!i||!oe.isExpression(i))return;let s=Yf(i,t,n,r,o);return typeof s=="number"?s:void 0}function Yf(e,t,n,r,o){if(oe.isNumericLiteral(e)||oe.isStringLiteral(e)||oe.isBooleanLiteral(e))return e.value;if(oe.isIdentifier(e))return e.name===t?r:e.name===n?o:void 0;if(oe.isMemberExpression(e)){let i=Fc(e,t);if(i)return Rt(r,i);let s=Fc(e,n);return s?Rt(o,s):void 0}if(oe.isBinaryExpression(e)&&e.operator==="-"){let i=oe.isExpression(e.left)?Yf(e.left,t,n,r,o):void 0,s=oe.isExpression(e.right)?Yf(e.right,t,n,r,o):void 0;return typeof i=="number"&&typeof s=="number"?i-s:void 0}}function mF(e){if(oe.isExpression(e.body))return e.body;for(let t of e.body.body)if(oe.isReturnStatement(t)&&t.argument&&oe.isExpression(t.argument))return t.argument;return null}function gF(e,t,n){let r=to(e,t,n);return typeof r=="boolean"?r:void 0}function to(e,t,n){if(oe.isStringLiteral(e)||oe.isNumericLiteral(e)||oe.isBooleanLiteral(e))return e.value;if(oe.isNullLiteral(e))return null;if(oe.isIdentifier(e))return e.name===t?n:void 0;if(oe.isMemberExpression(e)){let r=Fc(e,t);return r?Rt(n,r):void 0}if(oe.isUnaryExpression(e)&&e.operator==="!"){let r=to(e.argument,t,n);return r===void 0?void 0:!r}if(oe.isLogicalExpression(e)){let r=to(e.left,t,n);if(r===void 0)return;if(e.operator==="&&")return r&&to(e.right,t,n);if(e.operator==="||")return r||to(e.right,t,n)}if(oe.isBinaryExpression(e)){let r=oe.isExpression(e.left)?to(e.left,t,n):void 0,o=oe.isExpression(e.right)?to(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 OE(e){let t=[],n=e;for(;oe.isMemberExpression(n)||oe.isOptionalMemberExpression(n);){let r=n.property;if(n.computed)if(oe.isNumericLiteral(r))t.unshift({kind:"index",index:r.value});else if(oe.isStringLiteral(r))t.unshift({kind:"property",name:r.value});else if(oe.isExpression(r))t.unshift({kind:"dynamic",expression:r});else return null;else if(oe.isIdentifier(r))t.unshift({kind:"property",name:r.name});else return null;n=n.object}return oe.isIdentifier(n)?{base:n.name,segments:t}:null}function FE(e){return e.some(t=>t.kind==="dynamic")}function TE(e){return typeof e=="string"?{kind:"property",name:e}:Number.isInteger(e)?{kind:"index",index:e}:null}function LE(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 hF(e,t){let n=[],r=[];for(let o of t){let i=Rt(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 DE(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:E,fileCache:b,visited:S}=p,C=y.node.callee;if(!oe.isMemberExpression(C)||!oe.isIdentifier(C.property)||C.property.name!=="map")return null;let T=y.get("callee");if(!T.isMemberExpression())return null;let R=T.get("object");if(Array.isArray(R)||!R.isExpression())return null;let _=await a({currentFile:m,expressionPath:R,readFile:x,exists:E,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:b,visited:S});return!_||!Array.isArray(_.value)||_.value.length===0?null:_}async function a(p){let{currentFile:m,expressionPath:y,readFile:x,exists:E,fileCache:b,visited:S}=p;if(y.isIdentifier()){let C=y.scope.getBinding(y.node.name);if(!C)return null;let T=await t({currentFile:m,binding:C,readFile:x,exists:E,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:b,visited:S});return T?.kind==="static"?T:null}if(y.isCallExpression())return l({currentFile:m,callPath:y,readFile:x,exists:E,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:b,visited:S});if(y.isTSAsExpression()||y.isTSSatisfiesExpression()||y.isTSNonNullExpression()){let C=y.get("expression");if(!Array.isArray(C)&&C.isExpression())return a({...p,expressionPath:C})}if(y.isArrayExpression()){let C=ss(y.node);if(!C)return null;let T=await n(y.node,y.scope,m,x,E,b,S);return Array.isArray(T)?{kind:"static",file:m,root:{kind:"expression",sourceRange:C},value:T,sourceKind:"binding"}:null}if(y.isMemberExpression()){let C=await r({expression:y.node,scope:y.scope,currentFile:m,readFile:x,exists:E,fileCache:b,visited:S});if(!C)return null;let T=await o({currentFile:m,expressionPath:y,sourceInfo:C,readFile:x,exists:E,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:b,visited:S});if(!T||T.kind==="external")return null;let R=await c({currentFile:m,expressionPath:y,provenance:T,readFile:x,exists:E,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:b,visited:S});if(!R||R.kind!=="static")return null;if(T.collectionPathMap?.length){let A=hF(R.value,T.collectionPathMap);if(A)return{kind:"static",file:T.file,root:T.root,value:A.value,sourceKind:T.sourceKind,collectionPathMap:A.collectionPathMap}}let _=Rt(R.value,T.path);return Array.isArray(_)?{kind:"static",file:T.file,root:T.root,value:_,sourceKind:T.sourceKind,pathPrefix:T.path,collectionIndexMap:T.collectionIndexMap,collectionPathMap:T.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 S=await hn(m.file,p.readFile,p.fileCache);b=S.ast?cs(S.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 hn(m.file,p.readFile,p.fileCache);if(!y.ast)return null;let x=IE(y.ast,m.root.sourceRange);if(!x)return null;let E=await n(x.node,x.scope,m.file,p.readFile,p.exists,p.fileCache,p.visited);return E===void 0?null:{kind:"static",file:m.file,root:m.root,value:E,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(!oe.isMemberExpression(y)||!oe.isIdentifier(y.property)||y.property.name!=="filter")return null;let x=m.get("callee");if(!x.isMemberExpression())return null;let E=x.get("object");if(Array.isArray(E)||!E.isExpression())return null;let b=await a({currentFile:p.currentFile,expressionPath:E,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[S]=m.node.arguments;if(!oe.isArrowFunctionExpression(S)&&!oe.isFunctionExpression(S))return null;let C=S.params[0];if(!oe.isIdentifier(C))return null;let T=mF(S);if(!T)return null;let R=[],_=[],A=[];for(let[w,D]of b.value.entries()){let U=gF(T,C.name,D);if(typeof U!="boolean")return null;if(U){R.push(D),_.push(b.collectionIndexMap?.[w]??w);let z=b.collectionPathMap?.[w];z&&A.push(z)}}return{...b,value:R,pathPrefix:b.pathPrefix,collectionIndexMap:_,...A.length>0?{collectionPathMap:A}:{}}}async function d(p){let{callPath:m}=p,y=m.node.callee;if(!oe.isMemberExpression(y)||!oe.isIdentifier(y.property)||y.property.name!=="slice")return null;let x=m.get("callee");if(!x.isMemberExpression())return null;let E=x.get("object");if(Array.isArray(E)||!E.isExpression())return null;let b=await a({currentFile:p.currentFile,expressionPath:E,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[S,C]=m.node.arguments,T=_E(S,0),R=_E(C,b.value.length);if(T===null||R===null)return null;let _=Math.max(0,T<0?b.value.length+T:T),A=Math.max(0,R<0?b.value.length+R:R),w=b.value.map((U,z)=>b.collectionIndexMap?.[z]??z).slice(_,A),D=b.collectionPathMap?.slice(_,A);return{...b,value:b.value.slice(_,A),pathPrefix:b.pathPrefix,collectionIndexMap:w,...D?{collectionPathMap:D}:{}}}async function f(p){let{callPath:m}=p,y=m.node.callee;if(!oe.isMemberExpression(y)||!oe.isIdentifier(y.property)||y.property.name!=="sort"&&y.property.name!=="toSorted")return null;let x=m.get("callee");if(!x.isMemberExpression())return null;let E=x.get("object");if(Array.isArray(E)||!E.isExpression())return null;let b=await a({currentFile:p.currentFile,expressionPath:E,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[S]=m.node.arguments;if(!oe.isArrowFunctionExpression(S)&&!oe.isFunctionExpression(S))return null;let[C,T]=S.params;if(!oe.isIdentifier(C)||!oe.isIdentifier(T))return null;let R=b.value.map((A,w)=>({value:A,sourceIndex:b.collectionIndexMap?.[w]??w,originalIndex:w})),_=[...R];for(let A of R)for(let w of R)if(AE(S,C.name,T.name,A.value,w.value)===void 0)return null;return _.sort((A,w)=>{let D=AE(S,C.name,T.name,A.value,w.value)??0;return D===0?A.originalIndex-w.originalIndex:D}),{...b,value:_.map(A=>A.value),pathPrefix:b.pathPrefix,collectionIndexMap:_.map(A=>A.sourceIndex),...b.collectionPathMap?{collectionPathMap:_.map(A=>b.collectionPathMap?.[A.originalIndex]).filter(A=>!!A)}:{}}}async function g(p){let m=null,y=!1,x,E=[];for(let S of p.segments){if(S.kind!=="dynamic")continue;let C=await r({expression:S.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(!C)return null;let T=Zf(p.expressionPath,C.base),R;if(T){y=!0;let _=await s({currentFile:p.currentFile,callPath:T.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(!_||!Array.isArray(_.value))return null;R=_.value.map((A,w)=>{let D=Rt(_.value,[{kind:"index",index:w},...T.basePath,...C.path]);return TE(D)}),x??=_.collectionIndexMap}else{let _=await i({...p,sourceInfo:C});if(!_)return null;R=_.map(TE)}if(R.some(_=>_===null)||m!==null&&m!==R.length)return null;m=R.length,E.push(R)}if(m===null||m===0)return null;let b=[];for(let S=0;S<m;S+=1){let C=[...p.rootPath],T=0;for(let R of p.segments){if(R.kind==="dynamic"){let _=E[T]?.[S];if(!_)return null;C.push(_),T+=1;continue}C.push({...R})}b.push(C)}return{sourceKind:y||m>1?"repeat-template":"binding",...x?{collectionIndexMap:x}:{},collectionPathMap:b}}return{resolveRepeatCollectionTarget:s,resolveCollectionCallTarget:l,resolveDynamicMemberPathMap:g}}var{normalizeExpressionWithScope:yF,evaluateStaticExpression:Bc}=hE({resolveBindingTarget:e=>jc(e)}),{resolveRepeatCollectionTarget:xF,resolveCollectionCallTarget:bF,resolveDynamicMemberPathMap:EF}=DE({resolveBindingTarget:e=>jc(e),evaluateStaticExpression:Bc,buildExpressionSourceInfo:Fn,resolveSourceInfoProvenance:on,resolveComponentPropValues:e=>IF(e)}),{resolveExportValue:SF,resolveComponentPropBinding:vF,resolveComponentPropValues:IF,resolveBindingTarget:jc}=PE({resolveExternalExpression:op,resolveCollectionCallTarget:bF,evaluateStaticExpression:Bc,resolveSourceInfoProvenance:on,buildExpressionSourceInfo:Fn});function XE(e){return new Map([...e].map(t=>[t.file,{source:t.source,ast:t.ast}]))}var ME=new WeakMap;function kF(e){let t=ME.get(e);return t||(t=new WeakMap,ME.set(e,t)),t}function BE(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 zE(e){let{file:t,source:n,segment:r,readFile:o,exists:i}=e,s=e.fileCache??new Map,a=Lc(s,t,n);if(!a)return null;let c=Dc(a,r.sourceRange);if(!c)return null;let l=await Fn({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:o,exists:i,fileCache:s,visited:new Set});if(!l){let f=await cp({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?ep(f,$o(c.node,n)):null}let u=new Set,d=await zF({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?ep(d,l.expression):null}async function Uo(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=Lc(i,t,n);if(!s)return null;let a=e.sourceRange?Dc(s,e.sourceRange):e.expression!==void 0?as(s,n,e.expression):null;if(!a)return null;let c=$c(a);if(!c.isIdentifier()&&!c.isMemberExpression())return null;let l=new Set,u=await Fn({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:r,exists:o,fileCache:i,visited:l}),d=u?await on({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 eS({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 ep(d,e.expression??$o(c.node,n))}async function rp(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=Lc(i,t,n);if(!s)return Xt("unsupported-expression","Unable to parse source for provenance resolution");let a=new Set;return e.target.kind==="text-segment"?RF({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}):CF({file:t,source:n,ast:s,candidate:e.target.candidate,readFile:r,exists:o,graph:e.graph,fileCache:i,visited:a})}async function Fn(e){if(le.isIdentifier(e.expression))return{kind:"identifier",expression:e.expression.name,base:e.expression.name,path:[]};if(!le.isMemberExpression(e.expression))return null;let t=await yF(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:$o(e.expression,e.source),base:t.base,path:t.path}:null}function ep(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 RF(e){let{file:t,source:n,ast:r,segment:o,readFile:i,exists:s,fileCache:a,visited:c}=e,l=Dc(r,o.sourceRange),u=l?await Fn({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 jE(t,o.value);let f=await cp({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"?JE(t,f):np(t,$o(l.node,n),f):NF({expression:l.node,scope:l.scope,currentFile:t,source:n,readFile:i,exists:s,fileCache:a,visited:c,functionCallContracts:e.functionCallContracts})}if(!l)return Xt("unsupported-expression","Unable to locate text expression for provenance resolution");let d=await on({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=tp(l.node);if(f)return Xt(f.code,f.message);let g=l.scope.getBinding(u.base);if(g?.path.isVariableDeclarator()){let p=tp(g.path.node.init);if(p)return Xt(p.code,p.message)}return g?.path.isVariableDeclarator()&&le.isCallExpression(g.path.node.init)?PF("unsupported-expression",ZE(g.path.node.init,e.functionCallContracts)):Xt("unsupported-expression",`Unable to resolve provenance for expression "${u.expression}"`)}return d.kind==="external"?JE(t,d):np(t,u.expression,d)}async function CF(e){let{file:t,source:n,ast:r,candidate:o,readFile:i,exists:s,fileCache:a,visited:c}=e;if(!o.conditionSource)return Xt("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let l=as(r,n,o.conditionExpression);if(!l)return Xt("conditional-branch-unresolved",`Unable to locate conditional expression "${o.conditionExpression}"`);let u=await on({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 Xt("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);if(u.kind==="external")return Xt("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let d=np(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 jE(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 NF(e){let t=await WE(e);if(t.length===0)return Xt("unsupported-expression",`Unsupported expression type: ${e.expression.type}`);if(_F(e.expression))return HE(t);if(YE(e.expression))return Xt("unsupported-expression","i18n helpers require a static message id string");if(le.isMemberExpression(e.expression)&&e.expression.computed&&!le.isNumericLiteral(e.expression.property)&&!le.isStringLiteral(e.expression.property))return Xt("dynamic-key","Computed member expressions are not supported for provenance resolution");let[n]=t;return Xt(n.code,n.message)}function Xt(e,t){return{finalSource:null,chain:[],confidence:"unknown",editMode:"unsupported",diagnostics:[{code:e,message:t}]}}function PF(e,t){return HE([{code:e,message:t}])}function HE(e){return{finalSource:null,chain:[],confidence:"partial",editMode:"readonly",diagnostics:e}}function _F(e){return le.isCallExpression(e)||le.isConditionalExpression(e)||le.isLogicalExpression(e)||le.isBinaryExpression(e)}function us(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 WE(e){let{expression:t,scope:n,currentFile:r,readFile:o,exists:i,fileCache:s,visited:a,functionCallContracts:c}=e,l=tp(t);if(l)return[l];if(le.isCallExpression(t))return[{code:"unsupported-expression",message:ZE(t,c)}];if(le.isMemberExpression(t)&&t.computed){let u=t.property;if(!le.isNumericLiteral(u)&&!le.isStringLiteral(u)){if(!le.isExpression(u))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}];let f=await Bc(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 le.isBinaryExpression(t)?us([...await qf(t.left,t.right,e),{code:"unsupported-expression",message:"Mixed expressions are recognized but remain readonly until a safer composition editing strategy is available"}]):le.isLogicalExpression(t)?us([...await qf(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"}]):le.isConditionalExpression(t)?us([...await qf(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 tp(e){return YE(e)?$E("i18n helpers require a static message id string"):FF(e)?$E("CMS helpers require static entry id and field path string arguments"):null}async function qf(...e){let t=e[e.length-1],n=e.slice(0,-1),r=[];for(let o of n)r.push(...await WE({...t,expression:o}));return r}function AF(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:[TF(e.sourceType)]}}async function op(e){for(let n of BF){if(!VE(e.expressionPath,n.helperNames))continue;let r=await n.resolve(e);if(r)return KE(UE(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(!VE(e.expressionPath,n.helperNames))continue;let r=await n.resolve(t);if(r)return KE(UE(r),e.externalAdapters)}return null}function TF(e){return{code:"missing-adapter",message:`No external adapter is registered for ${e}`}}function wF(e){return{code:"external-source-readonly",message:e}}function $E(e){return{code:"unsupported-expression",message:e}}function ip(e){return!e||!le.isCallExpression(e)?null:le.isIdentifier(e.callee)?e.callee.name:le.isMemberExpression(e.callee)&&!e.callee.computed&&le.isIdentifier(e.callee.object)&&le.isIdentifier(e.callee.property)?`${e.callee.object.name}.${e.callee.property.name}`:null}function VE(e,t){if(!t||t.length===0)return!0;let n=ip(e.node);return n?t.includes(n):!1}function UE(e){return"match"in e?{match:e.match,editMode:e.editMode,diagnostics:us(e.diagnostics??[])}:{match:e,diagnostics:[]}}function KE(e,t){let n=AF(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:us([...e.diagnostics,...e.editMode==="readonly"||n.editMode==="readonly"?n.diagnostics:[]])}}function OF(e){if(!e.isCallExpression())return null;let t=e.node.callee;if(!le.isIdentifier(t)||t.name!=="getCmsField")return null;let[n,r]=e.node.arguments;if(!n||!r||!le.isStringLiteral(n)||!le.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 FF(e){return!!e&&le.isCallExpression(e)&&le.isIdentifier(e.callee)&&e.callee.name==="getCmsField"&&(e.arguments.length<2||!le.isStringLiteral(e.arguments[0])||!le.isStringLiteral(e.arguments[1]))}function GE(e){if(!(!e||!le.isCallExpression(e))){if(le.isIdentifier(e.callee)&&e.callee.name==="t"){let[t]=e.arguments;return t&&le.isStringLiteral(t)?t.value:null}if(le.isMemberExpression(e.callee)&&!e.callee.computed&&le.isIdentifier(e.callee.object)&&e.callee.object.name==="intl"&&le.isIdentifier(e.callee.property)&&e.callee.property.name==="formatMessage"){let[t]=e.arguments;if(!t||!le.isObjectExpression(t))return null;for(let n of t.properties)if(le.isObjectProperty(n)&&!n.computed&&(le.isIdentifier(n.key)&&n.key.name==="id"||le.isStringLiteral(n.key)&&n.key.value==="id")&&le.isStringLiteral(n.value))return n.value.value;return null}}}function YE(e){return GE(e)===null}async function LF(e,t,n){let r=new Set,o=ls.posix.dirname(e);for(;r.add(o),!(o==="."||o==="/");){let i=ls.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"]:[ls.posix.join(i,"locales"),ls.posix.join(i,"messages")];for(let a of s){let c=ls.posix.join(a,`${t}.json`);if(await n(c))return c}}return null}async function DF(e){let t=GE(e.expressionPath.node);if(typeof t!="string"||t.length===0)return null;let n="en",r=await LF(e.currentFile,n,e.exists);return r?{sourceType:"i18n-message",sourceId:`${n}:${t}`,file:r,displayPath:t}:null}async function MF(e){if(!e.expressionPath.isCallExpression())return null;let t=e.expressionPath.node.callee;if(!le.isIdentifier(t)||t.name!=="apiField")return null;let[n,r]=e.expressionPath.node.arguments;if(!n||!le.isExpression(n))return null;let o=await Bc(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:[wF("API mapping transforms must stay readonly until a reversible mapping strategy is registered")]}:i}var BF=[{helperNames:["getCmsField"],resolve:({expressionPath:e})=>OF(e)},{helperNames:["apiField"],resolve:e=>MF(e)},{helperNames:["t","intl.formatMessage"],resolve:({currentFile:e,expressionPath:t,exists:n})=>DF({currentFile:e,expressionPath:t,exists:n})}];function sp(e){return{...e,editMode:"readonly",diagnostics:[{code:"unsupported-expression",message:"Derived display values are readonly because no identity-preserving write target exists"}]}}function JE(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 np(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=XF(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 jF=[{helperName:"formatPrice",purity:"pure",sourceArgIndex:0},{helperName:"formatDate",purity:"pure",sourceArgIndex:0},{helperName:"pickLabel",purity:"pure",sourceArgIndex:0}];function ap(e,t){let n=[...jF,...t??[]];for(let r=n.length-1;r>=0;r-=1){let o=n[r];if(o?.helperName===e)return o}return null}function ZE(e,t){let n=e.callee;return le.isIdentifier(n)&&ap(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 cp(e){let t=await op(e);if(t)return t;let n=await qE({...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 Fn({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 on({...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 KF(e)}async function qE(e){let t=await yn({...e,allowComposed:!1});if(t?.kind!=="source")return null;let n=$c(e.expressionPath);return n.isIdentifier()||n.isMemberExpression()?t.provenance:sp(t.provenance)}async function yn(e){let t=$c(e.expressionPath),n=UF(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 Fn({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 on({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 Fn({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 on({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 yn({...e,expressionPath:r,allowComposed:!0}),a=await yn({...e,expressionPath:o,allowComposed:!1}),c=await yn({...e,expressionPath:i,allowComposed:!1});return Qf(s,a,c)}if(t.isCallExpression())return $F({...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 yn({...e,expressionPath:r,allowComposed:!0}),s=await yn({...e,expressionPath:o,allowComposed:!0});return Qf(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 yn({...e,expressionPath:r,allowComposed:!0}),s=await yn({...e,expressionPath:o,allowComposed:!0});return Qf(i,s)}if(t.isUnaryExpression()){let r=t.get("argument");return Array.isArray(r)||!r.isExpression()?null:yn({...e,expressionPath:r,allowComposed:!0})}return null}finally{n&&e.visited.delete(n)}}function $c(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 $F(e){let t=ip(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:yn({...e,expressionPath:r,allowComposed:!1})}let n=e.expressionPath.get("callee");if(n.isMemberExpression()&&!n.node.computed){let r=n.node.property;if(le.isIdentifier(r)&&(r.name==="toFixed"||r.name==="toString")){let o=n.get("object");return Array.isArray(o)||!o.isExpression()?null:yn({...e,expressionPath:o,allowComposed:!1})}}return null}function Qf(...e){let t=null;for(let n of e){if(!n)return null;if(n.kind!=="none"){if(!t){t=n.provenance;continue}if(!VF(t,n.provenance))return null}}return t?{kind:"source",provenance:t}:{kind:"none"}}function VF(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 UF(e,t){return t.start==null||t.end==null?null:`safe-derived:${e}:${t.start}:${t.end}`}async function KF(e){if(!e.expressionPath.isCallExpression())return null;let t=ip(e.expressionPath.node);if(!t)return null;let n=ap(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 QE({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?sp(i):null}async function QE(e){let t=await op({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 Fn({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 on({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 cp({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 JF(e){if(!e.binding.path.isVariableDeclarator())return null;let t=e.binding.path.node.init;if(!t||!le.isCallExpression(t))return null;let n=t.callee;if(!le.isIdentifier(n))return null;let r=ap(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 QE({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?sp(a):null}function XF(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=Vo(t,e.path);return{sourceId:o,displayPath:o}}async function zF(e){let t=e.segment.source;return t?on({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 on(e){let t=e.sourceInfo,n=Zf(e.expressionPath,t.base);if(n){let l=await xF({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=wE(n.callPath,[...n.basePath,...t.path]);return Hi(m)?BE(e.currentFile,m.sourceId,m.displayPath):null}let u=LE(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 Rt(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 Tr(e.currentFile,u.node.source.value,e.exists);if(!d)return null;let f=await SF({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 Rt(f.value,g)===void 0?null:{kind:"value",file:f.file,root:f.root,path:g,sourceKind:"imported-binding",collectionIndexMap:f.collectionIndexMap}}let o=Ix(r);if(o){let l=o.expressionPath,u=await Fn({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 on({...e,expressionPath:l,sourceInfo:{...u,expression:Vo(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 eS({...e,expressionPath:$c(l),memberSuffix:t.path});if(f?.kind==="value")return f}finally{e.visited.delete(d)}}if(t.path.length===0){let d=await qE({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 vF({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 JF({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=nc(r,t.path,kF(e.fileCache));if(Hi(s))return BE(e.currentFile,s.sourceId,s.displayPath);let a=await jc({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:Rt(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 eS(e){let t=OE(e.expressionPath.node);if(!t||!FE(t.segments))return null;let n=await on({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 EF({...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 jc({...e,binding:i}):null;if(s?.kind!=="static"||o.some(a=>Rt(s.value,a.slice(n.path.length))===void 0))return null}return{...n,path:o[0]??n.path,sourceKind:r.sourceKind,displayExpression:$o(e.expressionPath.node,e.fileCache.get(e.currentFile)?.source),...r.collectionIndexMap?{collectionIndexMap:r.collectionIndexMap}:{},collectionPathMap:o}}async function tS(e){let t=HF(e.propertyName);if(t.owner==="blocked")return kr(t.owner,t.diagnostic);if(t.owner==="class-name-source"||t.owner==="style")return kr(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 kr("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 GF(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 kr("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}:kr("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?kr("generic",{code:"remove-exposes-spread",message:`Removing '${e.propertyName}' would expose an earlier spread source`}):WF(e,s.attribute)}async function WF(e,t){if(t.resolution&&t.resolution.status!=="resolved"&&!t.source){let r=await Uo({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}}:kr("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 Uo({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"?kr("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 GF(e,t){let n=t.source?.expression;if(!n)return;let r=await Uo({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:YF(r,e.propertyName)}}function YF(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 kr(e,t){return{status:"blocked",owner:e,...t?{diagnostic:t}:{}}}function nS(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(no(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=>eL(a,r.componentName)),s=i.length===1?i[0].identity.key:null;return o.keys.set(r.componentName,s),s};return r=>ZF({...r,graph:e},n)}function ZF(e,t){let{key:n,element:r,graph:o,provenances:i}=e,s=QF(n,r,o,t),a=s?.tag??(no(r.tag)?r.tag:r.componentName),c=s?.identity.key??t(r,o)??n,l=nL(s),u=rL(n,r,o,i,s),d=qF(n,r,o,i,c);return{componentName:a,instanceKey:c,templateOwner:tL(s??r,a),...l.length>0?{variantKeys:l}:{},...u.length>0?{slotKeys:u}:{},editableStrategy:d,impactScope:oL(d),alternativeStrategies:iL(d)}}function qF(e,t,n,r,o){for(let i of r.values())if(i?.editMode==="upstream")return"upstream";return lp(e,n)?"instance":!no(t.tag)&&t.sourceFile!==n.routeId&&o!==e?"template":"instance"}function QF(e,t,n,r){if(no(t.tag))return t;let o=lp(e,n);if(o)return o;let i=r(t,n);return i?n.elements.get(i)??null:null}function eL(e,t){return e.exportName===t||e.tag===t||e.exportName==="default"}function tL(e,t){return no(e.tag)&&e.importedFrom?`${e.importedFrom}#${t}`:`${e.sourceFile}#${t}`}function nL(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 rL(e,t,n,r,o){let i=new Set,s=lp(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&&no(t.tag)&&t.childKeys.length>0&&i.add("children"),[...i]}function lp(e,t){let n=t.elements.get(e)?.parentKey??null;for(;n;){let r=t.elements.get(n);if(!r)break;if(no(r.tag))return r;n=r.parentKey}return null}function no(e){return/^[A-Z]/.test(e)}function oL(e){switch(e){case"template":return"component-template";case"upstream":return"upstream-source";default:return"current-instance"}}function iL(e){switch(e){case"template":return["instance"];case"upstream":return["template"];default:return["template"]}}function iS(e){let t=e.isRepeat??(e.graph?mL(e.element,e.graph):!1),n=e.propertyProvenance??new Map,r=e.repeatTargets??new Map,o=pL(e.element.attributes??[]),i=[...r.values()].some(u=>u.ok),s=o.map(u=>sL({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:gL(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 sL(e){let{attribute:t,provenance:n,repeatTarget:r}=e,o=e.selectionRef?.instanceIndex!==void 0&&r?.ok===!0?r:null,i=aL(t,n,e.isRepeat),s=["selection","template"].map(y=>({scope:y,result:dc({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=cL(t,n,l,e.isRepeat),d=c?dL(c,e.element,t.name):void 0,f=s.filter(({result:y})=>y.ok).map(({scope:y})=>y),g=f.length>0?uL(n,o,e.element):"unsupported",p=o?"repeat-item":e.isRepeat?"repeat-template":"node",m=fL(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 aL(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 cL(e,t,n,r){return n?rS(n.selectedResolution):t?.status==="blocked"?{status:"unresolved"}:r&&t?.status==="binding"?{status:"unresolved"}:rS(lL(e))}function lL(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 uL(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 dL(e,t,n){return e.kind==="repeat-property"?{kind:"value-path",file:e.target.sourceFile,isProxy:e.target.sourceFile!==t.sourceFile,displayPath:oS({...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:oS(e.locator)}:{kind:"jsx-node",file:t.sourceFile,isProxy:!1,displayPath:t.componentName+" > "+n}}function fL(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 pL(e){let t=new Set;return e.filter(n=>t.has(n.name)?!1:(t.add(n.name),!0))}function mL(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 oS(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 gL(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 hL(e){return e==="api-field"||e==="cms-field"||e==="i18n-message"||e==="config-entry"}var yL=160;function sS(e,t,n,r={}){let o=po(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 aS(e,t,n,r,o,i,s,a,c,l,u){let d=po(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=pS(e,t,f,p,m),x=m?SL(m):void 0,E=vL(i,m),b=f.textSegments.map(R=>({index:R.index,value:R.value,editable:mS(R,p,s?.get(R.index)??null),source:o.get(R.index)??null})),S=uS(f,t),C=f.childKeys.map(R=>{let _=t.elements.get(R);return _?{key:R,tag:_.tag,label:_.tag}:null}).filter(R=>R!==null),T=[];if(f.parentKey){let R=t.elements.get(f.parentKey);if(R)for(let _ of R.childKeys){if(_===e)continue;let A=t.elements.get(_);A&&T.push({key:_,tag:A.tag,label:A.tag})}}return{composition:d,key:e,tag:f.tag,componentName:f.componentName,sourceFile:f.sourceFile,sourceLocator:lS(f),label:f.tag,capabilities:y,writeTarget:i,effectiveWriteTarget:E,provenanceChain:x,componentSemantic:c,styleSource:l,conditional:a,...u?{dynamicData:u}:{},textSegments:b,boundaryKind:f.boundaryKind,isOpaque:f.isOpaque,ancestors:S,children:C,siblings:T}}function cS(e,t,n,r,o,i,s,a){let c=po(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=xL(l);return{composition:c,key:e,tag:l.tag,...g?{linkSourceKind:g}:{},componentName:l.componentName,sourceFile:l.sourceFile,sourceLocator:lS(l),label:l.tag,capabilities:pS(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:mS(p,d,i?.get(p.index)??null),source:m?{kind:m.kind}:null}}),boundaryKind:l.boundaryKind,isOpaque:l.isOpaque,ancestors:uS(l,t)}}function xL(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 lS(e){return{sourceFile:e.sourceFile,componentName:e.componentName,openingElementRange:bL(e.sourceRange),structuralPath:e.identity.structuralPath,...EL(e.textSegments)}}function uS(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 bL(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function EL(e){let t=e.map(n=>n.value.trim()).filter(Boolean).join(" ").replace(/\s+/g," ").trim();return t?{textPreview:t.slice(0,yL)}:{}}function dS(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 pS(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&&gS(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 mS(e,t,n){return!e.editable||!t.canUpdateText?!1:n?gS(n.editMode):!0}function gS(e){return e==="direct"||e==="proxy"||e==="upstream"}function SL(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 vL(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}:hL(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 up=["set-class-name-source","apply-style-draft"];function hS(e){let t=e.attributes?.find(n=>n.name==="className");if(!t)return{kind:"class-name-source",className:"",sourceKind:"missing",editable:!0,operationBoundary:up,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:up,sourcePath:n}}return{kind:"class-name-source",className:t.value,sourceKind:t.resolvedValue===void 0?"static-attribute":"static-expression",editable:!0,operationBoundary:up}}import yS from"node:path";function fp(){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 bS(e,t,n){let r=[],o=new Set;for(let i of e.intents){let s=CL(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 Vc(e){let t=()=>IL(e);return e.mutex?e.mutex.runExclusive(t):t()}async function IL(e){let t=await bS(e.plan,e.overlay,e.exists);if(!t.ok)return{ok:!1,stage:"precheck",reason:t.reason,error:t,recoveryRequired:!1};let n=kL(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 dp({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 dp({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 dp({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 xS("swap",l,"Live state swap failed after durable publish.")}try{await e.finalizeCandidate?.(c)}catch(l){return xS("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 kL(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 dp(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:RL(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 xS(e,t,n){return{ok:!1,stage:e,reason:n,error:t,recoveryRequired:!0}}function RL(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 CL(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)||yS.isAbsolute(e))return{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`};let t=yS.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 NL=50,PL=8*1024*1024;function IS(e,t={}){let n=[],r=[],o=t.externalAdapters??[],i=Math.max(0,t.maxUndoEntries??NL),s=Math.max(0,t.maxUndoBytes??PL);return{prepareRewritePlan:a,execute:c,executeFilePlan:l,undo:u,redo:d};async function a(R){let _=[...R.steps].sort((V,Y)=>V.order-Y.order),A=_.filter(V=>V.type!=="invoke-external-adapter");if(A.length!==_.length)return{ok:!1,errorCode:"unsupported-operation",reason:"External adapter writes require a transactional prepare/commit/rollback contract."};let w=new Set(A.map(V=>V.file)),D=await E(w),U=new Map(D.map(V=>[V.file,V.exists===!1?"":V.content])),z;for(let V of A){let Y=vS(V,U.get(V.file)??"");if(!Y.ok)return{ok:!1,errorCode:Y.errorCode,reason:Y.reason};U.set(V.file,Y.source),z=Y.selectionRef??z}return{ok:!0,filePlan:{operationId:R.operationId,kind:"source-edit",target:R.target,documentVersion:R.documentVersion,conflictPolicy:"compare-and-swap",edits:[...U].map(([V,Y])=>({operation:"upsert",file:V,content:Y,baseContentHash:D.find(ue=>ue.file===V)?.sha256??null}))},...z?{selectionRef:z}:{}}}async function c(R){let _=[...R.steps].sort((ue,st)=>ue.order-st.order),A=_.filter(ue=>ue.type!=="invoke-external-adapter"),w=_.filter(ue=>ue.type==="invoke-external-adapter"),D=new Set(A.map(ue=>ue.file));if(A.length>0&&w.length>0)return{ok:!1,operationId:R.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(R,w);let U=await E(D),z=new Map;for(let ue of U)z.set(ue.file,ue.exists===!1?"":ue.content);let V;for(let ue of A){let st=z.get(ue.file)??"",pt=vS(ue,st);if(!pt.ok)return{ok:!1,operationId:R.operationId,errorCode:pt.errorCode,reason:pt.reason,rolledBack:!1};z.set(ue.file,pt.source),pt.selectionRef&&(V=pt.selectionRef)}let Y=await S([...z].map(([ue,st])=>({file:ue,content:st,exists:!0,version:0,sha256:ve(st)})),U);return Y.ok===!1?{ok:!1,operationId:R.operationId,errorCode:Y.rolledBack?"writeback-failed":"rollback-failed",reason:Y.reason,rolledBack:Y.rolledBack}:(n.push({operationId:R.operationId,preSnapshots:U,postSnapshots:Y.snapshots,plan:R}),f(),r.length=0,{ok:!0,operationId:R.operationId,kind:R.kind,target:R.target,resultVersion:Math.max(...Y.snapshots.map(ue=>ue.version)),affectedFiles:[...D],...V?{selectionRef:V}:{}})}async function l(R){let _=new Set(R.edits.map(Y=>Y.file)),A=await E(_),w=x(R,A);if(w)return{ok:!1,operationId:R.operationId,errorCode:"stale-version",reason:w.reason,affectedFiles:[w.file],rolledBack:!1};let D=new Map(A.map(Y=>[Y.file,Y])),U=R.edits.find(Y=>Y.operation==="create-only"&&D.get(Y.file)?.exists!==!1);if(U)return{ok:!1,operationId:R.operationId,errorCode:"stale-version",reason:`MATERIALIZATION_INSTANCE_CONFLICT: create-only target already exists: ${U.file}`,affectedFiles:[U.file],rolledBack:!1};let z=R.edits.map(Y=>Y.operation==="delete"?{file:Y.file,content:"",exists:!1,version:0}:{file:Y.file,content:Y.content,exists:!0,version:0,sha256:ve(Y.content)}),V=await S(z,A,new Set(R.edits.filter(Y=>Y.operation==="create-only").map(Y=>Y.file)));return V.ok===!1?{ok:!1,operationId:R.operationId,errorCode:V.rolledBack?"writeback-failed":"rollback-failed",reason:V.reason,rolledBack:V.rolledBack}:(n.push({operationId:R.operationId,preSnapshots:A,postSnapshots:V.snapshots,plan:{operationId:R.operationId,kind:R.kind,target:R.target,documentVersion:R.documentVersion,steps:[],preSnapshots:A}}),f(),r.length=0,{ok:!0,operationId:R.operationId,kind:R.kind,target:R.target,resultVersion:Math.max(...V.snapshots.map(Y=>Y.version)),affectedFiles:[..._]})}async function u(){let R=n.at(-1);if(!R)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to undo"};let _=await S(R.preSnapshots,R.postSnapshots);return _.ok===!1?{ok:!1,operationId:R.operationId,errorCode:_.rolledBack?"writeback-failed":"rollback-failed",reason:_.reason,rolledBack:_.rolledBack}:(n.pop(),r.push(R),{ok:!0,operationId:R.operationId,kind:R.plan.kind,target:R.plan.target,resultVersion:Math.max(..._.snapshots.map(A=>A.version)),affectedFiles:R.preSnapshots.map(A=>A.file)})}async function d(){let R=r.at(-1);if(!R)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to redo"};let _=await S(R.postSnapshots,R.preSnapshots);return _.ok===!1?{ok:!1,operationId:R.operationId,errorCode:_.rolledBack?"writeback-failed":"rollback-failed",reason:_.reason,rolledBack:_.rolledBack}:(r.pop(),n.push(R),f(),{ok:!0,operationId:R.operationId,kind:R.plan.kind,target:R.plan.target,resultVersion:Math.max(..._.snapshots.map(A=>A.version)),affectedFiles:R.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((R,_)=>R+p(_),0)}function p(R){return m(R.preSnapshots)+m(R.postSnapshots)}function m(R){return R.reduce((_,A)=>_+A.file.length+A.content.length,0)}async function y(R,_){let A=[];for(let w of _){let D=w.capability??"write-text",U=o.find(V=>V.sourceType===w.sourceType&&(w.adapterId===void 0||V.adapterId===w.adapterId)&&(V.capabilities===void 0||V.capabilities.includes(D)));if(!U)return{ok:!1,operationId:R.operationId,errorCode:"unsupported-operation",reason:`No external adapter registered for ${w.sourceType}`,rolledBack:!1};let z=await U.execute(w);if(!z.ok)return{ok:!1,operationId:R.operationId,errorCode:"writeback-failed",reason:z.reason??`External adapter failed for ${w.sourceType}`,rolledBack:!1};A.push(w.file)}return{ok:!0,operationId:R.operationId,kind:R.kind,target:R.target,resultVersion:0,affectedFiles:A}}function x(R,_){if(R.conflictPolicy!=="compare-and-swap")return null;let A=new Map(_.map(w=>[w.file,w]));for(let w of R.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 D=A.get(w.file),U=w.baseContentHash;if(U===null){if(D?.exists!==!1)return{file:w.file,reason:`Source file ${w.file} was created or changed before save.`};continue}if(!U)return{file:w.file,reason:`Source file ${w.file} is missing baseContentHash. Reopen the file before saving.`};if(D?.exists===!1||D?.sha256!==U)return{file:w.file,reason:`Source file ${w.file} changed before save. Reload or explicitly overwrite the newer version.`}}return null}async function E(R){let _=[];for(let A of R)_.push(await b(A));return _}async function b(R){if(!await e.exists(R))return{file:R,content:"",version:0,exists:!1};let A=Math.max(1,e.getVersion(R)),w=await e.readFile(R);return{file:R,content:w,version:A,exists:!0,sha256:ve(w)}}async function S(R,_,A=new Set){let w=[];try{for(let D of R){if(A.has(D.file)){if(!e.createExclusive)throw new Error("Create-only write requires atomic exclusive-create support.");await e.createExclusive(D.file,D.content)}else await C(D);let U=e.bumpVersion(D.file);w.push(D.file),D.version=U}}catch(D){let U=await T(_.filter(V=>w.includes(V.file)));if(U.ok===!1)return{ok:!1,reason:`Writeback failed, then rollback failed for ${U.failedFiles.join(", ")}: ${SS(D)}`,rolledBack:!1,instanceConflict:ES(D)};let z=ES(D);return{ok:!1,reason:`${z?"MATERIALIZATION_INSTANCE_CONFLICT: ":""}Writeback failed and committed files were restored: ${SS(D)}`,rolledBack:!0,instanceConflict:z}}return{ok:!0,snapshots:R.map(_L)}}async function C(R){if(R.exists===!1){await e.deleteFile(R.file);return}await e.writeFile(R.file,R.content)}async function T(R){let _=[];for(let A of R)try{await C(A),e.bumpVersion(A.file)}catch{_.push(A.file)}return _.length===0?{ok:!0}:{ok:!1,failedFiles:_}}}function ES(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="EEXIST"}function _L(e){let t=e.exists!==!1;return{file:e.file,content:t?e.content:"",version:e.version,exists:t,...t?{sha256:ve(e.content)}:{}}}function SS(e){return e instanceof Error?e.message:String(e)}function vS(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 xt(qt({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-import":return xt(fo({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-node":return xt(jr({source:t,locator:e.locator,removeWhitespace:e.removeWhitespace}));case"insert-child":return xt(Zt({source:t,locator:e.parentLocator,node:e.node,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"update-text":return xt(zs({source:t,locator:e.locator,segmentIndex:e.segmentIndex,newText:e.newText}));case"update-value":return xt(fi({source:t,locator:e.locator,next:e.value}));case"update-array-item":return xt(fi({source:t,locator:e.locator,next:e.value}));case"insert-bound-array-item":return xt(qs({source:t,locator:e.locator,index:e.index,value:e.value}));case"insert-jsx-expression-child":return xt(Hs({source:t,locator:e.parentLocator,expression:e.expression,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"remove-bound-array-item":return xt(Qs({source:t,locator:e.locator,index:e.index}));case"move-array-item":return xt(ea({source:t,locator:e.locator,fromIndex:e.fromIndex,toIndex:e.toIndex}));case"move-node":return xt(Vr({source:t,locator:e.locator,targetParentLocator:e.targetParentLocator,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"move-repeat-template-child":return xt(Ws({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 AL(e,t);case"set-property-changes":return xt(Gs({source:t,locator:e.locator,changes:e.changes}));case"set-link-target":return xt(Ys({source:t,locator:e.locator,link:e.link,changes:e.changes}));case"set-property-binding":return xt(Zs({source:t,locator:e.locator,name:e.name,object:e.object,property:e.property}));case"upsert-object-property":return xt(na({source:t,objectLocator:e.locator,name:e.name,value:e.value}));default:return{ok:!1,reason:`Unknown step type: ${e.type}`,errorCode:"unknown"}}}function AL(e,t){let{request:n}=e;if(n.newAttrRaw!==null&&!Fg(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!==ve(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:Og({source:t,oldAttrRange:n.oldAttrRange,openingElementRange:n.openingElementRange,newAttrRaw:n.newAttrRaw})}}function xt(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 Uc,SiteEditCompositionContextSchema as TL,SiteEditCompositionSelectorSchema as wL}from"@vcp-dev/contracts";var Ct=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="SiteEditCompositionError"}};function kS(e,t){throw new Ct("INVALID_COMPOSITION",e,{value:t})}function Kc(e){let t=TL.safeParse(e);return t.success?t.data:kS("Invalid SiteEditCompositionContext.",e)}function RS(e){let t=[],n=new Map,r=new Map;for(let l of e.compositions){let u=Kc(l?.context);if(typeof l.entryFile!="string"||!l.entryFile)throw new Ct("INVALID_COMPOSITION","A registered composition must have a non-empty entryFile.");let d=Uc(u);if(n.has(d))throw new Ct("DUPLICATE_COMPOSITION",`Composition key ${d} is registered more than once.`,{key:d,context:u});let f=r.get(l.entryFile);if(f)throw new Ct("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 Ct("INVALID_COMPOSITION","At least one composition must be registered.");let o=new Map;for(let l of e.initialDocumentVersions??[]){let u=Kc(l?.composition);if(!Number.isInteger(l?.version)||(l?.version??-1)<0)throw new Ct("INVALID_INITIAL_DOCUMENT_VERSION","Initial document version must be a non-negative integer.",{context:u,version:l?.version});let d=Uc(u);if(!n.has(d))throw new Ct("UNKNOWN_COMPOSITION","Initial document version references an unregistered composition.",{context:u,key:d});if(o.has(d))throw new Ct("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=wL.safeParse(l);if(!u.success)return kS("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 Ct("AMBIGUOUS_COMPOSITION","The composition selector matches multiple registered contexts.",{selector:u.data}):new Ct("UNKNOWN_COMPOSITION","The composition selector is not registered.",{selector:u.data})}function s(l){let u=Kc(l),d=Uc(u),f=n.get(d);if(!f)throw new Ct("UNKNOWN_COMPOSITION","The composition context is not registered.",{context:u,key:d});return f}function a(l){let u=Kc(l?.context);if(typeof l.entryFile!="string"||!l.entryFile)throw new Ct("INVALID_COMPOSITION","A registered composition must have a non-empty entryFile.");let d=Uc(u),f=n.get(d);if(f){if(f.entryFile===l.entryFile)return f;throw new Ct("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 Ct("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 pp(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 CS(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 OL,stripSiteEditRepeatInstanceKeys as NS}from"@vcp-dev/contracts";function PS(e){let t=new Map,n=new Map,r=new Map;for(let o of e.entries){t.set(o.key,o);let i=NS(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 FL(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 Jc(e){return e?.map(t=>({...t}))}function mp(e,t){if(t===null||e?.kind!=="value-binding"||e.sourceKind!=="repeat-template")return e;let n=e.collectionIndexMap?.[t]??t,r=Jc(e.collectionPathMap?.[t])??Jc(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:Jc(e.path),locator:e.locator?{...e.locator,path:r}:e.locator,collectionIndexMap:e.collectionIndexMap?[...e.collectionIndexMap]:void 0,collectionPathMap:e.collectionPathMap?.map(o=>Jc(o)??[])}}function _S(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)=>OL(g,p),c=(g,p,m)=>{let y=o.get(g);if(!y)return a(g,m);let x=a(g,m),E={...y,key:x,parentKey:p,childKeys:[]};return i.push(E),E.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 E=0;E<y;E+=1)x.push(c(g,m,[...p,E]));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 E of[...x.textTargets.values(),...x.elementPropertyTargets.values()])if(!(E?.kind!=="value-binding"||E.sourceKind!=="repeat-template"))for(let b of LL(E))b.length<=p.length||DL(b,p)&&m.add(b[p.length])}}return m.size>0?m.size:FL(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 AS(e){let t=e.parts.at(-1);return typeof t?.repeatIndex=="number"?t.repeatIndex:null}function TS(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((NS(s.key)??s.key)===n){if(s.key===t)return i;i+=1}return null}function LL(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 DL(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 wS(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 OS(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 FS(e){return{path:e.path,code:e.code,message:e.message,...e.details?{details:JSON.parse(JSON.stringify(e.details))}:{}}}function ML(e){return e.map(t=>`${t.code} (${t.path}): ${t.message}`).join("; ")}var ds=class extends Error{constructor(t){let n=t.map(FS);super(ML(n)),this.name="RouteBuildDiagnosticsError",this.diagnostics=n}};function LS(e,t){let n=t instanceof Error&&t.message?t.message:String(t);return t instanceof ds?{routeId:e,message:n,diagnostics:t.diagnostics.map(FS)}:{routeId:e,message:n}}function gp(e){return e.map(({routeId:t,message:n})=>`${t}: ${n}`).join("; ")}function hp(e,t){let n=new Map(e);for(let r of t)n.delete(r);return n}function fs(e,t){e.clear();for(let[n,r]of t)e.set(n,r)}function DS(e,t){for(let n of t){if(n.exists===!1){e.delete(n.file);continue}e.set(n.file,n.content)}}function Xc(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 MS(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 XL=/^(?:src\/)?app\/.*\/?page\.[cm]?[jt]sx?$/,zL=["layout.tsx","layout.ts","layout.jsx","layout.js","layout.mjs","layout.cjs"],BS=32,Hc=256;function HL(e){return{expectedIndexDigest:e.digest,publishedIndexDigest:e.digest,publishedCursor:e.cursor,publishedCurrentId:e.currentId}}var jS={maxEntries:50,maxBytes:8*1024*1024};function WL(){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 ia(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 $S(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 GL(){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>jS.maxEntries||YL(e)>jS.maxBytes;)e.shift()}}function YL(e){return e.reduce((t,n)=>t+ZL(n),0)}function ZL(e){return VS(e.preSnapshots)+VS(e.postSnapshots)+qL(e.provenance)}function qL(e){return e?new TextEncoder().encode(JSON.stringify(e)).byteLength:0}function VS(e){return e.reduce((t,n)=>t+n.file.length+n.content.length,0)}function US(e,t){return{key:jL(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 Wc=class extends Error{constructor(t){super(t.reason),this.result=t}},ro=class extends Error{constructor(t){super(gp(t)),this.failedRoutes=t}};function KS(e,t){if(!e)return;let n=[...t];if(n.some(o=>o?.entries.some(i=>i.key===e.key)))return e;let r=Lt(e.key)??e.key;for(let o of n){let i=o?.entries.find(s=>(Lt(s.key)??s.key)===r);if(i)return{...e,key:i.key}}return e}function QL(e,t,n){if(!n)return;let r=Lt(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 eD=/\.(?:[cm]?[jt]sx?)$/i,tD=/\.json$/i,nD=/\.(?:css|scss|sass)$/i,rD=/\.mdx$/i,oD=/\.ya?ml$/i;function iD(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 sD(e){return{kind:e.isProxy?"component-proxy":"jsx-node",file:e.file,componentName:e.componentName,isProxy:e.isProxy}}function aD(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=GS(await e.listFiles(i)),a=new Map(s.files.map(l=>[l.path,l]));for(let[l,u]of n)if(cD(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 cD(e,t){return t.length===0?!0:t.some(n=>e===n||e.startsWith(`${n}/`))}function GS(e){return Array.isArray(e)?{files:e}:e}function lD(e){if(!VL(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!==KL||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=$L(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(eD.test(e.path)){let t=Sn({source:e.content,profile:Or({filePath:e.path,source:e.content})});if(!t.ok)return{ok:!1,errorCode:"ast-error",message:t.diagnostic.message,details:{path:e.path}}}if(tD.test(e.path))try{JSON.parse(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`JSON parse failed: ${Pt(t)}`,details:{path:e.path}}}if(nD.test(e.path)){let t=JS({content:e.content,path:e.path,profile:"css"});if(!t.ok)return t}if(rD.test(e.path)){let t=JS({content:e.content,path:e.path,profile:"mdx"});if(!t.ok)return t}if(oD.test(e.path))try{JL(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`YAML parse failed: ${Pt(t)}`,details:{path:e.path}}}return{ok:!0}}function JS({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
|
+
`,d);if(p===-1){l=!0;break}d=p,l=!0;continue}if(c){l=f===`
|
|
9
|
+
`||f==="\r";continue}if(s){f==="*"&&g==="/"&&(s=!1,d+=1),l=f===`
|
|
10
|
+
`||f==="\r";continue}if(a){f===`
|
|
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
|
+
`||f==="\r"))return Ko(t,`Unterminated string literal in ${t}.`);l=f===`
|
|
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 Ko(t,`Unexpected closing token "${f}" in ${t}.`);l=!1;continue}l=f===`
|
|
14
|
+
`||f==="\r"}if(s)return Ko(t,`Unterminated block comment in ${t}.`);if(o)return Ko(t,`Unterminated string literal in ${t}.`);if(c)return Ko(t,`Unterminated MDX code fence in ${t}.`);let u=r.at(-1);return u?Ko(t,`Unclosed token "${u.char}" in ${t}.`):{ok:!0}}function Ko(e,t){return{ok:!1,errorCode:"ast-error",message:t,details:{path:e}}}function Gc(e){let t="idle",n=e.fileSystem??WL(),r=Lg(),o=RS({compositions:e.compositions,initialDocumentVersions:e.initialDocumentVersions}),i=new Map,s=new Map,a=new Set,c=null,l=e.history??(e.historyStore?kh(e.historyStore):GL()),u=IS(n,{externalAdapters:e.externalAdapters}),d=new Map,f=Xg(Hc),g=new Set,p=0,m=e.historyStore?.recoveryRequired??!1,y=fp(),x=C();function E(h){return(zc.isAbsolute(h)?zc.relative(e.projectRoot,h):h).replace(/\\/g,"/").replace(/^\.\//,"")}function b(h,k){let I=zc.posix.dirname(h),P=k.replace(/\.(?:tsx?|jsx?)$/i,""),F=zc.posix.relative(I,P);return F.startsWith(".")?F:`./${F}`}function S(h,k){return h.startLine===k.startLine&&h.startColumn===k.startColumn&&h.endLine===k.endLine&&h.endColumn===k.endColumn}async function C(){let h=e.historyStore;if(h)try{let k=await h.readTransactionJournal();if(!k)return;let I=await h.readIndex(),P=await Promise.all(k.files.map(async L=>await n.exists(L.path)?ve(await n.readFile(L.path)):null));if(MS({journal:k,index:I,observedFileDigests:P})!=="ambiguous"){await h.clearTransactionJournal(k.transactionId);let L=await h.readStatus();L.recoveryRequired||(await h.cleanupTmp(),L=await h.readStatus()),m=L.recoveryRequired;return}await h.markRecoveryRequired(`Ambiguous transaction journal ${k.transactionId} at phase ${k.phase}`),m=!0}catch(k){m=!0,await h.markRecoveryRequired(`Transaction journal recovery failed: ${Pt(k)}`).catch(()=>{})}}function T(){return t==="disposed"}e.onEvent&&r.subscribe(e.onEvent);for(let h of o.entries){let k=US(h.context,h.entryFile);i.set(h.key,k),R(k,k.dependencyFiles)}function R(h,k){let I=new Set(k);_(h),h.dependencyFiles=I;for(let P of h.dependencyFiles){let F=s.get(P);F||(F=new Set,s.set(P,F)),F.add(h.key)}}function _(h){for(let k of h.dependencyFiles){let I=s.get(k);I&&(I.delete(h.key),I.size===0&&s.delete(k))}h.dependencyFiles.clear()}function A(h){let k=new Set;for(let I of h)for(let P of s.get(I)??[])k.add(P);return k}function w(h){for(let k of h)if(!s.has(k))return!1;return!0}async function D(h,k,I,P,F,L){let $=new Map,J=nS(h),q=XE(F.values()),H=Kb(F.values()),X=typeof L.exists=="function"?te=>L.exists(te):async()=>!1;for(let[te,ae]of h.elements){let Se=k.nodes.get(te);if(!Se)continue;let re=I.get(ae.sourceFile)??P.get(ae.sourceFile),Ne=new Map,be=new Map,M=new Map,Z=[];for(let Xe of ae.textSegments){if(!re){Ne.set(Xe.index,null);continue}let ei=await zE({file:ae.sourceFile,source:re,segment:Xe,readFile:Dt=>L.readFile(Dt),exists:X,graph:h,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Dt,adapterId:Ar,capabilities:Pl})=>({sourceType:Dt,adapterId:Ar,capabilities:Pl})),functionCallContracts:e.functionCallContracts,fileCache:q}),Nt=await rp({file:ae.sourceFile,source:re,target:{kind:"text-segment",segment:Xe},readFile:Dt=>L.readFile(Dt),exists:X,graph:h,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Dt,adapterId:Ar,capabilities:Pl})=>({sourceType:Dt,adapterId:Ar,capabilities:Pl})),functionCallContracts:e.functionCallContracts,fileCache:q}),Wt=iD(ei);Ne.set(Xe.index,Wt),be.set(Xe.index,ei),M.set(Xe.index,Nt),Z.push({editable:Xe.editable,source:Wt})}let pe=new Map,ke=new Map;if(re)for(let Xe of ae.attributes??[]){let ei=await Uo({file:ae.sourceFile,source:re,sourceRange:Xe.sourceRange,expression:Xe.source?.expression??Xe.value,sourceInfo:Xe.source,readFile:Wt=>L.readFile(Wt),exists:X,graph:h,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Wt,adapterId:Dt,capabilities:Ar})=>({sourceType:Wt,adapterId:Dt,capabilities:Ar})),functionCallContracts:e.functionCallContracts,fileCache:q}),Nt=await tS({element:ae,file:ae.sourceFile,source:re,propertyName:Xe.name,readFile:Wt=>L.readFile(Wt),exists:X,graph:h,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Wt,adapterId:Dt,capabilities:Ar})=>({sourceType:Wt,adapterId:Dt,capabilities:Ar})),functionCallContracts:e.functionCallContracts,fileCache:q});ke.set(Xe.name,Nt),pe.set(Xe.name,ei)}let Pe=dS(sD(Se.writeTarget),Z),Ge=J({key:te,element:ae,provenances:M}),Zn=hS(ae),bn=re?await Jb({element:ae,graph:h,file:ae.sourceFile,source:re,readFile:Xe=>L.readFile(Xe),exists:X,fileCache:H}):void 0,_r=h.regions.find(Xe=>Xe.kind==="conditional-region"&&Xe.childKeys.includes(te)),mt,Ht=_r?.sourceCandidates?.[0];if(re&&_r&&Ht?.kind==="conditional-branch"){let Xe=await rp({file:ae.sourceFile,source:re,target:{kind:"conditional-branch",candidate:Ht},readFile:Nt=>L.readFile(Nt),exists:X,graph:h,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Nt,adapterId:Wt,capabilities:Dt})=>({sourceType:Nt,adapterId:Wt,capabilities:Dt})),functionCallContracts:e.functionCallContracts,fileCache:q});mt={currentBranch:_r.childKeys.indexOf(te)<=0?"then":"else",availableBranches:_r.childKeys.length>1?["then","else"]:["then"],conditionExpression:Ht.conditionExpression,provenance:{finalSource:Xe.finalSource?{kind:Xe.finalSource.kind,file:Xe.finalSource.file,displayPath:Xe.finalSource.displayPath}:null,chain:Xe.chain.map(Nt=>({kind:Nt.kind,file:Nt.file,displayName:Nt.displayName,canEditHere:Nt.canEditHere})),confidence:Xe.confidence,editMode:Xe.editMode,diagnostics:Xe.diagnostics.map(Nt=>({code:Nt.code,message:Nt.message}))}}}$.set(te,{textSources:Ne,textTargets:be,elementPropertyTargets:pe,propertyProvenances:ke,isRepeat:RD(te,h),provenances:M,writeTarget:Pe,componentSemantic:Ge,styleSource:Zn,conditional:mt,dynamicData:bn})}return $}function U(h){return typeof n.getVersion=="function"?n.getVersion(h):0}function z(h,k){let I=o.initialVersions.get(h.key)??0;for(let P of k.values())I=Math.max(I,P);return Math.max(I,h.graph?.version??0)}function V(h){return i.get(h)?.graph?.version??o.initialVersions.get(h)??0}function Y(h){try{return V(o.resolveSelector(h.composition).key)}catch{return 0}}async function ue(h,k,I=n,P={}){let F=await ga(h,k,L=>I.readFile(L),L=>I.exists(L),{additionalEntries:await pt(h,I),...P});if(F.diagnostics.length>0)throw new ds(F.diagnostics);return P.validationOnly||f.remember(F.parsedModules.values()),F}async function st(h,k,I={}){let P=i.get(h);if(!P)return null;let F=I.sourceCache??hp(d,[]),L=I.fileSystem??pp(n),{graph:$,allSources:J,parsedModules:q,entryModule:H}=await ue(P.entryFile,k,L,{version:P.graph?.version??1}),X=new Map;for(let mt of J.keys())X.set(mt,U(mt));let te=Math.max(z(P,X),I.minimumVersion??0);I.changed&&te<=(P.graph?.version??0)&&(te=(P.graph?.version??0)+1),$.version=te;for(let[mt,Ht]of J)Xc(F,mt,Ht,Hc);let ae=await qo(P.composition,P.entryFile,J,F,L);$.routeId=P.routeId,$.composition=P.composition;let Se=Ja($),re=ra(Se,$),Ne=await D($,Se,J,F,q,L);rt(re,Ne);let be=xe($,re,Ne),M=Qo(Ne),Z=_S(sS($,Se,re,{canUpdateTextByKey:be,dynamicDataSummaryByKey:M}),$,Ne),pe=dn({route:P.routeId,composition:P.composition,entryFile:P.entryFile,version:te,source:k,ast:H?.ast}),ke=Cy(pe),Pe=null,Ge=[];if(pe.ok){dD(Z,$,pe.projection,q);let mt=Ka({composition:P.composition,entryFile:P.entryFile,graph:$,parsedModules:q,projection:pe.projection});if(mt.diagnostics.length===0){let Ht=Di({composition:P.composition,entryFile:P.entryFile,graph:$,parsedModules:q,projection:pe.projection,documentVersion:te,roots:mt.roots});Ht.diagnostics.length===0&&(Pe=Ht,Ge=Ht.descriptors)}}let Zn={...Z,composition:P.composition,pageBlocks:Ge,...ae?{styleContext:ae}:{},pageComposition:ke},bn=new Set([P.entryFile,...J.keys()]);if(ae){bn.add(ae.entryCss.path);for(let mt of ae.stylesheets)bn.add(mt.path)}let _r={...P,dependencyFiles:bn,graph:$,topology:Se,capabilities:re,document:Zn,pageBlockIndex:Pe,pageComposition:ke,pageCompositionProjection:pe.projection,pagePlacementByKey:pe.ok?pe.projection.placementByKey:null,pagePlacementUnitByKey:pe.ok?pe.projection.placementUnitByKey:null,pageUnitByKey:pe.ok?pe.projection.unitByKey:null,pagePlacementsByUnitKey:pe.ok?pe.projection.placementsByUnitKey:null,documentIndex:PS(Zn),detailProjections:Ne,fileVersions:X,styleContext:ae};if(I.publish===!1)return _r;for(let mt of bn){let Ht=J.get(mt)??F.get(mt);Ht!==void 0&&(Xc(d,mt,Ht,Hc),g.delete(mt))}return R(P,bn),Object.assign(P,_r),P}async function pt(h,k=n){let I=[];for(let P of bD(h))typeof k.exists=="function"&&await k.exists(P)&&I.push({file:P,source:await k.readFile(P)});return I}async function qo(h,k,I,P,F){let L=[];for(let[X,te]of I){if(yp(X)){L.push(X);continue}for(let ae of SD(te)){let Se=WS(X,ae);Se&&L.push(Se)}}if(!L.length){for(let X of ED(k))if(await F.exists(X)){L.push(X);break}}let $=new Map,J=kD(L).slice(0,BS);for(;J.length>0&&$.size<BS;){let X=J.shift();if($.has(X)||!yp(X))continue;let te=await sn(X,P,F);if(te!==null){$.set(X,{path:X,content:te});for(let ae of vD(te)){let Se=WS(X,ae);Se&&!$.has(Se)&&!J.includes(Se)&&J.push(Se)}}}let q=[...$.values()].map(X=>({...X,hash:ve(X.content)})),H=q[0];return H?{composition:h,revision:ve(JSON.stringify(q.map(({path:X,hash:te})=>({path:X,hash:te})))),entryCss:H,stylesheets:q.slice(1)}:null}async function sn(h,k,I){let P=k.get(h);if(P!==void 0)return P;if(!await I.exists(h))return null;let F=await I.readFile(h);return Xc(k,h,F,Hc),F}function Qo(h){let k=new Map;for(let[I,P]of h)P.dynamicData?.bindings.length&&k.set(I,nE(P.dynamicData.bindings));return k}function xe(h,k,I){let P=new Map;for(let[F,L]of h.elements){if(!k.get(F)?.canUpdateText){P.set(F,!1);continue}let J=I.get(F),q=L.textSegments.some(H=>{if(!H.editable)return!1;let X=J?.provenances.get(H.index)??null;return!X||Te(X)});P.set(F,q)}return P}function rt(h,k){for(let[I,P]of k){let F=h.get(I);F?.canUpdateText&&P.dynamicData?.bindings.some(L=>L.readonly&&(L.targetKind==="text"||L.targetKind==="richtext"))&&h.set(I,{...F,canUpdateText:!1})}}function Te(h){return h.editMode==="direct"||h.editMode==="proxy"||h.editMode==="upstream"}async function de(h,k={}){let I=[...new Set(h)],P=k.affectedCompositionKeys!==void 0,F=P?new Set(k.affectedCompositionKeys):A(I);if(!P&&(F.size===0||!w(I)))for(let H of i.values())am(H,I)&&F.add(H.key);let L=!P&&F.size===0&&I.some(HS),$=k.publish===!1?hp(d,I):void 0,J={rebuiltRoutes:[],failedRoutes:[],...k.publish===!1?{candidateRouteStates:[],candidateSourceCache:$}:{}},q=pp(n);for(let H of i.values())if(!(k.excludedCompositionKeys?.has(H.key)||!(F.has(H.key)||L)))try{let te=!!H.graph,ae=await q.readFile(H.entryFile),Se=await st(H.key,ae,{...k,fileSystem:q,...$?{sourceCache:$}:{}});Se?.graph&&(J.rebuiltRoutes.push({documentChanged:te,composition:H.composition,routeId:H.routeId,version:Se.graph.version}),J.candidateRouteStates?.push({composition:H.composition,key:H.key,routeId:H.routeId,state:Se}))}catch(te){J.failedRoutes.push({...LS(H.routeId,te),composition:H.composition})}return J}function Le(h){let k=[...new Set(h)],I=A(k);if(I.size>0&&w(k))return[...I];for(let P of i.values())am(P,k)&&I.add(P.key);return[...I]}function Et(h){let k=new Set(Le(h));return o.entries.filter(I=>k.has(I.key)).map(I=>I.context)}function an(h){return[...new Set(Le(h))].sort((I,P)=>I<P?-1:I>P?1:0).map(I=>o.getByKey(I)?.context).filter(I=>I!==void 0)}function St(h,k){let I=new Set(Le(k)),P=h.provenance?.affectedCompositions??[];if(P.length===0)return I;if([...new Set(P.map(L=>o.resolveContext(L).key))].some(L=>!I.has(L)))throw new Error("History provenance does not match the affected composition index.");return I}function Is(h,k){let I=h.composition??h.provenance?.initiatingComposition;if(I){let L=o.resolveContext(I);return{context:L.context,key:L.key}}let P=[...new Set(Le(k))];if(P.length!==1)throw new Error(`Legacy history entry cannot be attributed to a unique composition (affected composition count: ${P.length}).`);let F=o.getByKey(P[0]);if(!F)throw new Error("Legacy history entry references an unknown affected composition.");return{context:F.context,key:F.key}}function Sl(h,k){r.emit({type:"operation-completed",composition:h.composition,result:h});for(let{composition:I,version:P}of k.rebuiltRoutes)r.emit({type:"document-changed",composition:I,version:P});for(let{composition:I,message:P}of k.failedRoutes)r.emit({type:"graph-error",composition:I,message:P})}function am(h,k){return k.some(I=>h.dependencyFiles.has(I)||h.entryFile===I||h.graph?.fileIndex.has(I))}function cm(h){for(let k of h)a.add(k);c||T()||(c=(async()=>{t="building";let k=!1;try{for(;a.size>0;){if(T())return;await cI(),await y.runExclusive(async()=>{if(p>0||T())return;let I=[...a];a.clear();let P=await lm(I);if(P.length===0)return;let F=Le(P);for(let J of F){let q=i.get(J)?.composition;q&&r.emit({type:"graph-invalidated",composition:q})}let{rebuiltRoutes:L,failedRoutes:$}=await de(P,{changed:!0});for(let{documentChanged:J,composition:q,version:H}of L)r.emit({type:"graph-ready",composition:q,version:H}),J&&r.emit({type:"document-changed",composition:q,version:H});for(let{composition:J,message:q}of $)k=!0,r.emit({type:"graph-error",composition:J,message:q})})}}finally{c=null,t!=="disposed"&&(t=!k&&[...i.values()].some(I=>I.graph)?"ready":"idle"),a.size>0&&cm([])}})())}async function cI(){for(;p>0;)await new Promise(h=>setTimeout(h,0))}async function lm(h){let k=[];for(let I of new Set(h)){let P=d.get(I);if(P===void 0){if(g.has(I)&&!await n.exists(I))continue;g.delete(I),k.push(I);continue}try{await n.readFile(I)!==P&&(g.delete(I),k.push(I))}catch(F){if(!uD(F))try{if(await n.exists(I))continue}catch{continue}g.add(I),k.push(I)}}return k}function um(h){DS(d,h);for(let k of h)k.exists===!1?g.add(k.file):g.delete(k.file)}function dm(h){g.clear();for(let k of h)g.add(k)}async function fm(h){let k=await lm(h);if(k.length===0)return;let I=Le(k);for(let L of I){let $=i.get(L)?.composition;$&&r.emit({type:"graph-invalidated",composition:$})}let{rebuiltRoutes:P,failedRoutes:F}=await de(k,{changed:!0});for(let{documentChanged:L,composition:$,version:J}of P)r.emit({type:"graph-ready",composition:$,version:J}),L&&r.emit({type:"document-changed",composition:$,version:J});for(let{composition:L,message:$}of F)r.emit({type:"graph-error",composition:L,message:$})}async function lI(h,k){let I=ao(h,k);if(!I?.graph)return;let P=Lt(h)??h,F=I.graph.elements.get(P);F&&await fm([F.sourceFile])}async function pm(h){let k=new Set;if(h.target.kind==="node"){let I=ao(h.target.key,h.composition),P=Lt(h.target.key)??h.target.key,F=I?.graph?.elements.get(P);F&&k.add(F.sourceFile)}else if(h.target.kind==="route"){let I=i.get(o.resolveSelector(h.target.composition).key);I&&k.add(I.entryFile)}else if(h.target.kind==="page-unit"){let I=i.get(o.resolveSelector(h.target.composition).key);I&&k.add(I.entryFile)}else if(h.target.kind==="page-block"){let I=i.get(o.resolveSelector(h.target.composition).key),P=I?.pageBlockIndex?.bindings.get(h.target.blockKey);if(P&&(k.add(P.ownerFile),k.add(P.descriptor.source.file)),I?.pageBlockIndex&&h.params.kind==="move-node"&&"kind"in h.params.target&&h.params.target.kind==="block-boundary"){let F=I.pageBlockIndex.bindings.get(h.params.target.anchorBlockKey);F&&(k.add(F.ownerFile),k.add(F.descriptor.source.file))}}else if(h.target.kind==="source-file")k.add(h.target.path);else if(h.target.kind==="source-batch")for(let I of h.target.paths)k.add(I);if(h.params.kind==="move-node"&&!("kind"in h.params.target)){let I=[h.params.target.parentKey,...h.params.target.relation==="before"||h.params.target.relation==="after"?[h.params.target.anchorKey]:[]];for(let P of I){let F=ao(P,h.composition),L=Lt(P)??P,$=F?.graph?.elements.get(L);$&&k.add($.sourceFile)}}await fm(k)}async function uI(h){if(h.params.kind!=="source-edit")return kl(h,"invalid-params","source-edit requires source-edit params");for(let k of h.params.edits){let I=lD(k);if(!I.ok)return kl(h,I.errorCode,I.message,I.details)}p+=1;try{let k=await bI(h.params.edits);if(!k.ok)return kl(h,k.errorCode,k.message,k.details);await pm(h);let I={operationId:h.id,kind:"source-edit",target:h.target,documentVersion:h.documentVersion,conflictPolicy:h.params.conflictPolicy,edits:h.params.edits.map(P=>P.operation==="delete"?{operation:"delete",file:P.path,baseContentHash:P.baseContentHash??null}:{operation:"upsert",file:P.path,baseContentHash:P.baseContentHash??null,content:P.content})};return await Yn({request:h,filePlan:I})}catch(k){return{composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!1,resultVersion:Y(h),error:{code:B.INTERNAL_ERROR,message:Pt(k)}}}finally{p-=1}}async function dI(h){if(h.target.kind!=="project"||h.params.kind!=="insert-page-resource")return W(h,B.INVALID_PARAMS,"insert-page-resource requires project target and matching params.");p+=1;try{let k=await ni({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:[...h.params.artifact.components.flatMap(P=>P.materialization.files.map(F=>({path:F.pathTemplate,content:F.content}))),...h.params.artifact.pages.flatMap(P=>P.materialization.files.map(F=>({path:F.pathTemplate,content:F.content})))],exists:P=>n.exists(P),readFile:P=>n.readFile(P)});if(!k.ok)return W(h,B.MATERIALIZATION_REJECTED,k.message);let I=await Ku({artifact:h.params.artifact,exists:P=>n.exists(P)});return I.ok?await Yn({request:h,filePlan:{operationId:h.id,kind:"source-edit",target:h.target,documentVersion:h.documentVersion,conflictPolicy:"overwrite",edits:I.files},output:{kind:"insert-page-resource",package_instance_id:I.packageInstanceId,pages:I.pages},historyPolicy:"none"}):W(h,I.code==="MATERIALIZATION_CONFLICT"?B.MATERIALIZATION_CONFLICT:B.MATERIALIZATION_REJECTED,I.message,I.path?{path:I.path}:void 0)}catch(k){return W(h,B.INTERNAL_ERROR,Pt(k))}finally{p-=1}}async function fI(h){if(h.target.kind!=="project"||h.params.kind!=="delete-page-source")return W(h,B.INVALID_PARAMS,"delete-page-source requires project target and matching params.");if(!n.listFiles)return W(h,B.PLAN_FAILED,"Complete project file listing is required for page deletion.");p+=1;try{let k=GS(await n.listFiles({maxFiles:5e4,maxDepth:64}));if(k.truncated)return W(h,B.PLAN_FAILED,"Project file listing is incomplete; page deletion was refused.",{truncationReasons:k.truncated.reasons});let I=k.files.filter(({path:$})=>/\.(?:tsx?|jsx?)$/.test($)),P=Object.fromEntries(await Promise.all(I.map(async({path:$})=>[$,await n.readFile($)]))),F=vx({expectedUrlPath:h.params.expectedUrlPath,files:P});if(!F.ok)return W(h,F.code==="HOME_PAGE_LOCKED"?B.HOME_PAGE_LOCKED:F.code==="ROUTE_NOT_FOUND"?B.ROUTE_NOT_FOUND:B.PLAN_FAILED,F.message);let L=await Promise.all(F.edits.map(async $=>({...$,baseContentHash:ve(await n.readFile($.file))})));return Yn({request:h,filePlan:{operationId:h.id,kind:"source-edit",target:h.target,documentVersion:h.documentVersion,conflictPolicy:"compare-and-swap",edits:L},output:{kind:"delete-page-source",deleted_files:F.deletedFiles,updated_files:F.updatedFiles,preserved_shared_files:F.preservedSharedFiles,warnings:F.warnings},historyPolicy:"none"})}catch(k){return W(h,B.INTERNAL_ERROR,Pt(k))}finally{p-=1}}async function pI(h,k){if(h.kind!=="insert-child"&&h.kind!=="replace-node")return W(h,B.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 W(h,B.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 W(h,B.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.");if(h.params.position.documentVersion!==h.documentVersion)return W(h,B.VERSION_STALE,"Page-unit insert-child placement belongs to a different document version.")}let I=k.document,P=k.pageCompositionProjection;if(!I||I.pageComposition?.status!=="supported"||!P||P.status!=="supported")return W(h,B.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(h.documentVersion!==I.version||P.documentVersion!==I.version)return W(h,B.VERSION_STALE,`Document version ${h.documentVersion} is stale (current: ${I.version}).`);let F=h.params.node.kind==="component-call"?h.params.node.materialization:void 0;if(!F)return W(h,B.UNSUPPORTED_OPERATION,"Page-unit insertion currently requires a static materialization manifest.");let L=h.params.kind==="insert-child"?h.params.position:null,$=await ni({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:F.files.map(H=>({path:H.pathTemplate,content:H.content})),exists:H=>n.exists(H),readFile:H=>n.readFile(H)});if(!$.ok)return W(h,B.MATERIALIZATION_REJECTED,$.message);let J=await $S(n,Object.keys(F.projectDependencies??{})),q=await Yu({manifest:F,generatedRoot:"components/site/generated",controlledFiles:F.files.map(H=>({pathTemplate:H.pathTemplate})),exists:H=>n.exists(H),availableHostDependencies:J,hostCapabilities:Bu(),commit:async H=>{let X=await n.readFile(k.entryFile),te=k.document,ae=k.pageCompositionProjection;if(!te||te.pageComposition?.status!=="supported"||te.version!==h.documentVersion||!ae||ae.status!=="supported"||ae.documentVersion!==te.version)return{ok:!0,data:W(h,B.VERSION_STALE,"The route changed before the page-unit insertion could commit.")};let Se=H.entry.path,re=CI(H.instanceName),Ne,be=[];if(h.params.kind==="insert-child"){if(!L||!("kind"in L)||L.kind!=="page-composition")return{ok:!0,data:W(h,B.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.")};let ke=Pi({routeId:k.routeId,entryFile:k.entryFile,currentDocumentVersion:te.version,expectedDocumentVersion:h.documentVersion,source:X,projection:ae,placementKey:L.placementKey,component:{source:Se,exportName:H.entry.export.kind==="default"?"default":H.entry.export.name,localName:re}});if(!ke.ok)return{ok:!0,data:W(h,Nl(ke.error.code),ke.error.message,{diagnostics:ke.error.diagnostics})};let Pe=ke.plan.rewriteStep,Ge;switch(Pe.kind){case"insert-root-expression":Ge=_i({source:X,locator:Pe.locator,expectedSourceHash:Pe.sourceHash,action:{kind:"insert",jsx:Pe.node.jsx,placement:Pe.placement,replaceOriginal:Pe.replaceOriginal}});break;case"insert-child":Ge=Zt({source:X,locator:Pe.parentLocator,node:Pe.node,placement:Pe.placement,...Pe.anchorLocator?{anchorLocator:Pe.anchorLocator}:{}});break;default:Ge={ok:!1,source:X,diagnostic:{code:"unsupported-syntax",message:`Unsupported route composition rewrite: ${String(Pe)}`}}}if(!Ge.ok)return{ok:!0,data:W(h,B.AST_PARSE_ERROR,Ge.diagnostic.message)};Ne=Ge.source}else{let ke=gd({routeId:k.routeId,composition:k.composition,entryFile:k.entryFile,currentDocumentVersion:te.version,expectedDocumentVersion:h.documentVersion,source:X,projection:ae,placementUnitKey:h.target.placementUnitKey,operation:"replace-node"});if(!ke.ok)return{ok:!0,data:W(h,Nl(ke.error.code),ke.error.message,{diagnostics:ke.error.diagnostics})};let Pe=ke.plan.rewriteStep,Ge;switch(Pe.kind){case"replace-root-expression":Ge=_i({source:X,locator:Pe.locator,expectedSourceHash:Pe.sourceHash,action:{kind:"replace",jsx:`<${re} />`}});break;case"replace-node":Ge=lo({source:X,locator:Pe.locator,node:{jsx:`<${re} />`}});break;default:Ge={ok:!1,source:X,diagnostic:{message:`Unsupported page-unit replacement rewrite: ${Pe.kind}`}}}if(!Ge.ok)return{ok:!0,data:W(h,B.AST_PARSE_ERROR,Ge.diagnostic.message)};let Zn=await Il({routeState:k,placementUnitKey:h.target.placementUnitKey,source:X,mutatedSource:Ge.source});Ne=Zn.source,be=await Promise.all(Zn.files.map(async bn=>({operation:"delete",file:bn,baseContentHash:ve(await n.readFile(bn))})))}let M=qt({source:Ne,moduleSpecifier:b(k.entryFile,Se),imports:H.entry.export.kind==="default"?[{kind:"default",local:re}]:[{kind:"named",imported:H.entry.export.name,local:re}]});if(!M.ok)return{ok:!0,data:W(h,B.AST_PARSE_ERROR,M.diagnostic.message)};let Z=H.files.map(ke=>({operation:"create-only",file:ke.path,content:ke.content})),pe=[{operation:"upsert",file:k.entryFile,content:M.source,baseContentHash:ve(X)},...Z,...be];p+=1;try{let ke=await Yn({request:h,filePlan:{operationId:h.id,kind:"source-edit",target:{kind:"source-file",path:k.entryFile},documentVersion:h.documentVersion,conflictPolicy:"compare-and-swap",edits:pe}});return!ke.ok&&ke.error?.message.includes("MATERIALIZATION_INSTANCE_CONFLICT")?{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:ke.error?.message??"Static prefab instance conflicted during commit."}}:{ok:!0,data:ke}}finally{p-=1}}});return q.ok?q.data:W(h,q.error.code==="MATERIALIZATION_INSTANCE_CONFLICT"?B.MATERIALIZATION_CONFLICT:B.MATERIALIZATION_REJECTED,q.error.message,{materializationCode:q.error.code})}async function mI(h,k){if(h.kind!=="insert-child"&&h.kind!=="replace-node")return W(h,B.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 W(h,B.INVALID_PARAMS,"Page-block materialization operation kind must match its params.");let I=k.document,P=k.pageBlockIndex;if(!I||!P||P.diagnostics.length>0)return W(h,B.UNSUPPORTED_OPERATION,"The current route has no complete verified page-block index.");if(h.documentVersion!==I.version||P.documentVersion!==I.version)return W(h,B.VERSION_STALE,`Document version ${h.documentVersion} is stale (current: ${I.version}).`);let F=Ro(P,h.target,h.documentVersion,h.selectionRef);if(!F.ok)return W(h,ks(F.code),F.message);let L=F.binding;if(!(h.kind==="insert-child"?L.descriptor.capabilities.insert:L.descriptor.capabilities.replace)){let re=L.descriptor.unavailableReasons?.[h.kind==="insert-child"?"insert":"replace"]?.reason??"The selected page block does not permit this operation.";return W(h,B.UNSUPPORTED_OPERATION,re)}let J=(h.kind==="insert-child",h.params);if(J.kind!==h.kind)return W(h,B.INVALID_PARAMS,"Page-block materialization operation kind must match its params.");let q=J.node;if(q.kind!=="component-call"||!q.materialization)return W(h,B.UNSUPPORTED_OPERATION,"Page-block materialization requires a static component manifest.");let H;if(J.kind==="insert-child"){let re=J.position;if(!("kind"in re&&re.kind==="block-boundary"))return W(h,B.INVALID_PARAMS,"Page-block insert-child requires a block-boundary position.");if(re.documentVersion!==h.documentVersion)return W(h,B.VERSION_STALE,"The block insertion boundary belongs to a different document version.");let Ne=Xa(P,re);if(!Ne.ok)return W(h,ks(Ne.code),Ne.message);H=Ne.boundary}let X=q.materialization,te=await ni({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:X.files.map(re=>({path:re.pathTemplate,content:re.content})),exists:re=>n.exists(re),readFile:re=>n.readFile(re)});if(!te.ok)return W(h,B.MATERIALIZATION_REJECTED,te.message);let ae=await $S(n,Object.keys(X.projectDependencies??{})),Se=await Yu({manifest:X,generatedRoot:"components/site/generated",controlledFiles:X.files.map(re=>({pathTemplate:re.pathTemplate})),exists:re=>n.exists(re),availableHostDependencies:ae,hostCapabilities:Bu(),commit:async re=>{let Ne=k.document,be=k.pageBlockIndex;if(!Ne||!be||Ne.version!==h.documentVersion||be.documentVersion!==Ne.version||!be.bindings.has(L.blockKey))return{ok:!0,data:W(h,B.VERSION_STALE,"The route or selected block changed before materialization could commit.")};let M=be.bindings.get(L.blockKey);if(!M||M.ownerFile!==L.ownerFile||M.ownerSourceHash!==L.ownerSourceHash||M.sourceHash!==L.sourceHash)return{ok:!0,data:W(h,B.VERSION_STALE,"The selected block owner or source changed before materialization could commit.")};let Z=new Set([L.ownerFile,L.descriptor.source.file,...H?[H.ownerFile,H.anchorLocator.file,...H.parentLocator?[H.parentLocator.file]:[]]:[]]),pe=new Map;try{for(let Pe of Z)pe.set(Pe,await n.readFile(Pe))}catch{return{ok:!0,data:W(h,B.VERSION_STALE,"A selected owner, root, or boundary file is no longer readable.")}}let ke=nx({operationId:h.id,documentVersion:h.documentVersion,target:h.target,binding:L,...H?{boundary:H}:{},operation:J.kind,materialization:re,files:pe});if(!ke.ok){let Pe=xI(ke.code);return{ok:!0,data:W(h,Pe,ke.message,{materializationCode:ke.code})}}p+=1;try{let Pe=await Yn({request:h,filePlan:ke.plan});return!Pe.ok&&Pe.error?.message.includes("MATERIALIZATION_INSTANCE_CONFLICT")?{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:Pe.error.message||"Static prefab instance conflicted during commit."}}:{ok:!0,data:Pe}}finally{p-=1}}});return Se.ok?Se.data:W(h,Se.error.code==="MATERIALIZATION_INSTANCE_CONFLICT"?B.MATERIALIZATION_CONFLICT:B.MATERIALIZATION_REJECTED,Se.error.message,{materializationCode:Se.error.code})}async function gI(h,k){if(h.kind!=="move-node"&&h.kind!=="remove-node")return W(h,B.UNSUPPORTED_OPERATION,"Only page-unit move-node and remove-node are currently supported by the page composition transaction.");let I=k.document,P=k.pageCompositionProjection;if(!I||I.pageComposition?.status!=="supported"||!P||P.status!=="supported")return W(h,B.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(h.documentVersion!==I.version||P.documentVersion!==I.version)return W(h,B.VERSION_STALE,`Document version ${h.documentVersion} is stale (current: ${I.version}).`);let F=await n.readFile(k.entryFile),L=gd({routeId:k.routeId,composition:k.composition,entryFile:k.entryFile,currentDocumentVersion:I.version,expectedDocumentVersion:h.documentVersion,source:F,projection:P,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(!L.ok)return W(h,Nl(L.error.code),L.error.message,{diagnostics:L.error.diagnostics});let $=L.plan.rewriteStep,J;switch($.kind){case"move-node":J=Vr({source:F,locator:$.locator,targetParentLocator:$.targetParentLocator,placement:$.placement,...$.anchorLocator?{anchorLocator:$.anchorLocator}:{}});break;case"remove-node":J=jr({source:F,locator:$.locator});break;case"remove-root-expression":J=_i({source:F,locator:$.locator,expectedSourceHash:$.sourceHash,action:{kind:"remove"}});break;default:J={ok:!1,source:F,diagnostic:{message:`Unsupported page-unit mutation rewrite: ${$.kind}`}}}if(!J.ok)return W(h,B.AST_PARSE_ERROR,J.diagnostic.message);let q=J.source,H=[];if(h.kind==="remove-node"){let te=await Il({routeState:k,placementUnitKey:h.target.placementUnitKey,source:F,mutatedSource:q});q=te.source,H=await Promise.all(te.files.map(async ae=>({operation:"delete",file:ae,baseContentHash:ve(await n.readFile(ae))})))}let X=[{operation:"upsert",file:k.entryFile,content:q,baseContentHash:ve(F)},...H];p+=1;try{return await Yn({request:h,filePlan:{operationId:h.id,kind:"source-edit",target:{kind:"source-file",path:k.entryFile},documentVersion:h.documentVersion,conflictPolicy:"compare-and-swap",edits:X}})}finally{p-=1}}async function hI(h,k){if(h.kind!=="move-node"&&h.kind!=="remove-node")return W(h,B.UNSUPPORTED_OPERATION,"Only page-block move-node and remove-node use this source transaction.");let I=k.document,P=k.pageBlockIndex;if(!I||!P||P.diagnostics.length>0)return W(h,B.UNSUPPORTED_OPERATION,"The current route has no complete verified page-block index.");if(h.documentVersion!==I.version||P.documentVersion!==I.version)return W(h,B.VERSION_STALE,`Document version ${h.documentVersion} is stale (current: ${I.version}).`);let F=Ro(P,h.target,h.documentVersion,h.selectionRef);if(!F.ok)return W(h,ks(F.code),F.message);let L=F.binding;if(L.documentVersion!==I.version)return W(h,B.VERSION_STALE,"The resolved page-block binding is stale.");if(!(h.kind==="move-node"?L.descriptor.capabilities.move:L.descriptor.capabilities.remove)){let be=L.descriptor.unavailableReasons?.[h.kind==="move-node"?"move":"remove"]?.reason??"The selected block does not permit this operation.";return W(h,B.UNSUPPORTED_OPERATION,be)}if(h.kind==="remove-node"){let be=[...i.values()].filter(M=>M.dependencyFiles.has(L.ownerFile));if(be.includes(k)||be.push(k),be.some(M=>!M.pageBlockIndex||M.pageBlockIndex.descriptors.length<=1))return W(h,B.UNSUPPORTED_OPERATION,"The selected source is the last editable page block in an affected composition.")}let J=null;if(h.kind==="move-node"){if(h.params.kind!=="move-node"||!("kind"in h.params.target)||h.params.target.kind!=="block-boundary")return W(h,B.INVALID_PARAMS,"Page-block move requires a block-boundary target.");if(h.params.target.anchorBlockKey===L.blockKey)return W(h,B.INVALID_TARGET,"A page block cannot be moved relative to itself.");let be=Xa(P,h.params.target);if(!be.ok)return W(h,ks(be.code),be.message);let M=P.bindings.get(h.params.target.anchorBlockKey);if(!M||!L.descriptor.siblingBlockKeys.includes(M.blockKey)||!M.descriptor.siblingBlockKeys.includes(L.blockKey)||M.ownerFile!==L.ownerFile||M.root.ownerNode.kind!==L.root.ownerNode.kind||M.root.ownerNode.key!==L.root.ownerNode.key||M.root.parentStructuralPath!==L.root.parentStructuralPath)return W(h,B.INVALID_TARGET,"The selected block and boundary anchor are not verified same-owner source siblings.");if(J=be.boundary,J.ownerFile!==L.ownerFile||J.sourceHash!==L.ownerSourceHash||!J.parentLocator)return W(h,B.INVALID_TARGET,"The move boundary does not belong to the selected block's source owner.")}let q=L.ownerFile,H=await n.readFile(q);if(ve(H)!==L.ownerSourceHash)return W(h,B.VERSION_STALE,"The page-block owner source changed after resolution.");let X=L.descriptor.source.file===q?H:await n.readFile(L.descriptor.source.file);if(ve(X)!==L.descriptor.source.contentHash)return W(h,B.VERSION_STALE,"The selected page-block source changed after resolution.");let te=yI(L),ae=h.kind==="remove-node"?jr({source:H,locator:te}):Vr({source:H,locator:te,targetParentLocator:vl(J.parentLocator),anchorLocator:vl(J.anchorLocator),placement:J.placement});if(!ae.ok)return W(h,B.AST_PARSE_ERROR,ae.diagnostic.message);let Se=ae.source,re=[];if(h.kind==="remove-node"&&L.root.ownerNode.kind==="route-member"&&L.root.callChain.length>0&&L.descriptor.placementUnitKey){let be=await Il({routeState:k,placementUnitKey:L.descriptor.placementUnitKey,source:H,mutatedSource:Se});Se=be.source,re=be.files}let Ne=[{operation:"upsert",file:q,content:Se,baseContentHash:L.ownerSourceHash},...await Promise.all(re.map(async be=>({operation:"delete",file:be,baseContentHash:ve(await n.readFile(be))})))];p+=1;try{return await Yn({request:h,filePlan:{operationId:h.id,kind:"source-edit",target:h.target,documentVersion:h.documentVersion,conflictPolicy:"compare-and-swap",edits:Ne}})}finally{p-=1}}function yI(h){return vl(h.ownerLocator)}function vl(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 ks(h){return h==="VERSION_STALE"?B.VERSION_STALE:h==="INVALID_PARAMS"?B.INVALID_PARAMS:B.INVALID_TARGET}function xI(h){return h==="VERSION_STALE"?B.VERSION_STALE:h==="INVALID_PARAMS"?B.INVALID_PARAMS:h==="INVALID_TARGET"?B.INVALID_TARGET:h.startsWith("MATERIALIZATION_")?B.MATERIALIZATION_REJECTED:B.UNSUPPORTED_OPERATION}async function Il(h){let k={source:h.mutatedSource,files:[]},I=h.routeState.graph,P=h.routeState.pageCompositionProjection;if(!I||!P||P.status!=="supported"||!n.listFiles)return k;let L=P.placementUnitByKey.get(h.placementUnitKey)?.sourceRange;if(!L)return k;let $=[...I.elements.values()].find(M=>M.sourceFile===h.routeState.entryFile&&M.importedFrom&&S(M.sourceRange,L));if(!$?.importedFrom||!$.exportName)return k;let J=E($.importedFrom),q="components/site/generated/";if(!J.startsWith(q))return k;let H=J.slice(q.length).split("/")[0];if(!H||!/-[0-9a-f]{8}$/i.test(H))return k;let X=`${q}${H}`;if([...I.elements.values()].filter(M=>M.sourceFile===h.routeState.entryFile&&E(M.importedFrom??"")===J).length!==1)return k;let ae=await n.listFiles({maxFiles:5e3,maxDepth:32}),Se=Array.isArray(ae)?ae:ae.files;if(!Array.isArray(ae)&&ae.truncated)return k;let re=Se.map(({path:M})=>M).filter(M=>M===X||M.startsWith(`${X}/`));if(re.length===0||!re.includes(J))return k;for(let{path:M}of Se)if(!(M===h.routeState.entryFile||M===X||M.startsWith(`${X}/`)))try{if((await n.readFile(M)).includes(H))return k}catch{return k}let Ne=b(h.routeState.entryFile,J),be=fo({source:h.mutatedSource,moduleSpecifier:Ne,imports:$.exportName==="default"?[{kind:"default"}]:[{kind:"named",imported:$.exportName}]});return be.ok?be.source.includes(H)?{source:be.source,files:[]}:{source:be.source,files:re.sort((M,Z)=>M.localeCompare(Z))}:k}async function bI(h){if(n.getFileInfo){for(let $ of h)if(await n.exists($.path)&&await n.getFileInfo($.path)===null)return{ok:!1,errorCode:"invalid-params",message:`Source edit path must resolve to a regular non-symbolic-link file: ${$.path}`,details:{path:$.path}}}for(let $ of h){if($.operation!=="upsert"||!/^(?:src\/)?app\/globals\.css$/i.test($.path))continue;let J=await n.exists($.path)?await Kl(n,$.path):null;if(J?.ok){let q=BL(J.content,$.content);if(!q.ok)return{ok:!1,errorCode:"invalid-params",message:q.message,details:{path:$.path,code:q.code}}}}let k=EI(h);if(k.length===0)return{ok:!0};let I=aD(n,h),P=new Map,F=($,J)=>{let q=P.get($);if(q?.source===J)return q.result;let H=Ue($,J);return P.set($,{source:J,result:H}),H},L;try{L=await CS(k,async $=>{let J=i.get($);return J?[...(await ue(J.entryFile,await I.readFile(J.entryFile),I,{validationOnly:!0,parseModule:F,validatedImports:f.getImports})).parsedModules.values()]:[]})}catch($){return{ok:!1,errorCode:"ast-error",message:`Source edit preflight failed: ${Pt($)}`,details:{compositionKeys:k}}}for(let $ of L)f.remember($);return{ok:!0}}function EI(h){return h.map(I=>I.path).some(HS)?[...i.keys()]:[]}function kl(h,k,I,P){let F=ps(k);return{composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!1,resultVersion:Y(h),error:{code:F,message:I,...P?{details:P}:{}}}}async function Rl(h){let k=[];for(let I of new Set(h))k.push(await SI(I));return k}async function SI(h){if(!(typeof n.exists=="function"?await n.exists(h):!0))return{file:h,content:"",version:Math.max(0,U(h)),exists:!1};let I=await n.readFile(h);return{file:h,content:I,version:Math.max(1,U(h)),exists:!0,sha256:ve(I)}}async function mm(h,k,I,P){if(!e.historyStore)return null;let F=new Map(k.map(J=>[J.file,J])),L=new Map(I.map(J=>[J.file,J])),$=[...new Set([...F.keys(),...L.keys()])].sort().map(J=>{let q=F.get(J),H=L.get(J);return{path:J,preDigest:q?.exists===!1||!q?null:ve(q.content),postDigest:H?.exists===!1||!H?null:ve(H.content)}});return{schemaVersion:2,transactionId:`${h}:${P.expectedIndexDigest}`,operationId:h,phase:"prepared",historyTransition:P,files:$}}async function gm(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 Cl(h,k){let I=[];try{for(let P of h)await hm(P),typeof n.bumpVersion=="function"&&n.bumpVersion(P.file),I.push(P.file)}catch(P){let F=await vI(k.filter(L=>I.includes(L.file)));return F.ok?{ok:!1,reason:`Writeback failed and committed files were restored: ${Pt(P)}`,rolledBack:!0}:{ok:!1,reason:`Writeback failed, then rollback failed for ${F.failedFiles.join(", ")}: ${Pt(P)}`,rolledBack:!1}}return{ok:!0,snapshots:h.map(II)}}async function hm(h){if(h.exists===!1){await n.deleteFile(h.file);return}await n.writeFile(h.file,h.content)}async function vI(h){let k=[];for(let I of h)try{await hm(I),typeof n.bumpVersion=="function"&&n.bumpVersion(I.file)}catch{k.push(I.file)}return k.length===0?{ok:!0}:{ok:!1,failedFiles:k}}function II(h){let k=h.exists!==!1;return{file:h.file,content:k?h.content:"",version:h.version,exists:k,...k?{sha256:ve(h.content)}:{}}}async function Yn(h){return y.runExclusive(()=>kI(h))}async function kI(h){let k=h.filePlan.edits.map(M=>M.file),I=o.resolveSelector(h.request.composition),P=I.context,F=h.historyPolicy==="none"?void 0:{initiatingComposition:P,affectedCompositions:an(k)},L=await Rl(k),$=new Map(L.filter(M=>M.exists!==!1).map(M=>[M.file,M.content])),J=xm(),q=new Map(d),H=new Set(g),X=new Set([...i.values()].filter(M=>h.filePlan.edits.some(Z=>Z.operation==="delete"&&Z.file===M.entryFile)).map(M=>M.key)),te=h.filePlan.edits.map(M=>M.operation==="delete"?{file:M.file,content:"",version:0,exists:!1}:{file:M.file,content:M.content,version:0,exists:!0,sha256:ve(M.content)}),ae={operationId:h.filePlan.operationId,intents:h.filePlan.edits.map(M=>M.operation==="delete"?{kind:"delete",path:M.file}:{kind:M.operation==="create-only"?"create-only":"upsert",path:M.file,content:M.content})},Se=null,re=!1,Ne=await Vc({overlay:$,exists:M=>n.exists(M),plan:ae,buildCandidate:async({plan:M})=>({plan:M}),prepareHistory:async()=>{let M=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:L,postSnapshots:te,...h.selectionRef?{selectionRef:h.selectionRef}:{},...h.output?{output:h.output}:{},...F?{provenance:F}:{}}),Z=M?.historyTransition?M.historyTransition:e.historyStore?HL(await e.historyStore.readIndex()):null;if(e.historyStore&&!Z)throw new Error("Durable history did not provide an exact index transition.");return Se=await mm(h.request.id,L,te,Z),Se=await gm(Se),{history:M,historyTransition:Z}},reverify:async()=>{},writeCandidate:async()=>{let M=await u.executeFilePlan(h.filePlan);if(!M.ok)throw new Wc(M);return{postSnapshots:await Rl(M.affectedFiles),affectedFiles:M.affectedFiles,internalResultVersion:M.resultVersion}},validateCandidate:async({candidate:M,receipt:Z})=>{let pe=await de(Z.affectedFiles,{changed:!0,minimumVersion:Z.internalResultVersion,publish:!1,excludedCompositionKeys:X});if(pe.failedRoutes.length>0)throw new ro(pe.failedRoutes);let ke=Em(J,pe.candidateRouteStates??[]),Pe=bm(ke,I.key);return{...M,rebuild:pe,routeSnapshots:ke,resultVersion:Pe,...KS(h.selectionRef,ke.map(Ge=>Ge.state.document))?{selectionRef:KS(h.selectionRef,ke.map(Ge=>Ge.state.document))}:{}}},publishCandidate:async({candidate:M,history:Z,receipt:pe})=>{Z?.history&&(await l.publishPrepared(Z.history),re=!0);let ke=M.resultVersion??pe.internalResultVersion;return{composition:P,requestId:h.request.id,kind:h.request.kind,target:h.request.target,ok:!0,resultVersion:ke,affectedFiles:pe.affectedFiles,fileChanges:pe.postSnapshots.map(Pe=>({path:Pe.file,operation:Pe.exists===!1?"delete":"upsert"})),...h.output?{output:h.output}:{},...M.selectionRef?{selectionRef:M.selectionRef}:{}}},swapCandidate:({candidate:M,receipt:Z})=>{M.routeSnapshots&&Rs(M.routeSnapshots),M.rebuild?.candidateSourceCache&&fs(d,M.rebuild.candidateSourceCache),um(Z.postSnapshots)},finalizeCandidate:async()=>{await so(Se);for(let M of X)i.delete(M)},emitCommitted:({candidate:M,published:Z})=>{Sl(Z,M.rebuild??{rebuiltRoutes:[],failedRoutes:[]})},rollbackCandidate:async({history:M,receipt:Z})=>{if(re)throw new Error("history was published before transaction finalization failed");if(Z){let pe=await Cl(L,Z.postSnapshots);if(!pe.ok)throw new Error(pe.reason)}Rs(J),fs(d,q),dm(H),M?.history&&await l.discardPrepared?.(M.history),await so(Se)}});if(Ne.ok)return Ne.published;if(Ne.stage==="precheck"||Ne.stage==="build")try{await so(Se)}catch(M){let Z=await Ns(Pt(M));return W(h.request,Z,"Unable to clear an uncommitted transaction journal.")}if(Ne.recoveryRequired){let M=await Ns(Ne.reason);return W(h.request,M===B.RECOVERY_PERSIST_FAILED?M:B.ROLLBACK_FAILED,Ne.reason)}let be=Ne.error;return be instanceof Wc?{...W(h.request,ps(be.result.errorCode),be.result.reason),...be.result.affectedFiles?{affectedFiles:be.result.affectedFiles}:{}}:be instanceof ro?W(h.request,B.ROUTE_REBUILD_FAILED,`Route rebuild failed and source was rolled back: ${gp(be.failedRoutes)}`,{failedRoutes:be.failedRoutes}):W(h.request,vm(Ne.stage),Pt(be))}async function ym(h){return y.runExclusive(async()=>{let k=h==="undo"?await l.prepareUndo():await l.prepareRedo();return k?RI(h,k):{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:B.INTERNAL_ERROR,message:h==="undo"?"Nothing to undo":"Nothing to redo"}}})}async function RI(h,k){let I=k.entry,P=h==="undo"?I.preSnapshots:I.postSnapshots,F=h==="undo"?I.postSnapshots:I.preSnapshots,L=P.map(Z=>Z.file),{context:$,key:J}=Is(I,L),q=await Rl(L),H=new Map(q.filter(Z=>Z.exists!==!1).map(Z=>[Z.file,Z.content])),X=V(J),te=xm(),ae=new Map(d),Se=new Set(g),re=null,Ne=!1,be,M=await Vc({overlay:H,plan:{operationId:`${h}:${I.operationId}`,intents:P.map(Z=>Z.exists===!1?{kind:"delete",path:Z.file}:{kind:"upsert",path:Z.file,content:Z.content})},buildCandidate:async()=>({}),prepareHistory:async()=>(re=await mm(`${h}:${I.operationId}`,q,P,k.historyTransition),re=await gm(re),k),reverify:async()=>{},writeCandidate:async()=>{let Z=await Cl(P,F);if(!Z.ok)throw new Error(Z.reason);return{snapshots:Z.snapshots}},validateCandidate:async({candidate:Z})=>{be=St(I,L);let pe=await de(L,{changed:!0,minimumVersion:X+1,publish:!1,affectedCompositionKeys:be});if(pe.failedRoutes.length>0)throw new ro(pe.failedRoutes);let ke=Em(te,pe.candidateRouteStates??[]),Pe=bm(ke,J);return{...Z,rebuild:pe,routeSnapshots:ke,resultVersion:Pe}},publishCandidate:async({candidate:Z,history:pe,receipt:ke})=>{if(!pe)throw new Error("history cursor intent is missing");await l.publishPrepared(pe),Ne=!0;let Pe=Z.resultVersion??X+1;return{composition:$,requestId:h,kind:I.kind,target:I.target,ok:!0,resultVersion:Pe,affectedFiles:L,fileChanges:ke.snapshots.map(Ge=>({path:Ge.file,operation:Ge.exists===!1?"delete":"upsert"})),...I.output?{output:I.output}:{}}},swapCandidate:({candidate:Z,receipt:pe})=>{Z.routeSnapshots&&Rs(Z.routeSnapshots),Z.rebuild?.candidateSourceCache&&fs(d,Z.rebuild.candidateSourceCache),um(pe.snapshots)},finalizeCandidate:async()=>{await so(re)},emitCommitted:({candidate:Z,published:pe})=>Sl(pe,Z.rebuild??{rebuiltRoutes:[],failedRoutes:[]}),rollbackCandidate:async({history:Z,receipt:pe})=>{if(Ne)throw new Error("history cursor was published before transaction finalization failed");if(pe){let ke=await Cl(F,pe.snapshots);if(!ke.ok)throw new Error(ke.reason)}Rs(te),fs(d,ae),dm(Se),Z&&await l.discardPrepared?.(Z),await so(re)}});if(M.ok)return M.published;if(M.stage==="precheck"||M.stage==="build")try{await so(re)}catch(Z){let pe=await Ns(Pt(Z));return{composition:$,requestId:h,kind:I.kind,target:I.target,ok:!1,resultVersion:X,error:{code:pe,message:"Unable to clear an uncommitted transaction journal."}}}if(M.recoveryRequired){let Z=await Ns(M.reason);return{composition:$,requestId:h,kind:I.kind,target:I.target,ok:!1,resultVersion:X,affectedFiles:L,error:{code:Z===B.RECOVERY_PERSIST_FAILED?Z:B.ROLLBACK_FAILED,message:M.reason}}}return{composition:$,requestId:h,kind:I.kind,target:I.target,ok:!1,resultVersion:X,affectedFiles:L,error:{code:M.error instanceof ro?B.ROUTE_REBUILD_FAILED:vm(M.stage),message:Pt(M.error),...M.error instanceof ro?{details:{failedRoutes:M.error.failedRoutes}}:{}}}}function xm(){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 bm(h,k){return h.find(P=>P.key===k)?.state.graph?.version??o.initialVersions.get(k)??0}function Em(h,k){let I=new Map(h.map(P=>[P.key,P]));for(let P of k)I.set(P.key,P);return[...I.values()]}function Rs(h){for(let k of i.values())_(k);for(let k of h){let I={...k.state,dependencyFiles:new Set(k.state.dependencyFiles),fileVersions:new Map(k.state.fileVersions)};i.set(k.key,I),R(I,I.dependencyFiles)}}async function Cs(h){let k=i.get(h);if(!k)throw new Error(`Composition not found: ${h}`);if(k.graph)return;let I=await n.readFile(k.entryFile);await st(h,I)}function ao(h,k){let I=i.get(o.resolveSelector(k).key)??null;return!I||!Sm(I,h)?null:I}function Sm(h,k){if(h.documentIndex?.entriesByKey.has(k)||h.graph?.elements.has(k))return!0;let I=Lt(k);return I&&I!==k?h.graph?.elements.has(I)===!0:!1}function W(h,k,I,P){return{composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!1,resultVersion:Y(h),error:{code:k,message:I,...P?{details:P}:{}}}}function vm(h){return h==="validate"?B.ROUTE_REBUILD_FAILED:h==="publish"?B.HISTORY_COMMIT_FAILED:B.WRITE_IO_ERROR}async function Ns(h){if(m=!0,!l.markRecoveryRequired)return B.RECOVERY_REQUIRED;try{return await l.markRecoveryRequired(h),B.RECOVERY_REQUIRED}catch{return B.RECOVERY_PERSIST_FAILED}}function CI(h){let I=h.split(/[^a-zA-Z0-9]+/).filter(Boolean).map(P=>P.charAt(0).toUpperCase()+P.slice(1)).join("").replace(/^[^a-zA-Z_$]+/,"");return I?`Prefab${I}`:"GeneratedPrefab"}function Nl(h){return h==="VERSION_STALE"?B.VERSION_STALE:h==="CROSS_PAGE_MOVE_UNSUPPORTED"?B.CROSS_PAGE_MOVE_UNSUPPORTED:B.UNSUPPORTED_OPERATION}async function Im(h){if(h.target.kind==="route"){let I=i.get(o.resolveSelector(h.target.composition).key)??null;return I?(I.graph||await Cs(I.key),I):W(h,B.ROUTE_NOT_FOUND,"Composition not found for route target.")}if(h.target.kind==="page-unit"){let I=i.get(o.resolveSelector(h.target.composition).key)??null;return I?(I.graph||await Cs(I.key),I):W(h,B.ROUTE_NOT_FOUND,"Composition not found for page-unit target.")}if(h.target.kind==="page-block"){let I=i.get(o.resolveSelector(h.target.composition).key)??null;return I?(I.graph||await Cs(I.key),I):W(h,B.ROUTE_NOT_FOUND,"Composition not found for page-block target.")}if(h.target.kind!=="node")return W(h,B.UNSUPPORTED_OPERATION,`${h.kind} source target execution is not implemented yet.`);let k=i.get(o.resolveSelector(h.composition).key)??null;return k?(k.graph||await Cs(k.key),Sm(k,h.target.key)?k:W(h,B.NODE_NOT_FOUND,`Target key not found: ${h.target.key}`)):W(h,B.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,k){let I=o.register({context:h,entryFile:k}),P=i.get(I.key);if(P?.entryFile===k)return;P&&_(P);let F=US(I.context,k);i.set(I.key,F),R(F,F.dependencyFiles),r.emit({type:"graph-invalidated",composition:I.context})},unregisterComposition(h){let k=o.resolveSelector(h),I=i.get(k.key);I&&(_(I),i.delete(k.key),o.unregister(k.key),i.size===0&&(t="idle"),r.emit({type:"graph-invalidated",composition:k.context}))},getCompositionEntryFiles(){return[...i.values()].map(h=>h.entryFile)},getCompositionContext(h){return o.resolveSelector(h).context},async initializeComposition(h){let k=o.resolveSelector(h),I=i.get(k.key);if(!I)throw new Error(`Composition not registered: ${k.key}`);if(I.graph)t="ready";else{t="building";try{let P=await n.readFile(I.entryFile);await st(k.key,P),t="ready",r.emit({type:"graph-ready",composition:k.context,version:i.get(k.key)?.graph?.version??0})}catch(P){throw t="idle",r.emit({type:"graph-error",composition:k.context,message:Pt(P)}),P}}},getDocument(h){let k=o.resolveSelector(h),I=i.get(k.key);if(!I)throw new Error(`Composition not registered: ${k.key}`);if(!I.document)throw new Error(`Composition not built: ${k.key}`);return I.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,k,I){let P=ao(h,k),F=Lt(h)??h;if(P?.graph&&P.topology&&P.capabilities&&P.detailProjections){let L=P.detailProjections.get(F);if(L){let $=P.graph.elements.get(F);if(!$)throw new Error(`Key not found: ${h}`);let J=QL(h,F,I),q=new Map;if(L.isRepeat&&J?.instanceIndex!==void 0)for(let te of $.attributes??[])q.set(te.name,Jf({file:$.sourceFile,source:d.get($.sourceFile)??"",element:$,propertyName:te.name,selectionRef:J,graph:P.graph,sources:d}));let H=iS({element:$,graph:P.graph,source:d.get($.sourceFile),documentVersion:P.graph.version,selectionRef:I,isRepeat:L.isRepeat,propertyProvenance:L.propertyProvenances,repeatTargets:q}),X=cS(F,P.graph,P.topology,P.capabilities,L.textSources,L.provenances,L.dynamicData,H);return h===F?X:OS(X,h,P.document??null,P.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${h}`)},getRenderDetail(h,k){let I=ao(h,k),P=Lt(h)??h;if(I?.graph&&I.topology&&I.capabilities&&I.detailProjections){let F=I.detailProjections.get(P);if(F){let L=aS(P,I.graph,I.topology,I.capabilities,F.textSources,F.writeTarget,F.provenances,F.conditional,F.componentSemantic,F.styleSource,F.dynamicData);return h===P?L:wS(L,h,I.document??null,I.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${h}`)},getClassNameSource(h,k){let I=ao(h,k),P=Lt(h)??h;if(!I?.graph)throw new Error(`Key not found: ${h}`);let F=I.graph.elements.get(P);if(!F)throw new Error(`Key not found: ${h}`);let L=d.get(F.sourceFile);if(L===void 0)throw new Error(`Source not loaded: ${F.sourceFile}`);return cu({key:P,route:{composition:I.composition,routeId:I.routeId,graph:I.graph,source:L}})},refreshSourceForKey:lI,async execute(h){if(await x,m)return W(h,B.RECOVERY_REQUIRED,"The edit engine requires explicit recovery before accepting mutations.");if(h.kind==="source-edit")return uI(h);if(h.kind==="insert-page-resource")return dI(h);if(h.kind==="delete-page-source")return fI(h);let k=await Im(h);if("ok"in k)return k;await pm(h);let I=await Im(h);if("ok"in I)return I;let P=I;if(h.target.kind==="page-unit"){let X=h;return h.kind==="insert-child"||h.kind==="replace-node"?pI(X,P):h.kind==="move-node"||h.kind==="remove-node"?gI(X,P):W(h,B.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 X=h;return h.kind==="insert-child"||h.kind==="replace-node"?mI(X,P):h.kind==="move-node"||h.kind==="remove-node"?hI(X,P):W(h,B.UNSUPPORTED_OPERATION,"Page-block operation is not supported by the current structural transaction.")}let L=h.params,$=h.target.kind==="node"?h.target.key:null;if(L.kind==="move-node"&&"kind"in L.target&&L.target.kind==="source-sibling"){let X=L.target,te=$?P.document?.entries.find(Z=>Z.key===$):null,ae=P.document?.entries.find(Z=>Z.key===X.anchorKey),Se=te?.pageCompositionActionScope,re=Se?.kind==="source-siblings"?Se.siblingKeys:null,Ne=re?.indexOf(te?.key??"")??-1,be=re?.indexOf(X.anchorKey)??-1,M=X.relation==="before"?Ne-1:Ne+1;if(!te||!ae||!re||Ne<0||be!==M||ae.pageCompositionActionScope?.kind!=="source-siblings"||ae.pageCompositionActionScope.siblingKeys.length!==re.length||ae.pageCompositionActionScope.siblingKeys.some((Z,pe)=>Z!==re[pe])||!te.operationSummary.canMove)return W(h,B.INVALID_TARGET,"Source sibling move is unavailable because the current source sibling scope or adjacent anchor no longer matches.")}if(!P.graph||!P.topology||!P.capabilities)return{composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!1,resultVersion:Y(h),error:{code:h.target.kind==="route"?B.ROUTE_NOT_FOUND:B.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 J=yD(P,P.graph,P.capabilities,d,i),q=await new yc(J).plan(h);if(!q.ok)return{composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!1,resultVersion:Y(h),error:{code:ps(q.errorCode),message:q.reason}};let H=q.plan;if(H.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:Y(h),affectedFiles:[]}:{composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!1,resultVersion:Y(h),error:{code:B.PLAN_FAILED,message:"Planner could not generate a valid execution plan"}};p+=1;try{if(H.steps.some(te=>te.type==="invoke-external-adapter")){let te=await u.execute(H);if(!te.ok)return W(h,ps(te.errorCode),te.reason);let ae={composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!0,resultVersion:Math.max(Y(h),te.resultVersion),affectedFiles:te.affectedFiles,...te.selectionRef?{selectionRef:te.selectionRef}:{}};return Sl(ae,{rebuiltRoutes:[],failedRoutes:[]}),ae}let X=await u.prepareRewritePlan(H);return X.ok?await Yn({request:h,filePlan:X.filePlan,...X.selectionRef?{selectionRef:X.selectionRef}:{}}):W(h,ps(X.errorCode),X.reason)}catch(X){return{composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!1,resultVersion:Y(h),error:{code:B.INTERNAL_ERROR,message:Pt(X)}}}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:V(o.entries[0].key),error:{code:B.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting undo."}};p+=1;try{return await ym("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:V(o.entries[0].key),error:{code:B.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting redo."}};p+=1;try{return await ym("redo")}finally{p-=1}},notifyFileChanged(h){cm([h])},getAffectedCompositions(h){return Et(h)},subscribe(h){return r.subscribe(h)}}}function uD(e){return e instanceof Error&&"code"in e&&(e.code==="ENOENT"||e.code==="ENOTDIR")}function dD(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&&ms(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=Lt(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&&ms(g.sourceRange,n.container.sourceRange)&&u){d.pageCompositionUnitKey=u.placementUnitKey;continue}let y=n.placements.find(x=>x.members.some(E=>E.sourceRange!==null&&(ms(g.sourceRange,E.sourceRange)||hD(E.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)}fD(e,t,n,r)}function fD(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&&ms(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!==(Lt(f.key)??f.key))continue;let p=r.get(g.sourceFile);if(!p)continue;let m=Ee(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()&&ze(x))){u(g)===1&&XS(y)&&(f.pageCompositionActionScope={kind:"route-unit"});continue}if(!XS(x))continue;let E=d.get(x.node)??[];E.push({entry:f,element:g,parentPath:x}),d.set(x.node,E)}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 E of g.parentPath.node.children){if(pD(E))continue;if(!mD(E)){y=!1;break}let b=[...t.elements.values()].find(C=>C.sourceFile===g.element.sourceFile&&C.componentName===g.element.componentName&&ms(C.sourceRange,gD(E))),S=b?o.get(b.identity.key):null;if(!b||!S||S.parentKey||S.pageCompositionUnitKey!==p||u(b)!==1){y=!1;break}m.push(S)}if(!y||m.length!==f.length||f.some(({entry:E})=>!m.some(b=>b.key===E.key)))continue;if(m.length===1){m[0].pageCompositionActionScope={kind:"route-unit"};continue}if(m.length<2)continue;let x=m.map(E=>E.key);for(let E of m)E.pageCompositionActionScope={kind:"source-siblings",siblingKeys:x}}}function XS(e){let t=e.parentPath;return!!(t?.isReturnStatement?.()||t?.isArrowFunctionExpression?.()&&t.node.body===e.node)}function pD(e){return!!(e&&typeof e=="object"&&e.type==="JSXText"&&!(e.value??"").trim())}function mD(e){return!!(e&&typeof e=="object"&&e.type==="JSXElement")}function gD(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 ms(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function hD(e,t){return zS(e.startLine,e.startColumn,t.startLine,t.startColumn)<=0&&zS(e.endLine,e.endColumn,t.endLine,t.endColumn)>=0}function zS(e,t,n,r){return e!==n?e-n:t-r}function yD(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=Lt(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:cu({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 mp(e.detailProjections?.get(f.baseKey)?.textTargets.get(d)??null,f.repeatIndex)},async getElementPropertyWriteTarget(u,d){let f=c(u);return mp(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(E=>E.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 Jf({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=UL(u);return d?{baseKey:d.baseKey,repeatIndex:TS(e.document??null,u,d.baseKey,e.documentIndex)??AS(d)}:{baseKey:u,repeatIndex:null}}function l(u,d){let f=Lt(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 xD={"stale-version":B.VERSION_STALE,"capability-denied":B.CAPABILITY_REJECTED,"invalid-params":B.INVALID_PARAMS,"locator-miss":B.LOCATOR_FAILED,"route-not-found":B.ROUTE_NOT_FOUND,"unsupported-operation":B.UNSUPPORTED_OPERATION,"invalid-target":B.INVALID_TARGET,"ast-error":B.AST_PARSE_ERROR,"writeback-failed":B.WRITE_IO_ERROR,"rollback-failed":B.RECOVERY_REQUIRED,unknown:B.INTERNAL_ERROR};function ps(e){return xD[e]}function Pt(e){return e instanceof Error&&e.message?e.message:String(e)}function HS(e){return/\.(?:[cm]?[jt]sx?|css|scss|sass|mdx|json)$/i.test(e)}function bD(e){let t=oo(e);if(!XL.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=>zL.map(a=>`${s}/${a}`))}function ED(e){let n=oo(e).startsWith("src/app/")?"src/app":"app";return[`${n}/globals.css`,`${n}/global.css`]}function SD(e){return YS(e,/\bimport\s+(?:[^'";]+?\s+from\s+)?["']([^"']+\.css(?:\?[^"']*)?)["']/g)}function vD(e){return YS(e,/@import\s+(?:url\(\s*)?["']([^"']+)["']/g)}function YS(e,t){let n=[];for(let r of e.matchAll(t)){let o=ZS(r[1]??"");o&&n.push(o)}return n}function WS(e,t){let n=ZS(t);return!n||n.startsWith("tailwindcss")||n.startsWith("http:")||n.startsWith("https:")?null:n.startsWith("@/")?oo(`src/${n.slice(2)}`):n.startsWith("./")||n.startsWith("../")?oo(`${ID(e)}/${n}`):n.startsWith("/")?oo(n.slice(1)):yp(n)?oo(n):null}function ZS(e){return e.split(/[?#]/,1)[0]?.trim()??""}function yp(e){return/\.css$/i.test(e)}function ID(e){let t=oo(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function kD(e){return Array.from(new Set(e))}function oo(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 RD(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 Yc=class{constructor(t){this.options=t,this.fileSystem=new ri(t.files),this.engine=this.createEngine(this.fileSystem)}get status(){return this.engine.status}initializeComposition(t){return this.engine.initializeComposition(t)}getDocument(t){return Fs(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 Ls(r?this.engine.getObjectEditContext(t,n,r):this.engine.getObjectEditContext(t,n))}getClassNameSource(t,n){return this.engine.getClassNameSource(t,n)}getSourceTree(t){return Bs(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}getSourceFile(t){return js(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}resolveSourceLocation(t){return $s(t,this.engine.getRenderDetail(t.key,t.composition))}async planOperation(t){let n=ND.safeParse(t);if(!n.success)return{result:Os(t,n.error.issues.map(i=>i.message))};let r=new ri(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:Dr(i)},a=r.getChangedFiles();if(a.length===0)return{result:s};let c=PD.parse({siteId:t.siteId,baseSnapshotId:t.baseSnapshotId,operationId:t.id,reason:`site-edit:${t.kind}`,patches:a.map(l=>_D(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 Gc({projectRoot:"/snapshot",fileSystem:t,compositions:this.options.compositions,onEvent:r&&this.options.onEvent?o=>{let i=Ds(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 _D(e,t){return e.after===void 0?{path:e.path,operation:"delete",...t||e.before===void 0?{}:{expectedHash:ve(e.before)}}:{path:e.path,operation:e.before===void 0?"create":"update",...t||e.before===void 0?{}:{expectedHash:ve(e.before)},fullContent:e.after}}function AD(e){return new Yc(e)}import{SiteEditOperationRequestSchema as OD}from"@vcp-dev/contracts";import xn from"node:fs/promises";import _t from"node:path";import{SITE_EDIT_SOURCE_ALLOWED_DIRS as TD,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as wD}from"@vcp-dev/contracts";var Zc=class{constructor(t){this.options=t,this.fileSystem=this.createFileSystem(),this.engine=Gc({...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 Bs(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.engine.getCompositionEntryFiles()})}getSourceFile(t){return js(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.engine.getCompositionEntryFiles()})}resolveSourceLocation(t){return $s(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 xn.readFile(_t.join(n,r),"utf8")},async readFileBytes(r){return xn.readFile(_t.join(n,r))},async getFileInfo(r){let o=_t.join(n,...r.split("/"));try{let i=await xn.lstat(o);return!i.isFile()||i.isSymbolicLink()?null:{path:r,sizeBytes:i.size}}catch{return null}},async writeFile(r,o){await ia(_t.join(n,r),o)},async createExclusive(r,o){let i=_t.join(n,r);await xn.mkdir(_t.dirname(i),{recursive:!0});let s=await xn.open(i,"wx");try{await s.writeFile(o,"utf8")}catch(a){throw await s.close(),await xn.rm(i,{force:!0}),a}await s.close()},async deleteFile(r){await xn.rm(_t.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=_t.join(n,i),a=_t.dirname(_t.join(n,o));for(;a!==s&&a.startsWith(`${s}${_t.sep}`);){try{await xn.rmdir(a)}catch(c){if(c instanceof Error&&"code"in c&&c.code==="ENOENT"){a=_t.dirname(a);continue}break}a=_t.dirname(a)}},async exists(r){try{return await xn.access(_t.join(n,r)),!0}catch{return!1}},async listFiles(r={}){let o=r.roots??[...wD,...TD],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=_t.join(n,...d.split("/")),m;try{m=await xn.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 xn.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 xp(e){return new Zc(e)}var qc=class{constructor(t){this.options=t,this.listeners=new Set,this.engine=xp({projectRoot:t.projectRoot,fileSystem:t.fileSystem,compositions:t.compositions,onEvent:n=>{let r=Ds(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:Fs(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:Ls(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=OD.safeParse(r);if(!o.success)return Os(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:Dr(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:Dr(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:Dr(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 FD(e){return new qc(e)}import{GeneratedSiteCapabilitiesSchema as $D}from"@vcp-dev/contracts";import{GeneratedSiteCapabilitiesSchema as LD}from"@vcp-dev/contracts";function Qc(e){let t=MD(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)?Wn(e.node,"platform-managed","controlled platform package"):t?BD(e.node.path,t)?Wn(e.node,"host-public","declared Starter runtime dependency"):Wn(e.node,"unsupported-external-private","external package is not declared by the trusted Starter contract"):Wn(e.node,"unknown","trusted host capability contract is invalid"):qS(e.node.path,n)?Wn(e.node,"platform-managed","controlled platform path"):t?ev(e.node.path,t.generated_sections_path)?Wn(e.node,"private","site-generated section path"):qS(e.node.path,t.public_paths)?Wn(e.node,"host-public","declared Starter public path"):Wn(e.node,"private","site-local file outside host public paths"):Wn(e.node,"unknown","trusted host capability contract is invalid")}function DD(e){return e.nodes.map(t=>Qc({...e,node:t})).sort((t,n)=>t.path===n.path?t.ownership.localeCompare(n.ownership):t.path.localeCompare(n.path))}function Wn(e,t,n){return{path:e.path,kind:e.kind,ownership:t,reason:n}}function MD(e){let t=LD.safeParse(e);return t.success?t.data:null}function BD(e,t){return t.runtime_dependencies.some(({name:n})=>e===n||e.startsWith(`${n}/`))}function qS(e,t){return t.some(n=>ev(e,n))}function ev(e,t){let n=jD(t),r=tv(e);return n.endsWith("/*")?r.startsWith(n.slice(0,-1)):QS(r)===QS(n)}function jD(e){return tv(e.split("#",1)[0]??e)}function tv(e){return e.replace(/^@\//u,"").replace(/\\/g,"/").replace(/^\.\//u,"")}function QS(e){return e.replace(/\.(?:jsx?|tsx?|json)$/iu,"")}function VD(e){let t=$D.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=Qc({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=UD(n).sort(KD);return{complete:o.length===0,nodes:r.sort(JD),edges:[...e.closure.edges].sort(XD),errors:o}}function UD(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function KD(e,t){return zt(e.path,t.path)||zt(e.code,t.code)||zt(e.specifier??"",t.specifier??"")||zt(e.message,t.message)}function JD(e,t){return zt(e.path,t.path)||zt(e.kind,t.kind)||zt(e.ownership,t.ownership)||zt(e.status,t.status)}function XD(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*as At from"@babel/types";var nv=[".tsx",".ts",".jsx",".js"],zD=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 gs(e){let t=YD(e.files),n=ov(e.max_depth??32,"max_depth"),r=ov(e.max_nodes??512,"max_nodes"),o=[...new Set(e.entry_files.map(av).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(!Jo(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 T=o.includes(m.path)?"SOURCE_ENTRY_UNRESOLVED":Xo(m.path)?"SOURCE_ASSET_UNRESOLVED":"SOURCE_FILE_UNRESOLVED";Rr(i,{path:m.path,kind:Xo(m.path)?"asset":"source",depth:m.depth,status:"unresolved"}),a.push({code:T,path:m.path,message:`Portable source closure could not read ${m.path}.`});continue}let x=Xo(m.path)?"asset":"source";if(x==="asset"){let T=ZD(m.path,y);Rr(i,{path:m.path,kind:x,depth:m.depth,status:T?"parse-failed":"complete"}),T&&a.push(T);continue}let E=Ep(y),b=Ue(m.path,E);if(!b.ok){Rr(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 S=WD(b.module.ast),C=!1;for(let T of S){let R=HD({from:m.path,depth:m.depth,reference:T,files:t,nodes:i,errors:a,maxDepth:n,maxNodes:r,visited:u,queued:l,discovered:c});s.push(R.edge),R.next&&(R.next.depth>n?C=!0:!u.has(R.next.path)&&!l.has(R.next.path)&&(l.add(R.next.path),d.push(R.next))),R.depthExhausted&&(C=!0)}Rr(i,{path:m.path,kind:x,depth:m.depth,status:C?"depth-exhausted":"complete"}),C&&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(rM),g=tM(s).sort(oM),p=nM(a).sort(iM);return{entry_files:o.sort(Ln),nodes:f,edges:g,errors:p,complete:p.length===0,budget:{max_depth:n,max_nodes:r}}}function HD(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(!gt(t.specifier)){let o=QD(t.specifier);return Jo(o,e.discovered,e.maxNodes)?(Rr(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=Sp(e.from,t.specifier);if(cv(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}.`}),Jo(n,e.discovered,e.maxNodes)?Rr(e.nodes,{path:n,kind:Xo(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=sv(e.from,t.specifier,e.files);if(!r){let o=Xo(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}.`}),Jo(n,e.discovered,e.maxNodes)?Rr(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=Xo(r)?"asset":"source";return Jo(r,e.discovered,e.maxNodes)?Rr(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 Jo(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 WD(e){let t=[];for(let n of e.program.body)At.isImportDeclaration(n)?t.push({specifier:n.source.value,kind:n.importKind==="type"?"type":"import"}):At.isExportNamedDeclaration(n)&&n.source?t.push({specifier:n.source.value,kind:"export"}):At.isExportAllDeclaration(n)&&t.push({specifier:n.source.value,kind:"export"});return bp(e.program,n=>{if(At.isCallExpression(n)&&At.isImport(n.callee)){let r=n.arguments[0];At.isStringLiteral(r)?t.push({specifier:r.value,kind:"dynamic"}):t.push({specifier:null,kind:"dynamic"})}At.isTSImportType(n)&&t.push({specifier:At.isStringLiteral(n.argument)?n.argument.value:null,kind:"type"})}),eM(t)}function bp(e,t){t(e);for(let n of Object.values(e))if(Array.isArray(n))for(let r of n)iv(r)&&bp(r,t);else iv(n)&&bp(n,t)}function GD(e,t,n){let r=Sp(e,t);return!gt(t)||cv(e,t,r)?null:sv(e,t,n)}function sv(e,t,n){let r=Sp(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(qD(o))return null;for(let i of nv){let s=`${o}${i}`;if(n.has(s))return s}for(let i of nv){let s=`${o}/index${i}`;if(n.has(s))return s}return null}function Sp(e,t){let n=En(e,t);return av(n)}function av(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 YD(e){return e instanceof Map?e:new Map(Object.entries(e))}function Ep(e){return typeof e=="string"?e:Buffer.from(e).toString("utf8")}function ZD(e,t){if(e.toLowerCase().endsWith(".css")&&/[@\\]|url\s*\(/iu.test(Ep(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(Ep(t))}catch{return{code:"SOURCE_ASSET_INVALID",path:e,message:`Portable source closure found invalid JSON asset: ${e}.`}}return null}function Rr(e,t){let n=e.get(t.path);(!n||rv(t.status)>rv(n.status))&&e.set(t.path,t)}function Jo(e,t,n){return t.has(e)?!0:t.size>=n?!1:(t.add(e),!0)}function rv(e){return e==="complete"?1:0}function Xo(e){let n=e.replace(/[?#].*$/u,"").split(".").pop()?.toLowerCase();return n!==void 0&&zD.has(n)}function qD(e){return/\.[a-z0-9]+$/iu.test(e)}function QD(e){return e.startsWith("@")?e.split("/").slice(0,2).join("/"):e.split("/")[0]??e}function eM(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 tM(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}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 rM(e,t){return Ln(e.path,t.path)||Ln(e.kind,t.kind)}function oM(e,t){return Ln(e.from,t.from)||Ln(e.target??"",t.target??"")||Ln(e.specifier??"",t.specifier??"")||Ln(e.kind,t.kind)}function iM(e,t){return Ln(e.path,t.path)||Ln(e.code,t.code)||Ln(e.specifier??"",t.specifier??"")}function Ln(e,t){return e<t?-1:e>t?1:0}function ov(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`Portable source closure ${t} must be a positive safe integer.`);return e}function iv(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}function cv(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("/")}import{parse as al}from"@babel/parser";import*as j from"@babel/types";import{PortableCollectionRecipeFactsSchema as CM}from"@vcp-dev/contracts";import{parse as Cr}from"@babel/parser";import vp from"@babel/traverse";import*as K from"@babel/types";var sM=typeof vp=="function"?vp:vp.default;function Np(e){let t=hv(e.files),n=(d,f,g)=>({complete:!1,relation:null,errors:[{code:d,path:f,message:g}]}),r=zo(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(!lM(o,r,"listStrict"))return{complete:!0,relation:null,errors:[]};let i=cM(o,r),s=i?el(r,o,i,"listStrict"):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.entries()].flatMap(([d,f])=>{if(typeof f!="string"||!/\[slug\]\/page\.(?:[cm]?[jt]sx?)$/u.test(d))return[];let g=el(d,f,i,"getByUrlStrict",e.detail_prefix??`/${i}`);return g&&_p(g.ast,e.detail_prefix??`/${i}`)!==null?[g]:[]});if(a.length!==1)return n("RELATED_COLLECTION_DETAIL_CONSUMER_UNPROVEN",e.list_entry_file,"Exactly one dynamic detail route must consume the selected collection.");let c=a[0];if(c.adapter_source!==s.adapter_source||c.interface_name!==s.interface_name)return n("RELATED_COLLECTION_ADAPTER_UNPROVEN",c.path,"The list and detail routes do not share the selected collection adapter and view interface.");let l=zn(c.source,{filePath:c.path,exportName:"default"}).components.flatMap(d=>{let f=zo(c.path,d.source,t),g=f?t.get(f):void 0;return!f||typeof g!="string"||!fv(g,d.export_name)||!Rp(g,c.adapter_source,c.interface_name)?[]:[{path:f,export_name:d.export_name}]});if(l.length!==1)return n("RELATED_COLLECTION_DETAIL_CONSUMER_UNPROVEN",c.path,"The collection detail route does not prove one private detail view.");let u=l[0];return{complete:!0,relation:{slug:i,requirement_key:`cms-${i}`,list_entry_file:e.list_entry_file,detail_entry_file:c.path,detail_view_file:u.path,detail_view_export:u.export_name},errors:[]}}function Pp(e){let t=hv(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."}),Ip(t,e.collection.list_entry_file,"RELATED_LIST_ENTRY_MISSING",n),Ip(t,e.collection.detail_entry_file,"RELATED_DETAIL_ENTRY_MISSING",n),Ip(t,e.collection.detail_view_file,"RELATED_DETAIL_VIEW_MISSING",n),kp(o,{path:e.collection.list_entry_file,kind:"route",requirementKey:e.collection.requirement_key}),kp(o,{path:e.collection.detail_entry_file,kind:"route",requirementKey:e.collection.requirement_key});let s=gs({entry_files:[e.collection.detail_entry_file],files:t});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(yM(f.path,e.collection)){kp(o,{path:f.path,kind:f.path.includes("/page.")?"route":"adapter",requirementKey:e.collection.requirement_key});continue}xM(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"&&gM(c,e.collection.detail_view_file,s.nodes,t,r),e.page_template&&(i=hM(e.page_template,t,n));let l=e.trusted_schema===void 0?null:aM(e,t,n,e.trusted_schema),u=SM(r).map((f,g)=>({key:IM(f,g),pathTemplate:f.path,export:f.export,purpose:f.purpose,requirementKey:e.collection.requirement_key})),d=kM(n).sort(RM);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(vM),thin_entry_plan:i,collection_wiring:l,errors:d}}function aM(e,t,n,r){let o=n.length,i=r.fields.map(S=>({...S}));(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(S=>S.kind==="source"&&S.status==="complete"&&S.path!==e.collection.list_entry_file).flatMap(S=>{let C=t.get(S.path);if(typeof C!="string")return[];let T=el(S.path,C,e.collection.slug,"listStrict");return T?[T]:[]});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?lv(a,t,S=>S!==e.collection.detail_view_file):null;c?a&&!Rp(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"?el(e.collection.detail_entry_file,l,e.collection.slug,"getByUrlStrict"):null,d=u?lv(u,t,S=>S===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."}):Rp(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(S=>S.name)),g=a?zo(a.path,a.adapter_source,t):null,p=g?t.get(g):null,m=[...e.required_fields??i.filter(S=>S.required).map(S=>S.name)].sort(Cp),y=[...e.force_multi_media??(typeof p=="string"?pv(p):[])].sort(Cp);for(let S of[...m,...y])f.has(S)||n.push({code:"RELATED_COLLECTION_FIELD_UNPROVEN",path:`trusted-schema:${e.collection.slug}.${S}`,message:`Collection field ${S} is not present in the trusted schema.`});if(a&&y.length)for(let S of y)(typeof p!="string"||!mM(p,S))&&n.push({code:"RELATED_COLLECTION_FIELD_UNPROVEN",path:g??a.adapter_source,message:`The generated adapter does not prove multi-media handling for ${S}.`});let x=u?_p(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 E=u?fM(u.ast):null;E||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?pM(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},...E?{title:E}:{},...b&&b!=="unproven"?{breadcrumb:b}:{},...m.length>0?{required_fields:m}:{},...y.length>0?{force_multi_media:y}:{}}}function el(e,t,n,r,o=`/${n}`){let i;try{i=Cr(t,{sourceType:"module",sourceFilename:e,plugins:["jsx","typescript"]})}catch{return null}let s=io(i,l=>{if(!K.isCallExpression(l)||!tl(l.callee,r))return!1;let u=l.arguments[0];return r==="listStrict"?K.isStringLiteral(u)&&u.value===n:!0});if(r==="listStrict"&&s.length!==1||r==="getByUrlStrict"&&(s.length===0||_p(i,o)===null))return null;let c=i.program.body.flatMap(l=>K.isImportDeclaration(l)?l.specifiers.flatMap(u=>{if(!K.isImportSpecifier(u))return[];let d=K.isIdentifier(u.imported)?u.imported.name:u.imported.value,f=/^to([A-Za-z_$][A-Za-z0-9_$]*View)$/u.exec(d);return f?[{source:l.source.value,local_name:u.local.name,interface_name:f[1]}]:[]}):[]).filter(l=>io(i,u=>K.isIdentifier(u,{name:l.local_name})).length>1);return c.length!==1?null:{path:e,source:t,ast:i,adapter_source:c[0].source,interface_name:c[0].interface_name}}function cM(e,t){let n;try{n=Cr(e,{sourceType:"module",sourceFilename:t,plugins:["jsx","typescript"]})}catch{return null}let r=io(n,o=>K.isCallExpression(o)&&tl(o.callee,"listStrict")&&K.isStringLiteral(o.arguments[0])).map(o=>o.arguments[0].value);return r.length===1&&/^[a-z0-9]{1,30}$/u.test(r[0])?r[0]:null}function lM(e,t,n){let r;try{r=Cr(e,{sourceType:"module",sourceFilename:t,plugins:["jsx","typescript"]})}catch{return!1}return io(r,o=>K.isCallExpression(o)&&tl(o.callee,n)).length>0}function lv(e,t,n){let r=zn(e.source,{filePath:e.path,exportName:"default"});if(r.diagnostics.length>0)return null;let o=r.components.flatMap(i=>{let s=zo(e.path,i.source,t),a=s?t.get(s):null;return!s||!n(s)||typeof a!="string"||!fv(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 fv(e,t){let n;try{n=Cr(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return!1}for(let r of n.program.body){if(t==="default"&&K.isExportDefaultDeclaration(r))return!0;if(K.isExportNamedDeclaration(r)&&(r.declaration&&(K.isFunctionDeclaration(r.declaration)||K.isClassDeclaration(r.declaration)||K.isTSInterfaceDeclaration(r.declaration)||K.isTSTypeAliasDeclaration(r.declaration))&&r.declaration.id?.name===t||K.isVariableDeclaration(r.declaration)&&r.declaration.declarations.some(o=>K.isIdentifier(o.id,{name:t}))||r.specifiers.some(o=>K.isExportSpecifier(o)?(K.isIdentifier(o.exported)?o.exported.name:o.exported.value)===t:!1)))return!0}return!1}function Rp(e,t,n){if(typeof e!="string")return!1;let r;try{r=Cr(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return!1}return r.program.body.flatMap(i=>!K.isImportDeclaration(i)||i.source.value!==t?[]:i.specifiers.flatMap(s=>K.isImportSpecifier(s)?(K.isIdentifier(s.imported)?s.imported.name:s.imported.value)===n?[s.local.name]:[]:[])).some(i=>io(r,s=>K.isIdentifier(s,{name:i})).length>1)}function tl(e,t){return K.isMemberExpression(e)&&!e.computed&&K.isIdentifier(e.property,{name:t})&&K.isMemberExpression(e.object)&&!e.object.computed&&K.isIdentifier(e.object.property,{name:"collections"})&&K.isIdentifier(e.object.object,{name:"cms"})}function _p(e,t){let n=[];return sM(e,{CallExpression(r){tl(r.node.callee,"getByUrlStrict")&&n.push(uM(r.node.arguments[0],o=>dM(r,o)))}}),n.length===0?null:n.every(r=>r===t)?t:null}function uM(e,t){return K.isBinaryExpression(e,{operator:"+"})&&K.isStringLiteral(e.left)&&K.isIdentifier(e.right)&&t(e.right.name)&&/^\/[A-Za-z0-9_-]+\/$/u.test(e.left.value)?e.left.value.slice(0,-1):K.isTemplateLiteral(e)&&e.expressions.length===1&&K.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 dM(e,t){let n=e.scope.getBinding(t);if(!n?.constant||!n.path.isVariableDeclarator())return!1;let r=n.path.node;if(K.isObjectPattern(r.id)&&K.isAwaitExpression(r.init)&&K.isIdentifier(r.init.argument))return r.id.properties.some(a=>K.isObjectProperty(a)&&!a.computed&&nl(a.key)==="slug"&&K.isIdentifier(a.value,{name:t}))&&uv(n.path,r.init.argument.name);let o=r.init;if(!K.isIdentifier(r.id,{name:t})||!K.isCallExpression(o)||!K.isIdentifier(o.callee)||o.arguments.length!==1)return!1;let i=n.path.scope.getBinding(o.callee.name);if(!i?.constant||!i.path.isImportSpecifier()||!K.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 K.isMemberExpression(s)&&!s.computed&&K.isIdentifier(s.property,{name:"slug"})&&K.isAwaitExpression(s.object)&&K.isIdentifier(s.object.argument)&&uv(n.path,s.object.argument.name)}function uv(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=>K.isObjectPattern(i)&&i.properties.some(s=>K.isObjectProperty(s)&&!s.computed&&nl(s.key)==="params"&&K.isIdentifier(s.value,{name:t})))}function fM(e){for(let t of e.program.body)if(K.isVariableDeclaration(t))for(let n of t.declarations){if(!K.isIdentifier(n.id,{name:"PAGE_SEO"}))continue;let r=mv(n.init);if(!K.isObjectExpression(r))return null;let o=r.properties.find(i=>K.isObjectProperty(i)&&!i.computed&&nl(i.key)==="title");return o&&K.isStringLiteral(o.value)?o.value.value:null}return null}function pM(e,t,n){let o=zn(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=zo(e.path,o[0].source,t),s=i?t.get(i):null;if(typeof s!="string")return"unproven";let a;try{a=Cr(s,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return"unproven"}for(let c of io(a,l=>K.isArrayExpression(l))){let l=c.elements.flatMap(f=>{if(!K.isObjectExpression(f))return[];let g=new Map;for(let p of f.properties){if(!K.isObjectProperty(p)||p.computed)continue;let m=nl(p.key);m&&K.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 pv(e){let t;try{t=Cr(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return[]}return[...new Set(io(t,n=>{if(!K.isCallExpression(n))return!1;let r=n.callee;if(!K.isMemberExpression(r)||r.computed||!K.isIdentifier(r.property,{name:"images"}))return!1;let o=n.arguments[0];return K.isMemberExpression(o)&&!o.computed&&K.isIdentifier(o.object,{name:"d"})&&K.isIdentifier(o.property)}).flatMap(n=>{let r=n.arguments[0];return K.isMemberExpression(r)&&!r.computed&&K.isIdentifier(r.property)?[r.property.name]:[]}))].sort(Cp)}function mM(e,t){return pv(e).includes(t)}function io(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)dv(s)&&r(s);else dv(i)&&r(i)};return r(e),n}function dv(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}function mv(e){return e?K.isTSAsExpression(e)||K.isTSTypeAssertion(e)||K.isTSNonNullExpression(e)?mv(e.expression):e:null}function nl(e){return K.isIdentifier(e)?e.name:K.isStringLiteral(e)?e.value:null}function Cp(e,t){return e.localeCompare(t)}function gM(e,t,n,r,o){let i=zn(e,{filePath:t,exportName:"default"});for(let s of i.components){let a=zo(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"||bM(l)&&o.push({path:a,export:s.export_name==="default"?{kind:"default"}:{kind:"named",name:s.export_name},purpose:"client-importer"})}}function hM(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=zn(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 Ip(e,t,n,r){e.has(t)||r.push({code:n,path:t,message:`Portable related-entry analysis could not read ${t}.`})}function yM(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 xM(e,t,n){let r=e.replace(/\\/g,"/"),o=t.replace(/\.(?:tsx?|jsx?)$/u,""),i=gv(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 bM(e){try{let n=Cr(e,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0];return n?.type==="ExpressionStatement"&&n.expression.type==="StringLiteral"&&n.expression.value==="use client"}catch{return!1}}function zo(e,t,n){let r=t.startsWith("@/")?t.slice(2):EM(`${gv(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 gv(e){let t=e.lastIndexOf("/");return t<0?"":e.slice(0,t)}function EM(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 hv(e){return e instanceof Map?e:new Map(Object.entries(e))}function SM(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 kp(e,t){e.some(r=>r.path===t.path&&r.kind===t.kind)||e.push(t)}function vM(e,t){return e.path.localeCompare(t.path)||e.kind.localeCompare(t.kind)||e.requirementKey.localeCompare(t.requirementKey)}function IM(e,t){return`${`related.${e.purpose}.${e.path.replace(/[^A-Za-z0-9]+/gu,"-").replace(/^-|-$/gu,"")}`.slice(0,112)}.${t}`}function kM(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function RM(e,t){return e.path.localeCompare(t.path)||e.code.localeCompare(t.code)||e.message.localeCompare(t.message)}var NM=new Set(["blockId","block_id","targetBlockId","target_block_id","sourceBlockId","source_block_id"]),PM=new Set(["data-vcp-block-id","data-vcp-edit-key"]),_M=new Set(["data-vcp-order","sourceOrder","source_order"]);function Ho(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(ys)}),n;try{n=al(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=jM(n),o=zn(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(il(n,new Set,(f,g)=>{if(!j.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=Iv(p.name);if(!y)return;let x=UM(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=>Ev(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=Sv(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:Fp(d).sort(ys)}}function bv(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(ys)}),n;try{n=al(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(il(n,new Set,(a,c)=>{if(!j.isJSXElement(a))return;let l=a.openingElement;if(typeof l.start!="number"||Iv(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=>Ev(e,a.node,a.element,{kind:"local",local_name:e.target.local_name},a.context,a.ordinal)),s=Sv(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:Fp(s.errors).sort(ys)}: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 AM(e){let t;try{t=al(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=dn({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=zn(e.source,{filePath:e.file_path,exportName:"default"});if(i.components.length===0)return{invocation:null,errors:[]};let s=i.components.map(a=>Ho({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 TM(e){let t=Ho(e),n=Pp({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:FM(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=LM(e.files),s=n.collection_wiring,a=DM(e.file_path,e.target.source,i),c=a?i.get(a):null,l=a&&typeof c=="string"?wM(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=CM.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=Fp(r).sort(ys);return{...t,complete:d.length===0&&u!==null,errors:d,collection_recipe:u,collection_evidence:o.sort(BM),related_entries:n}}function wM(e,t,n){let r;try{r=al(e,{sourceType:"module",sourceFilename:t,plugins:["jsx","typescript"]})}catch{return null}let o=OM(r);if(!o)return null;let i=Ap(o,f=>{if(!j.isCallExpression(f))return!1;let g=f.callee;return j.isMemberExpression(g)&&!g.computed&&j.isIdentifier(g.property,{name:"listStrict"})&&j.isMemberExpression(g.object)&&!g.object.computed&&j.isIdentifier(g.object.property,{name:"collections"})&&j.isIdentifier(g.object.object,{name:"cms"})&&j.isStringLiteral(f.arguments[0],{value:n})});if(i.length!==1)return null;let s=i[0].arguments[1];if(!j.isObjectExpression(s)||s.properties.some(f=>j.isSpreadElement(f)))return null;let a=s.properties.find(f=>j.isObjectProperty(f)&&!f.computed&&ol(f.key)==="pageSize");if(!a||!j.isNumericLiteral(a.value)||!Number.isSafeInteger(a.value.value)||a.value.value<=0||!s.properties.some(f=>j.isObjectProperty(f)&&!f.computed&&ol(f.key)==="page"))return null;let l=s.properties.some(f=>j.isObjectProperty(f)&&!f.computed&&ol(f.key)==="category"),u=Ap(o,f=>j.isAwaitExpression(f)&&j.isIdentifier(f.argument,{name:"searchParams"})).length;if(u>1)return null;let d=Ap(o,f=>{if(!j.isCallExpression(f))return!1;let g=f.callee;return j.isMemberExpression(g)&&!g.computed&&j.isIdentifier(g.property,{name:"categories"})&&j.isMemberExpression(g.object)&&!g.object.computed&&j.isIdentifier(g.object.property,{name:"collections"})&&j.isIdentifier(g.object.object,{name:"cms"})&&j.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 OM(e){let t=e.program.body.find(n=>j.isExportDefaultDeclaration(n));return j.isExportDefaultDeclaration(t)&&(j.isFunctionDeclaration(t.declaration)||j.isFunctionExpression(t.declaration)||j.isArrowFunctionExpression(t.declaration))?t.declaration:null}function Ap(e,t){let n=[],r=o=>{if(!(o!==e&&Op(o))){t(o)&&n.push(o);for(let i of Object.values(o))if(Array.isArray(i))for(let s of i)sl(s)&&r(s);else sl(i)&&r(i)}};return r(e),n}function FM(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 LM(e){return e instanceof Map?e:new Map(Object.entries(e))}function DM(e,t,n){let r=e.includes("/")?e.slice(0,e.lastIndexOf("/")):"",o=t.startsWith("@/")?t.slice(2):MM(`${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 MM(e){let t=[];for(let n of e.split("/"))!n||n==="."||(n===".."?t.pop():t.push(n));return t.join("/")}function BM(e,t){return e.fact.localeCompare(t.fact)||e.path.localeCompare(t.path)}function jM(e){let t=new Map;for(let n of e.program.body){if(!j.isImportDeclaration(n))continue;let r=n.source.value;for(let o of n.specifiers)if(j.isIdentifier(o.local)){if(j.isImportDefaultSpecifier(o))t.set(o.local.name,{source:r,export_name:"default",local_name:o.local.name});else if(j.isImportNamespaceSpecifier(o))t.set(o.local.name,{source:r,export_name:"*",local_name:o.local.name});else if(j.isImportSpecifier(o)){let i=j.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 Ev(e,t,n,r,o,i){let s=JM(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(j.isJSXSpreadAttribute(m)){let S=Nr(m.argument);if(!S.ok||!vv(S.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[C,T]of Object.entries(S.value)){if(!xv(C)){a.push({code:"INVOCATION_VALUE_UNRESOLVED",path:`${e.file_path}:${C}`,message:`Portable invocation cannot encode prop ${C}.`,source_range:s});continue}g(C,Tp(T))}continue}let y=KM(m.name);if(!y)continue;let x=m.value,E=x&&j.isJSXExpressionContainer(x)?x.expression:null;if(PM.has(y)){let S=x?rl(x):{ok:!0,value:!0};!S.ok||typeof S.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=S.value;continue}if(_M.has(y)){let S=x?rl(x):{ok:!0,value:!0};!S.ok||typeof S.value!="number"||!Number.isSafeInteger(S.value)?a.push({code:"INVOCATION_ORDER_UNRESOLVED",path:`${e.file_path}:${y}`,message:"Portable invocation requires a literal original order.",source_range:s}):f=S.value;continue}if(!xv(y)){a.push({code:"INVOCATION_VALUE_UNRESOLVED",path:`${e.file_path}:${y}`,message:`Portable invocation cannot encode prop ${y}.`,source_range:s});continue}if(NM.has(y)){let S=x?rl(x):{ok:!0,value:!0};S.ok&&typeof S.value=="string"?d=S.value:E&&yv(E,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(E&&yv(E,o)){g(y,{kind:"route-search-params"});continue}let b=x?rl(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,Tp(b.value))}let p=$M(n);return p.ok?p.value!==void 0&&g("children",Tp(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 Sv(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 rl(e){return e===null?{ok:!0,value:!0}:j.isStringLiteral(e)?{ok:!0,value:e.value}:j.isJSXExpressionContainer(e)?Nr(e.expression):{ok:!1}}function Nr(e){if(!e)return{ok:!1};if(j.isStringLiteral(e))return{ok:!0,value:e.value};if(j.isNumericLiteral(e)&&Number.isFinite(e.value))return{ok:!0,value:e.value};if(j.isBooleanLiteral(e))return{ok:!0,value:e.value};if(j.isNullLiteral(e))return{ok:!0,value:null};if(j.isTemplateLiteral(e)&&e.expressions.length===0)return{ok:!0,value:e.quasis[0]?.value.cooked??""};if(j.isTSAsExpression(e)||j.isTSTypeAssertion(e)||j.isTSNonNullExpression(e))return Nr(e.expression);if(j.isUnaryExpression(e)){let t=Nr(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(j.isArrayExpression(e)){let t=[];for(let n of e.elements){let r=Nr(n);if(!r.ok)return{ok:!1};t.push(r.value)}return{ok:!0,value:t}}if(j.isObjectExpression(e)){let t={};for(let n of e.properties){if(j.isSpreadElement(n)){let i=Nr(n.argument);if(!i.ok||!vv(i.value))return{ok:!1};Object.assign(t,i.value);continue}if(!j.isObjectProperty(n)||n.computed)return{ok:!1};let r=ol(n.key);if(!r)return{ok:!1};let o=Nr(n.value);if(!o.ok)return{ok:!1};t[r]=o.value}return{ok:!0,value:t}}return{ok:!1}}function $M(e){if(e.children.length===0)return{ok:!0,value:void 0};let t=[];for(let n of j.react.buildChildren(e)){let r=Nr(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 il(e,t,n){let r=Op(e)?new Set([...t,...VM(e)]):t;n(e,{names:r});for(let o of Object.values(e))if(Array.isArray(o))for(let i of o)sl(i)&&il(i,r,n);else sl(o)&&il(o,r,n)}function VM(e){if(!Op(e))return[];let t=[];for(let n of e.params)hs(n,t);return t}function hs(e,t){if(j.isIdentifier(e)){t.push(e.name);return}if(j.isAssignmentPattern(e)){hs(e.left,t);return}if(j.isObjectPattern(e)){for(let n of e.properties)j.isRestElement(n)?hs(n.argument,t):j.isObjectProperty(n)&&hs(n.value,t);return}if(j.isArrayPattern(e))for(let n of e.elements)n&&hs(n,t)}function yv(e,t){return j.isIdentifier(e)?e.name==="searchParams"&&t.names.has(e.name):j.isMemberExpression(e)&&!e.computed&&j.isIdentifier(e.property)&&e.property.name==="searchParams"&&j.isIdentifier(e.object)&&t.names.has(e.object.name)}function Tp(e){return{kind:"json-literal",value:e}}function vv(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function xv(e){return/^[A-Za-z][A-Za-z0-9_]{0,127}$/u.test(e)}function Iv(e){if(j.isJSXIdentifier(e))return e.name;if(!j.isJSXMemberExpression(e))return null;let t=wp(e.object);return t?`${t}.${e.property.name}`:null}function wp(e){if(j.isJSXIdentifier(e))return e.name;if(!j.isJSXMemberExpression(e))return null;let t=wp(e.object);return t?`${t}.${e.property.name}`:null}function UM(e,t){if(j.isJSXIdentifier(e))return t.get(e.name)??null;if(!j.isJSXMemberExpression(e))return null;let n=wp(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 KM(e){return j.isJSXIdentifier(e)?e.name:j.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function ol(e){return j.isIdentifier(e)?e.name:j.isStringLiteral(e)||j.isNumericLiteral(e)?String(e.value):null}function Op(e){return j.isFunctionDeclaration(e)||j.isFunctionExpression(e)||j.isArrowFunctionExpression(e)}function sl(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}function JM(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 Fp(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function ys(e,t){return e.path.localeCompare(t.path)||e.code.localeCompare(t.code)||e.message.localeCompare(t.message)}import Lp from"@babel/generator";import{parse as XM}from"@babel/parser";import zM from"@babel/traverse";import*as lt from"@babel/types";var Dp=zM,HM=typeof Dp=="function"?Dp:Dp.default,WM=typeof Lp=="function"?Lp:Lp.default,_v="components/site/generated/{{$INSTANCE}}/",Av=new Set([".tsx",".ts",".jsx",".js"]),kv=new Set(["data-site-block-id","data-vcp-block-id","data-vcp-edit-key"]),GM=new Set(["data-site-block-order","data-vcp-order"]);function YM(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 S=Gn(b.path);if(!S||n.has(S)){t.push({code:"SOURCE_INPUT_INVALID",path:b.path,message:"Portable source files must have unique safe paths."});continue}n.set(S,{...b,path:S})}for(let b of e.ownership){let S=Gn(b.path);if(!S||r.has(S)){t.push({code:"SOURCE_INPUT_INVALID",path:b.path,message:"Portable source ownership entries must be unique and safe."});continue}r.set(S,{...b,path:S})}let o=Gn(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,S)=>b.localeCompare(S)),a=s.map(b=>({source_path:b,path_template:oB(b)})),c=new Map(a.map(b=>[b.source_path,b.path_template])),l=ZM(e.source_mapping??[],c,t),u=qM(e.required_source_paths??[],c,t),d=[],f=new Map,g=[];for(let b of s){let S=n.get(b);if(!S)continue;let C=eB(b,S.content,r,c,d,f,t);C!==null&&g.push({path_template:c.get(b),content:C,...S.role?{role:S.role}:{}})}let p=Nv(t).sort(Pv);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 S=a.find(T=>T.path_template===b.path_template)?.source_path,C=n.get(S)?.content??"";return{source_path:S,path_template:b.path_template,original_byte_size:Rv(C),output_byte_size:Rv(b.content),original_line_count:Cv(C),output_line_count:Cv(b.content)}}),y=[...f.values()].map(b=>({...b,normalized:!0})).sort((b,S)=>b.source_path.localeCompare(S.source_path)),x=c.get(o)??null;if(e.thin_entry_plan){let b=QM(e.thin_entry_plan,c,t);b&&(g.push(b),x=b.path_template)}let E=Nv(t).sort(Pv);return E.length>0?{complete:!1,entry_path_template:null,files:[],source_path_mappings:[],required_path_mappings:[],source_mapping:[],managed_rebindings:[],block_metadata:[],errors:E}:{complete:!0,entry_path_template:x,files:g.sort((b,S)=>b.path_template.localeCompare(S.path_template)),source_path_mappings:m.sort((b,S)=>b.path_template.localeCompare(S.path_template)),required_path_mappings:u,source_mapping:l,managed_rebindings:d.sort(lB),block_metadata:y,errors:[]}}function ZM(e,t,n){let r=new Set,o=[];for(let[i,s]of e.entries()){let a=Gn(s.generated_path),c=Gn(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 qM(e,t,n){let r=new Set,o=new Set,i=[];for(let[s,a]of e.entries()){let c=Gn(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 QM(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(Gn(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=Tv(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}
|
|
15
15
|
export default function PortableManagedRootEntry(props: Parameters<typeof Root>[0]) {
|
|
16
16
|
return <Root {...props} />;
|
|
17
17
|
}
|
|
18
|
-
`}}function
|
|
19
|
-
`).length}function
|
|
18
|
+
`}}function eB(e,t,n,r,o,i,s){if(!cB(e))return t;let a;try{a=XM(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=tB(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=Tv(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=nB(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 HM(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];(lt.isImport(u)||lt.isIdentifier(u,{name:"require"})&&l.node.arguments.length===1)&<.isStringLiteral(d)&&c(d)},JSXAttribute(l){let u=iB(l.node.name);if(!u||!kv.has(u)&&!GM.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};kv.has(u)?(p.original_block_attribute=u,p.original_block_id=sB(l.node.value)):p.original_order=aB(l.node.value),i.set(g,p),l.remove()}}),WM(a,{jsescOption:{minimal:!0}}).code}function tB(e,t,n){if(!t.startsWith(".")&&!t.startsWith("@/"))return{status:"external"};let r=t.startsWith("@/")?t.slice(2):Gn(`${Fv(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 Tv(e,t,n){let r=Fv(e),o=rB(r,t),i=o.startsWith(".")?o:`./${o}`;return wv(n)?i:Ov(i)}function nB(e,t){let n=`@/${e}`;return wv(t)?n:Ov(n)}function rB(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 oB(e){let t=Gn(e),n="components/site/generated/",r=t.startsWith(n)?t.slice(n.length):`source/${t}`;return`${_v}${r}`}function iB(e){return lt.isJSXIdentifier(e)?e.name:lt.isJSXNamespacedName(e)&<.isJSXIdentifier(e.name)?`${e.namespace.name}:${e.name.name}`:null}function sB(e){return e?lt.isStringLiteral(e)?e.value:lt.isJSXExpressionContainer(e)&<.isStringLiteral(e.expression)?e.expression.value:null:null}function aB(e){if(!e)return null;if(lt.isStringLiteral(e)){let t=Number(e.value);return Number.isFinite(t)?t:null}return lt.isJSXExpressionContainer(e)&<.isNumericLiteral(e.expression)?e.expression.value:null}function cB(e){return[...Av].some(t=>e.endsWith(t))}function wv(e){return/\.[a-z0-9]+(?:[?#].*)?$/iu.test(e)}function Ov(e){for(let t of Av)if(e.endsWith(t))return e.slice(0,-t.length);return e}function Gn(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 Fv(e){let t=e.lastIndexOf("/");return t<0?"":e.slice(0,t)}function Rv(e){return new TextEncoder().encode(e).byteLength}function Cv(e){return e.length===0?0:e.split(`
|
|
19
|
+
`).length}function Nv(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function Pv(e,t){return e.path.localeCompare(t.path)||e.code.localeCompare(t.code)||(e.specifier??"").localeCompare(t.specifier??"")}function lB(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{createHash as uB}from"node:crypto";import xs from"node:path";import Mp from"@babel/generator";import{parse as dB}from"@babel/parser";import fB from"@babel/traverse";import*as O from"@babel/types";import{SiteEditSourcePathSchema as pB}from"@vcp-dev/contracts";var Bp=fB,Kp=typeof Bp=="function"?Bp:Bp.default,mB=typeof Mp=="function"?Mp:Mp.default,Lv=new Set(["Array","Boolean","Infinity","JSON","Math","NaN","Number","Object","String","undefined"]),$v=new Map([["JSON",new Set(["stringify"])],["Object",new Set(["keys","values","entries","getOwnPropertyNames"])],["Array",new Set(["isArray"])]]),Vv=new Set(["Boolean","Number","String"]),gB=new Set(["assign","values","entries"]);function hB(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 bt("SOURCE_INPUT_INVALID",r,"The selected Portable entry path is not safe.");if(!pB.safeParse(t.source_file).success)return bt("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 bt("SOURCE_NOT_PORTABLE",t.source_file,"Nested component invocation bindings are not yet a proven independent entry.");if(t.invocation&&!t.invocation.complete)return bt("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 bt("SOURCE_INPUT_INVALID",t.entry_file,"A reusable entry must point at the proven selected component source.");let i=dl(n,t.source_file);return i===null||!jv(t,i)?bt("SOURCE_ENTRY_NOT_FOUND",t.source_file,"The reusable selected source is missing or does not match its pinned hash."):cl({entryFile:r,entryContent:i,files:n,selection:t})}let o=dl(n,t.source_file);if(o===null||!jv(t,o))return bt("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 cl({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 bt("SOURCE_INPUT_INVALID",r,"The proven collection container or isolated entry is unavailable.");let s=ur({component:"PortableCollection",bindings:t.invocation.bindings,targetBlockId:"portable-captured-collection"});if(!s.ok)return bt("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,"")}`)};
|
|
20
20
|
export default function PortableCollectionEntry(${a}) { return ${s.plan.jsx}; }
|
|
21
|
-
`;return al({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)?xt("SOURCE_INPUT_INVALID",r,"The deterministic extracted entry path collides with the fixed Snapshot map."):fB(t,o,n)}function fB(e,t,n){let r;try{r=sB(t,{sourceType:"module",sourceFilename:e.source_file,plugins:["jsx","typescript"]})}catch(T){return xt("SOURCE_PARSE_FAILED",e.source_file,T instanceof Error?T.message:String(T))}let o=pB(r,e);if(o.length!==1)return xt("SOURCE_NOT_PORTABLE",e.source_file,"The pinned source range must identify exactly one current JSX root.");let i=o[0],s=i.findParent(T=>T.isFunction());if(!s||!Wv(s.node))return xt("SOURCE_NOT_PORTABLE",e.source_file,"The selected JSX root is not inside one statically bounded component function.");let a=s,c=TB(a);if(!c.ok)return xt("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 T of r.program.body){if(!w.isImportDeclaration(T)||T.specifiers.length||T.importKind==="type")continue;let O=T.source.value,D=O.startsWith(".")||O.startsWith("@/")?dl(e.source_file,O,n):null;if(!D?.endsWith(".css"))return xt("SOURCE_NOT_PORTABLE",e.source_file,"A bare module effect is not a proven portable stylesheet dependency.");u.has(D)||l.imports.add(T),u.add(D)}let d=mB(a,e);if(!d.ok)return{complete:!1,errors:[d.error]};if(gB(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(T=>w.isVariableDeclaration(T)&&T.declarations.some(O=>w.isIdentifier(O.id,{name:c.translationBinding}))))return xt("SOURCE_NOT_PORTABLE",e.source_file,"The containing component's i18n hook is not part of the selected dependency closure.");let p=LB(r,"__vcpPortableProps"),m=w.cloneNode(i.node,!0),f=[];for(let T of[...l.imports].sort(Bp)){let O=PB(T,e.source_file,e.entry_file,n);if(!O.ok)return{complete:!1,errors:[O.error]};f.push(O.node)}let h=[...l.moduleDeclarations].sort(Bp).map(T=>w.cloneNode(T,!0)),y=[...l.functionDeclarations].sort(Bp).map(T=>w.cloneNode(T,!0)),x=w.returnStatement(m),E=[...l.props].filter(([T])=>!T.startsWith("@")).map(([T,O])=>w.variableDeclaration("const",[w.variableDeclarator(w.identifier(T),w.memberExpression(w.identifier(p),w.identifier(O)))]));l.propsObjectName&&E.push(w.variableDeclaration("const",[w.variableDeclarator(w.identifier(l.propsObjectName),w.identifier(p))]));let b=w.blockStatement([...E,...y,x]),S=l.props.size?[_B(p)]:[],N=w.functionDeclaration(w.identifier("PortableBlockEntry"),S,b),P=w.program([...f,...h,N,w.exportDefaultDeclaration(w.identifier("PortableBlockEntry"))]);P.directives=r.program.directives.map(T=>w.cloneNode(T,!0));let R=lB(w.file(P),{jsescOption:{minimal:!0}}).code,A={generated_path:e.entry_file,source_file:e.source_file,structural_path:e.structural_path};return al({entryFile:e.entry_file,entryContent:R,files:n,selection:e,sourceMapping:A,invocationBindings:FB(e,l.props)})}function pB(e,t){let n=[];return Up(e,{JSXElement(r){r.node.start===t.source_range.start_offset&&r.node.end===t.source_range.end_offset&&n.push(r)}}),n}function mB(e,t){let n=e.node.params;if(n.length>1)return{ok:!1,error:tt("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(w.isIdentifier(o))return{ok:!0,value:{bindingByLocalName:r,propsParameter:o}};if(!w.isObjectPattern(o))return{ok:!1,error:tt("SOURCE_NOT_PORTABLE",t.source_file,"Component props must use one identifier or a static object pattern.")};for(let i of o.properties){if(!w.isObjectProperty(i)||i.computed||!(w.isIdentifier(i.key)||w.isStringLiteral(i.key))||!(w.isIdentifier(i.value)||w.isAssignmentPattern(i.value)&&w.isIdentifier(i.value.left)))return{ok:!1,error:tt("SOURCE_NOT_PORTABLE",t.source_file,"Rest, computed, or nested component prop destructuring is not supported.")};let s=w.isIdentifier(i.key)?i.key.name:i.key.value,a=i.value,c=w.isIdentifier(a)?a.name:w.isAssignmentPattern(a)&&w.isIdentifier(a.left)?a.left.name:"";r.set(c,s)}return{ok:!0,value:{bindingByLocalName:r,propsParameter:null}}}function gB(e,t,n,r,o,i,s,a){let c=new Set,l=new Map,u=f=>{let h=l.get(f);if(h!==void 0)return h;let y=yB(n,r,f,o,a);return l.set(f,y),y||s.errors.push(tt("SOURCE_NOT_PORTABLE",o.source_file,`Selected prop ${f} is mutated or escapes its proven invocation value.`)),y},d=f=>{let h=f.node.name,y=f.scope.getBinding(h);if(!y){Fv.has(h)||s.errors.push(tt("SOURCE_NOT_PORTABLE",o.source_file,`The selected root references unbound identifier ${h}.`));return}if(!ll(y.path.node,t)){if(r.bindingByLocalName.has(h)&&y.scope===n.scope){let x=r.bindingByLocalName.get(h);Dv(o,x)?u(x)&&s.props.set(h,x):s.errors.push(tt("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&&f.parentPath?.isMemberExpression()&&f.parentPath.node.object===f.node){let x=f.parentPath.node,E=!x.computed&&w.isIdentifier(x.property)?x.property.name:x.computed&&w.isStringLiteral(x.property)?x.property.value:null;E&&Dv(o,E)?u(E)&&(s.propsObjectName=h,s.props.set(`@${h}.${E}`,E)):s.errors.push(tt("SOURCE_NOT_PORTABLE",o.source_file,`The selected root reads an unproven dynamic prop through ${h}.`));return}c.has(y)||(c.add(y),Lv(y,n,o,s,d,p,a))}},p=(f,h)=>{let y=Hv(f);if(!y||/^[a-z]/u.test(y.name))return;let x=h.scope.getBinding(y.name);if(!x){Fv.has(y.name)||s.errors.push(tt("SOURCE_NOT_PORTABLE",o.source_file,`The selected root component ${y.name} has no proven import or declaration.`));return}c.has(x)||ll(x.path.node,t)||(c.add(x),Lv(x,n,o,s,d,p,a))};(f=>{f.isIdentifier()&&f.isReferencedIdentifier()&&d(f),f.isJSXElement()&&p(f.node.openingElement.name,f),f.traverse({ReferencedIdentifier(h){d(h)},JSXOpeningElement(h){p(h.node.name,h)},CallExpression(h){zv(h,i)||s.errors.push(tt("SOURCE_NOT_PORTABLE",o.source_file,"A selected-root call is not a proven pure helper or statically bound translation."))},AssignmentExpression(h){s.errors.push(tt("SOURCE_NOT_PORTABLE",o.source_file,"Assignments inside a selected root are not a closed Portable dependency.")),h.stop()},UpdateExpression(h){s.errors.push(tt("SOURCE_NOT_PORTABLE",o.source_file,"Updates inside a selected root are not a closed Portable dependency.")),h.stop()},NewExpression(h){s.errors.push(tt("SOURCE_NOT_PORTABLE",o.source_file,"Dynamic object construction inside a selected root is not proven portable.")),h.stop()}})})(e)}function Lv(e,t,n,r,o,i,s){let a=e.path;if(OB(a,t)||a.isFunctionDeclaration()&&a.node===t.node){r.errors.push(tt("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(tt("SOURCE_NOT_PORTABLE",n.source_file,`Captured binding ${e.identifier.name} is rebound outside its declaration.`));return}if(SB(e)){r.errors.push(tt("SOURCE_NOT_PORTABLE",n.source_file,`Captured binding ${e.identifier.name} has a member write outside its declaration.`));return}let c=new cl(s),l=new Map,u=a.parentPath,d=u?.isImportDeclaration(),p=!1;if(d&&(u.node.source.value.startsWith(".")||u.node.source.value.startsWith("@/"))){let y=dl(n.source_file,u.node.source.value,s),x=y?c.get(y):void 0,E=a.isImportDefaultSpecifier()?"default":a.isImportSpecifier()&&a.node.importKind!=="type"?jt(a.node.imported,!1):null,b=x&&E&&u.node.importKind!=="type"?Fi(x,E,c):null,S=b?Bt(b):null;if(!S?.length){r.errors.push(tt("SOURCE_NOT_PORTABLE",n.source_file,"The imported value has no bounded unique Snapshot source."));return}l.set(e.identifier,S),p=S.every(N=>N.isFunctionDeclaration()||N.isFunctionExpression()||N.isArrowFunctionExpression())}else d&&(p=e.referencePaths.every(y=>y.parentPath?.isJSXOpeningElement()||y.parentPath?.isJSXClosingElement()||y.parentPath?.isCallExpression()&&y.parentPath.node.callee===y.node));if((d&&!p||hB(e))&&!Ss(e,{bindings:new Set,activeBindings:new Set,jsxCalls:new Set,inputs:l,files:s,modules:c},!1)){r.errors.push(tt("SOURCE_NOT_PORTABLE",n.source_file,`Captured binding ${e.identifier.name} is mutated or escapes its static object shape.`));return}let m=a.isImportDeclaration()?a:a.findParent(y=>y.isImportDeclaration());if(m?.isImportDeclaration()){r.imports.add(m.node);return}let f=a.isVariableDeclarator()?a:a.findParent(y=>y.isVariableDeclarator());if(f?.isVariableDeclarator()){let y=f.parentPath,x=f.get("init");if(!y?.isVariableDeclaration()||y.node.kind!=="const"||!x.node||!Jr(f.node.id)||!Jr(x.node)&&!wB(x)){r.errors.push(tt("SOURCE_NOT_PORTABLE",n.source_file,`Captured binding ${e.identifier.name} is not a side-effect-free const.`));return}let b=y.findParent(N=>N.isFunction())===t?r.functionDeclarations:r.moduleDeclarations,S=w.variableDeclaration("const",[w.cloneNode(f.node,!0)]);Mv(b,S,f.node),f.traverse({ReferencedIdentifier(N){N.isIdentifier()&&o(N)},JSXOpeningElement(N){i(N.node.name,N)}});return}let h=a.isFunctionDeclaration()?a:a.findParent(y=>y.isFunction());if(h?.isFunctionDeclaration()&&ja(h.node)){let x=h.findParent(E=>E.isFunction())===t?r.functionDeclarations:r.moduleDeclarations;Mv(x,w.cloneNode(h.node,!0),h.node),h.traverse({ReferencedIdentifier(E){E.isIdentifier()&&o(E)},JSXOpeningElement(E){i(E.node.name,E)}});return}r.errors.push(tt("SOURCE_NOT_PORTABLE",n.source_file,`Captured binding ${e.identifier.name} is not a statically portable declaration.`))}function hB(e){let t=e.path;if(!t.isVariableDeclarator())return!1;let n=t.get("init");if(!n.node)return!0;let r=NB(n.node);return w.isFunctionExpression(r)||w.isArrowFunctionExpression(r)||w.isCallExpression(r)&&$a(r)?!1:!Cd(e)?.every(i=>i.isFunctionExpression()||i.isArrowFunctionExpression()||Nd(i,new Map))}var cl=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=ul(this.files,t);if(r===null)return;let o=Ue(t,r);if(o.ok)return super.set(t,o.module),o.module}};function yB(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=w.file(w.program([w.expressionStatement(w.valueToNode(i.value.value))]));Up(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 cl(o)};if(t.propsParameter)return jp(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),!Ss(d,c,!0)))return!1}return!0}function xB(e,t){if(Nd(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(w.isJSXIdentifier(i)&&/^[a-z]/u.test(i.name))return!0;if(!w.isJSXIdentifier(i)||t.jsxCalls.has(o.node)||t.jsxCalls.size>=32)return!1;let s=bB(o,t);if(!s)return!1;let a={...t,bindings:new Set(t.bindings),jsxCalls:new Set(t.jsxCalls).add(o.node)},c=Bt(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 p of d.node.properties){if(!w.isObjectProperty(p)||p.computed)return!1;let m=jt(p.key,!1);if(m===null)return!1;u.add(m)}}return[...u].every(d=>{let p=Va(c,d,t.inputs);return p!==null&&jp(s,d,p,a)})}let l=r.isJSXAttribute()&&w.isJSXIdentifier(r.node.name)?r.node.name.name:"children";return jp(s,l,c,a)}function bB(e,t){let n=e.node.name;if(!w.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=dl(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=ln({module:c,exportName:l,parsedModules:t.modules});return u.ok?u.roots[0]?.getFunctionParent()??null:null}function jp(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(p=>c.scope.getBinding(p)?.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=Ss(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),Kv(c,{...r,inputs:i},!0))})}function Ss(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=>Kv(i,r,n));return o&&t.bindings.add(e),o}function Kp(e,t,n){let r=e.node.id;if(w.isIdentifier(r)){let o=e.scope.getBinding(r.name);return o?Ss(o,t,n):!1}if(w.isObjectPattern(r)||w.isArrayPattern(r)){let o=[];return Go(r,o)?EB(o,e,t):!1}return!1}function Go(e,t){if(w.isRestElement(e))return Go(e.argument,t);if(w.isIdentifier(e))return t.push(e.name),!0;if(w.isAssignmentPattern(e))return Go(e.left,t);if(w.isObjectPattern(e)){for(let n of e.properties){if(w.isRestElement(n)){if(!Go(n.argument,t))return!1;continue}if(!w.isObjectProperty(n)||n.computed||!(w.isIdentifier(n.key)||w.isStringLiteral(n.key)||w.isNumericLiteral(n.key))||!Go(n.value,t))return!1}return!0}if(w.isArrayPattern(e)){for(let n of e.elements)if(n&&!Go(n,t))return!1;return!0}return!1}function EB(e,t,n){return e.every(r=>{let o=t.scope.getBinding(r);return o?Ss(o,n,!0):!1})}function SB(e){return e.referencePaths.some(t=>{let{current:n,memberAccess:r}=Uv(t);if(!r)return!1;let o=n.parentPath;return!!(Vv(n)||o?.isUpdateExpression()||o?.isUnaryExpression({operator:"delete"}))})}function Vv(e){let t=e.findParent(n=>n.isAssignmentExpression()||n.isForXStatement());return t&&(t.isAssignmentExpression()||t.isForXStatement())?ll(e.node,t.node.left):!1}function Uv(e){let t=$p(e),n=!1;for(;t.parentPath&&(t.parentPath.isMemberExpression()||t.parentPath.isOptionalMemberExpression())&&t.parentPath.node.object===t.node;)n=!0,t=$p(t.parentPath);return{current:t,memberAccess:n}}function Kv(e,t,n){if(!kB(e,t))return!1;let{current:r,memberAccess:o}=Uv(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:Kp(i,t,o||n)}return Vv(r)||i.isUpdateExpression()||i.isUnaryExpression({operator:"delete"})?!1:i.isCallExpression()||i.isOptionalCallExpression()?i.node.callee===r.node?!1:vB(i,r,t):i.isNewExpression()?!1:i.isExportSpecifier()||i.isExportNamedDeclaration()||i.isExportDefaultDeclaration()||i.isTSTypeQuery()||n&&(i.isJSXOpeningElement()||i.isJSXClosingElement())?!0:i.isJSXExpressionContainer()||i.isJSXSpreadAttribute()?xB(r,t):i.isSpreadElement()||i.isArrayExpression()||i.isObjectExpression()||i.isObjectProperty()||i.isConditionalExpression()||i.isLogicalExpression()||i.isSequenceExpression()||i.isAwaitExpression()?IB(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 vB(e,t,n){if(!e.node.arguments.some(i=>i===t.node))return!1;let r=e.node.callee;if(w.isIdentifier(r)){if($v.has(r.name))return e.scope.getBinding(r.name)===void 0;let i=e.scope.getBinding(r.name);return!i||!Io(i)?!1:Es(e,n,new Set)}if(!w.isMemberExpression(r)&&!w.isOptionalMemberExpression(r)||!w.isIdentifier(r.property))return!1;let o=Jp(r);return!o||e.scope.getBinding(o.name)?!1:o.name==="Object"&&r.property.name==="assign"?e.node.arguments[0]===t.node?!1:Es(e,n,new Set):jv.get(o.name)?.has(r.property.name)??!1?Xv(e)?Es(e,n,new Set):!0:!1}function IB(e,t,n,r){let o=Jv(e);return o.kind==="declarator"?Kp(o.declarator,r,o.directValue):o.kind==="escape"||o.kind==="call"?!1:t||n}function Jv(e){let t=$p(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 Es(e,t,n){if(n.has(e.node))return!0;n.add(e.node);let r=Jv(e);return r.kind==="declarator"?Kp(r.declarator,t,r.directValue):r.kind==="escape"?!1:r.kind==="call"?r.call.node.callee===e.node?!1:Xv(r.call)?Es(r.call,t,n):CB(r.call):!0}function kB(e,t){let n=e.findParent(o=>o.isFunction());if(!n||!Wv(n.node))return!0;let r=RB(n);return!r||!Io(r)?!0:r.referencePaths.every(o=>{let i=o.parentPath;return!i?.isCallExpression()||i.node.callee!==o.node?!0:Es(i,t,new Set)})}function RB(e){let t=e.node,n=null;if(w.isFunctionDeclaration(t)?n=t.id?.name??null:(w.isArrowFunctionExpression(t)||w.isFunctionExpression(t))&&e.parentPath?.isVariableDeclarator()&&w.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 Xv(e){let t=e.node.callee;if(w.isIdentifier(t)){let r=e.scope.getBinding(t.name);return!!(r&&Io(r))}if(!w.isMemberExpression(t)&&!w.isOptionalMemberExpression(t)||!w.isIdentifier(t.property))return!1;let n=Jp(t);return!n||e.scope.getBinding(n.name)?!1:n.name==="Object"&&uB.has(t.property.name)}function CB(e){let t=e.node.callee;if(w.isIdentifier(t))return $v.has(t.name)&&e.scope.getBinding(t.name)===void 0;if(!w.isMemberExpression(t)&&!w.isOptionalMemberExpression(t)||!w.isIdentifier(t.property))return!1;let n=Jp(t);return!n||e.scope.getBinding(n.name)||n.name==="Object"&&t.property.name==="assign"?!1:jv.get(n.name)?.has(t.property.name)??!1}function $p(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 NB(e){let t=e;for(;t&&(w.isTSAsExpression(t)||w.isTSTypeAssertion(t)||w.isTSNonNullExpression(t)||w.isTSSatisfiesExpression(t)||w.isParenthesizedExpression(t));)t=t.expression;return t&&w.isExpression(t)?t:null}function Jp(e){return!e.computed&&w.isIdentifier(e.object)?e.object:null}function _B(e){let t=w.identifier(e);return t.typeAnnotation=w.tsTypeAnnotation(w.tsTypeReference(w.identifier("Record"),w.tsTypeParameterInstantiation([w.tsStringKeyword(),w.tsAnyKeyword()]))),t}function al(e){let t=new Map(e.files);t.set(e.entryFile,e.entryContent);let n=hs({entry_files:[e.entryFile],files:t});if(!n.complete)return{complete:!1,errors:n.errors.map(i=>tt(DB(i.code),i.path,i.message))};let r=[];for(let i of n.nodes){if(i.kind!=="source"&&i.kind!=="asset")continue;let s=ul(t,i.path);if(s===null)return xt("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 PB(e,t,n,r){let o=w.cloneNode(e,!0),i=e.source.value;if(i.startsWith("./")||i.startsWith("../")){let s=dl(t,i,r);if(!s)return{ok:!1,error:tt("SOURCE_IMPORT_UNRESOLVED",t,`The selected import ${i} cannot be resolved in the fixed Snapshot map.`)};o.source.value=AB(n,s)}return{ok:!0,node:o}}function dl(e,t,n){let r=t.startsWith("@/")?t.slice(2):bs.posix.normalize(bs.posix.join(bs.posix.dirname(e),t));if(!Vp(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 AB(e,t){let n=bs.posix.relative(bs.posix.dirname(e),t);return n.startsWith(".")?n:`./${n}`}function TB(e){let t=null,n=0,r=!1;return e.traverse({CallExpression(o){let i=o.node.callee;if(!w.isIdentifier(i)||!/^use[A-Z0-9]/u.test(i.name))return;if(i.name!=="useTranslations"||o.node.arguments.length!==1||!w.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"||!w.isIdentifier(s.path.node.imported,{name:"useTranslations"})){r=!0,o.stop();return}n+=1;let c=o.findParent(l=>l.isVariableDeclarator());if(!c?.isVariableDeclarator()||!w.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 zv(e,t){let n=e.node.callee;if(w.isImport(n))return!1;if(t&&w.isIdentifier(n,{name:t})&&e.node.arguments.length>0&&e.node.arguments.every(o=>w.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!!(w.isCallExpression(s)&&$a(s))}if(!w.isIdentifier(n))return!1;let r=e.scope.getBinding(n.name);return r?Io(r):!1}function wB(e){return e.isCallExpression()&&zv(e,null)&&w.isIdentifier(e.node.callee)&&e.scope.getBinding(e.node.callee.name)?.constantViolations.length===0&&e.node.arguments.every(t=>w.isExpression(t)&&Jr(t))}function Hv(e){return w.isJSXIdentifier(e)?w.isValidIdentifier(e.name)?w.identifier(e.name):null:w.isJSXMemberExpression(e)?Hv(e.object):null}function OB(e,t){return e.scope===t.scope&&(t.node.params.some(n=>n===e.node)||e.isIdentifier()&&t.node.params.some(n=>w.isObjectPattern(n)&&n.properties.some(r=>w.isObjectProperty(r)&&w.isIdentifier(r.value,{name:e.node.name}))))}function ll(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 Wv(e){return w.isFunction(e)}function Dv(e,t){return!!e.invocation?.bindings.some(n=>n.propName===t)}function FB(e,t){let n=new Set(t.values());return e.invocation?.bindings.filter(r=>n.has(r.propName))??[]}function LB(e,t){let n=new Set;Up(e,{Identifier(o){n.add(o.node.name)}});let r=t;for(;n.has(r);)r+="_";return r}function Mv(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 Bp(e,t){return(e.start??0)-(t.start??0)}function ul(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 Bv(e,t){let n=iB("sha256").update(t).digest("hex");return e.content_hash===`sha256:${n}`}function Vp(e){return!!e&&!e.startsWith("/")&&!e.includes("\\")&&e.split("/").every(t=>t&&t!=="."&&t!==".."&&!t.startsWith("."))}function DB(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 xt(e,t,n){return{complete:!1,errors:[tt(e,t,n)]}}function tt(e,t,n){return{code:e,path:t,message:n}}import MB from"node:path";import{GeneratedSiteCapabilitiesSchema as BB,FormDefinitionIdSchema as jB,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as $B,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as VB,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as UB,SiteEditMaterializationExportSchema as KB,SiteEditMaterializationSchema as JB,SiteEditSourcePathSchema as XB}from"@vcp-dev/contracts";var fl="components/site/generated",zB=/^[a-z][a-z0-9._-]{0,127}$/,ml=/^[a-z][a-z0-9._-]{0,127}$/,HB=new Set(["collection-detail-view","i18n-companion","client-importer"]);function WB(e){if(!Yo(e))return je("PORTABLE_INPUT_INVALID","Portable materialization input must be an object.","input");if(typeof e.instanceId!="string"||!zB.test(e.instanceId))return je("PORTABLE_INSTANCE_INVALID","Portable instanceId must be a single safe directory name.","instanceId");let t=BB.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(!qB(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(f=>{if(typeof f!="string")return!0;let h=/^@\/components\/site\/generated\/forms\/form-([^/]+)$/u.exec(f)?.[1];return!jB.safeParse(h).success||!pl(e.existingSources,`${f.slice(2)}.tsx`)})))return je("PORTABLE_INPUT_INVALID","Trusted managed imports must name exact existing canonical form sources.","trustedManagedImports");let n=GB(e.resolved);if(!n.ok)return n;let r=JB.safeParse(n.materialization);if(!r.success)return je("PORTABLE_INPUT_INVALID","Resolved portable materialization failed the strict contract.","resolved.materialization");let o=YB(n.relatedEntries,r.data);if(!o.ok)return o;let i=ZB(e.entryConsumers,o.data,r.data,e.existingSources);if(!i.ok)return i;let s=MB.posix.join(fl,e.instanceId),a=[],c=new Set;for(let f of r.data.files){let h=Ci({pathTemplate:f.pathTemplate,generatedRoot:fl,instanceName:e.instanceId,instanceRoot:s});if(!h.ok)return Xp(h.error);if(c.has(h.data))return je("MATERIALIZATION_PATH_INVALID",`Portable materialization resolves duplicate target path: ${h.data}`,h.data);c.add(h.data),a.push({kind:"create-only",path:h.data,content:f.content,...f.role?{role:f.role}:{},sourcePathTemplate:f.pathTemplate})}if(a.length>VB)return je("MATERIALIZATION_LIMIT_EXCEEDED","Portable materialization file count exceeds the reusable limit.");let l=0;for(let f of a){let h=Buffer.byteLength(f.content,"utf8");if(h>$B)return je("MATERIALIZATION_LIMIT_EXCEEDED","Portable materialization file exceeds the per-file content limit.",f.path);l+=h}if(l>UB)return je("MATERIALIZATION_LIMIT_EXCEEDED","Portable materialization exceeds the reusable total content limit.");let u=Gv(r.data.entry.pathTemplate,r.data.entry.export,c,e.instanceId,s);if(!u.ok)return u;let d=[],p=[u.data];for(let f of o.data){let h=Gv(f.pathTemplate,f.export,c,e.instanceId,s);if(!h.ok)return h;d.push({...f,path:h.data.path}),p.push(h.data)}if(pl(e.existingSources,s)||a.some(f=>pl(e.existingSources,f.path)))return je("PORTABLE_INSTANCE_CONFLICT","Portable materialization cannot overwrite an existing instance source.",s);let m=Gu({preserveCapturedStyles:!0,files:a,instanceRoot:s,entries:p,hostCapabilities:t.data,trustedManagedImports:e.trustedManagedImports});return m.ok?(a.sort((f,h)=>f.path.localeCompare(h.path)),{ok:!0,data:{kind:"portable-materialization",instanceId:e.instanceId,generatedRoot:fl,instanceRoot:s,entry:u.data,relatedEntries:d.sort((f,h)=>f.path.localeCompare(h.path)),entryConsumers:i.data,files:a}}):Xp(m.error)}function GB(e){if(!Yo(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&&!Yo(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 YB(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(!Yo(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,p=c.purpose,m=KB.safeParse(c.export);if(typeof l!="string"||!ml.test(l)||typeof u!="string"||!ml.test(u)||typeof d!="string"||typeof p!="string"||!HB.has(p)||!m.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:m.data,purpose:p,requirementKey:u})}return{ok:!0,data:s}}function ZB(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(!Yo(u))return je("PORTABLE_INPUT_INVALID","Every entry consumer must be an object.",`entryConsumers[${l}]`);let d=u.entry_key,p=u.requirement_key,m=u.kind,f=u.consumer_path;if(typeof d!="string"||!ml.test(d)||typeof p!="string"||!ml.test(p)||typeof f!="string"||!f.trim()||m!=="route"&&m!=="capability"&&m!=="preserved-route")return je("PORTABLE_INPUT_INVALID","Entry consumers must declare a strict entry, requirement, kind and path.",`entryConsumers[${l}]`);let h=o.get(d);if(!h)return je("PORTABLE_ENTRY_UNCONSUMED","An entry consumer must reference a declared related entry.",d);if(m==="preserved-route"&&(h.purpose!=="collection-detail-view"||!XB.safeParse(f).success||!/^app\/.*\/page\.tsx$/u.test(f)||!pl(r,f)))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(h.requirementKey!==p)return je("PORTABLE_REQUIREMENT_UNRESOLVED","An entry consumer must use the related entry requirement.",d);if(!i.has(p))return je("PORTABLE_REQUIREMENT_UNRESOLVED","An entry consumer must reference a resolved managed requirement.",p);s.add(d),a.push({entry_key:d,requirement_key:p,kind:m,consumer_path:f})}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 Gv(e,t,n,r,o){let i=Ci({pathTemplate:e,generatedRoot:fl,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):Xp(i.error)}function pl(e,t){return Array.isArray(e)?e.includes(t):e instanceof Map?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function qB(e){return Array.isArray(e)||e instanceof Map||Yo(e)}function Yo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Xp(e){return{ok:!1,error:e}}function je(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{path:n}:{}}}}import Yv from"node:path";import{SiteEditSourcePathSchema as zp}from"@vcp-dev/contracts";function QB(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||!zp.safeParse(e.entryFile).success||!zp.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 ft("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 ft("INVALID_TARGET","The verified Portable owner is absent from the fixed source map.",t.ownerFile);if(ve(n)!==t.sourceHash)return ft("VERSION_STALE","The Portable boundary owner changed after resolution.",t.ownerFile);let r=rj(e);return r||(e.binding.root.ownerNode.kind==="route-member"?t.ownerFile!==e.entryFile?ft("INVALID_TARGET","A route-member block boundary must remain in its route entry file.",t.ownerFile):ej(e,n):nj(e,n))}function ej(e,t){let n=Ue(e.entryFile,t);if(!n.ok)return ft("PORTABLE_ROUTE_SOURCE_INVALID",n.diagnostic.message,e.entryFile);let r=un({route:e.routeId,composition:e.binding.composition,entryFile:e.entryFile,version:e.documentVersion,source:t,ast:n.module.ast});if(!r.ok)return ft("PORTABLE_ROUTE_UNSUPPORTED","The route owner does not expose a supported composition boundary.",e.entryFile);let o=tj(r.projection.placements,e.resolvedBoundary.anchorLocator.sourceRange,e.resolvedBoundary.placement);if(!o)return ft("INVALID_TARGET","The exact route-member boundary has no unique page-composition member.",e.entryFile);let i=fd({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 ft(i.error.code,i.error.message,e.entryFile);if(i.patch.path!==e.resolvedBoundary.ownerFile||i.patch.expectedSourceHash!==e.resolvedBoundary.sourceHash)return ft("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||!Wp(a,e.resolvedBoundary.anchorLocator.sourceRange))?ft("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 tj(e,t,n){let r=e.flatMap(o=>o.relation!==n||!o.anchorSourceRange||!Wp(o.anchorSourceRange,t)?[]:Zv(o.members).filter(i=>i.sourceRange!==null&&Wp(i.sourceRange,t)));return r.length===1?r[0].label:null}function Zv(e){return e.flatMap(t=>[t,...Zv(t.children)])}function nj(e,t){let n=e.resolvedBoundary,r=n.parentLocator;if(!r)return ft("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 ft("INVALID_TARGET","The verified shared owner parent is not a JSX child container.",n.ownerFile);let o=ur({component:e.component.localName,bindings:e.invocation.bindings,targetBlockId:e.invocation.targetBlockId,targetOrder:e.invocation.targetOrder});if(!o.ok)return ft(o.error.code,o.error.message,n.ownerFile);let i=oj(t,n.ownerFile,r,o.plan.bindings);if(i)return i;let s=Yt({source:t,locator:Hp(r),anchorLocator:Hp(n.anchorLocator),placement:n.placement,node:{jsx:o.plan.jsx}});if(!s.ok)return ft("PORTABLE_BLOCK_PATCH_FAILED",s.diagnostic.message,n.ownerFile);let a=Zt({source:s.source,moduleSpecifier:ij(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}]}:ft("PORTABLE_BLOCK_PATCH_FAILED",a.diagnostic.message,n.ownerFile)}function rj(e){return!zp.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)?ft("INVALID_TARGET","The Portable component source or export is not a safe materialized reference.",e.component.source):null}function oj(e,t,n,r){if(!r.some(s=>s.value.kind==="route-search-params"))return null;let o=Ue(t,e);if(!o.ok)return ft("INVOCATION_VALUE_UNRESOLVED",o.diagnostic.message,t);let i=Ee(o.module.ast,Hp(n));return!i.ok||!i.match.path.scope.getBinding("searchParams")?ft("INVOCATION_VALUE_UNRESOLVED","The shared owner has no proven searchParams binding for this invocation.",t):null}function Hp(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 ij(e,t){let n=Yv.posix.relative(Yv.posix.dirname(e),t.replace(/\.(?:tsx?|jsx?)$/u,""));return n=n.replaceAll("\\","/"),n.startsWith(".")?n:`./${n}`}function Wp(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function ft(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{path:n}:{}}}}import{SiteEditPageBlockTargetSchema as sj,SiteIdSchema as aj,SnapshotIdSchema as cj}from"@vcp-dev/contracts";async function lj(e){if(!aj.safeParse(e.site_id).success||!cj.safeParse(e.base_snapshot_id).success||!sj.safeParse(e.target).success)return Fn("INVALID_PARAMS","Invalid site, snapshot, or page block identity.");if(!dj(e.composition,e.target.composition))return Fn("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(!Gp(u))return Fn("INVALID_PARAMS","Snapshot contains an unsafe source path.");let p=typeof d=="string"?d:uj(u,d);p!==null&&(n.set(u,p),/\.(?:[cm]?[jt]sx?)$/i.test(u)&&t.set(u,p))}let r;try{r=Za({files:n})}catch{return Fn("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 Fn("INVALID_TARGET","The requested route/template is absent from this snapshot.");let i=t.get(o.entryFile);if(i===void 0)return Fn("INVALID_TARGET","The selected composition entry is unavailable.");let s=await ha(o.entryFile,i,async u=>{if(!Gp(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=>Gp(u)&&t.has(u),{version:e.document_version});if(s.diagnostics.length>0||!s.entryModule)return Fn("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=un({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 Fn("INVALID_TARGET","The selected snapshot page composition is unsupported.");let c=Ja({composition:s.graph.composition,entryFile:o.entryFile,graph:s.graph,parsedModules:s.parsedModules,projection:a.projection});if(c.diagnostics.length>0)return Fn("INVALID_TARGET","The selected snapshot has unproven page block roots.");let l=Bi({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?{...Fn("INVALID_TARGET","The selected snapshot block index is incomplete."),index:l}:{...Ro(l,e.target,e.document_version,e.selection_ref),index:l}}function uj(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 Gp(e){return e.length>0&&!e.startsWith("/")&&!e.includes("\\")&&!e.includes("\0")&&e.split("/").every(t=>t.length>0&&t!=="."&&t!=="..")}function dj(e,t){return e.routeId===t.routeId&&e.templateId===t.templateId}function Fn(e,t){return{ok:!1,code:e,message:t}}import{createHash as qv}from"node:crypto";import Yp from"node:path";import Zp from"@babel/traverse";import*as Ve from"@babel/types";import{GeneratedSiteCapabilitiesSchema as fj,SiteEditSourcePathSchema as pj}from"@vcp-dev/contracts";var mj=typeof Zp=="function"?Zp:Zp.default,qp=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=gl(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=Ue(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 gj(e){let{binding:t,files:n}=e;if(e.hostCapabilities!==null&&!fj.safeParse(e.hostCapabilities).success)return nt("INVOCATION_VALUE_UNRESOLVED","generated-site-capabilities","Trusted host capabilities failed their strict schema.");if(!vs(t.descriptor.source.file)||!vs(t.ownerFile))return nt("INVOCATION_TARGET_NOT_RENDERED",t.descriptor.source.file,"The resolved block source path is not a safe Snapshot source path.");let r=gl(n,t.descriptor.source.file),o=gl(n,t.ownerFile);if(r===null||o===null)return nt("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(ve(r)!==t.descriptor.source.contentHash||ve(r)!==t.sourceHash||ve(o)!==t.ownerSourceHash)return nt("INVOCATION_TARGET_NOT_RENDERED",t.descriptor.source.file,"The pinned block or owner source hash no longer matches the resolved binding.");let i=Ue(t.descriptor.source.file,r);if(!i.ok)return nt("INVOCATION_PARSE_FAILED",t.descriptor.source.file,i.diagnostic.message);let s=hl(i.module.ast,t.rootLocator.sourceRange);if(s.length!==1)return nt("INVOCATION_TARGET_AMBIGUOUS",t.descriptor.source.file,"The selected block source range does not identify exactly one JSX element.");let a=s[0],c=eI(a.node);if(!c)return nt("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 qp(n),p=hj(e,c,d);if(p)return p;if(u.some(y=>(y.alternativeLocators?.length??0)>1))return nt("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 E=gl(n,x.sourceFile);if(E===null||!vs(x.sourceFile))return nt("INVOCATION_TARGET_NOT_RENDERED",x.sourceFile,"A statically proven call-chain source is missing from the fixed Snapshot map.");let b=Ue(x.sourceFile,E);if(!b.ok)return nt("INVOCATION_PARSE_FAILED",x.sourceFile,b.diagnostic.message);let S=hl(b.module.ast,x.callLocator.sourceRange);if(S.length!==1)return nt("INVOCATION_TARGET_AMBIGUOUS",x.sourceFile,"A call-chain locator does not identify exactly one current JSX element.");let N=u[y+1]?.sourceFile??t.descriptor.source.file,P=u[y+1]?.callLocator.sourceRange??t.rootLocator.sourceRange,R=cr({module:b.module,componentName:x.component,callSourceRange:x.callLocator.sourceRange});if(R.ok){if(R.sourceFile!==N)return nt("INVOCATION_TARGET_NOT_RENDERED",x.sourceFile,"The selected local component does not resolve to the source definition proven by the block graph.");if(R.roots.filter(st=>Zo(st.node,P)).length!==1)return nt("INVOCATION_TARGET_NOT_RENDERED",R.sourceFile,"The local component definition does not select exactly one proven JSX root.");let ye=xv({file_path:x.sourceFile,source:E,target:{kind:"local",local_name:x.component},call_source_range:{start_line:x.callLocator.sourceRange.startLine,start_column:x.callLocator.sourceRange.startColumn}});if(!ye.call||!ye.complete)return{complete:!1,errors:ye.errors.length>0?ye.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:ye.call,invocation:ye,definition:R,entryExport:null});continue}let A=Qp(b.module.ast,S[0].node.openingElement.name,x.component,x.exportName);if(!A)return nt("INVOCATION_TARGET_NOT_RENDERED",x.sourceFile,"The statically proven component call no longer resolves through one exact import.");let T=em(x.sourceFile,A.source,n);if(!T)return nt("INVOCATION_TARGET_NOT_RENDERED",x.sourceFile,"The selected component import is not a resolvable local Snapshot source.");let O=d.read(T);if(!O.ok)return nt(O.missing?"INVOCATION_TARGET_NOT_RENDERED":"INVOCATION_PARSE_FAILED",T,O.message);let D=ln({module:O.module,exportName:A.exportName,parsedModules:d});if(!D.ok)return nt("INVOCATION_TARGET_NOT_RENDERED",D.diagnostic.file,D.diagnostic.message);if(D.sourceFile!==N)return nt("INVOCATION_TARGET_NOT_RENDERED",x.sourceFile,"The selected component import does not resolve to the source definition proven by the block graph.");let V=D.roots.filter(H=>Zo(H.node,P));if(V.length!==1)return nt("INVOCATION_TARGET_NOT_RENDERED",D.sourceFile,"The unique component export does not select exactly one proven JSX root.");let Q=null;if(y===u.length-1&&u.length===1&&!nI(t.ownerFile)&&Zo(V[0].node,t.rootLocator.sourceRange)){let H=d.read(D.sourceFile);if(!H.ok)return nt(H.missing?"INVOCATION_TARGET_NOT_RENDERED":"INVOCATION_PARSE_FAILED",D.sourceFile,H.message);if(Q=Qv(H.module,D.componentName,A.exportName),!Q)return nt("INVOCATION_TARGET_AMBIGUOUS",D.sourceFile,"The proven component definition has no unique final export for a Portable entry.")}let U=Wo({file_path:x.sourceFile,source:E,target:{source:A.source,export_name:A.exportName,local_name:A.localName},call_source_range:{start_line:x.callLocator.sourceRange.startLine,start_column:x.callLocator.sourceRange.startColumn}});if(!U.call||!U.complete)return{complete:!1,errors:U.errors.length>0?U.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:U.call,invocation:U,definition:D,entryExport:Q})}let m={kind:"page-block",composition:tI(t.composition),blockKey:t.blockKey},f=yj(t,a,l,n,e.hostCapabilities);if(!f.ok)return{complete:!1,errors:[f.error]};let h=l[0]?.invocation??null;return{complete:!0,selection:{target:m,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:f.strategy,entry_file:f.entryFile,entry_export:f.entryExport,invocation:h}}}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=hl(c.ast,s.callLocator.sourceRange);if(l.length!==1)return null;let u=Qp(c.ast,l[0].node.openingElement.name,s.component,s.exportName);if(!u)return null;let d=em(s.sourceFile,u.source,o),p=d?n.get(d):void 0;if(!p)return null;let m=ln({module:p,exportName:u.exportName,parsedModules:n});if(!m.ok||m.sourceFile!==a.sourceFile)return null;let f=n.get(m.sourceFile);if(!f||Qv(f,m.componentName,"default")?.kind!=="default")return null;let h=Cp({files:o,list_entry_file:s.sourceFile,selected_component_source:`@/${m.sourceFile.replace(/\.[cm]?[jt]sx?$/u,"")}`});if(!h.complete||!h.relation)return null;let y=a.alternativeLocators?.length?a.alternativeLocators:[a.callLocator],x=m.returnAlternatives?.length?m.returnAlternatives:m.roots;if(x.length!==y.length||!x.every(N=>y.filter(P=>Zo(N.node,P.sourceRange)).length===1))return null;for(let N of y){let P=hl(f.ast,N.sourceRange);if(P.length!==1)return null;let R=Qp(f.ast,P[0].node.openingElement.name,a.component,a.exportName);if(!R)return null;let A=em(m.sourceFile,R.source,o),T=A?n.get(A):void 0;if(!T)return null;let O=ln({module:T,exportName:R.exportName,parsedModules:n});if(!O.ok||O.sourceFile!==r.descriptor.source.file||O.roots.length!==1||!Zo(O.roots[0].node,r.rootLocator.sourceRange))return null}let E=Wo({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(!E.complete||!E.call)return{complete:!1,errors:E.errors};let S=`components/site/portable/${qv("sha256").update(JSON.stringify(["collection-container",r.composition,r.blockKey,r.sourceHash,ve(f.source)])).digest("hex").slice(0,24)}/page.tsx`;return o.has(S)?nt("INVOCATION_TARGET_AMBIGUOUS",S,"The isolated collection entry collides with a pinned Snapshot source."):{complete:!0,selection:{target:{kind:"page-block",composition:tI(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:[E.call],strategy:"collection-container",collection_container_file:m.sourceFile,entry_file:S,entry_export:{kind:"default"},invocation:E}}}function yj(e,t,n,r,o){let i=n.at(-1);if(i?.kind==="import"){let l=i.definition.roots.length===1&&Zo(i.definition.roots[0].node,e.rootLocator.sourceRange),u=nI(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(!eI(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/${qv("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!vs(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 Qv(e,t,n){let r=new Set;for(let i of e.ast.program.body){if(Ve.isExportDefaultDeclaration(i)){let s=i.declaration;(Ve.isFunctionDeclaration(s)&&(s.id?.name===t||t==="default")||Ve.isIdentifier(s)&&s.name===t)&&r.add("default");continue}if(!(!Ve.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)Ve.isExportSpecifier(s)&&s.exportKind!=="type"&&nm(s.local)===t&&r.add(nm(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 Ve.isFunctionDeclaration(e)?e.id?.name===t?t:null:Ve.isVariableDeclaration(e)&&e.declarations.some(n=>Ve.isIdentifier(n.id)&&n.id.name===t)?t:null}function Qp(e,t,n,r){let o=tm(t);if(!o||o!==n)return null;let i=Ve.isJSXMemberExpression(t)?tm(t.object):Ve.isJSXNamespacedName(t)?t.namespace.name:o,s=Ve.isJSXMemberExpression(t)?t.property.name:null;for(let a of e.program.body)if(Ve.isImportDeclaration(a))for(let c of a.specifiers){if(Ve.isImportDefaultSpecifier(c)&&c.local.name===i)return r==="default"&&!s?{source:a.source.value,exportName:"default",localName:o}:null;if(Ve.isImportSpecifier(c)&&c.local.name===i){let l=nm(c.imported);return l===r&&!s?{source:a.source.value,exportName:l,localName:o}:null}if(Ve.isImportNamespaceSpecifier(c)&&c.local.name===i&&s)return s===r?{source:a.source.value,exportName:s,localName:o}:null}return null}function hl(e,t){let n=[];return mj(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 eI(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 Zo(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 gl(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 em(e,t,n){let r=t.startsWith("@/")?t.slice(2):t.startsWith("./")||t.startsWith("../")?Yp.posix.normalize(Yp.posix.join(Yp.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=>vs(i)&&n.has(i))??null}function tm(e){if(Ve.isJSXIdentifier(e))return e.name;if(Ve.isJSXMemberExpression(e)){let t=tm(e.object);return t?`${t}.${e.property.name}`:null}return null}function nm(e){return Ve.isIdentifier(e)?e.name:e.value}function tI(e){return{routeId:e.routeId,...e.effectiveTemplateId!==void 0?{templateId:e.effectiveTemplateId}:{}}}function vs(e){return pj.safeParse(e).success}function nI(e){return/(?:^|\/)\.vcp\/page-templates\//u.test(e)}function nt(e,t,n){return{complete:!1,errors:[{code:e,path:t,message:n}]}}import{parse as bj}from"@babel/parser";import rm from"@babel/traverse";import*as it from"@babel/types";var Ej=typeof rm=="function"?rm:rm.default,Sj=new Set(["slice","map","trim","toString"]);function vj(e){let t=new Set;try{let n=bj(e,{sourceType:"module",plugins:["jsx","typescript"]});Ej(n,{JSXExpressionContainer(r){let o=r.get("expression");Is(o,new Set)==="url"&&t.add(`${r.node.start}:${r.node.end}`)}})}catch{}return t}function Is(e,t){if(e.isMemberExpression()||e.isOptionalMemberExpression()){let a=Is(e.get("object"),t),c=e.node;return!c.computed&&it.isIdentifier(c.property,{name:"thumbnail"})&&a==="record"?"array":c.computed&&it.isNumericLiteral(c.property)&&Number.isSafeInteger(c.property.value)&&c.property.value>=0&&a==="array"?"item":!c.computed&&it.isIdentifier(c.property,{name:"url"})&&a==="item"?"url":null}if(e.isCallExpression()){let a=e.get("callee");return!a.isMemberExpression()||a.node.computed||!it.isIdentifier(a.node.property,{name:"slice"})||!e.node.arguments.every(c=>it.isNumericLiteral(c)&&Number.isSafeInteger(c.value)&&c.value>=0)?null:Is(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)||!om(n,new Set))return null;let r=new Set(t).add(n);if(n.path.isVariableDeclarator()&&it.isIdentifier(n.path.node.id))return Is(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=>it.isObjectPattern(a)&&a.properties.some(c=>it.isObjectProperty(c)&&!c.computed&&it.isIdentifier(c.key,{name:"record"})&&it.isIdentifier(c.value,{name:"record"}))))return"record";if(!o.isArrowFunctionExpression()||!it.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||!it.isIdentifier(s.node.property,{name:"map"})?null:Is(s.get("object"),r)==="array"?"item":null}function om(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(!it.isIdentifier(o.node.id)||o.node.init!==r.node)return!1;let i=o.scope.getBinding(o.node.id.name);return!!i&&om(i,t)}if(o.isCallExpression()||o.isOptionalCallExpression()){if(!(o.node.callee===r.node&&(r.isMemberExpression()||r.isOptionalMemberExpression())&&!r.node.computed&&it.isIdentifier(r.node.property)&&Sj.has(r.node.property.name)))return!1;if((r.isMemberExpression()||r.isOptionalMemberExpression())&&it.isIdentifier(r.node.property,{name:"map"})){let s=o.get("arguments.0");if(!s?.isArrowFunctionExpression()||!it.isIdentifier(s.node.params[0]))return!1;let a=s.scope.getBinding(s.node.params[0].name);if(!a||!om(a,t))return!1}return!0}return r!==n}):!1)}import{createHash as Ij}from"node:crypto";import kj from"@babel/traverse";import*as Fe from"@babel/types";var im=kj,Rj=typeof im=="function"?im:im.default,Cj=new Set(["avif","bmp","gif","jpeg","jpg","mp3","mp4","ogg","png","svg","wav","webm","webp"]),qo=new Set(["backgroundimage","image","imageurl","media","mediaurl","poster","src","srcset","thumbnail","thumbnailurl"]),Nj=/(?:asset|avatar|gallery|image|media|photo|poster|thumbnail|video)/iu,_j=/^(?:audio|img|image|picture|safeimage|source|video|media|.*(?:audio|image|video))$/iu;function Pj(e){let t=Ue(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=oI(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=oI(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})};Rj(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=iI(c.node.name),u=_j.test(l);for(let d of c.node.attributes){if(Fe.isJSXSpreadAttribute(d)){u&&i({node:d.argument,kind:"object",source:"jsx-attribute",value:null,complete:!1});continue}let p=wj(d);if(!p||!Tj(p,u))continue;let m=_r(d.value);i({node:d.value??d,kind:rI(p),source:"jsx-attribute",value:m.value,complete:m.complete})}},ObjectProperty(c){let l=bl(c.node.key);if(!l||!qo.has(l)&&!(Lj(c)&&sI(l))||qo.has(l)&&yl(c.node.value)&&xl(c.node.value))return;let u=_r(c.node.value);i({node:c.node.value,kind:rI(l),source:"object-property",value:u.value,complete:u.complete})},ArrayExpression(c){if(Fj(c))for(let l of c.node.elements){if(!l||yl(l)&&xl(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(!Fe.isIdentifier(l,{name:"mediaAsset"})||c.node.arguments.length!==1)return;let u=c.node.arguments[0];if(!Fe.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):Fe.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&&Cj.has(n)}function Tj(e,t){return e!=="src"||t?qo.has(e):!1}function rI(e){return e==="srcset"?"srcset":e==="poster"?"poster":e.startsWith("thumbnail")?"thumbnail":e==="src"?"src":"object"}function wj(e){return Fe.isJSXIdentifier(e.name)?e.name.name.toLowerCase():Fe.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`.toLowerCase():null}function iI(e){return Fe.isJSXIdentifier(e)?e.name:Fe.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:`${iI(e.object)}.${e.property.name}`}function bl(e){return Fe.isIdentifier(e)?e.name.toLowerCase():Fe.isStringLiteral(e)?e.value.toLowerCase():null}function Oj(e){return Fe.isIdentifier(e,{name:"mediaAssets"})}function Fj(e){let t=e.parentPath;if(t?.isObjectProperty()){let n=bl(t.node.key);return n!==null&&qo.has(n)}return t?.isVariableDeclarator()&&Fe.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=bl(n.node.key);return r!==null&&qo.has(r)}function sI(e){return e==="src"||e==="srcset"||e==="url"||e==="thumbnail_url"}function yl(e){return Fe.isObjectExpression(e)||Fe.isArrayExpression(e)}function xl(e){if(Fe.isArrayExpression(e))return e.elements.some(n=>n!==null&&(yl(n)?xl(n):!0));let t=!1;for(let n of e.properties){if(!Fe.isObjectProperty(n))return!1;let r=bl(n.key);if(r!==null&&(qo.has(r)||sI(r))){t=!0;continue}yl(n.value)&&xl(n.value)&&(t=!0)}return t}function _r(e){return e?Fe.isStringLiteral(e)?{value:e.value,complete:!0}:Fe.isJSXExpressionContainer(e)?_r(e.expression):Fe.isTemplateLiteral(e)&&e.expressions.length===0?{value:e.quasis.map(t=>t.value.cooked??t.value.raw).join(""),complete:!0}:Fe.isTSAsExpression(e)||Fe.isTSTypeAssertion(e)||Fe.isParenthesizedExpression(e)?_r(e.expression):{value:null,complete:!1}:{value:null,complete:!1}}function oI(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:${Ij("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)}export{ge as FileHistoryStoreError,$i as PageTemplateManagedSourceError,Zc as PreviewFileSystemSiteEditEngineRuntime,Ph as SITE_EDIT_RAW_COLOR_LITERAL_RE,Gc as SnapshotSiteEditEngineRuntime,CM as analyzePortableCollectionInvocation,Wo as analyzePortableInvocation,Np as analyzePortableRelatedEntries,Xu as auditGeneratedCode,DD as auditPortableDependencies,Bi as buildPageBlockIndex,ur as buildPortableInvocation,WB as buildPortableMaterializationPlan,hs as buildPortableSourceClosure,ri as checkComponentI18nHostCompatibility,qc as classifyPortableDependencyOwnership,ix as computeManagedPageTemplatePaths,PD as createPreviewSiteEditEngineRuntime,RD as createSiteEditEngineRuntime,nx as decodePageTemplateKey,Cp as discoverPortableCollectionSourceRelation,Ld as encodePageTemplateId,dB as extractPortableBlockEntry,WI as instrumentSiteEditRuntimeAttributes,sx as isManagedPageTemplateSourcePath,wP as normalizePortableBlockMetadata,XM as normalizePortableSource,rh as openFileHistoryStore,wI as parseSourceModule,QB as planPortableBlockPatch,fd as planPortableRouteCompositionPatch,Ai as planRouteCompositionRewrite,vj as provenRecordThumbnailRanges,OI as resolveImportBase,bT as resolveManagedPageTemplateComposition,za as resolvePageBlockBoundary,lj as resolvePageBlockFromSnapshot,Ro as resolvePageBlockTarget,un as resolvePageCompositionProjection,gj as resolvePortableBlockSelection,TD as resolvePortableDependencyOwnership,JD as resolvePortableSourcePath,Ya as scanManagedPageTemplateCandidates,Pj as scanPortableMediaReferences,Za as scanSiteEditCompositionsFromFiles,Ri as scanSiteEditThemeStyleViolations,RM as selectPortablePageUnitInvocation};
|
|
21
|
+
`;return cl({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)?bt("SOURCE_INPUT_INVALID",r,"The deterministic extracted entry path collides with the fixed Snapshot map."):yB(t,o,n)}function yB(e,t,n){let r;try{r=dB(t,{sourceType:"module",sourceFilename:e.source_file,plugins:["jsx","typescript"]})}catch(A){return bt("SOURCE_PARSE_FAILED",e.source_file,A instanceof Error?A.message:String(A))}let o=xB(r,e);if(o.length!==1)return bt("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||!Gv(s.node))return bt("SOURCE_NOT_PORTABLE",e.source_file,"The selected JSX root is not inside one statically bounded component function.");let a=s,c=DB(a);if(!c.ok)return bt("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,D=w.startsWith(".")||w.startsWith("@/")?fl(e.source_file,w,n):null;if(!D?.endsWith(".css"))return bt("SOURCE_NOT_PORTABLE",e.source_file,"A bare module effect is not a proven portable stylesheet dependency.");u.has(D)||l.imports.add(A),u.add(D)}let d=bB(a,e);if(!d.ok)return{complete:!1,errors:[d.error]};if(EB(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 bt("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=FB(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),E=[...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&&E.push(O.variableDeclaration("const",[O.variableDeclarator(O.identifier(l.propsObjectName),O.identifier(f))]));let b=O.blockStatement([...E,...y,x]),S=l.props.size?[OB(f)]:[],C=O.functionDeclaration(O.identifier("PortableBlockEntry"),S,b),T=O.program([...p,...m,C,O.exportDefaultDeclaration(O.identifier("PortableBlockEntry"))]);T.directives=r.program.directives.map(A=>O.cloneNode(A,!0));let R=mB(O.file(T),{jsescOption:{minimal:!0}}).code,_={generated_path:e.entry_file,source_file:e.source_file,structural_path:e.structural_path};return cl({entryFile:e.entry_file,entryContent:R,files:n,selection:e,sourceMapping:_,invocationBindings:jB(e,l.props)})}function xB(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 bB(e,t){let n=e.node.params;if(n.length>1)return{ok:!1,error:tt("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:tt("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:tt("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 EB(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=vB(n,r,p,o,a);return l.set(p,y),y||s.errors.push(tt("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){Lv.has(m)||s.errors.push(tt("SOURCE_NOT_PORTABLE",o.source_file,`The selected root references unbound identifier ${m}.`));return}if(!ul(y.path.node,t)){if(r.bindingByLocalName.has(m)&&y.scope===n.scope){let x=r.bindingByLocalName.get(m);Mv(o,x)?u(x)&&s.props.set(m,x):s.errors.push(tt("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,E=!x.computed&&O.isIdentifier(x.property)?x.property.name:x.computed&&O.isStringLiteral(x.property)?x.property.value:null;E&&Mv(o,E)?u(E)&&(s.propsObjectName=m,s.props.set(`@${m}.${E}`,E)):s.errors.push(tt("SOURCE_NOT_PORTABLE",o.source_file,`The selected root reads an unproven dynamic prop through ${m}.`));return}c.has(y)||(c.add(y),Dv(y,n,o,s,d,f,a))}},f=(p,m)=>{let y=Wv(p);if(!y||/^[a-z]/u.test(y.name))return;let x=m.scope.getBinding(y.name);if(!x){Lv.has(y.name)||s.errors.push(tt("SOURCE_NOT_PORTABLE",o.source_file,`The selected root component ${y.name} has no proven import or declaration.`));return}c.has(x)||ul(x.path.node,t)||(c.add(x),Dv(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){Hv(m,i)||s.errors.push(tt("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(tt("SOURCE_NOT_PORTABLE",o.source_file,"Assignments inside a selected root are not a closed Portable dependency.")),m.stop()},UpdateExpression(m){s.errors.push(tt("SOURCE_NOT_PORTABLE",o.source_file,"Updates inside a selected root are not a closed Portable dependency.")),m.stop()},NewExpression(m){s.errors.push(tt("SOURCE_NOT_PORTABLE",o.source_file,"Dynamic object construction inside a selected root is not proven portable.")),m.stop()}})})(e)}function Dv(e,t,n,r,o,i,s){let a=e.path;if(BB(a,t)||a.isFunctionDeclaration()&&a.node===t.node){r.errors.push(tt("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(tt("SOURCE_NOT_PORTABLE",n.source_file,`Captured binding ${e.identifier.name} is rebound outside its declaration.`));return}if(CB(e)){r.errors.push(tt("SOURCE_NOT_PORTABLE",n.source_file,`Captured binding ${e.identifier.name} has a member write outside its declaration.`));return}let c=new ll(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=fl(n.source_file,u.node.source.value,s),x=y?c.get(y):void 0,E=a.isImportDefaultSpecifier()?"default":a.isImportSpecifier()&&a.node.importKind!=="type"?jt(a.node.imported,!1):null,b=x&&E&&u.node.importKind!=="type"?wi(x,E,c):null,S=b?Bt(b):null;if(!S?.length){r.errors.push(tt("SOURCE_NOT_PORTABLE",n.source_file,"The imported value has no bounded unique Snapshot source."));return}l.set(e.identifier,S),f=S.every(C=>C.isFunctionDeclaration()||C.isFunctionExpression()||C.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))&&!Es(e,{bindings:new Set,activeBindings:new Set,jsxCalls:new Set,inputs:l,files:s,modules:c},!1)){r.errors.push(tt("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||!Jr(p.node.id)||!Jr(x.node)&&!MB(x)){r.errors.push(tt("SOURCE_NOT_PORTABLE",n.source_file,`Captured binding ${e.identifier.name} is not a side-effect-free const.`));return}let b=y.findParent(C=>C.isFunction())===t?r.functionDeclarations:r.moduleDeclarations,S=O.variableDeclaration("const",[O.cloneNode(p.node,!0)]);Bv(b,S,p.node),p.traverse({ReferencedIdentifier(C){C.isIdentifier()&&o(C)},JSXOpeningElement(C){i(C.node.name,C)}});return}let m=a.isFunctionDeclaration()?a:a.findParent(y=>y.isFunction());if(m?.isFunctionDeclaration()&&Ba(m.node)){let x=m.findParent(E=>E.isFunction())===t?r.functionDeclarations:r.moduleDeclarations;Bv(x,O.cloneNode(m.node,!0),m.node),m.traverse({ReferencedIdentifier(E){E.isIdentifier()&&o(E)},JSXOpeningElement(E){i(E.node.name,E)}});return}r.errors.push(tt("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=wB(n.node);return O.isFunctionExpression(r)||O.isArrowFunctionExpression(r)||O.isCallExpression(r)&&ja(r)?!1:!Pd(e)?.every(i=>i.isFunctionExpression()||i.isArrowFunctionExpression()||_d(i,new Map))}var ll=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=dl(this.files,t);if(r===null)return;let o=Ue(t,r);if(o.ok)return super.set(t,o.module),o.module}};function vB(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 ll(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),!Es(d,c,!0)))return!1}return!0}function IB(e,t){if(_d(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=kB(o,t);if(!s)return!1;let a={...t,bindings:new Set(t.bindings),jsxCalls:new Set(t.jsxCalls).add(o.node)},c=Bt(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=$a(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 kB(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=fl(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=un({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=Es(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),Jv(c,{...r,inputs:i},!0))})}function Es(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=>Jv(i,r,n));return o&&t.bindings.add(e),o}function Jp(e,t,n){let r=e.node.id;if(O.isIdentifier(r)){let o=e.scope.getBinding(r.name);return o?Es(o,t,n):!1}if(O.isObjectPattern(r)||O.isArrayPattern(r)){let o=[];return Wo(r,o)?RB(o,e,t):!1}return!1}function Wo(e,t){if(O.isRestElement(e))return Wo(e.argument,t);if(O.isIdentifier(e))return t.push(e.name),!0;if(O.isAssignmentPattern(e))return Wo(e.left,t);if(O.isObjectPattern(e)){for(let n of e.properties){if(O.isRestElement(n)){if(!Wo(n.argument,t))return!1;continue}if(!O.isObjectProperty(n)||n.computed||!(O.isIdentifier(n.key)||O.isStringLiteral(n.key)||O.isNumericLiteral(n.key))||!Wo(n.value,t))return!1}return!0}if(O.isArrayPattern(e)){for(let n of e.elements)if(n&&!Wo(n,t))return!1;return!0}return!1}function RB(e,t,n){return e.every(r=>{let o=t.scope.getBinding(r);return o?Es(o,n,!0):!1})}function CB(e){return e.referencePaths.some(t=>{let{current:n,memberAccess:r}=Kv(t);if(!r)return!1;let o=n.parentPath;return!!(Uv(n)||o?.isUpdateExpression()||o?.isUnaryExpression({operator:"delete"}))})}function Uv(e){let t=e.findParent(n=>n.isAssignmentExpression()||n.isForXStatement());return t&&(t.isAssignmentExpression()||t.isForXStatement())?ul(e.node,t.node.left):!1}function Kv(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 Jv(e,t,n){if(!_B(e,t))return!1;let{current:r,memberAccess:o}=Kv(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:Jp(i,t,o||n)}return Uv(r)||i.isUpdateExpression()||i.isUnaryExpression({operator:"delete"})?!1:i.isCallExpression()||i.isOptionalCallExpression()?i.node.callee===r.node?!1:NB(i,r,t):i.isNewExpression()?!1:i.isExportSpecifier()||i.isExportNamedDeclaration()||i.isExportDefaultDeclaration()||i.isTSTypeQuery()||n&&(i.isJSXOpeningElement()||i.isJSXClosingElement())?!0:i.isJSXExpressionContainer()||i.isJSXSpreadAttribute()?IB(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 NB(e,t,n){if(!e.node.arguments.some(i=>i===t.node))return!1;let r=e.node.callee;if(O.isIdentifier(r)){if(Vv.has(r.name))return e.scope.getBinding(r.name)===void 0;let i=e.scope.getBinding(r.name);return!i||!Io(i)?!1:bs(e,n,new Set)}if(!O.isMemberExpression(r)&&!O.isOptionalMemberExpression(r)||!O.isIdentifier(r.property))return!1;let o=Xp(r);return!o||e.scope.getBinding(o.name)?!1:o.name==="Object"&&r.property.name==="assign"?e.node.arguments[0]===t.node?!1:bs(e,n,new Set):$v.get(o.name)?.has(r.property.name)??!1?zv(e)?bs(e,n,new Set):!0:!1}function PB(e,t,n,r){let o=Xv(e);return o.kind==="declarator"?Jp(o.declarator,r,o.directValue):o.kind==="escape"||o.kind==="call"?!1:t||n}function Xv(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 bs(e,t,n){if(n.has(e.node))return!0;n.add(e.node);let r=Xv(e);return r.kind==="declarator"?Jp(r.declarator,t,r.directValue):r.kind==="escape"?!1:r.kind==="call"?r.call.node.callee===e.node?!1:zv(r.call)?bs(r.call,t,n):TB(r.call):!0}function _B(e,t){let n=e.findParent(o=>o.isFunction());if(!n||!Gv(n.node))return!0;let r=AB(n);return!r||!Io(r)?!0:r.referencePaths.every(o=>{let i=o.parentPath;return!i?.isCallExpression()||i.node.callee!==o.node?!0:bs(i,t,new Set)})}function AB(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 zv(e){let t=e.node.callee;if(O.isIdentifier(t)){let r=e.scope.getBinding(t.name);return!!(r&&Io(r))}if(!O.isMemberExpression(t)&&!O.isOptionalMemberExpression(t)||!O.isIdentifier(t.property))return!1;let n=Xp(t);return!n||e.scope.getBinding(n.name)?!1:n.name==="Object"&&gB.has(t.property.name)}function TB(e){let t=e.node.callee;if(O.isIdentifier(t))return Vv.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=Xp(t);return!n||e.scope.getBinding(n.name)||n.name==="Object"&&t.property.name==="assign"?!1:$v.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 wB(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 Xp(e){return!e.computed&&O.isIdentifier(e.object)?e.object:null}function OB(e){let t=O.identifier(e);return t.typeAnnotation=O.tsTypeAnnotation(O.tsTypeReference(O.identifier("Record"),O.tsTypeParameterInstantiation([O.tsStringKeyword(),O.tsAnyKeyword()]))),t}function cl(e){let t=new Map(e.files);t.set(e.entryFile,e.entryContent);let n=gs({entry_files:[e.entryFile],files:t});if(!n.complete)return{complete:!1,errors:n.errors.map(i=>tt(VB(i.code),i.path,i.message))};let r=[];for(let i of n.nodes){if(i.kind!=="source"&&i.kind!=="asset")continue;let s=dl(t,i.path);if(s===null)return bt("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 FB(e,t,n,r){let o=O.cloneNode(e,!0),i=e.source.value;if(i.startsWith("./")||i.startsWith("../")){let s=fl(t,i,r);if(!s)return{ok:!1,error:tt("SOURCE_IMPORT_UNRESOLVED",t,`The selected import ${i} cannot be resolved in the fixed Snapshot map.`)};o.source.value=LB(n,s)}return{ok:!0,node:o}}function fl(e,t,n){let r=t.startsWith("@/")?t.slice(2):xs.posix.normalize(xs.posix.join(xs.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 LB(e,t){let n=xs.posix.relative(xs.posix.dirname(e),t);return n.startsWith(".")?n:`./${n}`}function DB(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 Hv(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)&&ja(s))}if(!O.isIdentifier(n))return!1;let r=e.scope.getBinding(n.name);return r?Io(r):!1}function MB(e){return e.isCallExpression()&&Hv(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)&&Jr(t))}function Wv(e){return O.isJSXIdentifier(e)?O.isValidIdentifier(e.name)?O.identifier(e.name):null:O.isJSXMemberExpression(e)?Wv(e.object):null}function BB(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 ul(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 Gv(e){return O.isFunction(e)}function Mv(e,t){return!!e.invocation?.bindings.some(n=>n.propName===t)}function jB(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 Bv(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 dl(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 jv(e,t){let n=uB("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 VB(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 bt(e,t,n){return{complete:!1,errors:[tt(e,t,n)]}}function tt(e,t,n){return{code:e,path:t,message:n}}import UB from"node:path";import{GeneratedSiteCapabilitiesSchema as KB,FormDefinitionIdSchema as JB,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as XB,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as zB,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as HB,SiteEditMaterializationExportSchema as WB,SiteEditMaterializationSchema as GB,SiteEditSourcePathSchema as YB}from"@vcp-dev/contracts";var pl="components/site/generated",ZB=/^[a-z][a-z0-9._-]{0,127}$/,gl=/^[a-z][a-z0-9._-]{0,127}$/,qB=new Set(["collection-detail-view","i18n-companion","client-importer"]);function QB(e){if(!Go(e))return je("PORTABLE_INPUT_INVALID","Portable materialization input must be an object.","input");if(typeof e.instanceId!="string"||!ZB.test(e.instanceId))return je("PORTABLE_INSTANCE_INVALID","Portable instanceId must be a single safe directory name.","instanceId");let t=KB.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(!rj(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!JB.safeParse(m).success||!ml(e.existingSources,`${p.slice(2)}.tsx`)})))return je("PORTABLE_INPUT_INVALID","Trusted managed imports must name exact existing canonical form sources.","trustedManagedImports");let n=ej(e.resolved);if(!n.ok)return n;let r=GB.safeParse(n.materialization);if(!r.success)return je("PORTABLE_INPUT_INVALID","Resolved portable materialization failed the strict contract.","resolved.materialization");let o=tj(n.relatedEntries,r.data);if(!o.ok)return o;let i=nj(e.entryConsumers,o.data,r.data,e.existingSources);if(!i.ok)return i;let s=UB.posix.join(pl,e.instanceId),a=[],c=new Set;for(let p of r.data.files){let m=ki({pathTemplate:p.pathTemplate,generatedRoot:pl,instanceName:e.instanceId,instanceRoot:s});if(!m.ok)return zp(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>zB)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>XB)return je("MATERIALIZATION_LIMIT_EXCEEDED","Portable materialization file exceeds the per-file content limit.",p.path);l+=m}if(l>HB)return je("MATERIALIZATION_LIMIT_EXCEEDED","Portable materialization exceeds the reusable total content limit.");let u=Yv(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=Yv(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(ml(e.existingSources,s)||a.some(p=>ml(e.existingSources,p.path)))return je("PORTABLE_INSTANCE_CONFLICT","Portable materialization cannot overwrite an existing instance source.",s);let g=Zu({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:pl,instanceRoot:s,entry:u.data,relatedEntries:d.sort((p,m)=>p.path.localeCompare(m.path)),entryConsumers:i.data,files:a}}):zp(g.error)}function ej(e){if(!Go(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&&!Go(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 tj(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(!Go(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=WB.safeParse(c.export);if(typeof l!="string"||!gl.test(l)||typeof u!="string"||!gl.test(u)||typeof d!="string"||typeof f!="string"||!qB.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 nj(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(!Go(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"||!gl.test(d)||typeof f!="string"||!gl.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"||!YB.safeParse(p).success||!/^app\/.*\/page\.tsx$/u.test(p)||!ml(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 Yv(e,t,n,r,o){let i=ki({pathTemplate:e,generatedRoot:pl,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):zp(i.error)}function ml(e,t){return Array.isArray(e)?e.includes(t):e instanceof Map?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function rj(e){return Array.isArray(e)||e instanceof Map||Go(e)}function Go(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function zp(e){return{ok:!1,error:e}}function je(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{path:n}:{}}}}import Zv from"node:path";import{SiteEditSourcePathSchema as Hp}from"@vcp-dev/contracts";function oj(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||!Hp.safeParse(e.entryFile).success||!Hp.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 ft("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 ft("INVALID_TARGET","The verified Portable owner is absent from the fixed source map.",t.ownerFile);if(ve(n)!==t.sourceHash)return ft("VERSION_STALE","The Portable boundary owner changed after resolution.",t.ownerFile);let r=cj(e);return r||(e.binding.root.ownerNode.kind==="route-member"?t.ownerFile!==e.entryFile?ft("INVALID_TARGET","A route-member block boundary must remain in its route entry file.",t.ownerFile):ij(e,n):aj(e,n))}function ij(e,t){let n=Ue(e.entryFile,t);if(!n.ok)return ft("PORTABLE_ROUTE_SOURCE_INVALID",n.diagnostic.message,e.entryFile);let r=dn({route:e.routeId,composition:e.binding.composition,entryFile:e.entryFile,version:e.documentVersion,source:t,ast:n.module.ast});if(!r.ok)return ft("PORTABLE_ROUTE_UNSUPPORTED","The route owner does not expose a supported composition boundary.",e.entryFile);let o=sj(r.projection.placements,e.resolvedBoundary.anchorLocator.sourceRange,e.resolvedBoundary.placement);if(!o)return ft("INVALID_TARGET","The exact route-member boundary has no unique page-composition member.",e.entryFile);let i=md({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 ft(i.error.code,i.error.message,e.entryFile);if(i.patch.path!==e.resolvedBoundary.ownerFile||i.patch.expectedSourceHash!==e.resolvedBoundary.sourceHash)return ft("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||!Gp(a,e.resolvedBoundary.anchorLocator.sourceRange))?ft("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 sj(e,t,n){let r=e.flatMap(o=>o.relation!==n||!o.anchorSourceRange||!Gp(o.anchorSourceRange,t)?[]:qv(o.members).filter(i=>i.sourceRange!==null&&Gp(i.sourceRange,t)));return r.length===1?r[0].label:null}function qv(e){return e.flatMap(t=>[t,...qv(t.children)])}function aj(e,t){let n=e.resolvedBoundary,r=n.parentLocator;if(!r)return ft("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 ft("INVALID_TARGET","The verified shared owner parent is not a JSX child container.",n.ownerFile);let o=ur({component:e.component.localName,bindings:e.invocation.bindings,targetBlockId:e.invocation.targetBlockId,targetOrder:e.invocation.targetOrder});if(!o.ok)return ft(o.error.code,o.error.message,n.ownerFile);let i=lj(t,n.ownerFile,r,o.plan.bindings);if(i)return i;let s=Zt({source:t,locator:Wp(r),anchorLocator:Wp(n.anchorLocator),placement:n.placement,node:{jsx:o.plan.jsx}});if(!s.ok)return ft("PORTABLE_BLOCK_PATCH_FAILED",s.diagnostic.message,n.ownerFile);let a=qt({source:s.source,moduleSpecifier:uj(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}]}:ft("PORTABLE_BLOCK_PATCH_FAILED",a.diagnostic.message,n.ownerFile)}function cj(e){return!Hp.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)?ft("INVALID_TARGET","The Portable component source or export is not a safe materialized reference.",e.component.source):null}function lj(e,t,n,r){if(!r.some(s=>s.value.kind==="route-search-params"))return null;let o=Ue(t,e);if(!o.ok)return ft("INVOCATION_VALUE_UNRESOLVED",o.diagnostic.message,t);let i=Ee(o.module.ast,Wp(n));return!i.ok||!i.match.path.scope.getBinding("searchParams")?ft("INVOCATION_VALUE_UNRESOLVED","The shared owner has no proven searchParams binding for this invocation.",t):null}function Wp(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 uj(e,t){let n=Zv.posix.relative(Zv.posix.dirname(e),t.replace(/\.(?:tsx?|jsx?)$/u,""));return n=n.replaceAll("\\","/"),n.startsWith(".")?n:`./${n}`}function Gp(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function ft(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{path:n}:{}}}}import{SiteEditPageBlockTargetSchema as dj,SiteIdSchema as fj,SnapshotIdSchema as pj}from"@vcp-dev/contracts";async function mj(e){if(!fj.safeParse(e.site_id).success||!pj.safeParse(e.base_snapshot_id).success||!dj.safeParse(e.target).success)return Dn("INVALID_PARAMS","Invalid site, snapshot, or page block identity.");if(!hj(e.composition,e.target.composition))return Dn("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(!Yp(u))return Dn("INVALID_PARAMS","Snapshot contains an unsafe source path.");let f=typeof d=="string"?d:gj(u,d);f!==null&&(n.set(u,f),/\.(?:[cm]?[jt]sx?)$/i.test(u)&&t.set(u,f))}let r;try{r=Ya({files:n})}catch{return Dn("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 Dn("INVALID_TARGET","The requested route/template is absent from this snapshot.");let i=t.get(o.entryFile);if(i===void 0)return Dn("INVALID_TARGET","The selected composition entry is unavailable.");let s=await ga(o.entryFile,i,async u=>{if(!Yp(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=>Yp(u)&&t.has(u),{version:e.document_version});if(s.diagnostics.length>0||!s.entryModule)return Dn("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=dn({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 Dn("INVALID_TARGET","The selected snapshot page composition is unsupported.");let c=Ka({composition:s.graph.composition,entryFile:o.entryFile,graph:s.graph,parsedModules:s.parsedModules,projection:a.projection});if(c.diagnostics.length>0)return Dn("INVALID_TARGET","The selected snapshot has unproven page block roots.");let l=Di({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?{...Dn("INVALID_TARGET","The selected snapshot block index is incomplete."),index:l}:{...Ro(l,e.target,e.document_version,e.selection_ref),index:l}}function gj(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 Yp(e){return e.length>0&&!e.startsWith("/")&&!e.includes("\\")&&!e.includes("\0")&&e.split("/").every(t=>t.length>0&&t!=="."&&t!=="..")}function hj(e,t){return e.routeId===t.routeId&&e.templateId===t.templateId}function Dn(e,t){return{ok:!1,code:e,message:t}}import{createHash as Qv}from"node:crypto";import Zp from"node:path";import qp from"@babel/traverse";import*as Ve from"@babel/types";import{GeneratedSiteCapabilitiesSchema as yj,SiteEditSourcePathSchema as xj}from"@vcp-dev/contracts";var bj=typeof qp=="function"?qp:qp.default,Qp=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=hl(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=Ue(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 Ej(e){let{binding:t,files:n}=e;if(e.hostCapabilities!==null&&!yj.safeParse(e.hostCapabilities).success)return nt("INVOCATION_VALUE_UNRESOLVED","generated-site-capabilities","Trusted host capabilities failed their strict schema.");if(!Ss(t.descriptor.source.file)||!Ss(t.ownerFile))return nt("INVOCATION_TARGET_NOT_RENDERED",t.descriptor.source.file,"The resolved block source path is not a safe Snapshot source path.");let r=hl(n,t.descriptor.source.file),o=hl(n,t.ownerFile);if(r===null||o===null)return nt("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(ve(r)!==t.descriptor.source.contentHash||ve(r)!==t.sourceHash||ve(o)!==t.ownerSourceHash)return nt("INVOCATION_TARGET_NOT_RENDERED",t.descriptor.source.file,"The pinned block or owner source hash no longer matches the resolved binding.");let i=Ue(t.descriptor.source.file,r);if(!i.ok)return nt("INVOCATION_PARSE_FAILED",t.descriptor.source.file,i.diagnostic.message);let s=yl(i.module.ast,t.rootLocator.sourceRange);if(s.length!==1)return nt("INVOCATION_TARGET_AMBIGUOUS",t.descriptor.source.file,"The selected block source range does not identify exactly one JSX element.");let a=s[0],c=tI(a.node);if(!c)return nt("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 Qp(n),f=Sj(e,c,d);if(f)return f;if(u.some(y=>(y.alternativeLocators?.length??0)>1))return nt("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 E=hl(n,x.sourceFile);if(E===null||!Ss(x.sourceFile))return nt("INVOCATION_TARGET_NOT_RENDERED",x.sourceFile,"A statically proven call-chain source is missing from the fixed Snapshot map.");let b=Ue(x.sourceFile,E);if(!b.ok)return nt("INVOCATION_PARSE_FAILED",x.sourceFile,b.diagnostic.message);let S=yl(b.module.ast,x.callLocator.sourceRange);if(S.length!==1)return nt("INVOCATION_TARGET_AMBIGUOUS",x.sourceFile,"A call-chain locator does not identify exactly one current JSX element.");let C=u[y+1]?.sourceFile??t.descriptor.source.file,T=u[y+1]?.callLocator.sourceRange??t.rootLocator.sourceRange,R=cr({module:b.module,componentName:x.component,callSourceRange:x.callLocator.sourceRange});if(R.ok){if(R.sourceFile!==C)return nt("INVOCATION_TARGET_NOT_RENDERED",x.sourceFile,"The selected local component does not resolve to the source definition proven by the block graph.");if(R.roots.filter(st=>Yo(st.node,T)).length!==1)return nt("INVOCATION_TARGET_NOT_RENDERED",R.sourceFile,"The local component definition does not select exactly one proven JSX root.");let ue=bv({file_path:x.sourceFile,source:E,target:{kind:"local",local_name:x.component},call_source_range:{start_line:x.callLocator.sourceRange.startLine,start_column:x.callLocator.sourceRange.startColumn}});if(!ue.call||!ue.complete)return{complete:!1,errors:ue.errors.length>0?ue.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:ue.call,invocation:ue,definition:R,entryExport:null});continue}let _=em(b.module.ast,S[0].node.openingElement.name,x.component,x.exportName);if(!_)return nt("INVOCATION_TARGET_NOT_RENDERED",x.sourceFile,"The statically proven component call no longer resolves through one exact import.");let A=tm(x.sourceFile,_.source,n);if(!A)return nt("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 nt(w.missing?"INVOCATION_TARGET_NOT_RENDERED":"INVOCATION_PARSE_FAILED",A,w.message);let D=un({module:w.module,exportName:_.exportName,parsedModules:d});if(!D.ok)return nt("INVOCATION_TARGET_NOT_RENDERED",D.diagnostic.file,D.diagnostic.message);if(D.sourceFile!==C)return nt("INVOCATION_TARGET_NOT_RENDERED",x.sourceFile,"The selected component import does not resolve to the source definition proven by the block graph.");let U=D.roots.filter(Y=>Yo(Y.node,T));if(U.length!==1)return nt("INVOCATION_TARGET_NOT_RENDERED",D.sourceFile,"The unique component export does not select exactly one proven JSX root.");let z=null;if(y===u.length-1&&u.length===1&&!rI(t.ownerFile)&&Yo(U[0].node,t.rootLocator.sourceRange)){let Y=d.read(D.sourceFile);if(!Y.ok)return nt(Y.missing?"INVOCATION_TARGET_NOT_RENDERED":"INVOCATION_PARSE_FAILED",D.sourceFile,Y.message);if(z=eI(Y.module,D.componentName,_.exportName),!z)return nt("INVOCATION_TARGET_AMBIGUOUS",D.sourceFile,"The proven component definition has no unique final export for a Portable entry.")}let V=Ho({file_path:x.sourceFile,source:E,target:{source:_.source,export_name:_.exportName,local_name:_.localName},call_source_range:{start_line:x.callLocator.sourceRange.startLine,start_column:x.callLocator.sourceRange.startColumn}});if(!V.call||!V.complete)return{complete:!1,errors:V.errors.length>0?V.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:V.call,invocation:V,definition:D,entryExport:z})}let g={kind:"page-block",composition:nI(t.composition),blockKey:t.blockKey},p=vj(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 Sj(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=yl(c.ast,s.callLocator.sourceRange);if(l.length!==1)return null;let u=em(c.ast,l[0].node.openingElement.name,s.component,s.exportName);if(!u)return null;let d=tm(s.sourceFile,u.source,o),f=d?n.get(d):void 0;if(!f)return null;let g=un({module:f,exportName:u.exportName,parsedModules:n});if(!g.ok||g.sourceFile!==a.sourceFile)return null;let p=n.get(g.sourceFile);if(!p||eI(p,g.componentName,"default")?.kind!=="default")return null;let m=Np({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(C=>y.filter(T=>Yo(C.node,T.sourceRange)).length===1))return null;for(let C of y){let T=yl(p.ast,C.sourceRange);if(T.length!==1)return null;let R=em(p.ast,T[0].node.openingElement.name,a.component,a.exportName);if(!R)return null;let _=tm(g.sourceFile,R.source,o),A=_?n.get(_):void 0;if(!A)return null;let w=un({module:A,exportName:R.exportName,parsedModules:n});if(!w.ok||w.sourceFile!==r.descriptor.source.file||w.roots.length!==1||!Yo(w.roots[0].node,r.rootLocator.sourceRange))return null}let E=Ho({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(!E.complete||!E.call)return{complete:!1,errors:E.errors};let S=`components/site/portable/${Qv("sha256").update(JSON.stringify(["collection-container",r.composition,r.blockKey,r.sourceHash,ve(p.source)])).digest("hex").slice(0,24)}/page.tsx`;return o.has(S)?nt("INVOCATION_TARGET_AMBIGUOUS",S,"The isolated collection entry collides with a pinned Snapshot source."):{complete:!0,selection:{target:{kind:"page-block",composition:nI(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:[E.call],strategy:"collection-container",collection_container_file:g.sourceFile,entry_file:S,entry_export:{kind:"default"},invocation:E}}}function vj(e,t,n,r,o){let i=n.at(-1);if(i?.kind==="import"){let l=i.definition.roots.length===1&&Yo(i.definition.roots[0].node,e.rootLocator.sourceRange),u=rI(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(!tI(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/${Qv("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!Ss(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 eI(e,t,n){let r=new Set;for(let i of e.ast.program.body){if(Ve.isExportDefaultDeclaration(i)){let s=i.declaration;(Ve.isFunctionDeclaration(s)&&(s.id?.name===t||t==="default")||Ve.isIdentifier(s)&&s.name===t)&&r.add("default");continue}if(!(!Ve.isExportNamedDeclaration(i)||i.exportKind==="type")){if(i.declaration){let s=Ij(i.declaration,t);s&&r.add(s)}if(!i.source)for(let s of i.specifiers)Ve.isExportSpecifier(s)&&s.exportKind!=="type"&&rm(s.local)===t&&r.add(rm(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 Ij(e,t){return Ve.isFunctionDeclaration(e)?e.id?.name===t?t:null:Ve.isVariableDeclaration(e)&&e.declarations.some(n=>Ve.isIdentifier(n.id)&&n.id.name===t)?t:null}function em(e,t,n,r){let o=nm(t);if(!o||o!==n)return null;let i=Ve.isJSXMemberExpression(t)?nm(t.object):Ve.isJSXNamespacedName(t)?t.namespace.name:o,s=Ve.isJSXMemberExpression(t)?t.property.name:null;for(let a of e.program.body)if(Ve.isImportDeclaration(a))for(let c of a.specifiers){if(Ve.isImportDefaultSpecifier(c)&&c.local.name===i)return r==="default"&&!s?{source:a.source.value,exportName:"default",localName:o}:null;if(Ve.isImportSpecifier(c)&&c.local.name===i){let l=rm(c.imported);return l===r&&!s?{source:a.source.value,exportName:l,localName:o}:null}if(Ve.isImportNamespaceSpecifier(c)&&c.local.name===i&&s)return s===r?{source:a.source.value,exportName:s,localName:o}:null}return null}function yl(e,t){let n=[];return bj(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 tI(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 Yo(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 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 tm(e,t,n){let r=t.startsWith("@/")?t.slice(2):t.startsWith("./")||t.startsWith("../")?Zp.posix.normalize(Zp.posix.join(Zp.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=>Ss(i)&&n.has(i))??null}function nm(e){if(Ve.isJSXIdentifier(e))return e.name;if(Ve.isJSXMemberExpression(e)){let t=nm(e.object);return t?`${t}.${e.property.name}`:null}return null}function rm(e){return Ve.isIdentifier(e)?e.name:e.value}function nI(e){return{routeId:e.routeId,...e.effectiveTemplateId!==void 0?{templateId:e.effectiveTemplateId}:{}}}function Ss(e){return xj.safeParse(e).success}function rI(e){return/(?:^|\/)\.vcp\/page-templates\//u.test(e)}function nt(e,t,n){return{complete:!1,errors:[{code:e,path:t,message:n}]}}import{parse as kj}from"@babel/parser";import om from"@babel/traverse";import*as it from"@babel/types";var Rj=typeof om=="function"?om:om.default,Cj=new Set(["slice","map","trim","toString"]);function Nj(e){let t=new Set;try{let n=kj(e,{sourceType:"module",plugins:["jsx","typescript"]});Rj(n,{JSXExpressionContainer(r){let o=r.get("expression");vs(o,new Set)==="url"&&t.add(`${r.node.start}:${r.node.end}`)}})}catch{}return t}function vs(e,t){if(e.isMemberExpression()||e.isOptionalMemberExpression()){let a=vs(e.get("object"),t),c=e.node;return!c.computed&&it.isIdentifier(c.property,{name:"thumbnail"})&&a==="record"?"array":c.computed&&it.isNumericLiteral(c.property)&&Number.isSafeInteger(c.property.value)&&c.property.value>=0&&a==="array"?"item":!c.computed&&it.isIdentifier(c.property,{name:"url"})&&a==="item"?"url":null}if(e.isCallExpression()){let a=e.get("callee");return!a.isMemberExpression()||a.node.computed||!it.isIdentifier(a.node.property,{name:"slice"})||!e.node.arguments.every(c=>it.isNumericLiteral(c)&&Number.isSafeInteger(c.value)&&c.value>=0)?null:vs(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)||!im(n,new Set))return null;let r=new Set(t).add(n);if(n.path.isVariableDeclarator()&&it.isIdentifier(n.path.node.id))return vs(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=>it.isObjectPattern(a)&&a.properties.some(c=>it.isObjectProperty(c)&&!c.computed&&it.isIdentifier(c.key,{name:"record"})&&it.isIdentifier(c.value,{name:"record"}))))return"record";if(!o.isArrowFunctionExpression()||!it.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||!it.isIdentifier(s.node.property,{name:"map"})?null:vs(s.get("object"),r)==="array"?"item":null}function im(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(!it.isIdentifier(o.node.id)||o.node.init!==r.node)return!1;let i=o.scope.getBinding(o.node.id.name);return!!i&&im(i,t)}if(o.isCallExpression()||o.isOptionalCallExpression()){if(!(o.node.callee===r.node&&(r.isMemberExpression()||r.isOptionalMemberExpression())&&!r.node.computed&&it.isIdentifier(r.node.property)&&Cj.has(r.node.property.name)))return!1;if((r.isMemberExpression()||r.isOptionalMemberExpression())&&it.isIdentifier(r.node.property,{name:"map"})){let s=o.get("arguments.0");if(!s?.isArrowFunctionExpression()||!it.isIdentifier(s.node.params[0]))return!1;let a=s.scope.getBinding(s.node.params[0].name);if(!a||!im(a,t))return!1}return!0}return r!==n}):!1)}import{createHash as Pj}from"node:crypto";import _j from"@babel/traverse";import*as Fe from"@babel/types";var sm=_j,Aj=typeof sm=="function"?sm:sm.default,Tj=new Set(["avif","bmp","gif","jpeg","jpg","mp3","mp4","ogg","png","svg","wav","webm","webp"]),Zo=new Set(["backgroundimage","image","imageurl","media","mediaurl","poster","src","srcset","thumbnail","thumbnailurl"]),wj=/(?:asset|avatar|gallery|image|media|photo|poster|thumbnail|video)/iu,Oj=/^(?:audio|img|image|picture|safeimage|source|video|media|.*(?:audio|image|video))$/iu;function Fj(e){let t=Ue(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=iI(c.node),u=Vj(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:Uj(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=iI(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})};Aj(t.module.ast,{ImportDeclaration(c){let l=c.node.source.value;Lj(l)&&i({node:c.node.source,kind:"import",source:"import",value:l,complete:!0})},JSXOpeningElement(c){let l=sI(c.node.name),u=Oj.test(l);for(let d of c.node.attributes){if(Fe.isJSXSpreadAttribute(d)){u&&i({node:d.argument,kind:"object",source:"jsx-attribute",value:null,complete:!1});continue}let f=Mj(d);if(!f||!Dj(f,u))continue;let g=Pr(d.value);i({node:d.value??d,kind:oI(f),source:"jsx-attribute",value:g.value,complete:g.complete})}},ObjectProperty(c){let l=El(c.node.key);if(!l||!Zo.has(l)&&!($j(c)&&aI(l))||Zo.has(l)&&xl(c.node.value)&&bl(c.node.value))return;let u=Pr(c.node.value);i({node:c.node.value,kind:oI(l),source:"object-property",value:u.value,complete:u.complete})},ArrayExpression(c){if(jj(c))for(let l of c.node.elements){if(!l||xl(l)&&bl(l))continue;let u=Pr(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(!Fe.isIdentifier(l,{name:"mediaAsset"})||c.node.arguments.length!==1)return;let u=c.node.arguments[0];if(!Fe.isExpression(u)){s(c.node,null);return}let d=Pr(u);s(c.node,d.complete?d.value:null)},MemberExpression(c){if(!Bj(c.node.object))return;let l=c.node.computed?Pr(c.node.property):Fe.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=Kj(r).sort(Jj);return{complete:a.length===0,references:n.map((c,l)=>({...c,occurrence:l})),errors:a}}function Lj(e){let n=(e.split(/[?#]/u,1)[0]??"").split(".").pop()?.toLowerCase();return n!==void 0&&Tj.has(n)}function Dj(e,t){return e!=="src"||t?Zo.has(e):!1}function oI(e){return e==="srcset"?"srcset":e==="poster"?"poster":e.startsWith("thumbnail")?"thumbnail":e==="src"?"src":"object"}function Mj(e){return Fe.isJSXIdentifier(e.name)?e.name.name.toLowerCase():Fe.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`.toLowerCase():null}function sI(e){return Fe.isJSXIdentifier(e)?e.name:Fe.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:`${sI(e.object)}.${e.property.name}`}function El(e){return Fe.isIdentifier(e)?e.name.toLowerCase():Fe.isStringLiteral(e)?e.value.toLowerCase():null}function Bj(e){return Fe.isIdentifier(e,{name:"mediaAssets"})}function jj(e){let t=e.parentPath;if(t?.isObjectProperty()){let n=El(t.node.key);return n!==null&&Zo.has(n)}return t?.isVariableDeclarator()&&Fe.isIdentifier(t.node.id)?wj.test(t.node.id.name):!1}function $j(e){let n=e.parentPath?.parentPath;if(!n?.isObjectProperty())return!1;let r=El(n.node.key);return r!==null&&Zo.has(r)}function aI(e){return e==="src"||e==="srcset"||e==="url"||e==="thumbnail_url"}function xl(e){return Fe.isObjectExpression(e)||Fe.isArrayExpression(e)}function bl(e){if(Fe.isArrayExpression(e))return e.elements.some(n=>n!==null&&(xl(n)?bl(n):!0));let t=!1;for(let n of e.properties){if(!Fe.isObjectProperty(n))return!1;let r=El(n.key);if(r!==null&&(Zo.has(r)||aI(r))){t=!0;continue}xl(n.value)&&bl(n.value)&&(t=!0)}return t}function Pr(e){return e?Fe.isStringLiteral(e)?{value:e.value,complete:!0}:Fe.isJSXExpressionContainer(e)?Pr(e.expression):Fe.isTemplateLiteral(e)&&e.expressions.length===0?{value:e.quasis.map(t=>t.value.cooked??t.value.raw).join(""),complete:!0}:Fe.isTSAsExpression(e)||Fe.isTSTypeAssertion(e)||Fe.isParenthesizedExpression(e)?Pr(e.expression):{value:null,complete:!1}:{value:null,complete:!1}}function iI(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 Vj(e,t){return e.slice(t.start_offset,t.end_offset)}function Uj(e){return`sha256:${Pj("sha256").update(e).digest("hex")}`}function Kj(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)}export{he as FileHistoryStoreError,Bi as PageTemplateManagedSourceError,qc as PreviewFileSystemSiteEditEngineRuntime,Bh as SITE_EDIT_RAW_COLOR_LITERAL_RE,Yc as SnapshotSiteEditEngineRuntime,TM as analyzePortableCollectionInvocation,Ho as analyzePortableInvocation,Pp as analyzePortableRelatedEntries,Hu as auditGeneratedCode,VD as auditPortableDependencies,Di as buildPageBlockIndex,ur as buildPortableInvocation,QB as buildPortableMaterializationPlan,gs as buildPortableSourceClosure,ni as checkComponentI18nHostCompatibility,Qc as classifyPortableDependencyOwnership,sx as computeManagedPageTemplatePaths,FD as createPreviewSiteEditEngineRuntime,AD as createSiteEditEngineRuntime,rx as decodePageTemplateKey,Np as discoverPortableCollectionSourceRelation,Md as encodePageTemplateId,hB as extractPortableBlockEntry,GI as instrumentSiteEditRuntimeAttributes,ax as isManagedPageTemplateSourcePath,D_ as normalizePortableBlockMetadata,YM as normalizePortableSource,oh as openFileHistoryStore,OI as parseSourceModule,oj as planPortableBlockPatch,md as planPortableRouteCompositionPatch,Pi as planRouteCompositionRewrite,Nj as provenRecordThumbnailRanges,FI as resolveImportBase,IT as resolveManagedPageTemplateComposition,Xa as resolvePageBlockBoundary,mj as resolvePageBlockFromSnapshot,Ro as resolvePageBlockTarget,dn as resolvePageCompositionProjection,Ej as resolvePortableBlockSelection,DD as resolvePortableDependencyOwnership,GD as resolvePortableSourcePath,Ga as scanManagedPageTemplateCandidates,Fj as scanPortableMediaReferences,Ya as scanSiteEditCompositionsFromFiles,Ju as scanSiteEditThemeStyleViolations,AM as selectPortablePageUnitInvocation};
|