@vcp-dev/site-edit-engine 0.10.42 → 0.10.43
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.js +8 -8
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
import*as fy from"@babel/parser";import*as Ge from"@babel/types";import*as tn from"node:path";var Bs=[".tsx",".ts",".jsx",".js"],py=Bs.map(e=>`/index${e}`),my=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 au(e){let t=e.replace(/[?#].*$/,""),n=/\.([a-z0-9]+)$/i.exec(t);return n!==null&&my.has(n[1].toLowerCase())}function cu(e){let t=[];for(let n of e.program.body)Ge.isImportDeclaration(n)&&typeof n.source.value=="string"&&Nt(n.source.value)&&t.push(n.source.value),Ge.isExportNamedDeclaration(n)&&n.source&&typeof n.source.value=="string"&&Nt(n.source.value)&&t.push(n.source.value),Ge.isExportAllDeclaration(n)&&typeof n.source.value=="string"&&Nt(n.source.value)&&t.push(n.source.value);return Ge.traverseFast(e.program,n=>{let r=Ge.isImportExpression(n)?n.source:Ge.isCallExpression(n)&&Ge.isImport(n.callee)?n.arguments[0]:null;Ge.isStringLiteral(r)&&Nt(r.value)&&t.push(r.value)}),t}function Nt(e){return e.startsWith("./")||e.startsWith("../")||e.startsWith("@/")}function bn(e,t){if(t.startsWith("@/"))return t.slice(2).replace(/\\/g,"/");let n=tn.dirname(e);return tn.join(n,t).replace(/\\/g,"/")}async function gy(e,t){if(Bs.some(n=>e.endsWith(n))&&await t(e))return e;for(let n of Bs){let r=`${e}${n}`;if(await t(r))return r}for(let n of py){let r=`${e}${n}`;if(await t(r))return r}return null}async function Sn(e,t,n){let r=await Oo(e,t,n);return r.ok?r.path:null}async function Oo(e,t,n){let r=bn(e,t);try{if(!hy(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 gy(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 hy(e,t,n){if(!Nt(t)||t.includes("\0")||t.includes("\\")||tn.posix.isAbsolute(n))return!1;let r=tn.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!tn.posix.isAbsolute(e)}import{createHash as xy}from"node:crypto";import*as lu from"@babel/parser";function En(e,t,n,r){return{code:e,message:t,locatorKind:n,details:r}}function J(e,t,n,r,o){return{ok:!1,source:e,diagnostic:En(t,n,r,o)}}function js(e,t,n,r,o){return{ok:!1,source:e,diagnostic:En(t,n,r,o)}}var yy={"tsx-module":["jsx","typescript"],"ts-module":["typescript"],"next-app-entry":["jsx","typescript"]};function Pt(e){let{source:t,profile:n}=e;try{return{ok:!0,ast:lu.parse(t,{sourceType:"module",plugins:yy[n]})}}catch(r){return{ok:!1,source:t,diagnostic:En("parse-failed",`AST parse failed: ${r instanceof Error?r.message:String(r)}`)}}}function $s(e,t){return Pt({source:e,profile:uu(t.kind)})}function kr(e,t){return Pt({source:e,profile:uu(t)})}function uu(e){return"next-app-entry"}function vn(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 Ut=(e,t)=>{let n=Pt({source:t,profile:vn({filePath:e,source:t})});return n.ok?{ok:!0,module:{file:e,source:t,sourceHash:`sha256:${xy("sha256").update(t).digest("hex")}`,ast:n.ast,imports:cu(n.ast).map(r=>({specifier:r}))}}:{ok:!1,diagnostic:{path:e,code:"parse-failed",message:n.diagnostic.message}}};function by(e,t){return Ut(e,t)}function Sy(e,t){return bn(e,t)}import{COMPONENT_I18N_FILE_SUFFIX as Ey,parseComponentI18nResourcesJson as vy,resolveSiteTextDirection as ky,SiteLocaleSchema as Iy}from"@vcp-dev/contracts";var Cy=["i18next","react-i18next"],Ry="components/ui/site-locale-provider.tsx",wy="components/ui/component-i18n-provider.tsx",du="app/layout.tsx";async function Lo(e){let t=e.files.filter(m=>m.path.endsWith(Ey));if(t.length===0)return{ok:!0};for(let m of["package.json",du,Ry,wy])if(!await e.exists(m))return nn(`Target snapshot is missing required i18n host file: ${m}`);let n;try{n=JSON.parse(await e.readFile("package.json"))}catch{return nn("Target snapshot package.json is invalid.")}let r=fu(n)&&fu(n.dependencies)?n.dependencies:{},o=Cy.filter(m=>typeof r[m]!="string"||r[m].trim().length===0);if(o.length>0)return nn(`Target snapshot must already declare: ${o.join(", ")}.`);let i=await e.readFile(du),s=Vs(i,"html","lang"),a=Vs(i,"html","dir"),c=Vs(i,"SiteLocaleProvider","locale"),l=Iy.safeParse(s);if(!l.success||!a||!c||s!==c||a!==ky(l.data))return nn("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 nn("Target snapshot root layout is not wired to SiteLocaleProvider.");let u=l.data;if(e.targetLocale&&e.targetLocale!==u)return nn("Target snapshot locale does not match the authoritative site language.");let f=u.split("-")[0];for(let m of t){let d=vy(m.content);if(!d.success)return nn(`Component i18n resource is invalid: ${m.path}.`);if(!e.deferTargetLocale&&!Object.hasOwn(d.data,u)&&!Object.hasOwn(d.data,f))return nn(`Component i18n resource ${m.path} has no locale for ${u} or ${f}.`)}return{ok:!0}}function Vs(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 fu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function nn(e){return{ok:!1,message:e}}import Us from"@babel/generator";import*as xu from"@babel/parser";import Js from"@babel/traverse";import*as Re from"@babel/types";import{computeSiteEditSourceIdentityKey as Py}from"@vcp-dev/contracts";var pu="data-vcp-ui-component",Do="components/ui";function Jt(e){if(!e)return!1;let t=Ks(e);return t===Do||t.startsWith(`${Do}/`)||t.includes(`/${Do}/`)||t.endsWith(`/${Do}`)}function kn(e,t){return e?e.startsWith("@/")||e.startsWith("~/")?Jt(e.slice(2)):e.startsWith("./")||e.startsWith("../")?Jt(Ks(`${Ny(t)}/${e}`)):Jt(e):!1}function Ks(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 Ny(e){let t=Ks(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}import{stripSiteEditRepeatInstanceKeys as oP}from"@vcp-dev/contracts";import{isSiteEditRuntimeContainerTag as sP,isSiteEditRuntimeTextTag as aP}from"@vcp-dev/contracts/site-edit-runtime-capability";var mu={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 Ay=typeof Us=="function"?Us:Us.default,Ty=typeof Js=="function"?Js:Js.default,Fy=new Set(["base","body","head","html","link","meta","noscript","script","style","template","title"]),_y="suppressHydrationWarning",My=new Set(["SiteEditBootstrap"]);function Oy(e){let t=By(e.file,e.projectRoot);if(!Dy(e.source)||Jt(t))return{code:e.source,elements:[]};let n=e.attributes??mu,r=xu.parse(e.source,{sourceType:"module",plugins:["jsx","typescript"]}),o=[],i=$y(r,t);return Ty(r,{JSXElement(s){let a=s.node.openingElement,c=a.name;if(!Ky(c)||bu(a,n.key))return;let l=Jy(s)??"default",u=zy(s),f=Py(t,l,u),m=jo(c)??"unknown",d=jy(c)?"jsx":"component-call";if(d==="component-call"&&!Xy(s.node.children)&&My.has(m))return;let g=d==="component-call"&&Vy(m,i);Uy(a,n.key,f),g&&gu(a,pu),Ly(s)&&gu(a,_y),o.push({key:f,tag:m,componentName:l,sourceFile:t,sourceKind:d})}}),o.length===0?{code:e.source,elements:o}:{code:Ay(r,{jsescOption:{minimal:!0}}).code,elements:o}}function Ly(e){return!e.findParent(t=>t.isJSXElement())}function Dy(e){return/(?:^|[=(:,?;\[{>&|\n\r]|return\s+)\s*<(?:[A-Za-z][\w.:-]*|>)(?:\s|>|\/)/m.test(e)}function By(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 jy(e){return Re.isJSXIdentifier(e)&&/^[a-z]/.test(e.name)}function jo(e){return Re.isJSXIdentifier(e)?e.name:Re.isJSXMemberExpression(e)?Eu(e):null}function $y(e,t){let n=new Set;for(let r of e.program.body)if(!(!Re.isImportDeclaration(r)||!kn(r.source.value,t)))for(let o of r.specifiers)n.add(o.local.name);return n}function Vy(e,t){let n=e.split(".")[0]??e;return t.has(n)}function Ky(e){let t=jo(e);return!t||t==="Fragment"||t.endsWith(".Fragment")?!1:!Fy.has(t)}function bu(e,t){return e.attributes.some(n=>Re.isJSXAttribute(n)&&Re.isJSXIdentifier(n.name,{name:t}))}function Uy(e,t,n){Su(e,Re.jsxAttribute(Re.jsxIdentifier(t),Re.stringLiteral(n)))}function gu(e,t){bu(e,t)||Su(e,Re.jsxAttribute(Re.jsxIdentifier(t),null))}function Su(e,t){let n=e.attributes.findIndex(r=>Re.isJSXSpreadAttribute(r));if(n>=0){e.attributes.splice(n,0,t);return}e.attributes.push(t)}function Eu(e){return`${Re.isJSXIdentifier(e.object)?e.object.name:Eu(e.object)}.${e.property.name}`}function Jy(e){let t=e;for(;t;){if(t.isFunctionDeclaration()||t.isClassDeclaration())return t.node.id?.name??null;if(t.isVariableDeclarator()&&Re.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 Xy(e){return e.some(t=>Re.isJSXElement(t)||Re.isJSXFragment(t))}var hu=new WeakMap,Bo=new WeakMap,Xs=new WeakMap;function zy(e){let t=hu.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=Wy(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return hu.set(e.node,o),o}function Wy(e){let t=jo(e.node.openingElement.name);return!t||t==="Fragment"||t.endsWith(".Fragment")?null:/^[A-Z]/.test(t)?`component:${t}#${yu(e,t)}`:`${t}#${yu(e,t)}`}function yu(e,t){let n=vu(e)??e.getFunctionParent();if(!n)return 0;let r=Xs.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=Xs.get(n.node);o||(o=new Map,Xs.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()?$o(n):Hy(n);for(let c of a)if(jo(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 Hy(e){let t=Bo.get(e.node);if(t)return t;let n=[];return e.traverse({JSXElement(r){r.getFunctionParent()?.node===e.node&&!vu(r)&&n.push(r)}}),Bo.set(e.node,n),n}function vu(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 $o(e){let t=Bo.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(...$o(o));continue}o.isJSXExpressionContainer()&&n.push(...In(o.get("expression")))}return Bo.set(e.node,n),n}function In(e){if(e.isJSXElement())return[e];if(e.isJSXFragment())return $o(e);if(e.isParenthesizedExpression())return In(e.get("expression"));if(e.isLogicalExpression()&&e.node.operator==="&&")return In(e.get("right"));if(e.isConditionalExpression())return[...In(e.get("consequent")),...In(e.get("alternate"))];if(e.isCallExpression()&&Yy(e.node)){let t=e.get("arguments")[0];return Gy(t)}return[]}function Gy(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return[t];if(t.isJSXFragment())return $o(t);if(t.isParenthesizedExpression())return In(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?In(r):[]}return[]}function Yy(e){return Re.isMemberExpression(e.callee)&&Re.isIdentifier(e.callee.property)&&e.callee.property.name==="map"}import{SiteEditOperationRequestSchema as MN,SiteEditPatchPlanSchema as ON}from"@vcp-dev/contracts";function Cn(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 Vo(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 Ko(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}:{}})),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 Uo(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:Zy(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 Jo(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:Cn(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 Zy(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 Jw,computeSiteEditCompositionKey as Xw,getSiteEditSourceDeleteProtectionReason as zw,isSiteEditTextSourcePath as Ww,parseSiteEditRepeatInstanceKey as Hw,SITE_EDIT_SOURCE_DELETE_CAPABILITY as Gw,stripSiteEditRepeatInstanceKeys as it}from"@vcp-dev/contracts";import Is from"node:path";import{parse as Yw}from"yaml";import Ys from"node:path";import{TextDecoder as qy}from"node:util";import{SITE_EDIT_SOURCE_ALLOWED_APP_FILES as Iu,SITE_EDIT_SOURCE_ALLOWED_DIRS as Cu,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as Ru,SiteEditCompositionContextSchema as ex,SiteEditSourceFileResponseSchema as zs,SiteEditSourceLocationSchema as tx,SiteEditSourcePathSchema as Xo,SiteEditSourceTreeResponseSchema as nx,isSiteEditTextSourcePath as rx}from"@vcp-dev/contracts";import{createHash as Qy}from"node:crypto";var Ir=class{constructor(t){this.original=new Map,this.files=new Map,this.versions=new Map;for(let n of t)this.original.set(n.path,n.content),this.files.set(n.path,n.content),this.versions.set(n.path,n.version??1)}async readFile(t){let n=this.files.get(t);if(n===void 0)throw new Error(`Snapshot file not found: ${t}`);return n}async readFileBytes(t){return Buffer.from(await this.readFile(t),"utf8")}async getFileInfo(t){let n=this.files.get(t);return n===void 0?null:{path:t,sizeBytes:Buffer.byteLength(n,"utf8")}}async writeFile(t,n){this.files.set(t,n)}async createExclusive(t,n){if(this.files.has(t))throw Object.assign(new Error(`Snapshot file already exists: ${t}`),{code:"EEXIST"});this.files.set(t,n)}async deleteFile(t){this.files.delete(t)}async exists(t){return this.files.has(t)}async listFiles(t={}){let n=t.roots??[],r=[...this.files.keys()].filter(a=>n.length===0?!0:n.some(c=>a===c||a.startsWith(`${c}/`))),o=[],i=new Set,s=0;for(let a of r.sort()){let c=Buffer.byteLength(this.files.get(a)??"","utf8"),l=a.split("/").length;if(t.maxDepth!==void 0&&l>t.maxDepth){i.add("max-depth");continue}if(t.maxFiles!==void 0&&o.length>=t.maxFiles){i.add("max-files");break}if(t.maxTotalBytes!==void 0&&s+c>t.maxTotalBytes){i.add("max-total-bytes");break}o.push({path:a,sizeBytes:c}),s+=c}return i.size>0?{files:o,truncated:{reasons:[...i]}}:{files:o}}getVersion(t){return this.versions.get(t)??0}bumpVersion(t){let n=this.getVersion(t)+1;return this.versions.set(t,n),n}getChangedFiles(){let t=new Set([...this.original.keys(),...this.files.keys()]),n=[];for(let r of[...t].sort()){let o=this.original.get(r),i=this.files.get(r);o!==i&&n.push({path:r,before:o,after:i})}return n}};function ke(e){return`sha256:${Qy("sha256").update(e).digest("hex")}`}var ox=[...Ru,...Iu,...Cu];function Zs(e){if(!e.composition)throw new Error("Composition unavailable for source access policy.");return ex.parse(e.composition)}var Ws=2e3,Hs=12,Gs=24*1024*1024,ku=512*1024,ix=new Set(["image/avif","image/gif","image/jpeg","image/png","image/webp","image/x-icon"]),sx={".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"},ax={".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"},cx=new qy("utf-8",{fatal:!0});async function zo(e,t={}){let n=Zs(t),{files:r,truncated:o}=await gx(e,t),i=xx(r.map(s=>s.metadata));return nx.parse({composition:n,nodes:i,defaultPath:bx(r.map(s=>s.metadata)),totalFiles:r.length,...o?{truncated:o}:{}})}async function Wo(e,t,n={}){let r=Zs(n),o=Xo.parse(t.path),i=await ux(e,o,n);if(!i)throw new Error(`Source file not found: ${o}`);if(qs(o)){let a=Pu(o),c=await fx(e,{path:o,sizeBytes:i.sizeBytes,mimeType:a});return zs.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:i.sizeBytes,mimeType:a,readonly:!0,...c})}let s=await Qs(e,o);return s.ok?zs.parse({composition:r,path:o,kind:"text",language:Au(o),sizeBytes:s.sizeBytes,contentHash:ke(s.content),readonly:!1,content:s.content}):zs.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:s.sizeBytes,mimeType:"application/octet-stream",readonly:!0,previewUnavailableReason:"unsupported-mime"})}async function Qs(e,t){if(e.readFileBytes){let o=await e.readFileBytes(t),i=lx(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 lx(e){if(e.includes(0))return null;try{return cx.decode(e)}catch{return null}}async function ux(e,t,n){if(!px(t,n))return null;let r=await dx(e,t);return r?{path:t,sizeBytes:r.sizeBytes}:null}async function dx(e,t){if(e.getFileInfo)return e.getFileInfo(t);if(e.listFiles){let o=wu(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(qs(t))return{path:t,sizeBytes:0};let n=await e.readFile(t);return{path:t,sizeBytes:Buffer.byteLength(n,"utf8")}}async function fx(e,t){if(!ix.has(t.mimeType))return{previewUnavailableReason:"unsupported-mime"};if(t.sizeBytes>ku)return{previewUnavailableReason:"too-large"};if(!e.readFileBytes)return{previewUnavailableReason:"bytes-unavailable"};let n=await e.readFileBytes(t.path);return n.byteLength>ku?{previewUnavailableReason:"too-large"}:{contentBase64:Buffer.from(n).toString("base64")}}function px(e,t){return Ru.some(n=>n===e)||Iu.some(n=>n===e)||Cu.some(n=>e===n||e.startsWith(`${n}/`))?!0:!e.startsWith("app/")&&!e.startsWith("src/app/")?!1:(t.routeEntryFiles??[]).some(n=>{let r=Xo.safeParse(n);return r.success&&r.data===e})}function Ho(e,t){if(!t.sourceLocator)throw new Error(`Source location not available for key: ${e.key}`);return tx.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 wu(e){return Array.isArray(e)?{files:e}:e}function mx(e){return["max-files","max-depth","max-total-bytes"].filter(n=>e.includes(n))}async function gx(e,t){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let n=wu(await e.listFiles({roots:hx(t),maxFiles:Ws+1,maxDepth:Hs,maxTotalBytes:Gs+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=Xo.safeParse(a.path);if(!c.success)continue;let l=c.data;if(l.split("/").length>Hs){o.add("max-depth");continue}if(r.size>=Ws){o.add("max-files");break}if(i+a.sizeBytes>Gs){o.add("max-total-bytes");break}r.set(l,{path:l,sizeBytes:a.sizeBytes,metadata:yx(l,a.sizeBytes,Zs(t))}),i+=a.sizeBytes}return{files:[...r.values()].sort((a,c)=>a.path.localeCompare(c.path)),...o.size>0?{truncated:{reasons:mx([...o]),maxFiles:Ws,maxDepth:Hs,maxTotalBytes:Gs}}:{}}}function hx(e){let t=new Set(ox);for(let n of e.routeEntryFiles??[]){let r=Xo.safeParse(n);r.success&&(r.data.startsWith("app/")||r.data.startsWith("src/app/"))&&t.add(r.data)}return[...t]}function yx(e,t,n){return qs(e)?{composition:n,path:e,kind:"binary",language:null,sizeBytes:t,mimeType:Pu(e),readonly:!0}:{composition:n,path:e,kind:"text",language:Au(e),sizeBytes:t,readonly:!1}}function xx(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 Nu(t)}function Nu(e){return e.map(t=>t.kind==="directory"?{...t,children:Nu(t.children)}:t).sort((t,n)=>t.kind!==n.kind?t.kind==="directory"?-1:1:t.name.localeCompare(n.name))}function bx(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 qs(e){return!rx(e)}function Pu(e){let t=Ys.posix.extname(e).toLowerCase();return!t&&Ys.posix.basename(e).toLowerCase()==="favicon"?"image/x-icon":sx[t]??"application/octet-stream"}function Au(e){let t=Ys.posix.extname(e).toLowerCase();return ax[t]??"plaintext"}import ea from"@babel/traverse";import*as At from"@babel/types";function Me(e){if(e.isJSXFragment())return!0;if(!e.isJSXElement())return!1;let t=e.node.openingElement.name;if(At.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(At.isIdentifier(s)&&s.name==="Fragment"||At.isStringLiteral(s)&&s.value==="Fragment")&&Tu(i.parentPath)}if(!At.isJSXMemberExpression(t)||!At.isJSXIdentifier(t.property)||t.property.name!=="Fragment"||!At.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())&&Tu(r.parentPath)}function Tu(e){return e?.isImportDeclaration()===!0&&e.node.source.value==="react"}var rn=typeof ea=="function"?ea:ea.default,Go=new WeakMap,Yo=new WeakMap;function Tt(e,t){let n=$s(e,t);if(!n.ok)return js(e,n.diagnostic.code,n.diagnostic.message,t.kind);let r=se(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}}:js(e,r.diagnostic.code,r.diagnostic.message,t.kind,r.diagnostic.details)}function se(e,t){return t.kind==="jsx-node"?Ou(e,t):t.kind==="jsx-attribute"?Cx(e,t):t.kind==="value"?Rx(e,t):t.kind==="expression"?wx(e,t):t.kind==="directive"?Nx(e,t):t.kind==="export"?Px(e,t):{ok:!1,diagnostic:En("unsupported-syntax",`Unsupported locator kind: ${t.kind}`)}}function Ou(e,t){return t.strategy==="source-range"?Sx(e,t):Ex(e,t)}function Sx(e,t){let n=null;if(rn(e,{JSXElement(o){if(!Rn(o.node,t.sourceRange))return;let i=De("jsx-node",o);if(i){if(!n){n=i;return}i.end-i.start<n.end-n.start&&(n=i)}},JSXFragment(o){if(!Rn(o.node,t.sourceRange))return;let i=De("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXExpressionContainer(o){if(!Rn(o.node,t.sourceRange))return;let i=De("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXText(o){if(!Rn(o.node,t.sourceRange))return;let i=De("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)}}),!n)return Be("jsx-node","locator-miss","JSX node not found for source-range locator");let r=n;return t.expectedIdentity&&!Vx(r.path,t.expectedIdentity)?Be("jsx-node","locator-miss","JSX node failed expected identity validation"):{ok:!0,match:r}}function Ex(e,t){if(t.structuralPath===""){let r=kx(e,t.component);if(r){let o=Ix(r);if(o)return o}}let n=null;return rn(e,{JSXElement(r){if(Rr(r)!==t.component||na(r)!==t.structuralPath)return;let i=De("jsx-node",r);i&&(n=i,r.stop())},JSXFragment(r){if(Rr(r)!==t.component||na(r)!==t.structuralPath)return;let i=De("jsx-node",r);i&&(n=i,r.stop())}}),!n&&t.expectedRange&&(n=vx(e,t.component,t.expectedRange)),n?{ok:!0,match:n}:Be("jsx-node","locator-miss","JSX node not found for structural-path locator")}function vx(e,t,n){let r=null;return rn(e,{JSXElement(o){if(Rr(o)!==t||!Rn(o.node,n))return;let i=De("jsx-node",o);i&&(r=i,o.stop())},JSXFragment(o){if(Rr(o)!==t||!Rn(o.node,n))return;let i=De("jsx-node",o);i&&(r=i,o.stop())}}),r}function kx(e,t){let n=null;return rn(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 Ix(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 Be("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}return null}return(t.isParenthesizedExpression()?t.get("expression"):t).isJSXFragment()?Be("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 Be("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}}}return null}function Cx(e,t){let n=Ou(e,t.element);if(!n.ok)return n;let s=n.match.path.get("openingElement").get("attributes").find(c=>Kx(c,t.name));if(!s||!s.isJSXAttribute())return Be("jsx-attribute","locator-miss",`JSX attribute '${t.name}' not found`);let a=De("jsx-attribute",s);return a?{ok:!0,match:a}:Be("jsx-attribute","locator-miss",`JSX attribute '${t.name}' has no source range`)}function Rx(e,t){let n=Ax(e,t);if(!n.ok)return n;let r=Tx(n.match.path,t.path??[]);return r.ok?t.expectedRange&&!zt(r.match.path.node.loc,t.expectedRange)?Be("value","locator-miss","Resolved value does not match expected range"):{ok:!0,match:r.match}:r}function wx(e,t){let n=null;return rn(e,{Identifier(r){if(!Dx(r))return;let o=_u(r);if(!o||!Mu(o,t))return;let i=De("expression",r);i&&(t.expectedRange&&!zt(r.node.loc,t.expectedRange)||(n=i,r.stop()))},MemberExpression(r){let o=_u(r);if(!o||!Mu(o,t))return;let i=De("expression",r);i&&(t.expectedRange&&!zt(r.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:Be("expression","locator-miss","Expression not found")}function Nx(e,t){let n=null;return rn(e,{Program(r){let i=r.get("directives").find(a=>a.node.value.value===t.value);if(!i||t.expectedRange&&!zt(i.node.loc,t.expectedRange))return;let s=De("directive",i);s&&(n=s,r.stop())}}),n?{ok:!0,match:n}:Be("directive","locator-miss",`Directive '${t.value}' not found`)}function Px(e,t){let n=null;return rn(e,{ExportNamedDeclaration(r){if(t.exportKind==="generate-metadata"){let c=r.get("declaration");if(c.isFunctionDeclaration()&&c.node.id?.name==="generateMetadata"){let m=De("export",c);if(!m||t.expectedRange&&!zt(c.node.loc,t.expectedRange))return;n=m,r.stop();return}if(!c.isVariableDeclaration())return;let l=ra(c,"generateMetadata");if(!l||!l.isVariableDeclarator())return;let u=l.get("init");if(!u.node)return;let f=De("export",u);if(!f||t.expectedRange&&!zt(u.node.loc,t.expectedRange))return;n=f,r.stop();return}let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=ra(o,t.exportKind==="named"?t.name:"metadata");if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node||t.expectedRange&&!zt(s.node.loc,t.expectedRange))return;let a=De("export",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(t.exportKind!=="default")return;let o=r.get("declaration"),i=De("export",o);i&&(t.expectedRange&&!zt(o.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:Be("export","export-not-found",`Export '${$x(t)}' not found`)}function Ax(e,t){let n=null;return rn(e,{Expression(r){if(n||t.root.kind!=="expression"||!Rn(r.node,t.root.sourceRange))return;let o=De("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 d=r.get("init");if(!d.node)return;let g=De("value",d);if(!g)return;n=g,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(d=>d?.type==="Identifier"&&d.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,f=r.get(`init.arguments.${u}`);if(!f||Array.isArray(f)||!f.node)return;let m=De("value",f);m&&(n=m,r.stop())},ExportNamedDeclaration(r){if(n||t.root.kind!=="named-export")return;let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=ra(o,t.root.name);if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node)return;let a=De("value",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(n||t.root.kind!=="default-export")return;let o=r.get("declaration"),i=De("value",o);i&&(n=i,r.stop())}}),n?{ok:!0,match:n}:Be("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 Tx(e,t){let n=ta(e);for(let o of t){if(n=ta(n),o.kind==="property"){if(!n.isObjectExpression())return Be("value","unsupported-syntax","Property path requires object expression");let a=n.get("properties");if(a.some(l=>!l.isObjectProperty()))return Be("value","unsupported-syntax","Spread properties are not supported");let c=a.find(l=>Ux(l,o.name));if(!c||!c.isObjectProperty())return Be("value","property-not-found",`Property '${o.name}' not found`);n=c.get("value");continue}if(!n.isArrayExpression())return Be("value","unsupported-syntax","Array index path requires array expression");let i=n.get("elements");if(i.some(a=>a.node?.type==="SpreadElement"))return Be("value","unsupported-syntax","Spread array elements are not supported");let s=i[o.index];if(!s?.node)return Be("value","array-index-out-of-range",`Array index ${o.index} is out of range`);n=s}n=ta(n);let r=De("value",n);return r?{ok:!0,match:r}:Be("value","locator-miss","Resolved value has no source range")}function ta(e){let t=e;for(;t.isTSAsExpression()||t.isTSSatisfiesExpression()||t.isTSNonNullExpression();)t=t.get("expression");return t}function De(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 Rn(e,t){return zt(e.loc,t)}function zt(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 na(e){let t=[],n=e,r=e.node;for(;n;){if(n.isJSXElement()){if(!Me(n)){let o=Du(n.node.openingElement);o&&(/^[A-Z]/.test(o)?t.unshift(`component:${o}#${Fu(n,o)}`):t.unshift(`${o}#${Fu(n,o)}`))}}else n.isJSXFragment()&&n.node===r&&t.unshift("fragment");if(!n.parentPath||Ox(n.parentPath)&&!Lx(n.parentPath))break;n=n.parentPath}return t.join("/")}function Fu(e,t){let n=Lu(e)??e.getFunctionParent();if(!n)return 0;let r=Go.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=0,i=Go.get(n.node)?.get(t);if(!i){let a=Go.get(n.node);a||(a=new Map,Go.set(n.node,a)),i=new WeakMap,a.set(t,i)}let s=n.isJSXElement()||n.isJSXFragment()?Cr(n):Fx(n);for(let a of s)if(Du(a.node.openingElement)===t){if(i.set(a.node,o),a.node===e.node)return o;o++}return i.get(e.node)??0}function Fx(e){let t=Yo.get(e.node);if(t)return t;let n=[];return e.traverse({JSXElement(r){r.getFunctionParent()?.node===e.node&&!Lu(r)&&n.push(r)}}),Yo.set(e.node,n),n}function Lu(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(Me(t)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function Cr(e){let t=Yo.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(Me(o)){n.push(...Cr(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...Cr(o));continue}o.isJSXExpressionContainer()&&n.push(...Xt(o.get("expression")))}return Yo.set(e.node,n),n}function Xt(e){if(e.isJSXElement())return Me(e)?Cr(e):[e];if(e.isJSXFragment())return Cr(e);if(e.isParenthesizedExpression())return Xt(e.get("expression"));if(e.isLogicalExpression()&&_x(e.node.operator))return Xt(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(...Xt(c))}if(s.isReturnStatement()){let a=s.get("argument");a.isExpression()&&i.push(...Xt(a));break}}return i}else if(o.node&&o.isExpression())return Xt(o)}}}}return e.isConditionalExpression()?[...Xt(e.get("consequent")),...Xt(e.get("alternate"))]:e.isArrayExpression()?e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:Xt(t)):[]}function _x(e){return e==="&&"||e==="||"||e==="??"}function Du(e){return e.name.type==="JSXIdentifier"?e.name.name:e.name.type==="JSXMemberExpression"?Mx(e.name):null}function Mx(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 Rr(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 Ox(e){return!!(e.isFunctionDeclaration()||e.isFunctionExpression()||e.isArrowFunctionExpression())}function Lx(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 Dx(e){return!(!e.isExpression()||e.parentPath?.isMemberExpression({property:e.node}))}function _u(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 Mu(e,t){return e.base===t.base&&Bx(e.path,t.path??[])}function Bx(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 jx(e){return e.key.type==="Identifier"?e.key.name:e.key.type==="StringLiteral"?e.key.value:null}function $x(e){return e.exportKind==="named"?e.name:e.exportKind}function Be(e,t,n,r){return{ok:!1,diagnostic:En(t,n,e,r)}}function Vx(e,t){return Rr(e)!==t.component?!1:na(e)===t.structuralPath}function Kx(e,t){return!e.isJSXAttribute()||e.node.name.type!=="JSXIdentifier"?!1:e.node.name.name===t}function ra(e,t){return e.get("declarations").find(n=>!n.isVariableDeclarator()||n.node.id.type!=="Identifier"?!1:n.node.id.name===t)}function Ux(e,t){return e.isObjectProperty()?jx(e.node)===t:!1}import*as ju from"@babel/parser";import{arrayExpression as Hx,booleanLiteral as Gx,identifier as Yx,jsxAttribute as Zx,jsxExpressionContainer as Qx,jsxIdentifier as qx,nullLiteral as eb,numericLiteral as tb,objectExpression as nb,objectProperty as rb,stringLiteral as ia}from"@babel/types";import oa from"@babel/generator";var Jx=typeof oa=="function"?oa:oa.default;function Xx(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 Zo(e){let{ast:t,source:n}=e;try{let r=Xx(n),i=Jx(t,{comments:!0,jsescOption:{minimal:!0,quotes:"single"}},n).code;return r!=="2"&&(i=Wx(i,r)),{ok:!0,source:i}}catch(r){return J(n,"printer-failed",`AST print failed: ${r instanceof Error?r.message:String(r)}`)}}function Bu(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 wr(e,t,n){return{ok:!0,source:t,operation:{type:n.kind,nodeId:n.target,kind:n.kind,target:n.target,beforeSourceHash:Bu(e),afterSourceHash:Bu(t),inverse:n.inverse}}}function he(e,t,n){let r=Zo({ast:e,source:t});return r.ok?wr(t,r.source,n):r}function we(e,t){let n=kr(e,t);return n.ok?{ok:!0,ast:n.ast}:{ok:!1,result:{ok:!1,source:e,diagnostic:n.diagnostic}}}function Qo(e,t){return Zo({ast:e,source:t})}function ob(e,t,n){let r=se(e,t);return r.ok?{ok:!0,match:r.match}:{ok:!1,result:{ok:!1,source:n,diagnostic:r.diagnostic}}}function Wn(e,t,n){let r=ob(e,t,n);return r.ok?r.match.path.isJSXElement()?r:{ok:!1,result:J(n,"unsupported-syntax","JSX locator must resolve to JSXElement","jsx-node")}:r}function on(e){return typeof e=="string"?ia(e):typeof e=="number"?tb(e):typeof e=="boolean"?Gx(e):e===null?eb():Array.isArray(e)?Hx(e.map(t=>on(t))):nb(Object.entries(e).map(([t,n])=>{let r=rb(sa(t),on(n));return t==="__proto__"&&(r.computed=!0),r}))}function ib(e){return typeof e=="string"?ia(e):Qx(on(e))}function Nr(e,t){return Zx(qx(e),ib(t))}function qo(e,t){try{let r=ju.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:J(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:J(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function sa(e){return/^[$A-Z_][0-9A-Z_$]*$/i.test(e)?Yx(e):ia(e)}function ei(e){let{source:t,locator:n,segmentIndex:r,newText:o}=e,i=we(t,"jsx-node");if(!i.ok)return i.result;let s=se(i.ast,n);if(!s.ok)return{ok:!1,source:t,diagnostic:s.diagnostic};let c=sb(s.match.path)[r];if(!c)return J(t,"locator-miss",`Text segment ${r} not found`,"jsx-node");switch(c.kind){case"jsx-text":c.path.node.value=ab(c.path.node.value,o);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,c.path.node.quasis[l].value.cooked=o;break}}return he(i.ast,t,{kind:"update-text",target:"jsx-node",inverse:"restore-text"})}function sb(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=cb(r.get("expression"));o.length>0&&t.push(...o)}}return t}function ab(e,t){let n=e.match(/^\s*/)?.[0]??"",r=e.match(/\s*$/)?.[0]??"";return`${n}${t.trim()}${r}`}function cb(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&&t.push({kind:"template-literal",path:e,quasiIndex:r});if(t.length>0)return t}return e.isCallExpression()?[]:[]}import{nullLiteral as aa}from"@babel/types";function Hn(e){let{source:t,locator:n}=e,r=we(t,"jsx-node");if(!r.ok)return r.result;let o=se(r.ast,n);return o.ok?(lb(o.match.path),he(r.ast,t,{kind:"remove-node",target:"jsx-node",inverse:"insert-child"})):{ok:!1,source:t,diagnostic:o.diagnostic}}function lb(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(aa());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(aa());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(aa());return}e.remove()}import{cloneNode as ub}from"@babel/types";function ti(e){let t=we(e.source,"jsx-node");if(!t.ok)return t.result;let n=se(t.ast,e.locator);if(!n.ok)return{ok:!1,source:e.source,diagnostic:n.diagnostic};let r=qo(e.source,e.node.jsx);return r.ok?(n.match.path.replaceWith(ub(r.node,!0)),he(t.ast,e.source,{kind:"replace-node",target:"jsx-node",inverse:"replace-node"})):r.result}import{cloneNode as Eb}from"@babel/types";import ca from"@babel/traverse";import*as Q from"@babel/types";function Pr(e,t,n){return`${e}::${t}::${n}`}var K={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 db=typeof ca=="function"?ca:ca.default;function mt(e,t,n,r){if(!e.ok)return e;let o=pt(n,t);if(!o)return e;let i=fb(t,o,r);return i?{...e,selectionRef:i}:e}function fb(e,t,n){let r=pb(e,t);if(!r)return;let o=n.sourceLocator?$u(n.sourceLocator):void 0,i=n.targetParentLocator?$u(n.targetParentLocator):void 0,s=n.file??i?.file??o?.file,a=n.component??gb(r)??i?.component??o?.component;if(!(!s||!a))return{key:Pr(s,a,hb(r))}}function $u(e){return e.strategy==="structural-path"?{file:e.file,component:e.component,structuralPath:e.structuralPath}:e.expectedIdentity}function pb(e,t){let n=zu(e,t);return!n||n.node.type!=="JSXElement"?null:n}function zu(e,t){let n=null;return db(e,{JSXElement(r){r.node===t&&(n=r,r.stop())},JSXFragment(r){r.node===t&&(n=r,r.stop())}}),n}function pt(e,t){if(!e)return null;if(Q.isJSXElement(e))return Sb(t,e)?Vu(e.children,t):e;if(Q.isJSXFragment(e))return Vu(e.children,t);if(Q.isJSXExpressionContainer(e)||Q.isParenthesizedExpression(e)||Q.isTSAsExpression(e)||Q.isTSSatisfiesExpression(e)||Q.isTSTypeAssertion(e)||Q.isTSNonNullExpression(e))return pt(e.expression,t);if(Q.isLogicalExpression(e))return pt(e.right,t);if(Q.isConditionalExpression(e))return pt(e.consequent,t)??pt(e.alternate,t);if(Q.isCallExpression(e)||Q.isOptionalCallExpression(e))return Wu(e)?mb(e.arguments[0],t):null;if(Q.isArrayExpression(e))for(let n of e.elements){if(!n)continue;let r=pt(n,t);if(r)return r}return null}function Vu(e,t){for(let n of e){let r=pt(n,t);if(r)return r}return null}function mb(e,t){return!e||!Q.isArrowFunctionExpression(e)&&!Q.isFunctionExpression(e)?null:Q.isBlockStatement(e.body)?Ar(e.body.body,t):pt(e.body,t)}function Ar(e,t){for(let n of e){if(Q.isReturnStatement(n)){let r=pt(n.argument,t);if(r)return r;continue}if(Q.isBlockStatement(n)){let r=Ar(n.body,t);if(r)return r;continue}if(Q.isIfStatement(n)){let r=Ku(n.consequent,t);if(r)return r;let o=n.alternate?Ku(n.alternate,t):null;if(o)return o;continue}if(Q.isSwitchStatement(n))for(let r of n.cases){let o=Ar(r.consequent,t);if(o)return o}}return null}function Ku(e,t){return Q.isBlockStatement(e)?Ar(e.body,t):Ar([e],t)}function gb(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(Q.isFunctionDeclaration(n))return n.id?.name??"default"}if(t.isVariableDeclarator()&&Q.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 Uu=new WeakMap,Ju=new WeakMap,la=new WeakMap;function hb(e){let t=Uu.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=yb(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return Uu.set(e.node,o),o}function yb(e){let t=Hu(e.node.openingElement.name);return!t||Me(e)?null:/^[A-Z]/.test(t)?`component:${t}#${Xu(e,t)}`:`${t}#${Xu(e,t)}`}function Xu(e,t){let n=xb(e);if(!n)return 0;let r=la.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=la.get(n.node);o||(o=new Map,la.set(n.node,o));let i=o.get(t);i||(i=new WeakMap,o.set(t,i));let s=0;for(let a of wn(n))if(Hu(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 xb(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(Me(t)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function wn(e){let t=Ju.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(Me(o)){n.push(...wn(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...wn(o));continue}o.isJSXExpressionContainer()&&n.push(...Ft(o.get("expression")))}return Ju.set(e.node,n),n}function Ft(e){if(e.isJSXElement())return Me(e)?wn(e):[e];if(e.isJSXFragment())return wn(e);if(e.isParenthesizedExpression())return Ft(e.get("expression"));if(e.isLogicalExpression())return Ft(e.get("right"));if(e.isConditionalExpression())return[...Ft(e.get("consequent")),...Ft(e.get("alternate"))];if(e.isArrayExpression())return e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:Ft(t));if((e.isCallExpression()||e.isOptionalCallExpression())&&Wu(e.node)){let t=e.get("arguments"),n=Array.isArray(t)?t[0]:void 0;return n?bb(n):[]}return[]}function bb(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return Me(t)?wn(t):[t];if(t.isJSXFragment())return wn(t);if(t.isParenthesizedExpression())return Ft(t.get("expression"));if(t.isLogicalExpression()||t.isConditionalExpression())return Ft(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(...Ft(s))}if(!r.isReturnStatement())continue;let o=r.get("argument");return o.node&&n.push(...Ft(o)),n}return n}function Wu(e){let t=e.callee;return(Q.isMemberExpression(t)||Q.isOptionalMemberExpression(t))&&Q.isIdentifier(t.property)&&t.property.name==="map"&&!t.computed}function Sb(e,t){let n=zu(e,t);return n?Me(n):!1}function Hu(e){return Q.isJSXIdentifier(e)?e.name:Q.isJSXMemberExpression(e)?Gu(e):Q.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function Gu(e){return`${Q.isJSXIdentifier(e.object)?e.object.name:Gu(e.object)}.${e.property.name}`}function sn(e,t){if(t.parentPath===e&&t.listKey==="children"&&ua(e))return e;if(!t.parentPath||t.listKey!=="children")return null;let n=t.parentPath;if(!ua(n))return null;let r=n;for(;r&&r!==e;){if(!ua(r)||!Me(r)||r.listKey!=="children")return null;r=r.parentPath}return r===e?n:null}function ua(e){return e.isJSXElement()||e.isJSXFragment()}function Gn(e){let{source:t,locator:n,node:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=we(t,"jsx-node");if(!a.ok)return a.result;let c=se(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};if(!c.match.path.isJSXElement()&&!c.match.path.isJSXFragment())return J(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 v=c.match.path.node;if(!v.closingElement||v.openingElement.selfClosing)return J(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=qo(t,r.jsx);if(!u.ok)return u.result;let f=Eb(u.node,!0),m=l.node.children,d={...s,targetParentLocator:n},g=v=>s?mt(v,a.ast,f,d):v;if(o==="append")return m.push(f),g(he(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return m.unshift(f),g(he(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(!i)return J(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let h=se(a.ast,i);if(!h.ok)return{ok:!1,source:t,diagnostic:h.diagnostic};let S=sn(c.match.path,h.match.path);if(!S)return J(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");l=S;let E=l.node.children,y=E.findIndex(v=>v===h.match.path.node);return y===-1?J(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(E.splice(o==="before"?y:y+1,0,f),g(he(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"})))}import*as Yu from"@babel/parser";import{cloneNode as vb}from"@babel/types";function ni(e){let{source:t,locator:n,expression:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=we(t,"jsx-node");if(!a.ok)return a.result;let c=kb(t,r);if(!c.ok)return c.result;let l=se(a.ast,n);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return J(t,"unsupported-syntax","insert-jsx-expression-child target must be a JSXElement or JSXFragment","jsx-node");if(l.match.path.isJSXElement()){let E=l.match.path.node;if(!E.closingElement||E.openingElement.selfClosing)return J(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=l.match.path,f=null;if(i){let E=se(a.ast,i);if(!E.ok)return{ok:!1,source:t,diagnostic:E.diagnostic};let y=sn(l.match.path,E.match.path);if(!y)return J(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=y,f=E.match.path.node}else if(o==="before"||o==="after")return J(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let m=vb(c.node,!0),d=u.node.children,g={...s,targetParentLocator:n},h=E=>s?mt(E,a.ast,m,g):E;if(o==="append")return d.push(m),h(he(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return d.unshift(m),h(he(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));let S=d.findIndex(E=>E===f);return S===-1?J(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(d.splice(o==="before"?S:S+1,0,m),h(he(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"})))}function kb(e,t){try{let r=Yu.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:J(e,"unsupported-syntax","Expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:J(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}import{cloneNode as Ib,nullLiteral as da}from"@babel/types";import*as an from"@babel/types";import*as Zu from"@babel/types";function Tr(e,t){let n=e.parentPath;if(!n?.isConditionalExpression()||e.key!=="consequent"||!Zu.isNullLiteral(n.node.alternate))return e;let r=n.parentPath;return!r?.isJSXExpressionContainer()||r.parentPath?.node!==t.node||r.listKey!=="children"?e:r}function Yn(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=we(t,"jsx-node");if(!a.ok)return a.result;let c=se(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};let l=se(a.ast,r);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return J(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 v=l.match.path.node;if(!v.closingElement||v.openingElement.selfClosing)return J(t,"self-closing-element","Cannot move child into self-closing element","jsx-node")}let f=null;if(i){let v=se(a.ast,i);if(!v.ok)return{ok:!1,source:t,diagnostic:v.diagnostic};let C=v.match.path.isJSXElement()?Tr(v.match.path,l.match.path):v.match.path,N=sn(l.match.path,C);if(!N)return J(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=N,f=C}else if(o==="before"||o==="after")return J(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let m=f&&typeof f.key=="number"?f.key:-1;if(f&&m===-1)return J(t,"locator-miss","Anchor node does not exist in target parent","jsx-node");let d=c.match.path.isJSXElement()?Tr(c.match.path,l.match.path):c.match.path,g=Ib(d.node,!0);if(!an.isJSXElement(g)&&!an.isJSXExpressionContainer(g)&&!an.isJSXFragment(g)&&!an.isJSXText(g))return J(t,"unsupported-syntax","move-node source must resolve to a JSX child","jsx-node");let h=d.parentPath?.node===u.node&&typeof d.key=="number"?d.key:-1;if(f&&d.parentPath?.node===f.parentPath?.node&&d.key===f.key)return J(t,"invalid-parent-child-relation","Cannot move a node relative to itself","jsx-node");Cb(d);let S=u.node.children,E={...s,sourceLocator:n,targetParentLocator:r};if(o==="append")return S.push(g),mt(Qo(a.ast,t),a.ast,g,E);if(o==="prepend")return S.unshift(g),mt(Qo(a.ast,t),a.ast,g,E);let y=m-(h!==-1&&h<m?1:0);return S.splice(o==="before"?y:y+1,0,g),mt(Qo(a.ast,t),a.ast,g,E)}function Cb(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(da());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(da());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(da());return}e.remove()}import*as Qu from"@babel/parser";import{cloneNode as Rb,nullLiteral as fa}from"@babel/types";function ri(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,repeatExpression:s,selectionContext:a}=e,c=we(t,"jsx-node");if(!c.ok)return c.result;let l=wb(t,s);if(!l.ok)return l.result;let u=se(c.ast,n);if(!u.ok)return{ok:!1,source:t,diagnostic:u.diagnostic};let f=se(c.ast,r);if(!f.ok)return{ok:!1,source:t,diagnostic:f.diagnostic};if(!f.match.path.isJSXElement()&&!f.match.path.isJSXFragment())return J(t,"unsupported-syntax","move-repeat-template-child target parent must be a JSXElement or JSXFragment","jsx-node");if(f.match.path.isJSXElement()){let v=f.match.path.node;if(!v.closingElement||v.openingElement.selfClosing)return J(t,"self-closing-element","Cannot move repeat child into self-closing element","jsx-node")}let m=f.match.path,d=null;if(i){let v=se(c.ast,i);if(!v.ok)return{ok:!1,source:t,diagnostic:v.diagnostic};let C=sn(f.match.path,v.match.path);if(!C)return J(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");m=C,d=v.match.path.node}else if(o==="before"||o==="after")return J(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");if(!u.match.path.isJSXElement())return J(t,"unsupported-syntax","move-repeat-template-child source must be a JSXElement","jsx-node");let g=m.node,h=Rb(l.node,!0);Nb(u.match.path);let S={...a,sourceLocator:n,targetParentLocator:r},E=g.children;if(o==="append")return E.push(h),mt(he(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,h,S);if(o==="prepend")return E.unshift(h),mt(he(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,h,S);let y=E.findIndex(v=>v===d);return y===-1?J(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(E.splice(o==="before"?y:y+1,0,h),mt(he(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,h,S))}function wb(e,t){try{let r=Qu.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:J(e,"unsupported-syntax","Repeat expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:J(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function Nb(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(fa());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(fa());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(fa());return}e.remove()}import{SiteEditSetPropsParamsSchema as Pb,classifySiteEditPropertyName as Ab}from"@vcp-dev/contracts";import*as Zn from"@babel/types";function oi(e){let t=Pb.safeParse({kind:"set-props",scope:"selection",changes:e.changes});if(!t.success)return J(e.source,"unsupported-syntax","Invalid typed JSX property changes","jsx-node",{issues:t.error.issues});let n=we(e.source,"jsx-node");if(!n.ok)return n.result;let r=Wn(n.ast,e.locator,e.source);if(!r.ok)return r.result;for(let a of t.data.changes){let c=Ab(a.name);if(c.owner!=="generic")return J(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(Zn.isJSXAttribute),s=new Map;for(let a of i){let c=Tb(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 J(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=Nr(a.name,a.value).value;c?c.value=l:o.attributes.push(Nr(a.name,a.value))}return he(n.ast,e.source,{kind:"set-props",target:"jsx-node",inverse:"set-props"})}function Tb(e){return Zn.isJSXIdentifier(e.name)?e.name.name:Zn.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:null}import{SiteEditOperationParamsSchema as Fb}from"@vcp-dev/contracts";import*as z from"@babel/types";var qu=["prefetch","replace","scroll","locale","onNavigate"],_b=/^on(?:Click|DoubleClick|AuxClick|MouseDown|MouseUp|PointerDown|PointerUp|TouchStart|TouchEnd|KeyDown|KeyUp|ContextMenu)(?:Capture)?$/;function Mb(e){let t=e;for(;t;){if(t.isJSXElement()&&t.node.openingElement.attributes.some(n=>z.isJSXAttribute(n)&&z.isJSXIdentifier(n.name)&&_b.test(n.name.name)))return!0;t=t.parentPath}return!1}function ii(e){let t=we(e.source,"jsx-node");if(!t.ok)return t.result;let n=Wn(t.ast,e.locator,e.source);if(!n.ok)return n.result;let r=Fb.safeParse({kind:"set-link-target",scope:"selection",link:e.link,changes:e.changes});if(!r.success||r.data.kind!=="set-link-target")return Wt(e.source,"Invalid typed link-target changes");let o=n.match.path,i=o.node,s=i.openingElement,a=Vb(s.name);if(!a)return Wt(e.source,"Unsupported JSX link tag");if(s.attributes.some(z.isJSXSpreadAttribute))return Wt(e.source,"Link elements with spread props cannot be transformed safely");let c=new Map;for(let g of s.attributes){if(!z.isJSXAttribute(g))continue;let h=ma(g);if(!h)return Wt(e.source,"Unsupported JSX attribute name");let S=c.get(h)??[];S.push(g),c.set(h,S)}if([...c.values()].some(g=>g.length>1))return Wt(e.source,"Duplicate JSX attributes cannot be transformed safely");let l=c.get("href")?.[0];if(l&&!$b(l))return Wt(e.source,"Dynamic link href cannot be transformed safely");let u=a==="a",f=u?null:Db(o,s.name);if(!u&&!f)return Wt(e.source,"Only native anchors and imported next/link components are supported");if(e.link.kind==="none"&&Mb(o))return Wt(e.source,"A link with an active event handler in its JSX ancestry cannot become an inert anchor");let m=null;if(e.link.kind==="internal-route")if(f)m=a;else{let g=Bb(t.ast,o);if(!g.ok)return Wt(e.source,g.reason);m=g.localName}if(f&&e.link.kind!=="internal-route"){let g=z.jsxIdentifier("a");s.name=g,i.closingElement&&(i.closingElement.name=z.jsxIdentifier("a")),jb(t.ast,f,o)}else m&&u&&(s.name=z.jsxIdentifier(m),i.closingElement&&(i.closingElement.name=z.jsxIdentifier(m)));let d=new Set;return e.link.kind==="none"?(d.add("href"),d.add("target"),d.add("rel"),qu.forEach(g=>d.add(g))):(d.add("href"),e.link.kind==="native-link"&&qu.forEach(g=>d.add(g))),s.attributes=s.attributes.filter(g=>{if(!z.isJSXAttribute(g))return!0;let h=ma(g);return!h||!d.has(h)}),e.link.kind!=="none"&&s.attributes.push(z.jsxAttribute(z.jsxIdentifier("href"),z.stringLiteral(e.link.href))),Ob(s,e.changes),he(t.ast,e.source,{kind:"set-link-target",target:"jsx-node",inverse:"set-link-target"})}function Ob(e,t){for(let n of t){let r=e.attributes.find(s=>z.isJSXAttribute(s)&&ma(s)===n.name);if(n.operation==="remove"){e.attributes=e.attributes.filter(s=>s!==r);continue}let o=typeof n.value=="string"?z.stringLiteral(n.value):z.jsxExpressionContainer(pa(n.value)),i=z.jsxAttribute(z.jsxIdentifier(n.name),o);r&&z.isJSXAttribute(r)?r.value=i.value:e.attributes.push(i)}}function pa(e){return e===null?z.nullLiteral():typeof e=="string"?z.stringLiteral(e):typeof e=="number"?z.numericLiteral(e):typeof e=="boolean"?z.booleanLiteral(e):Array.isArray(e)?z.arrayExpression(e.map(t=>pa(t))):typeof e=="object"?z.objectExpression(Object.entries(e).map(([t,n])=>z.objectProperty(z.isValidIdentifier(t)?z.identifier(t):z.stringLiteral(t),pa(n)))):z.nullLiteral()}function Lb(e){return z.isImportDefaultSpecifier(e)||z.isImportSpecifier(e)&&e.importKind!=="type"&&(z.isIdentifier(e.imported,{name:"default"})||z.isStringLiteral(e.imported,{value:"default"}))}function ed(e){return!e.parentPath?.isImportDeclaration()||e.parentPath.node.importKind==="type"?!1:e.isImportDefaultSpecifier()||e.isImportSpecifier()&&e.node.importKind!=="type"&&(z.isIdentifier(e.node.imported,{name:"default"})||z.isStringLiteral(e.node.imported,{value:"default"}))}function Db(e,t){if(!z.isJSXIdentifier(t))return null;let n=e.scope.getBinding(t.name);if(!n||!ed(n.path))return null;let r=n.path.parentPath;return!r?.isImportDeclaration()||r.node.source.value!=="next/link"?null:t.name}function Bb(e,t){let n=e.program.body.filter(c=>z.isImportDeclaration(c)&&c.source.value==="next/link"&&c.importKind!=="type"),r=n[0],o=n.flatMap(c=>c.specifiers).find(Lb);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=z.importDefaultSpecifier(z.identifier(s));if(r)r.specifiers.unshift(a);else{let c=z.importDeclaration([a],z.stringLiteral("next/link")),l=0;for(;l<e.program.body.length&&z.isImportDeclaration(e.program.body[l]);)l+=1;e.program.body.splice(l,0,c)}return{ok:!0,localName:s}}function jb(e,t,n){let r=n.scope.getProgramParent();r.crawl();let o=r.getBinding(t);if(!o||!ed(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 $b(e){return!e.value||z.isStringLiteral(e.value)}function Vb(e){return z.isJSXIdentifier(e)?e.name:null}function ma(e){return z.isJSXIdentifier(e.name)?e.name.name:null}function Wt(e,t){return J(e,"unsupported-syntax",t,"jsx-node")}import*as Ke from"@babel/types";import{classifySiteEditPropertyName as td}from"@vcp-dev/contracts";function si(e){let t=td(e.name),n=td(e.property);if(t.owner!=="generic"||n.owner!=="generic")return J(e.source,"unsupported-syntax","Property binding is only available for generic properties","jsx-node");if(!nd(e.object))return J(e.source,"unsupported-syntax","Property binding object must be a single identifier","jsx-node");if(e.property.length===0)return J(e.source,"unsupported-syntax","Property binding requires a non-empty property name","jsx-node");let r=we(e.source,"jsx-node");if(!r.ok)return r.result;let o=Wn(r.ast,e.locator,e.source);if(!o.ok)return o.result;let i=o.match.path.node.openingElement,s=i.attributes.filter(l=>Ke.isJSXAttribute(l)&&Ub(l)===e.name);if(s.length>1)return J(e.source,"unsupported-syntax",`JSX attribute '${e.name}' has multiple sources`,"jsx-node");let a=Kb(e.object,e.property),c=s[0];if(c)c.value=Ke.jsxExpressionContainer(a);else{let l=Nr(e.name,"");l.value=Ke.jsxExpressionContainer(a),i.attributes.push(l)}return he(r.ast,e.source,{kind:"set-property-binding",target:"jsx-node",inverse:"restore-property-binding"})}function Kb(e,t){return nd(t)?Ke.memberExpression(Ke.identifier(e),Ke.identifier(t)):Ke.memberExpression(Ke.identifier(e),Ke.stringLiteral(t),!0)}function nd(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(e)}function Ub(e){return Ke.isJSXIdentifier(e.name)?e.name.name:Ke.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:null}import{getBindingIdentifiers as Xb,identifier as Fr,importDeclaration as zb,importDefaultSpecifier as Wb,importNamespaceSpecifier as Hb,importSpecifier as Gb,isImportDefaultSpecifier as rd,isImportNamespaceSpecifier as od,isImportSpecifier as id,stringLiteral as Yb}from"@babel/types";function Qn(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(S=>!iS(S));if(o!==-1){let S=r[o],E=S&&typeof S=="object"&&"kind"in S?S.kind:void 0;return J(t,"unsupported-syntax",`Unsupported import spec kind: ${String(E)}`)}let i=nS(r);if(!i.ok)return J(t,"unsupported-syntax",i.message);let s=we(t);if(!s.ok)return s.result;let{ast:a}=s,c=a.program,l=c.body.filter(S=>S.type==="ImportDeclaration"&&S.source.value===n),u=new Set(l.flatMap(S=>S.specifiers.flatMap(E=>{let y=sS(S,E);return y?[y]:[]}))),f=i.imports.filter(S=>!u.has(dd(S)));if(f.length===0)return wr(t,t,{kind:"add-import",target:"import",inverse:"remove-import"});let m=rS(c.body),d=f.find(S=>m.has(ga(S)));if(d)return J(t,"unsupported-syntax",`Import local binding already exists: ${ga(d)}`);let g=tS(f);if(g.reduce((S,E)=>S+E.length,0)!==f.length)return J(t,"unsupported-syntax","Unsupported import specifier grouping");for(let S of g){if(!ld(ad(S)))return J(t,"unsupported-syntax","Unsupported import specifier combination");let E=l.find(y=>Zb(y,S));if(E)Qb(E,S);else{let y=zb(sd(S),Yb(n));oS(c.body,y),l.push(y)}}return he(a,t,{kind:"add-import",target:"import",inverse:"remove-import"})}function Zb(e,t){return e.importKind==="type"?!1:ld(eS(qb(e),ad(t)))}function Qb(e,t){let n=!1,r=new Set(e.specifiers.map(o=>ha(o)));for(let o of sd(t)){let i=ha(o);r.has(i)||(e.specifiers.push(o),r.add(i),n=!0)}return ud(e.specifiers),{changed:n}}function sd(e){let t=e.map(n=>{switch(n.kind){case"named":return Gb(n.local?Fr(n.local):Fr(n.imported),Fr(n.imported));case"default":return Wb(Fr(n.local));case"namespace":return Hb(Fr(n.local));default:return n}});return ud(t),t}function ad(e){let t=cd();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 qb(e){let t=cd();for(let n of e.specifiers)rd(n)?t.defaultLocals.add(n.local.name):od(n)?t.namespaceLocals.add(n.local.name):t.hasNamed=!0;return t}function cd(){return{defaultLocals:new Set,hasNamed:!1,namespaceLocals:new Set}}function eS(e,t){return{defaultLocals:new Set([...e.defaultLocals,...t.defaultLocals]),hasNamed:e.hasNamed||t.hasNamed,namespaceLocals:new Set([...e.namespaceLocals,...t.namespaceLocals])}}function ld(e){return e.defaultLocals.size>1||e.namespaceLocals.size>1?!1:!(e.hasNamed&&e.namespaceLocals.size>0)}function ud(e){let t=[...e.filter(n=>rd(n)),...e.filter(n=>od(n)),...e.filter(n=>id(n))];e.splice(0,e.length,...t)}function tS(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 nS(e){let t=new Map,n=new Map;for(let r of e){let o=dd(r);if(t.has(o))continue;let i=ga(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 rS(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(Xb(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 oS(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 iS(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 dd(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 ga(e){return e.kind==="named"?e.local??e.imported:e.local}function sS(e,t){return e.importKind==="type"||id(t)&&t.importKind==="type"?null:ha(t)}function ha(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 qn(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(u=>!cS(u));if(o!==-1){let u=r[o],f=u&&typeof u=="object"&&"kind"in u?u.kind:void 0;return J(t,"unsupported-syntax",`Unsupported remove import spec kind: ${String(f)}`)}let i=we(t);if(!i.ok)return i.result;let{ast:s}=i,a=s.program,c=a.body.findIndex(u=>u.type==="ImportDeclaration"&&u.source.value===n);if(c===-1)return wr(t,t,{kind:"remove-import",target:"import",inverse:"add-import"});let l=a.body[c];return r.length===0?(a.body.splice(c,1),he(s,t,{kind:"remove-import",target:"import",inverse:"add-import"})):(l.specifiers=l.specifiers.filter(u=>!r.some(f=>aS(u,f))),l.specifiers.length===0&&a.body.splice(c,1),he(s,t,{kind:"remove-import",target:"import",inverse:"add-import"}))}function aS(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 cS(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 _r(e){let{source:t,locator:n,next:r}=e,o=ui(t,n);return o.ok?(o.path.replaceWith(on(r)),he(o.ast,t,{kind:"update-value",target:"value",inverse:"restore-value"})):o.result}function ai(e){let{source:t,locator:n,index:r,value:o}=e,i=ui(t,n);return i.ok?i.path.isArrayExpression()?i.path.node.elements.some(s=>s?.type==="SpreadElement")?J(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>i.path.node.elements.length?J(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(i.path.node.elements.splice(r,0,on(o)),he(i.ast,t,{kind:"insert-array-element",target:"value",inverse:"remove-array-element"})):J(t,"unsupported-syntax","Array operations require array expression target","value"):i.result}function ci(e){let{source:t,locator:n,index:r}=e,o=ui(t,n);return o.ok?o.path.isArrayExpression()?o.path.node.elements.some(i=>i?.type==="SpreadElement")?J(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>=o.path.node.elements.length?J(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(o.path.node.elements.splice(r,1),he(o.ast,t,{kind:"remove-array-element",target:"value",inverse:"insert-array-element"})):J(t,"unsupported-syntax","Array operations require array expression target","value"):o.result}function li(e){let{source:t,locator:n,fromIndex:r,toIndex:o}=e,i=ui(t,n);if(!i.ok)return i.result;if(!i.path.isArrayExpression())return J(t,"unsupported-syntax","Array operations require array expression target","value");if(i.path.node.elements.some(c=>c?.type==="SpreadElement"))return J(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 J(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),he(i.ast,t,{kind:"move-array-element",target:"value",inverse:"move-array-element-back"})}function ui(e,t){let n=we(e,"value");if(!n.ok)return{ok:!1,result:n.result};let r=se(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 Xe from"@babel/types";function di(e){let t=we(e.source,"value");if(!t.ok)return t.result;let n=se(t.ast,e.objectLocator);if(!n.ok)return{ok:!1,source:e.source,diagnostic:n.diagnostic};if(!n.match.path.isObjectExpression())return J(e.source,"unsupported-syntax","Object property upsert requires an ObjectExpression parent","value");let r=n.match.path.node;if(r.properties.some(a=>Xe.isSpreadElement(a)||Xe.isObjectProperty(a)&&a.computed))return J(e.source,"unsupported-syntax","Object property upsert does not support spreads or computed keys","value");let o=r.properties.filter(a=>Xe.isObjectProperty(a)&&lS(a.key)===e.name);if(o.length>1)return J(e.source,"unsupported-syntax",`Object property '${e.name}' has multiple sources`,"value");let i=e.value.kind==="undefined"?Xe.unaryExpression("void",Xe.numericLiteral(0)):on(e.value.value),s=o[0];if(s)s.value=i,s.shorthand=!1;else{let a=Xe.objectProperty(sa(e.name),i);e.name==="__proto__"&&(a.computed=!0),r.properties.push(a)}return he(t.ast,e.source,{kind:"upsert-object-property",target:"value",inverse:"restore-object-property"})}function lS(e){return Xe.isIdentifier(e)?e.name:Xe.isStringLiteral(e)?e.value:Xe.isNumericLiteral(e)?String(e.value):null}import{isSiteEditRuntimeContainerTag as uS,isSiteEditRuntimeVoidElementTag as dS}from"@vcp-dev/contracts/site-edit-runtime-capability";function er(e){if(!e.composition)throw new Error("Composition unavailable for render source graph.");return e.composition}function fS(e,t,n){let r=er(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(C=>({kind:C.kind,message:C.reason})),a=i.isOpaque,l=o.parentKey===null&&i.componentName==="Page",u=i.tag.toLowerCase(),f=i.tag!==u,m=!f&&dS(u),d=f||uS(u),g=f&&i.childKeys.length>0&&!i.isPublicUiComponent,h=i.textSegments.length>0&&i.textSegments.some(C=>C.editable);m&&!s.some(C=>C.kind==="void-element")&&s.push({kind:"void-element",message:`Element '${i.tag}' is void: children cannot be inserted`}),!m&&!d&&!s.some(C=>C.kind==="void-element")&&s.push({kind:"void-element",message:`Element '${i.tag}' cannot contain structured children`});let S=h&&(!a||i.importedFrom==="next/link"),E=!i.isPublicUiComponent&&!m&&d&&(!a||g);return{composition:r,key:e,canUpdateText:S,canInsertChild:E,canMove:!l,canRemove:!l,constraints:s}}function fd(e,t){let n=new Map;for(let r of e.nodes.keys())n.set(r,fS(r,e,t));return n}function ya(e){let t=e.route.graph.elements.get(e.key);if(!t)return{key:e.key,composition:e.route.composition,filePath:"",componentName:"",sourceKind:"missing",attrRaw:null,valueRaw:null,attrRange:null,openingElementRange:{start:0,end:0},version:{documentVersion:e.route.graph.version,contentHash:ke(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Key not found: ${e.key}`}]};let n=pS(e.route.source,t);if(!n)return{key:e.key,composition:e.route.composition,filePath:t.sourceFile,componentName:t.componentName,sourceKind:"missing",attrRaw:null,valueRaw:null,attrRange:null,openingElementRange:{start:0,end:0},version:{documentVersion:e.route.graph.version,contentHash:ke(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Unable to locate JSX element for key ${t.identity.key}`}]};let r=n.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:md(r),version:{documentVersion:e.route.graph.version,contentHash:ke(e.route.source)}};if(!o)return{...i,sourceKind:"missing",attrRaw:null,valueRaw:null,attrRange:null,diagnostics:[{code:"missing-class-name",message:"No className attribute is present on this element."}]};let s=o.value,a=s?.type==="StringLiteral"?"stringLiteral":"expression";return{...i,sourceKind:a,attrRaw:pd(e.route.source,o),valueRaw:s?pd(e.route.source,s):null,attrRange:md(o),diagnostics:[]}}function gd(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 pS(e,t){let n=Pt({source:e,profile:vn({filePath:t.sourceFile,source:e})});if(!n.ok)return null;let r=se(n.ast,{kind:"jsx-node",strategy:"structural-path",file:t.identity.file,component:t.identity.component,structuralPath:t.identity.structuralPath,expectedRange:mS(t.sourceRange)});return!r.ok||r.match.node.type!=="JSXElement"?null:r.match.node}function hd(e){let t=Pt({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 pd(e,t){return t.start==null||t.end==null?"":e.slice(t.start,t.end)}function md(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 mS(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function yd(){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 gS}from"node:crypto";import fi from"node:fs/promises";import xa from"node:path";import{setTimeout as hS}from"node:timers/promises";var yS={async mkdir(e,t){await fi.mkdir(e,t)},async writeFile(e,t,n){await fi.writeFile(e,t,n)},async rename(e,t){await fi.rename(e,t)},async rm(e,t){await fi.rm(e,t)}},xS=new Set(["EACCES","EBUSY","EPERM"]),bS=[10,20,40,80,160];async function SS(e,t,n){for(let r of bS)try{await e.rename(t,n);return}catch(o){if(!ES(o))throw o;await hS(r)}await e.rename(t,n)}function ES(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&xS.has(e.code)}async function pi(e,t,n=yS){let r=xa.dirname(e),o=xa.basename(e),i=xa.join(r,`.${o}.${process.pid}.${gS()}.tmp`),s=!1;try{await n.mkdir(r,{recursive:!0}),await n.writeFile(i,t,"utf8"),await SS(n,i,e),s=!0}finally{if(!s)try{await n.rm(i,{force:!0})}catch{}}}import ba from"@babel/traverse";import*as k from"@babel/types";import*as fe from"@babel/types";function _t(e,t={}){if(fe.isTSAsExpression(e)||fe.isTSSatisfiesExpression(e)||fe.isTSNonNullExpression(e)||fe.isTypeCastExpression(e)||fe.isParenthesizedExpression(e))return _t(e.expression,t);if(fe.isStringLiteral(e))return{status:"resolved",value:e.value};if(fe.isNumericLiteral(e))return Number.isFinite(e.value)?{status:"resolved",value:e.value}:{status:"unresolved"};if(fe.isBooleanLiteral(e))return{status:"resolved",value:e.value};if(fe.isNullLiteral(e))return{status:"resolved",value:null};if(fe.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(fe.isIdentifier(e))return e.name==="undefined"&&!t.resolveIdentifier?{status:"undefined"}:t.resolveIdentifier?.(e.name)??{status:"unresolved"};if(fe.isUnaryExpression(e)&&e.operator==="void"&&fe.isNumericLiteral(e.argument)&&e.argument.value===0)return{status:"undefined"};if(fe.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||fe.isSpreadElement(r))return{status:"unresolved"};let o=_t(r,t);if(o.status!=="resolved")return{status:"unresolved"};n.push(o.value)}return{status:"resolved",value:n}}if(fe.isObjectExpression(e)){let n=Object.create(null);for(let r of e.properties){if(!fe.isObjectProperty(r)||r.computed||!fe.isExpression(r.value))return{status:"unresolved"};let o=vS(r.key);if(o===null)return{status:"unresolved"};let i=_t(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 fe.isMemberExpression(e)||fe.isOptionalMemberExpression(e)?t.resolveMember?.(e)??{status:"unresolved"}:{status:"unresolved"}}function vS(e){return fe.isIdentifier(e)?e.name:fe.isStringLiteral(e)?e.value:fe.isNumericLiteral(e)?String(e.value):null}var kS=typeof ba=="function"?ba:ba.default;function Ye(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 IS(e){return/^[A-Z]/.test(e)}function Ia(e){let t=e.openingElement;return k.isJSXIdentifier(t.name)?t.name.name==="Fragment":k.isJSXMemberExpression(t.name)?t.name.property.name==="Fragment":!1}function nr(e){return k.isJSXFragment(e)}function bd(e){return k.isJSXIdentifier(e.name)?e.name.name:k.isJSXMemberExpression(e.name)?Sd(e.name):k.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:"unknown"}function Sd(e){return k.isJSXIdentifier(e.object)?`${e.object.name}.${e.property.name}`:k.isJSXMemberExpression(e.object)?`${Sd(e.object)}.${e.property.name}`:e.property.name}function CS(e){return e.split(".")[0]??e}function RS(e){let t=e;for(;t;){let n=t.node;if(k.isFunctionDeclaration(n)&&n.id||k.isVariableDeclarator(n)&&k.isIdentifier(n.id))return n.id.name;if(k.isExportDefaultDeclaration(n)){let r=n.declaration;if(k.isFunctionDeclaration(r)&&r.id)return r.id.name;if(k.isFunctionDeclaration(r)&&!r.id)return"default"}t=t.parentPath}return null}function wS(){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 NS(e){let t=new Map;for(let n of e.program.body){if(!k.isImportDeclaration(n))continue;let r=n.source.value;for(let o of n.specifiers)if(k.isImportDefaultSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"default"});else if(k.isImportNamespaceSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"*"});else if(k.isImportSpecifier(o)){let i=k.isIdentifier(o.imported)?o.imported.name:o.imported.value;t.set(o.local.name,{specifier:r,exportName:i})}}return t}function Ht(e,t=[]){if(k.isIdentifier(e))return t.push(e.name),t;if(k.isObjectPattern(e)){for(let n of e.properties)k.isObjectProperty(n)?Ht(n.value,t):k.isRestElement(n)&&Ht(n.argument,t);return t}if(k.isArrayPattern(e)){for(let n of e.elements)n&&(k.isRestElement(n)?Ht(n.argument,t):Ht(n,t));return t}return k.isAssignmentPattern(e)?(Ht(e.left,t),t):(k.isRestElement(e)&&Ht(e.argument,t),t)}function Et(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function Mr(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 PS(e,t,n){e.set(t,{resolved:!0,value:n})}function Ca(e,t){e.set(t,{resolved:!1})}function Ed(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 $e(e,t,n){if(k.isTSAsExpression(e)||k.isTSSatisfiesExpression(e)||k.isTSNonNullExpression(e)||k.isTypeCastExpression(e)||k.isParenthesizedExpression(e))return $e(e.expression,t,n);if(k.isLogicalExpression(e))return mi([$e(e.left,t,n),$e(e.right,t,n)]);if(k.isBinaryExpression(e))return mi([k.isExpression(e.left)?$e(e.left,t,n):null,k.isExpression(e.right)?$e(e.right,t,n):null]);if(k.isConditionalExpression(e))return mi([$e(e.consequent,t,n),$e(e.alternate,t,n)]);if(k.isTemplateLiteral(e))return mi(e.expressions.filter(k.isExpression).map(i=>$e(i,t,n)));if(k.isIdentifier(e))return{kind:"identifier",expression:e.name,base:e.name,path:[]};if(!k.isMemberExpression(e)&&!k.isOptionalMemberExpression(e))return null;let r=[],o=e;for(;k.isMemberExpression(o)||k.isOptionalMemberExpression(o);){if(o.computed)if(k.isNumericLiteral(o.property))r.unshift({kind:"index",index:o.property.value});else if(k.isStringLiteral(o.property))r.unshift({kind:"property",name:o.property.value});else if(n&&k.isExpression(o.property)){let i=cn(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(!k.isIdentifier(o.property))return null;r.unshift({kind:"property",name:o.property.name})}o=o.object}return k.isIdentifier(o)?{kind:r.some(i=>i.kind==="index")?"index-expression":"member-expression",expression:Et(e,t),base:o.name,path:r}:null}function mi(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 cn(e,t){if(k.isStringLiteral(e)||k.isNumericLiteral(e)||k.isBooleanLiteral(e))return e.value;if(k.isNullLiteral(e))return null;if(k.isTemplateLiteral(e))return e.expressions.length===0&&e.quasis.length===1?e.quasis[0].value.cooked??e.quasis[0].value.raw:void 0;if(k.isIdentifier(e)){let n=Mr(e.name,t.valueScopes);return n.kind==="resolved"?n.value:void 0}if(k.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||k.isSpreadElement(r))return;let o=cn(r,t);if(o===void 0)return;n.push(o)}return n}if(k.isObjectExpression(e)){let n={};for(let r of e.properties){if(!k.isObjectProperty(r)||r.computed||!k.isExpression(r.value))return;let o=null;if(k.isIdentifier(r.key)?o=r.key.name:k.isStringLiteral(r.key)&&(o=r.key.value),!o)return;let i;if(r.shorthand){if(!k.isIdentifier(r.value))return;let s=Mr(r.value.name,t.valueScopes);if(s.kind!=="resolved")return;i=s.value}else i=cn(r.value,t);if(i===void 0)return;n[o]=i}return n}if(k.isMemberExpression(e)){let n=$e(e,"",t);if(!n)return;let r=Mr(n.base,t.valueScopes);if(r.kind!=="resolved")return;let o=Ed(r.value,n.path);return o.kind==="resolved"?o.value:void 0}if(k.isCallExpression(e))return kd(e,t)??void 0}function vd(e,t,n){let r=$e(e,n,t);if(!r)return k.isMemberExpression(e)||k.isBinaryExpression(e)||k.isLogicalExpression(e)||k.isConditionalExpression(e)||k.isCallExpression(e)?{value:Et(e,n),source:null}:null;let o=Mr(r.base,t.valueScopes),i=r.kind==="identifier"?o:o.kind==="resolved"?Ed(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 Sa(e,t,n,r,o,i){return{file:e,componentName:t,elements:n,regions:r,ordinalTracker:wS(),parentStack:[],valueScopes:i,importMap:o}}function va(e,t,n){for(let r of e)for(let o of r.declarations){for(let s of Ht(o.id))Ca(n,s);if(!k.isIdentifier(o.id)||!o.init||!k.isExpression(o.init))continue;let i=cn(o.init,t);i!==void 0&&PS(n,o.id.name,i)}}function AS(e){let t=[];for(let n of e){if(k.isVariableDeclaration(n)){t.push(n);continue}k.isExportNamedDeclaration(n)&&n.declaration&&k.isVariableDeclaration(n.declaration)&&t.push(n.declaration)}return t}function TS(e,t,n){let r=[],o=0;for(let i of e)if(k.isJSXText(i)){let s=i.value.trim();s&&r.push({index:o++,value:s,sourceRange:Ye(i),editable:!0,source:null})}else if(k.isJSXExpressionContainer(i)&&k.isStringLiteral(i.expression))r.push({index:o++,value:i.expression.value,sourceRange:Ye(i),editable:!0,source:null});else if(k.isJSXExpressionContainer(i)&&k.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:Ye(i),editable:!0,source:null}):r.push({index:o++,value:Et(s,n),sourceRange:Ye(i),editable:!0,source:$e(s,n,t)})}else if(k.isJSXExpressionContainer(i)&&k.isExpression(i.expression)){let s=vd(i.expression,t,n);s&&r.push({index:o++,value:s.value,sourceRange:Ye(i),editable:!0,source:s.source})}return r}function FS(e,t,n){let r=[];for(let[o,i]of e.attributes.entries()){if(!k.isJSXAttribute(i))continue;let s=MS(i.name);if(!s)continue;let a=Et(i,n);if(k.isStringLiteral(i.value)){r.push({name:s,value:i.value.value,sourceRange:Ye(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:Ye(i),source:null,syntaxKind:"boolean-shorthand",raw:a,order:o,resolution:{status:"resolved",value:!0},resolvedValue:!0});continue}if(k.isJSXExpressionContainer(i.value)&&k.isExpression(i.value.expression)){let c=cn(i.value.expression,t);if(s==="className"){let d=typeof c=="string"?c:c===void 0?kd(i.value.expression,t):null;if(d){r.push({name:s,value:d,sourceRange:Ye(i),source:null,resolvedValue:d,syntaxKind:"expression",raw:a,order:o,resolution:{status:"resolved",value:d}});continue}}let l=vd(i.value.expression,t,n);if(c!==void 0){r.push({name:s,value:VS(c),sourceRange:Ye(i),source:$e(i.value.expression,n,t),resolvedValue:c,syntaxKind:"expression",raw:a,order:o,resolution:{status:"resolved",value:c}});continue}let u=OS(i.value.expression,t),f=$e(i.value.expression,n,t),m=l?.value??Et(i.value.expression,n);r.push({name:s,value:u.status==="undefined"?"undefined":m,sourceRange:Ye(i),source:l?.source??f,syntaxKind:"expression",raw:a,order:o,resolution:u})}}return r}function _S(e,t,n){return e.attributes.flatMap((r,o)=>!k.isJSXSpreadAttribute(r)||!k.isExpression(r.argument)?[]:[{raw:Et(r.argument,n),sourceRange:Ye(r),order:o,source:$e(r.argument,n,t)}])}function MS(e){return k.isJSXIdentifier(e)?e.name:k.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function OS(e,t){return _t(e,{resolveIdentifier(n){let r=Mr(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=cn(n,t);return r===void 0?{status:"unresolved"}:{status:"resolved",value:r}}})}function kd(e,t){let n=tr(e,t);return n&&n.map(o=>o.trim()).filter(Boolean).join(" ")||null}function tr(e,t){if(k.isStringLiteral(e))return[e.value];if(k.isTemplateLiteral(e))return e.expressions.length>0?null:[e.quasis.map(n=>n.value.cooked??"").join("")];if(k.isNullLiteral(e))return[];if(k.isBooleanLiteral(e))return e.value?null:[];if(k.isIdentifier(e)||k.isMemberExpression(e)){if(k.isIdentifier(e)&&e.name==="undefined")return[];let n=cn(e,t);return typeof n=="string"?[n]:null}if(k.isConditionalExpression(e)){let n=tr(e.consequent,t),r=tr(e.alternate,t);return!n||!r?null:[...n,...r]}if(k.isLogicalExpression(e)){if(e.operator!=="&&")return null;let n=cn(e.left,t);return n===!1||n===null?[]:tr(e.right,t)}if(k.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||k.isSpreadElement(r))return null;let o=tr(r,t);if(!o)return null;n.push(...o)}return n}if(k.isObjectExpression(e)){let n=[];for(let r of e.properties){if(!k.isObjectProperty(r))return null;let o=DS(r.key);if(!o)return null;n.push(o)}return n}if(k.isCallExpression(e)){let n=LS(e.callee);if(!n||!["cn","clsx","twMerge"].includes(n))return null;let r=[];for(let o of e.arguments){if(!k.isExpression(o))return null;let i=tr(o,t);if(!i)return null;r.push(...i)}return r}return null}function LS(e){return k.isIdentifier(e)?e.name:k.isMemberExpression(e)&&k.isIdentifier(e.property)?e.property.name:null}function DS(e){return k.isIdentifier(e)?e.name:k.isStringLiteral(e)?e.value:null}function BS(e,t){let n=e.attributes.find(r=>k.isJSXAttribute(r)&&k.isJSXIdentifier(r.name)&&r.name.name===t);return!n||!k.isJSXAttribute(n)||!k.isJSXExpressionContainer(n.value)?null:n.value.expression}function jS(e,t){for(let n of t){let r=BS(e,n);if(r)return r}return null}function $S(e){return k.isJSXIdentifier(e.name)?e.name.name:null}function VS(e){return e===null?"null":typeof e=="boolean"?e?"true":"false":JSON.stringify(e)}function KS(e){if(!k.isCallExpression(e)&&!k.isOptionalCallExpression(e))return null;let t=e.callee;return!k.isMemberExpression(t)&&!k.isOptionalMemberExpression(t)||!k.isIdentifier(t.property)||t.property.name!=="map"||t.computed||!k.isExpression(t.object)?null:{call:e,collection:t.object,callback:e.arguments[0]}}function Ea(e){return k.isArrowFunctionExpression(e)||k.isFunctionExpression(e)}function US(e){return e==="render"||e==="itemRender"||e==="rowRender"||e==="children"}function JS(e){return e==="empty"||e==="emptyRender"||e==="loading"||e==="loadingRender"||e==="error"||e==="errorRender"||e==="fallback"||e==="headerRender"||e==="footerRender"}function xd(e,t,n,r){if(!e||!k.isExpression(e))return null;let o={kind:"repeat-template",collectionExpression:Et(e,n),collectionSource:$e(e,n,r)};if(t){let i=t.params[0],s=t.params[1];k.isIdentifier(i)&&(o.itemParamName=i.name),k.isIdentifier(s)&&(o.indexParamName=s.name)}return o}function Gt(e,t,n){if(!e)return[];if(k.isJSXElement(e)){if(Ia(e))return bi(e.children,t,n);let r=yi(e,t,n);return r?[r]:[]}return nr(e)?xi(e,t,n):k.isParenthesizedExpression(e)?Gt(e.expression,t,n):k.isExpression(e)?Si(e,t,n):[]}function gi(e,t,n){let r=new Map;for(let o of e.params)for(let i of Ht(o))Ca(r,i);t.valueScopes.push(r);try{if(!k.isBlockStatement(e.body))return Gt(e.body,t,n);let o=new Map;t.valueScopes.push(o);try{return Id(e.body.body,t,n)}finally{t.valueScopes.pop()}}finally{t.valueScopes.pop()}}function Id(e,t,n){let r=[];for(let o of e){if(k.isVariableDeclaration(o)){let i=t.valueScopes[t.valueScopes.length-1];if(i){va([o],t,i);for(let s of o.declarations)k.isIdentifier(s.id)&&(k.isJSXElement(s.init)||k.isJSXFragment(s.init))&&r.push(...Gt(s.init,t,n))}continue}r.push(...ka(o,t,n))}return r}function ka(e,t,n){if(k.isReturnStatement(e))return e.argument?Gt(e.argument,t,n):[];if(k.isBlockStatement(e))return Nn(e.body,t,n);if(k.isIfStatement(e)){let r=k.isBlockStatement(e.consequent)?Nn(e.consequent.body,t,n):ka(e.consequent,t,n),o=e.alternate?k.isBlockStatement(e.alternate)?Nn(e.alternate.body,t,n):ka(e.alternate,t,n):[];return[...r,...o]}if(k.isSwitchStatement(e))return Nn(e.cases.flatMap(r=>r.consequent),t,n);if(k.isTryStatement(e)){let r=Nn(e.block.body,t,n);return e.handler&&r.push(...Nn(e.handler.body.body,t,n)),e.finalizer&&r.push(...Nn(e.finalizer.body,t,n)),r}return[]}function Nn(e,t,n){let r=new Map;t.valueScopes.push(r);try{return Id(e,t,n)}finally{t.valueScopes.pop()}}function hi(e,t,n,r,o,i){o.length!==0&&e.regions.push({kind:t,ownerKey:n,childKeys:o,sourceRange:Ye(r),sourceCandidates:i&&i.length>0?i:void 0})}function XS(e,t,n,r){let o=jS(e.openingElement,["items","dataSource","data"]),i={key:t,tag:bd(e.openingElement)};n.parentStack.push(i);try{for(let s of e.openingElement.attributes){if(!k.isJSXAttribute(s))continue;let a=$S(s);if(!a||!k.isJSXExpressionContainer(s.value))continue;let c=s.value.expression;if(!k.isJSXEmptyExpression(c)){if(US(a)&&Ea(c)){let l=gi(c,n,r),u=xd(o,c,r,n);hi(n,"repeat-region",t,s,l,u?[u]:void 0);continue}if(JS(a)){let l=Ea(c)?gi(c,n,r):Gt(c,n,r);hi(n,"conditional-region",t,s,l)}}}if(o)for(let s of e.children){if(!k.isJSXExpressionContainer(s)||!Ea(s.expression))continue;let a=gi(s.expression,n,r),c=xd(o,s.expression,r,n);hi(n,"repeat-region",t,s,a,c?[c]:void 0)}}finally{n.parentStack.pop()}}function yi(e,t,n){let r=bd(e.openingElement);if(r==="Fragment"||Ia(e))return bi(e.children,t,n),null;let o=t.parentStack[t.parentStack.length-1]??null,i=o?.key??null,s=IS(r),a;if(s){let C=t.ordinalTracker.getOrdinal(i,r);a=`component:${r}#${C}`}else{let C=t.ordinalTracker.getOrdinal(i,r);a=`${r}#${C}`}let c=o?t.elements.get(o.key)?.identity.structuralPath:void 0,l=c?`${c}/${a}`:a,u=Pr(t.file,t.componentName,l),f={file:t.file,component:t.componentName,structuralPath:l,key:u},m=s?"component-boundary":null,d=TS(e.children,t,n),g=FS(e.openingElement,t,n),h=_S(e.openingElement,t,n),S,E,y=!1;if(s){let C=t.importMap.get(r)??t.importMap.get(CS(r));C&&(S=C.specifier,E=C.exportName,y=kn(C.specifier,t.file))}let v={identity:f,tag:r,componentName:t.componentName,sourceFile:t.file,sourceRange:Ye(e),parentKey:i,childKeys:[],textSegments:d,attributes:g.length>0?g:void 0,attributeSpreads:h.length>0?h:void 0,boundaryKind:m,isOpaque:s,...y?{isPublicUiComponent:!0}:{},importedFrom:S,exportName:E};return t.elements.set(u,v),i&&t.elements.has(i)&&t.elements.get(i).childKeys.push(u),XS(e,u,t,n),(!s||e.children.length>0)&&(t.parentStack.push({key:u,tag:r}),zS(e.children,t,n),t.parentStack.pop()),u}function xi(e,t,n){return bi(e.children,t,n)}function bi(e,t,n){let r=[];for(let o of e)if(k.isJSXElement(o))if(Ia(o))r.push(...bi(o.children,t,n));else{let i=yi(o,t,n);i&&r.push(i)}else nr(o)?r.push(...xi(o,t,n)):k.isJSXExpressionContainer(o)&&r.push(...Si(o.expression,t,n));return r}function zS(e,t,n){for(let r of e)k.isJSXElement(r)?yi(r,t,n):nr(r)?xi(r,t,n):k.isJSXExpressionContainer(r)&&Si(r.expression,t,n)}function WS(e){return e==="&&"||e==="||"||e==="??"}function Si(e,t,n){if(k.isJSXEmptyExpression(e))return[];let r=KS(e);if(r){let o=r.call,i=t.parentStack[t.parentStack.length-1]??null,s=[],a=r.callback,c={kind:"repeat-template",collectionExpression:Et(r.collection,n),collectionSource:$e(r.collection,n,t)};if(k.isArrowFunctionExpression(a)||k.isFunctionExpression(a)){let u=a.params[0],f=a.params[1];k.isIdentifier(u)&&(c.itemParamName=u.name),k.isIdentifier(f)&&(c.indexParamName=f.name)}s.push(c);let l={kind:"repeat-region",ownerKey:i?.key??"",childKeys:[],sourceRange:Ye(o),sourceCandidates:s.length>0?s:void 0};return t.regions.push(l),(k.isArrowFunctionExpression(a)||k.isFunctionExpression(a))&&l.childKeys.push(...gi(a,t,n)),l.childKeys}if(k.isConditionalExpression(e)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:Et(e.test,n),conditionSource:$e(e.test,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:Ye(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...Gt(e.consequent,t,n)),s.childKeys.push(...Gt(e.alternate,t,n)),s.childKeys}if(k.isLogicalExpression(e)&&WS(e.operator)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:Et(e.left,n),conditionSource:$e(e.left,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:Ye(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...Gt(e.right,t,n)),s.childKeys}if(k.isParenthesizedExpression(e))return Si(e.expression,t,n);if(k.isJSXElement(e)){let o=yi(e,t,n);return o?[o]:[]}return nr(e)?xi(e,t,n):[]}function HS(e){let t=e.argument;return t&&(k.isExpression(t)||nr(t))?t:null}function Or(e,t){let n=[];for(let r of e){if(k.isReturnStatement(r)){let o=HS(r);o&&n.push({argument:o,statement:r,condition:t});continue}if(k.isIfStatement(r)){let o=k.isBlockStatement(r.consequent)?r.consequent.body:[r.consequent];if(n.push(...Or(o,r.test)),r.alternate){let i=k.isBlockStatement(r.alternate)?r.alternate.body:[r.alternate];n.push(...Or(i,r.test))}continue}if(k.isSwitchStatement(r))for(let o of r.cases){let i=o.test?k.binaryExpression("===",r.discriminant,o.test):r.discriminant;n.push(...Or(o.consequent,i))}}return n}function Cd(e){return{routeId:e,rootKeys:[],elements:new Map,regions:[],fileIndex:new Map,version:1,diagnostics:[]}}function Rd(e){let{file:t,source:n,ast:r}=e,o=e.imports.map(f=>f.specifier),i=new Map,s=[],a=[],c=new Map,l=NS(r);kS(r,{"FunctionDeclaration|FunctionExpression|ArrowFunctionExpression"(f){let m=RS(f);if(!m)return;let d=f.node,g=[];if(k.isArrowFunctionExpression(d))k.isExpression(d.body)||nr(d.body)?g=[{argument:d.body,statement:k.returnStatement(k.isExpression(d.body)?d.body:null)}]:k.isBlockStatement(d.body)&&(g=Or(d.body.body));else{let C=d.body;k.isBlockStatement(C)&&(g=Or(C.body))}if(g.length===0){f.skip();return}let h=new Map;va(AS(r.program.body),Sa(t,m,i,s,l,[h]),h);let S=new Map;for(let C of d.params)for(let N of Ht(C))Ca(S,N);let E=k.isBlockStatement(d.body)?d.body.body:[],y=g[0]?.statement??null;for(let C of E){if(y&&C===y)break;k.isVariableDeclaration(C)&&va([C],Sa(t,m,i,s,l,[h,S]),S)}let v=Sa(t,m,i,s,l,[h,S]);for(let C of g){let N=Gt(C.argument,v,n);for(let A of N)a.includes(A)||a.push(A);if(C.condition){let A={kind:"conditional-branch",conditionExpression:Et(C.condition,n),conditionSource:$e(C.condition,n,v)};hi(v,"conditional-region","",C.statement,N,[A])}}f.skip()}});let u=[...i.keys()];return u.length>0&&c.set(t,u),{graph:{routeId:t,rootKeys:a,elements:i,regions:s,fileIndex:c,version:1,diagnostics:[]},localImports:o}}function Ra(e,t,n,r){return[...e.map(o=>({...o})),{fromFile:t,specifier:n,targetPath:r}]}function Ei(e,t,n){return{...e,details:{...e.details??{},entryFile:t,importStack:n.map(r=>({...r}))}}}async function GS(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 wd(e,t,n,r,o={}){let i=o.maxDepth??10,s=o.version??1,a=o.parseModule??Ut,c=new Map,l=new Map,u=new Map,f=[],m=new Set,d=E=>{let y=`${E.path}\0${E.code}\0${E.message}\0${JSON.stringify(E.details??{})}`;m.has(y)||(m.add(y),f.push(E))},g=[{file:e,source:t,depth:0,diagnosticEntryFile:e,importStack:[]},...(o.additionalEntries??[]).map(E=>({file:E.file,source:E.source,depth:0,diagnosticEntryFile:E.file,importStack:[]}))],h=new Set;for(;g.length>0;){let E=g.shift(),{file:y,source:v,depth:C,diagnosticEntryFile:N,importStack:A}=E;if(h.has(y))continue;h.add(y),c.set(y,v);let R=a(y,v);if(!R.ok){d(Ei(R.diagnostic,N,A));continue}u.set(y,R.module);let{graph:F,localImports:_}=o.validationOnly&&C<i?{graph:Cd(y),localImports:R.module.imports.map(L=>L.specifier)}:Rd(R.module);for(let L of F.elements.values())if(L.importedFrom&&Nt(L.importedFrom)){let oe=L.importedFrom,me=await Oo(y,oe,r);me.ok?(L.importedFrom=me.path,Jt(me.path)&&(L.isPublicUiComponent=!0)):kn(oe,y)||d(Ei(me.diagnostic,N,Ra(A,y,oe,me.diagnostic.path)))}if(l.set(y,F),C>=i)continue;let D=await GS(_,async L=>{if(au(L))return null;let oe=await Oo(y,L,r);if(!oe.ok)return kn(L,y)?null:{diagnostic:Ei(oe.diagnostic,N,Ra(A,y,L,oe.diagnostic.path))};let me=oe.path;if(h.has(me)||Jt(me))return null;let ee=Ra(A,y,L,me);try{let ce=await n(me);return{entry:{file:me,source:ce,depth:C+1,diagnosticEntryFile:N,importStack:ee}}}catch(ce){return{diagnostic:Ei({path:me,code:"import-read-failed",message:`Failed to read imported file: ${me}`,details:{fromFile:y,specifier:L,reason:ce instanceof Error?ce.message:String(ce)}},N,ee)}}});for(let L of D)L&&"entry"in L?g.push(L.entry):L&&d(L.diagnostic)}let S=YS(e,l,s,(o.additionalEntries??[]).map(E=>E.file));return S.diagnostics=f,{graph:S,allSources:c,diagnostics:f,parsedModules:u,entryModule:u.get(e)??null}}function YS(e,t,n,r=[]){let o=new Map,i=[],s=new Map,a=[];for(let[c,l]of t){for(let[u,f]of l.elements)o.set(u,f);for(let u of l.regions)i.push(u);for(let[u,f]of l.fileIndex){let m=s.get(u)??[];s.set(u,[...m,...f])}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}}import{SiteEditHistoryProvenanceSchema as CE}from"@vcp-dev/contracts";import{createHash as ZS,randomUUID as La}from"node:crypto";import Oe from"node:fs/promises";import Le from"node:path";var Dd=new WeakMap;function rr(e){return Dd.get(e)?.()??e.readIndex()}var gt=1,Na=1,QS=2,qS="index.json",eE="recovery.json",tE="transaction-journal.json",nE="document-version.json",Ii={maxEntries:100,maxSessionBytes:512*1024*1024,maxEntryBytes:128*1024*1024},te={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"},re=class extends Error{constructor(t,n,r){super(n),this.name="FileHistoryStoreError",this.code=t,r?.cause!==void 0&&(this.cause=r.cause)}};function Yt(){return{entries:new Map,blobSizes:new Map}}function vi(e,t){let n={entries:new Map,blobs:new Map,objectBytes:0};for(let r of e)Bd(n,r,t);return n}function Bd(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 jd(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 $d(e,t={}){let n=bE(e),r=kE(t.limits),o=wa(n),i=SE(n),s=await nt(i),a=await nt(o)||s;a||(await dE(n),await fE(n)),a||await IE(n);let c=Yt(),l=await Ri(n,c),u=new Set(a?(await Ti(n)).map(y=>y.stageId):[]);a||await Fd(n,l.entryIds,c);let f=l.digest,m=vi(l.entryIds,c),d=async y=>{let{index:v,sizeBytes:C}=await $r(n);if(Wd(v,y),v.digest!==f){let N=Yt();await Jd(n,v.entryIds,N,C),m=vi(v.entryIds,N),f=v.digest}return{...Fi(v),totalBytes:m.objectBytes+C}},g=async y=>{Da(y),await d(),await Ad(n,m,[y.entryId],y.blobIds,y.stageId),await Ci(n,y.stageId)},h=async(y,v)=>{let C=await d(v);Kd(y,C.entryIds.length);let N=Yt();for(let A of C.entryIds.slice(Math.min(C.cursor,y)+1,Math.max(C.cursor,y)+1))await Dr(n,A,N);return C},S=async()=>{if(await nt(o)||s)throw new re(te.RECOVERY_PENDING,"history store requires explicit recovery before accepting writes")},E={rootDir:n,recoveryRequired:a,async readDocumentVersion(){return Od(n)},async writeDocumentVersion(y){if(await S(),!Number.isInteger(y)||y<0)throw new re(te.INVALID_SCHEMA,"document version must be a non-negative integer");let v=await Od(n);y<=v||await Lr(Zd(n),{schemaVersion:1,version:Math.max(v,y)})},async stageAppend(y,v={}){await S();let C=await iE(y,r),N={schemaVersion:Na,stageId:La(),entryId:C.entryId,blobIds:C.blobs.map(A=>A.digest)};try{await sE(n,C),await cE(n,N,v.durableManifest!==!1)}catch(A){try{await g(N)}catch(R){throw new re(te.INDEX_CORRUPT,"staged history cleanup failed after preparation error",{cause:R})}throw A}return{stageId:N.stageId,entryId:N.entryId,blobIds:N.blobIds}},async discardStage(y){await S(),Ta(y);let v=await Pa(n,y);v&&await g(v)},async previewStagedAppend(y,v){await S();let C=await d(v);return(await Nd(n,r,y,C,m)).transition},async previewCursor(y,v){await S();let C=await h(y,v);return Vd(C,C.entryIds,y)},async publishStagedAppend(y,v,C){if(await S(),Ni(y,"entryId"),C){Ta(C);let _=await Pa(n,C);if(!_||_.entryId!==y)throw new re(te.INVALID_SCHEMA,"history stage does not match the published entry")}let N=await d(v),A=m,R=await Nd(n,r,y,N,A),F=await Md({rootDir:n,previousDigest:R.current.digest,entryIds:R.entryIds,cursor:R.cursor,readback:async()=>_d(n,R.usage),afterWrite:async()=>{C?await Ci(n,C):await uE(n,y),await Ad(n,R.usage,[...A.entries.keys()].filter(_=>!R.usage.entries.has(_)),[...A.blobs.keys()].filter(_=>!R.usage.blobs.has(_)))}});return m=R.usage,f=F.digest,F},async append(y){await S();let v=await d(),C=await E.stageAppend(y);try{return await E.publishStagedAppend(C.entryId,v.digest,C.stageId)}catch(N){throw await E.discardStage(C.stageId),N}},async readEntry(y){return Ni(y,"entryId"),Dr(n,y)},async readBlob(y){Ni(y,"blobId");let v=await qd(n,y),C=await Br(v,te.NOT_FOUND,"blob");return Yd(C,y,v),C},async readIndex(){let y=Yt(),v=await Ri(n,y);return m=vi(v.entryIds,y),f=v.digest,v},async readStatus(){let y=await wi(n);return{canUndo:y.undoIds.length>0,canRedo:y.redoIds.length>0,undoDepth:y.undoIds.length,redoDepth:y.redoIds.length,cursor:y.cursor,recoveryRequired:await nt(o)||await nt(i)}},async readUndoRedoIds(){let y=await wi(n);return{undoIds:y.undoIds,redoIds:y.redoIds,currentId:y.currentId}},async setCursor(y,v){await S();let C=await h(y,v),N=await Md({rootDir:n,previousDigest:C.digest,entryIds:C.entryIds,cursor:y,readback:async()=>_d(n,m)});return f=N.digest,N},async markRecoveryRequired(y){await nt(o)||await Lr(wa(n),{schemaVersion:gt,reason:EE(y),createdAt:new Date().toISOString()})},async clearRecoveryRequired(){await Oe.rm(wa(n),{force:!0})},async readTransactionJournal(){return await nt(i)?ki(i):null},async writeTransactionJournal(y){await S(),Qd(y);try{await Lr(i,y)}catch(C){let N=await ki(i).catch(()=>null);if(N&&Buffer.from(rt(N)).equals(Buffer.from(rt(y))))return;throw N?new re(te.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous",{cause:C}):C}let v=await ki(i);if(!Buffer.from(rt(v)).equals(Buffer.from(rt(y))))throw new re(te.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous")},async clearTransactionJournal(y){let v=await nt(i)?await ki(i):null;if(v&&v.transactionId!==y)throw new re(te.INVALID_SCHEMA,"transaction journal changed concurrently");try{await Oe.rm(i,{force:!0})}catch(C){if(!await nt(i))return;throw C}if(await nt(i))throw new re(te.INDEX_CORRUPT,"transaction journal clear outcome is ambiguous");s=!1},async cleanupTmp(){await S();for(let C of u)await Ci(n,C),u.delete(C);await pE(n);let y=Yt(),v=await Ri(n,y);await Fd(n,v.entryIds,y),m=vi(v.entryIds,y),f=v.digest}};return Dd.set(E,()=>wi(n)),E}async function Nd(e,t,n,r,o){Ni(n,"entryId");let i=Yt(),s=await Dr(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))jd(a,u);Bd(a,s.id,i),c.push(s.id);let l=aE(c,t,a);return{current:r,entryIds:l.entryIds,cursor:l.cursor,usage:a,transition:Vd(r,l.entryIds,l.cursor)}}function Vd(e,t,n){return Kd(n,t.length),{expectedIndexDigest:e.digest,publishedIndexDigest:rE(t,n),publishedCursor:n,publishedCurrentId:t[n]??null}}function rE(e,t){return ln(rt({schemaVersion:gt,entryIds:e,cursor:t}))}function Kd(e,t){if(!Number.isInteger(e)||e<-1||e>=t)throw new re(te.INVALID_SCHEMA,`history cursor is out of bounds: ${e}`)}function oE(e){if(!vt(e))return!1;let t=e.publishedCursor,n=e.publishedCurrentId;return!at(e.expectedIndexDigest)||!at(e.publishedIndexDigest)||!Number.isInteger(t)||t<-1||n!==null&&!at(n)?!1:t===-1?n===null:at(n)}async function iE(e,t){if(!e.kind.trim())throw new re(te.INVALID_JSON,"history entry kind must not be empty");let n=[],r=[];for(let c of e.blobs??[]){if(!c.name.trim())throw new re(te.INVALID_JSON,"history blob name must not be empty");let l=xE(c.data),u=ln(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:gt,kind:e.kind,manifest:e.manifest,blobs:r},i=rt({...o}),s=ln(i),a=i.byteLength+n.reduce((c,l)=>c+l.sizeBytes,0);if(a>t.maxEntryBytes)throw new re(te.CAPACITY_EXCEEDED,`history entry exceeds maxEntryBytes (${a} > ${t.maxEntryBytes})`);return{entryBody:o,entryId:s,blobs:n}}async function sE(e,t){let n=Va(e,t.entryId),r={id:t.entryId,...t.entryBody},o=[...t.blobs.map(a=>Pd(Ka(e,a.digest),a.bytes,{kind:"blob",digest:a.digest},Ja(e,a.digest))),Pd(n,rt(r),{kind:"entry",digest:t.entryId},Ua(e,t.entryId))],s=(await Promise.allSettled(o)).find(a=>a.status==="rejected");if(s)throw s.reason}async function Pd(e,t,n,r){let o=await Ma(e)??(r?await Ma(r):null);if(o!==null){if(Buffer.compare(o,t)!==0)throw new re(n.kind==="blob"?te.BLOB_CORRUPT:te.ENTRY_CORRUPT,`${n.kind} content mismatch for ${n.digest}`);return}await Hd(e,t)}function aE(e,t,n){let r=[...e],o=r.length-1;for(;;){if(n.objectBytes+rt(zd(r,o)).byteLength<=t.maxSessionBytes&&r.length<=t.maxEntries)return{entryIds:r,cursor:o};if(o<=0||r.length===0)throw new re(te.CAPACITY_EXCEEDED,"history store exceeds capacity limits and the current entry cannot be trimmed");jd(n,r.shift()),o-=1}}async function cE(e,t,n){Da(t);let r=$a(e,t.stageId);if(n){await Lr(r,t);return}await yE(r,t)}async function Pa(e,t){let n=await Ma($a(e,t));if(n===null)return null;let r=Vr(Buffer.from(n).toString("utf8"),`history stage ${t}`),o=Da(r);if(o.stageId!==t)throw new re(te.INVALID_SCHEMA,`history stage id mismatch: ${t}`);return o}async function Ti(e){let t=[];for(let n of await Ai(ja(e))){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);Ta(r);let o=await Pa(e,r);o&&t.push(o)}return t}async function Ad(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 Ti(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 Td(Va(e,a),Ua(e,a));for(let a of new Set(r))!t.blobs.has(a)&&!s.has(a)&&await Td(Ka(e,a),Ja(e,a));await Oa(Kr(e)),await Oa(Ur(e))}async function Ci(e,t){await Aa($a(e,t)),await lE(e)}async function lE(e){try{await Oe.rmdir(ja(e))}catch(t){if(Jr(t)||vt(t)&&t.code==="ENOTEMPTY")return;throw t}}async function uE(e,t){for(let n of await Ti(e))n.entryId===t&&await Ci(e,n.stageId)}async function Aa(e){if(await Oe.rm(e,{force:!0}),await nt(e))throw new re(te.INDEX_CORRUPT,`unable to remove staged history object: ${e}`)}async function Td(e,t){await Aa(e),await Aa(t)}function Da(e){if(!vt(e)||e.schemaVersion!==Na||typeof e.stageId!="string"||!Ud(e.stageId)||!at(e.entryId))throw new re(te.INVALID_SCHEMA,"history stage schema is invalid");let t=Gd(e.blobIds,"history stage blobIds");return{schemaVersion:Na,stageId:e.stageId,entryId:e.entryId,blobIds:t}}function Ta(e){if(!Ud(e))throw new re(te.INVALID_PATH,"history stageId must be a UUID")}function Ud(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 Fd(e,t,n=Yt()){let r=new Set(t),o=new Set;for(let l of t){let u=await Dr(e,l,n);for(let f of u.blobs)o.add(f.digest)}for(let l of await Ti(e)){r.add(l.entryId);for(let u of l.blobIds)o.add(u)}let i=Kr(e),s=await Ai(i);for(let l of s){if(!l.endsWith(".json"))continue;let u=Ld(l.slice(0,-5));u&&!r.has(u)&&await Pi(Le.join(i,l))}let a=Ur(e),c=await Ai(a);for(let l of c){let u=Ld(l);u&&!o.has(u)&&await Pi(Le.join(a,l))}}async function Ri(e,t=Yt()){let{index:n,sizeBytes:r}=await $r(e),{totalBytes:o}=await Jd(e,n.entryIds,t,r);return{...Fi(n),totalBytes:o}}async function _d(e,t){let{index:n,sizeBytes:r}=await $r(e);return{...Fi(n),totalBytes:t.objectBytes+r}}async function $r(e){let t=Ba(e),n=await Br(t,te.NOT_FOUND,"index"),r=Vr(Buffer.from(n).toString("utf8"),"index");return{index:mE(r),sizeBytes:n.byteLength}}async function wi(e){return Fi((await $r(e)).index)}function Fi(e){let t=[...e.entryIds],n=t.slice(0,e.cursor+1).reverse(),r=t.slice(e.cursor+1);return{schemaVersion:gt,digest:e.digest,entryIds:t,cursor:e.cursor,currentId:t[e.cursor]??null,undoIds:n,redoIds:r}}async function Jd(e,t,n,r){let o=0,i=new Set;o+=r??(await $r(e)).sizeBytes;for(let s of new Set(t)){let a=await Dr(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 Dr(e,t,n=Yt()){let r=n.entries.get(t);if(r)return r.entry;let o=await vE(e,t),i=await Br(o,te.NOT_FOUND,"entry"),s=Vr(Buffer.from(i).toString("utf8"),`entry ${t}`),a=gE(s);if(a.id!==t)throw new re(te.ENTRY_CORRUPT,`entry id mismatch for ${t}`);if(ln(rt({schemaVersion:a.schemaVersion,kind:a.kind,manifest:a.manifest,blobs:a.blobs}))!==t)throw new re(te.ENTRY_CORRUPT,`entry hash mismatch for ${t}`);for(let l of a.blobs){if(n.blobSizes.has(l.digest))continue;let u=await qd(e,l.digest),f=await Br(u,te.NOT_FOUND,"blob");Yd(f,l.digest,u),n.blobSizes.set(l.digest,f.byteLength)}return n.entries.set(t,{entry:a,sizeBytes:i.byteLength}),a}async function Xd(e,t,n){await Lr(Ba(e),zd(t,n))}function zd(e,t){return{schemaVersion:gt,digest:ln(rt({schemaVersion:gt,entryIds:e,cursor:t})),entryIds:e,cursor:t}}function Wd(e,t){if(t!==void 0&&e.digest!==t)throw new re(te.INVALID_SCHEMA,`history index changed concurrently (expected ${t}, current ${e.digest})`)}async function Md(e){Wd(await wi(e.rootDir),e.previousDigest);let t=ln(rt({schemaVersion:gt,entryIds:e.entryIds,cursor:e.cursor}));try{await Xd(e.rootDir,e.entryIds,e.cursor),await e.afterWrite?.();let n=await e.readback();if(n.digest!==t)throw new re(te.INDEX_CORRUPT,"history index readback did not match the published transition");return n}catch(n){let r=await Ri(e.rootDir).catch(()=>null);if(r?.digest===t)return r;throw r?.digest===e.previousDigest?n:new re(te.INDEX_CORRUPT,"history index publish outcome is ambiguous",{cause:n})}}async function dE(e){await Oe.mkdir(e,{recursive:!0}),await Oe.mkdir(Kr(e),{recursive:!0}),await Oe.mkdir(Ur(e),{recursive:!0}),await Oe.mkdir(jr(e),{recursive:!0})}async function fE(e){await Oe.rm(jr(e),{recursive:!0,force:!0}),await Oe.mkdir(jr(e),{recursive:!0})}async function pE(e){let t=jr(e);await Oe.mkdir(t,{recursive:!0});for(let n of await Ai(t))n!=="stages"&&await Oe.rm(Le.join(t,n),{recursive:!0,force:!0})}function mE(e){if(!vt(e))throw new re(te.INDEX_CORRUPT,"index.json must be an object");if(e.schemaVersion!==gt)throw new re(te.INVALID_SCHEMA,`unsupported index schemaVersion: ${String(e.schemaVersion)}`);let t=Gd(e.entryIds,"index.entryIds"),n=e.cursor;if(!Number.isInteger(n)||n<-1||n>=t.length)throw new re(te.INDEX_CORRUPT,"index cursor is out of bounds");let r=n,o=e.digest;if(!at(o))throw new re(te.INDEX_CORRUPT,"index digest is invalid");let i=ln(rt({schemaVersion:gt,entryIds:t,cursor:r}));if(o!==i)throw new re(te.INDEX_CORRUPT,"index digest mismatch");return{schemaVersion:gt,digest:o,entryIds:t,cursor:r}}function gE(e){if(!vt(e))throw new re(te.ENTRY_CORRUPT,"entry must be an object");if(e.schemaVersion!==gt)throw new re(te.INVALID_SCHEMA,`unsupported entry schemaVersion: ${String(e.schemaVersion)}`);let t=e.id;if(!at(t))throw new re(te.ENTRY_CORRUPT,"entry id is invalid");let n=e.kind;if(typeof n!="string"||n.trim().length===0)throw new re(te.ENTRY_CORRUPT,"entry kind is invalid");let r=_a(e.manifest,"entry.manifest"),o=hE(e.blobs);return{id:t,schemaVersion:gt,kind:n,manifest:r,blobs:o}}function hE(e){if(!Array.isArray(e))throw new re(te.ENTRY_CORRUPT,"entry blobs must be an array");return e.map((t,n)=>{if(!vt(t))throw new re(te.ENTRY_CORRUPT,`entry blob ref ${n} must be an object`);let r=t.name;if(typeof r!="string"||r.trim().length===0)throw new re(te.ENTRY_CORRUPT,`entry blob ref ${n} name is invalid`);let o=t.digest;if(!at(o))throw new re(te.ENTRY_CORRUPT,`entry blob ref ${n} digest is invalid`);let i=t.sizeBytes;if(!Number.isInteger(i)||i<0)throw new re(te.ENTRY_CORRUPT,`entry blob ref ${n} sizeBytes is invalid`);return{name:r,digest:o,sizeBytes:i}})}async function Lr(e,t){await Hd(e,rt(t))}async function yE(e,t){let n=Le.dirname(e),r=Le.basename(e),o=Le.join(n,`.${r}.${process.pid}.${La()}.tmp`);await Oe.mkdir(n,{recursive:!0});try{await Oe.writeFile(o,rt(t),{flag:"wx"}),await Oe.rename(o,e)}finally{await Pi(o)}}async function Hd(e,t){let n=Le.dirname(e),r=Le.basename(e),o=Le.join(n,`.${r}.${process.pid}.${La()}.tmp`);await Oe.mkdir(n,{recursive:!0});try{let i=await Oe.open(o,"wx");try{await i.writeFile(t),await i.sync()}finally{await i.close()}await Oe.rename(o,e),await Oa(n)}finally{await Pi(o)}}function rt(e){return Buffer.from(JSON.stringify(Fa(e)),"utf8")}function Fa(e){if(Array.isArray(e))return e.map(t=>Fa(t));if(vt(e)){let t={};for(let n of Object.keys(e).sort())t[n]=Fa(e[n]);return t}return e}function Vr(e,t){try{return JSON.parse(e)}catch(n){throw new re(te.INVALID_JSON,`${t} is not valid JSON`,{cause:n})}}function _a(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=>_a(n,t));if(vt(e)){let n={};for(let[r,o]of Object.entries(e))n[r]=_a(o,t);return n}break}throw new re(te.INVALID_JSON,`${t} must be JSON-serializable`)}function Gd(e,t){if(!Array.isArray(e))throw new re(te.INDEX_CORRUPT,`${t} must be an array`);return e.map((n,r)=>{if(!at(n))throw new re(te.INDEX_CORRUPT,`${t}[${r}] is invalid`);return n})}function Ni(e,t){if(!at(e))throw new re(te.INVALID_PATH,`${t} must be a sha256 digest`)}function at(e){return typeof e=="string"&&/^sha256:[a-f0-9]{64}$/u.test(e)}function ln(e){return`sha256:${ZS("sha256").update(e).digest("hex")}`}function xE(e){return typeof e=="string"?Buffer.from(e,"utf8"):Buffer.from(e)}async function Br(e,t,n){try{return await Oe.readFile(e)}catch(r){throw new re(t,`${n} not found: ${e}`,{cause:r})}}async function Ma(e){try{return await Oe.readFile(e)}catch(t){if(Jr(t))return null;throw t}}function Yd(e,t,n){if(ln(e)!==t)throw new re(te.BLOB_CORRUPT,`blob hash mismatch for ${n}`)}async function nt(e){try{return await Oe.access(e),!0}catch(t){if(Jr(t))return!1;throw t}}async function Pi(e){try{await Oe.rm(e,{force:!0,recursive:!0})}catch{}}async function Oa(e){try{let t=await Oe.open(e,"r");try{await t.sync()}finally{await t.close()}}catch{}}async function Ai(e){try{return await Oe.readdir(e)}catch(t){if(Jr(t))return[];throw t}}function bE(e){if(typeof e!="string"||e.trim().length===0)throw new re(te.INVALID_ROOT,"history store rootDir must be a non-empty string");return Le.resolve(e)}function Ba(e){return Le.join(e,qS)}function wa(e){return Le.join(e,eE)}function SE(e){return Le.join(e,tE)}function Zd(e){return Le.join(e,nE)}async function Od(e){try{let t=await Oe.readFile(Zd(e),"utf8"),n=Vr(t,"document version");if(!vt(n)||n.schemaVersion!==1||!Number.isInteger(n.version)||n.version<0)throw new re(te.INVALID_SCHEMA,"document version schema is invalid");return n.version}catch(t){if(Jr(t))return 0;throw t}}async function ki(e){let t=await Br(e,te.RECOVERY_PENDING,"transaction journal"),n=Vr(Buffer.from(t).toString("utf8"),"transaction journal");return Qd(n),n}function Qd(e){if(!vt(e)||e.schemaVersion!==QS||typeof e.transactionId!="string"||e.transactionId.length===0||typeof e.operationId!="string"||e.operationId.length===0||!["prepared","files-written","history-published"].includes(e.phase)||!oE(e.historyTransition)||!Array.isArray(e.files))throw new re(te.INVALID_SCHEMA,"transaction journal schema is invalid");for(let t of e.files)if(!vt(t)||typeof t.path!="string"||t.path.length===0||t.preDigest!==null&&!at(t.preDigest)||t.postDigest!==null&&!at(t.postDigest))throw new re(te.INVALID_SCHEMA,"transaction journal file digest is invalid")}function EE(e){return e.replace(/[\r\n]+/g," ").slice(0,512)}function Kr(e){return Le.join(e,"entries")}function Ur(e){return Le.join(e,"blobs")}function jr(e){return Le.join(e,"tmp")}function ja(e){return Le.join(jr(e),"stages")}function $a(e,t){return Le.join(ja(e),`${t}.json`)}function Va(e,t){return Le.join(Kr(e),`${tf(t)}.json`)}function Ka(e,t){return Le.join(Ur(e),tf(t))}function Ua(e,t){return Le.join(Kr(e),`${t}.json`)}function Ja(e,t){return Le.join(Ur(e),t)}async function vE(e,t){return ef(Va(e,t),Ua(e,t))}async function qd(e,t){return ef(Ka(e,t),Ja(e,t))}async function ef(e,t){return await nt(e)?e:await nt(t)?t:e}function tf(e){return e.slice(7)}function Ld(e){let t=e.startsWith("sha256:")?e:`sha256:${e}`;return at(t)?t:null}function vt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Jr(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function kE(e){return{maxEntries:e?.maxEntries??Ii.maxEntries,maxSessionBytes:e?.maxSessionBytes??Ii.maxSessionBytes,maxEntryBytes:e?.maxEntryBytes??Ii.maxEntryBytes}}async function IE(e){let t=Ba(e);await nt(t)||await Xd(e,[],-1)}var RE={affectedCompositions:[]};function af(e){let t=null,n=new WeakMap;async function r(){return t??=wE(e),t}async function o(i){if(!i)return null;let s=Xa(i);return s?NE(e,s):i}return{async prepareAppend(i){let s=await rr(e),a=await e.stageAppend(of(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 rr(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),f={kind:"undo",entry:s,historyTransition:u};return n.set(f,{expectedDigest:a.digest,cursor:l}),f},async prepareRedo(){let i=await r(),s=await o(i.redo.at(-1));if(!s?.historyId)return null;let a=await rr(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),f={kind:"redo",entry:s,historyTransition:u};return n.set(f,{expectedDigest:a.digest,cursor:l}),f},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);nf(c,i.historyTransition),i.entry.historyId=s.entryId,Object.assign(a,or(c))}else{if(s.cursor===void 0)throw new Error("prepared cursor is missing");let c=i.kind==="undo"?a.undo:a.redo;if(Xa(c.at(-1))!==Xa(i.entry))throw new Error("history state changed before publish");let l=await e.setCursor(s.cursor,s.expectedDigest);nf(l,i.historyTransition),Object.assign(a,or(l))}n.delete(i)},async discardPrepared(i){let s=n.get(i);if(!s)return;let a=i.historyTransition;if(a){let c=await rr(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 f=await e.setCursor(u);Object.assign(s,or(f));return}catch(f){throw s.redo.push(i),f}}let c=await e.append(of(i)),l=c.currentId;if(!l)throw new Error("history store did not publish an entry");i.historyId=l,Object.assign(s,or(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,or(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 nf(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 Xa(e){return typeof e=="string"?e:e?.historyId}async function wE(e){let t=await rr(e);return or(t)}function or(e){return{undo:[...e.undoIds].reverse(),redo:[...e.redoIds].reverse(),entryIds:[...e.entryIds],cursor:e.cursor}}async function NE(e,t){let n=await e.readEntry(t),r=PE(n),o=r.provenance??RE;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 rf(e,n,r.preSnapshots),postSnapshots:await rf(e,n,r.postSnapshots)}}async function rf(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(FE(r,o.blobName))).toString("utf8"):"";return{file:o.file,content:i,version:o.version,exists:o.exists,...o.sha256?{sha256:o.sha256}:{}}}))}function of(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=AE(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 PE(e){if(!lf(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:cf(t.provenance)}:{},preSnapshots:sf(t.preSnapshots,"preSnapshots"),postSnapshots:sf(t.postSnapshots,"postSnapshots")}}function AE(e){if(e.provenance!==void 0)return cf(e.provenance);if(e.composition)return{initiatingComposition:e.composition,affectedCompositions:[]}}function cf(e){let t=CE.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 sf(e,t){return e.map((n,r)=>{if(!lf(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&&!TE(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 TE(e){return/^sha256:[0-9a-f]{64}$/.test(e)}function FE(e,t){let n=e.get(t);if(!n)throw new Error(`durable history blob is missing: ${t}`);return n}function lf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{randomBytes as WE}from"node:crypto";import Mi from"node:path";import{parse as bf}from"@babel/parser";import HE from"@babel/traverse";import*as Sf from"@babel/types";import{COMPONENT_I18N_FILE_SUFFIX as Wa,PageResourceArtifactSchema as GE,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as YE,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as ZE,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as QE,parseComponentI18nResourcesJson as qE}from"@vcp-dev/contracts";var df=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\(/i,ff=/\b(?:bg-black|bg-white|text-white|text-black)(?:\b|\/)/g,_E=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke)-\[#(?:[0-9a-fA-F]{3,8})\](?:\/\d+)?/g,ME=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*#[0-9a-fA-F]{3,8}[^'"]*['"]/g,OE=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*rgba?\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,LE=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,DE=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,BE=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*(?:oklch|lab|lch|hsla?)\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,jE=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*(?:oklch|lab|lch|hsla?)\([^)]+\)[^'"]*['"]/gi,$E=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*color-mix\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,VE=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*color-mix\([^'"]*['"]/gi,KE=/\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,UE=/var\(\s*--(?:_|private-|vcp-)[^)]+\)/gi,JE=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\([^)]*\)/gi;function Xr(e,t){let n=_i([...ht(e,_E),...ht(e,ME),...ht(e,OE),...ht(e,t.includeRgbBackgroundImage?LE:DE),...t.includeExtendedColorFunctions?[...ht(e,BE),...ht(e,jE)]:[]]),r=_i([...ht(e,$E),...ht(e,VE)]).filter(o=>t.colorMixPolicy==="always"||df.test(o));return n.push(...r.filter(o=>!n.includes(o))),t.rejectTailwindPalette&&n.push(...ht(e,KE).filter(o=>!n.includes(o))),t.rejectAnyRawColorLiteral&&n.push(...ht(e,JE).filter(o=>!n.includes(o))),{hardCodedSurfaceHits:_i(ht(e,ff)),hardCodedSurfaceOccurrences:zE(e),rawColorHits:n,privateTokenHits:t.rejectPrivateTokens?_i(ht(e,UE)):[]}}function ht(e,t){return e.match(new RegExp(t.source,t.flags))??[]}var uf=160,XE=/((?:[a-z][a-z0-9-]*(?:\[[^\]]*\])?:)+)$/;function zE(e){let t=new RegExp(ff.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),d=e.slice(n[f]??0,m===-1?void 0:m).trim();o.push({token:a,variant:u?.[1]??"",alpha:c?Number(c[1]):null,line:f+1,snippet:d.length>uf?`${d.slice(0,uf-1)}\u2026`:d})}return o}function _i(e){return[...new Set(e)]}var Ha="{{$INSTANCE}}",ev=/\{\{\$PAGE_ROUTE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,tv=/\{\{\$PAGE_TITLE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,Ga="components/site/generated",nv=/\.(?:tsx?|json)$/,rv=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,ov=["react","react/","next","next/","lucide-react","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],iv=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),za=HE,sv=typeof za=="function"?za:za.default;async function Ya(e){let t=GE.safeParse(e.artifact);if(!t.success)return Te("Page resource artifact failed contract validation.");let n=t.data,r=e.randomHex??(()=>WE(4).toString("hex")),o=Math.max(1,Math.min(e.maxAttempts??5,5)),i=gv(r());if(!i)return Te("Random instance suffix must be 8 lowercase hex chars.");let s=`${hv(n.resource_id)}-${i}`,a=new Map,c=new Map,l=[];for(let v of n.pages){let C=v.final_route.slice(1);a.set(v.template_page_id,v.final_route),c.set(v.template_page_id,v.title),l.push({template_page_id:v.template_page_id,title:v.title,final_route:v.final_route,route_file_path:`app/${C}/page.tsx`})}let u=[],f=new Set,m=new Set,d=new Map,g=new Map,h=[],S=new Set(n.pages.flatMap(v=>v.components.map(C=>C.component_id)));for(let v of n.components){if(!S.has(v.component_id))continue;let C=pf({materialization:v.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c});if(!C.ok)return C;for(let N of C.files){let A=gf(N,f,u);if(A)return A}m.add(C.entry),g.set(C.entry,C.entryExport),d.set(v.component_id,C.entry)}for(let[v,C]of n.pages.entries()){let N=l[v],A=pf({materialization:C.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c,pageEntryTarget:N.route_file_path,pageTitle:N.title});if(!A.ok)return A;for(let R of A.files){let F=gf(R,f,u);if(F)return F}m.add(A.entry),g.set(A.entry,A.entryExport),h.push({entry:A.entry,declaredComponentIds:new Set(C.components.map(R=>R.component_id))})}let E=cv(u,m,s,d,h,g);if(!E.ok)return E;for(let v of u)if(await e.exists(v.file))return!v.file.startsWith("app/")&&o>1?Ya({...e,randomHex:r,maxAttempts:o-1}):{ok:!1,code:"MATERIALIZATION_CONFLICT",message:`Page resource create-only target already exists: ${v.file}`,path:v.file};let y=lv(u);return y||(u.sort((v,C)=>v.file.localeCompare(C.file)),{ok:!0,packageInstanceId:s,pages:l,files:u})}function pf(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:mf(o.pathTemplate,e.packageInstanceId);if(!s)return Te("Materialization path cannot be mapped into the package namespace.",o.pathTemplate);let a=av(o.content,e.packageInstanceId,e.routeByPage,e.titleByPage);if(!a.ok)return a;let c=i&&e.pageTitle!==void 0?dv(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??mf(t,e.packageInstanceId);return!r||!n.some(o=>o.file===r)?Te("Materialization entry must match one controlled source file.",t):{ok:!0,files:n,entry:r,entryExport:e.materialization.entry.export}}function av(e,t,n,r){let o,i=e.replace(ev,(c,l)=>{let u=n.get(l);return u||(o=l,c)});if(o)return Te(`Page route placeholder references unknown template page: ${o}`);let s=i.replace(tv,(c,l)=>{let u=r.get(l);return u?JSON.stringify(u):(o=l,c)});if(o)return Te(`Page title placeholder references unknown template page: ${o}`);let a=s.replaceAll(Ha,t);return a.includes("{{$PAGE_ROUTE:")||a.includes("{{$PAGE_TITLE:")||a.includes("{{$INSTANCE}}")?Te("Materialization contains an unresolved placeholder."):{ok:!0,data:a}}function mf(e,t){let n=`${Ga}/${t}`;if(e.split(Ha).length>2)return null;let o=e.replace(Ha,t),i=`${Ga}/${t}/`,s=o.startsWith(i)?o:`${n}/${o}`,a=Mi.posix.normalize(s);return a!==s||!a.startsWith(`${n}/`)||!nv.test(a)||rv.test(a)?null:a}function gf(e,t,n){return t.has(e.file)?Te(`Page resource materializations resolve duplicate target: ${e.file}`,e.file):(t.add(e.file),n.push(e),null)}function cv(e,t,n,r,o,i){let s=new Set(e.map(d=>d.file)),a=`${Ga}/${n}`,c=new Map(e.map(d=>[d.file,new Set])),l=new Map;for(let d of e){if(d.file.endsWith(".json")){try{JSON.parse(d.content)}catch{return Te("Materialization JSON file must contain valid JSON.",d.file)}if(d.file.endsWith(Wa)&&!qE(d.content).success)return Te("Materialization component i18n resources are invalid.",d.file);continue}try{let h=bf(d.content,{sourceType:"module",plugins:["jsx","typescript"]});l.set(d.file,h);for(let E of h.program.body)if((E.type==="ImportDeclaration"||E.type==="ExportAllDeclaration"||E.type==="ExportNamedDeclaration"&&E.source)&&E.source){let y=E.source.value,v=pv(d.file,y,s,a);if(!v.allowed)return Te(`Materialization import is outside the controlled package: ${y}`,d.file);v.internalPath&&c.get(d.file).add(v.internalPath)}let S;if(sv(h,{Identifier(E){E.isReferencedIdentifier()&&iv.has(E.node.name)&&(S??=E.node.name,E.stop())},JSXAttribute(E){E.node.name.type==="JSXIdentifier"&&E.node.name.name==="style"&&(S??="inline style",E.stop())},JSXOpeningElement(E){E.node.name.type==="JSXIdentifier"&&E.node.name.name.toLowerCase()==="style"&&(S??="style element",E.stop())}}),S)return Te(`Materialization source uses forbidden capability: ${S}`,d.file)}catch{return Te("Materialization source must parse as TS/TSX.",d.file)}let g=Xr(d.content,{colorMixPolicy:"always",includeExtendedColorFunctions:!0,includeRgbBackgroundImage:!0,rejectAnyRawColorLiteral:!0,rejectPrivateTokens:!0,rejectTailwindPalette:!0});if(g.hardCodedSurfaceHits.length>0||g.rawColorHits.length>0||g.privateTokenHits.length>0)return Te("Materialization source violates the public theme token policy.",d.file)}if([...t].some(d=>!s.has(d)))return Te("Materialization entry is outside the controlled package.");for(let d of t)if(d.endsWith(".json"))return Te("Materialization JSON files cannot be package entries.");for(let[d,g]of i){let h=l.get(d);if(!h||!uv(h,g))return Te("Materialization entry does not declare its contracted export.",d)}let u=new Map([...r].map(([d,g])=>[g,d]));for(let d of o){let g=xf(d.entry,c);for(let h of d.declaredComponentIds){let S=r.get(h);if(!S||!g.has(S))return Te(`Page entry does not reach declared component: ${h}`,d.entry)}for(let h of g){let S=u.get(h);if(S&&!d.declaredComponentIds.has(S))return Te(`Page entry imports undeclared component: ${S}`,d.entry)}}let f=new Set;for(let d of t)for(let g of xf(d,c))f.add(g);if(f.size!==e.length)return Te("Every materialization file must be reachable from a package entry.");let m=mv(e,l,c);return m||{ok:!0}}function lv(e){if(e.length>YE)return Te("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>ZE)return Te("Page resource file exceeds the content byte limit.",n.file);t+=r}return t>QE?Te("Page resource exceeds the aggregate content byte limit."):null}function uv(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 dv(e,t,n){let r;try{r=bf(e,{sourceType:"module",sourceFilename:n,plugins:["jsx","typescript"]})}catch{return Te("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=hf(s.init);if(a?.type!=="ObjectExpression")return{ok:!0,data:e};let c=a.properties.find(u=>u.type==="ObjectProperty"&&!u.computed&&fv(u.key));if(!c||c.type!=="ObjectProperty")return{ok:!0,data:e};let l=hf(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 hf(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression"||t?.type==="TSNonNullExpression";)t=t.expression;return t&&Sf.isExpression(t)?t:null}function fv(e){return e.type==="Identifier"&&e.name==="title"||e.type==="StringLiteral"&&e.value==="title"}function pv(e,t,n,r){if(t.startsWith(`@/${r}/`)){let s=t.slice(2),a=yf(s,n);return a?{allowed:!0,internalPath:a}:{allowed:!1}}if(!t.startsWith("."))return{allowed:ov.some(s=>s.endsWith("/")?t.startsWith(s):t===s)};if(t.includes("\\")||t.includes("\0"))return{allowed:!1};let o=Mi.posix.normalize(Mi.posix.join(Mi.posix.dirname(e),t)),i=yf(o,n);return i&&(i.startsWith(`${r}/`)||i.startsWith("app/"))?{allowed:!0,internalPath:i}:{allowed:!1}}function yf(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 mv(e,t,n){let r=new Set(e.map(o=>o.file));for(let o of e){if(!o.file.endsWith(Wa))continue;let i=o.file.slice(0,-Wa.length),s=[`${i}.tsx`,`${i}.ts`].find(u=>r.has(u));if(!s)return Te("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 Te("Component i18n resources must have exactly one same-name Client Component static importer.",s)}return null}function xf(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 gv(e){return/^[a-f0-9]{8}$/.test(e)?e:null}function hv(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"page-resource"}function Te(e,t){return{ok:!1,code:"MATERIALIZATION_REJECTED",message:e,...t?{path:t}:{}}}import{randomBytes as yv}from"node:crypto";import Zt from"node:path";import{parse as xv}from"@babel/parser";import bv from"@babel/traverse";import{COMPONENT_I18N_FILE_SUFFIX as Oi,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as Ef,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as Sv,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as Ev,SiteEditMaterializationSchema as vv,parseComponentI18nResourcesJson as kv}from"@vcp-dev/contracts";var qa="components/site/generated",vf="{{$INSTANCE}}",Li=5,Iv=/^[a-z][a-z0-9-]{0,48}$/,Cv=/^[a-f0-9]{8}$/,kf=/\.tsx?$/,Rv=/\.json$/,wv=/\.(?:tsx?|json)$/,Nv=/^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/,Pv=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,Av=["react","react/","next","next/","lucide-react","react-i18next","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],Za=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),Qa=bv,Tv=typeof Qa=="function"?Qa:Qa.default;function Fv(e){let t=Array.isArray(e.manifest.files)?e.manifest.files:[];if(t.length>Ef)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file count exceeds the reusable limit."}};let n=Uv(t);if(n)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Static prefab resolves duplicate target path: ${n}`,path:n}};let r=vv.safeParse(e.manifest);if(!r.success)return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab manifest failed schema validation."}};let o=$v(e.generatedRoot);if(!o)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Generated root must be ${qa}.`,path:e.generatedRoot}};if(!Pf(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=Rf(r.data.files),s=Rf(e.controlledFiles);if(!Jv(i,s))return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Controlled file list must exactly match the manifest file templates."}};if(i.size>Ef)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>Sv)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>Ev?{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 _v(e){let t=Fv(e);if(!t.ok)return t;let n=Object.keys(e.manifest.projectDependencies??{}),r=new Set(e.availableHostDependencies??[]),o=n.find(u=>!Nv.test(u)||!r.has(u));if(o)return{ok:!1,error:{code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:`Declared project dependency is not available in the target site host: ${o}.`,path:o}};let i=n.flatMap(u=>[u,`${u}/`]),s=[...e.allowedExternalImports??Av,...i],a=t.data.generatedRoot,c=Pf(e.manifest.instanceBaseName),l=Math.max(1,Math.min(Li,e.maxAttempts??Li));for(let u=0;u<l;u+=1){let f=Vv(e.instanceNameGenerator?.()??yv(4).toString("hex"));if(!f)return{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_INVALID",message:"Static prefab instance suffix must be 8 lowercase hex chars."}};let m=`${c}-${f}`,d=Tf(a,m),g=Mv({manifest:e.manifest,generatedRoot:a,instanceName:m,instanceRoot:d,allowedExternalImports:s});if(!g.ok)return g;if(!await Ov(e.exists,d,g.data.files))return{ok:!0,data:g.data}}return{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:"Unable to allocate a create-only static prefab instance after repeated conflicts."}}}async function Nf(e){let t=Math.max(1,Math.min(Li,e.maxAttempts??Li));for(let n=0;n<t;n+=1){let r=await _v({...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 Mv(e){let t=[],n=new Set;for(let i of e.manifest.files){let s=If({pathTemplate:i.pathTemplate,generatedRoot:e.generatedRoot,instanceName:e.instanceName,instanceRoot:e.instanceRoot});if(!s.ok)return s;if(n.has(s.data))return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Static prefab resolves duplicate target path: ${s.data}`,path:s.data}};n.add(s.data),t.push({kind:"create-only",path:s.data,content:i.content,...i.role?{role:i.role}:{},sourcePathTemplate:i.pathTemplate})}t.sort((i,s)=>i.path.localeCompare(s.path));let r=If({pathTemplate:e.manifest.entry.pathTemplate,generatedRoot:e.generatedRoot,instanceName:e.instanceName,instanceRoot:e.instanceRoot});if(!r.ok)return r;if(!t.some(i=>i.path===r.data))return{ok:!1,error:{code:"MATERIALIZATION_ENTRY_INVALID",message:"Entry path must match one of the static prefab files.",path:r.data}};let o=Lv(t,e.instanceRoot,r.data,e.manifest.entry.export,e.allowedExternalImports);return o.ok?{ok:!0,data:{kind:"static-prefab-materialization",instanceName:e.instanceName,generatedRoot:e.generatedRoot,instanceRoot:e.instanceRoot,entry:{path:r.data,export:e.manifest.entry.export},files:t}}:o}async function Ov(e,t,n){if(await e(t))return!0;for(let r of n)if(await e(r.path))return!0;return!1}function If(e){if(e.pathTemplate.split(vf).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(vf,e.instanceName),n=Kv(t);return n?Tf(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||!wv.test(n)||Pv.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 Lv(e,t,n,r,o){let i=new Set(e.map(f=>f.path)),s=new Map,a=new Map(e.map(f=>[f.path,new Set])),c=new Map;for(let f of e){if(Rv.test(f.path)){if(f.path.endsWith(Oi)){let g=kv(f.content);if(!g.success)return Pn("MATERIALIZATION_DATA_UNSUPPORTED",g.error.message,f.path);c.set(f.path,new Set)}else try{JSON.parse(f.content)}catch{return Pn("MATERIALIZATION_DATA_UNSUPPORTED","Static prefab JSON file must contain valid JSON.",f.path)}continue}let m;try{m=xv(f.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:f.path}}}let d=Xr(f.content,{colorMixPolicy:"always",includeExtendedColorFunctions:!0,includeRgbBackgroundImage:!0,rejectAnyRawColorLiteral:!0,rejectPrivateTokens:!0,rejectTailwindPalette:!0});if(d.hardCodedSurfaceHits.length>0||d.rawColorHits.length>0||d.privateTokenHits.length>0)return{ok:!1,error:{code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source must use public semantic design tokens instead of raw colors or private tokens.",file:f.path}};s.set(f.path,m)}for(let f of e){if(!kf.test(f.path))continue;let m=s.get(f.path),d=null;if(Tv(m,{ImportDeclaration(g){let h=Cf({importer:f.path,source:g.node.source.value,instanceRoot:t,filePaths:i,allowedExternalImports:o});if(!h.allowed)d??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab imports must resolve within the controlled instance or match the starter allowlist.",file:f.path},g.stop();else if(h.internalPath&&(a.get(f.path).add(h.internalPath),h.internalPath.endsWith(Oi))){let S=Dv({importer:f.path,imported:h.internalPath,source:g.node.source.value,ast:m});S.ok?c.get(h.internalPath).add(f.path):(d??=S.error,g.stop())}},ExportAllDeclaration(g){d??={code:"MATERIALIZATION_ENTRY_INVALID",message:"Static prefab files cannot use export-star declarations.",file:f.path},g.stop()},ExportNamedDeclaration(g){if(g.node.source){let h=Cf({importer:f.path,source:g.node.source.value,instanceRoot:t,filePaths:i,allowedExternalImports:o});!h.allowed||!h.internalPath?(d??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab re-exports must resolve within the controlled instance.",file:f.path},g.stop()):a.get(f.path).add(h.internalPath)}},CallExpression(g){if(g.node.callee.type==="Import"){d??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab files cannot use dynamic import().",file:f.path},g.stop();return}g.node.callee.type==="Identifier"&&g.node.callee.name==="require"&&(d??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab files cannot use require().",file:f.path},g.stop())},NewExpression(g){g.node.callee.type==="Identifier"&&g.node.callee.name==="Function"&&(d??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot construct functions dynamically.",file:f.path},g.stop())},MetaProperty(g){g.node.meta.type==="Identifier"&&g.node.meta.name==="import"&&(d??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot use import.meta.",file:f.path},g.stop())},MemberExpression(g){let h=wf(g.node);h&&Za.has(h)&&(d??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${h}.`,file:f.path},g.stop())},OptionalMemberExpression(g){let h=wf(g.node);h&&Za.has(h)&&(d??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${h}.`,file:f.path},g.stop())},Identifier(g){g.isReferencedIdentifier()&&Za.has(g.node.name)&&(d??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${g.node.name}.`,file:f.path},g.stop())},JSXAttribute(g){g.node.name.type==="JSXIdentifier"&&g.node.name.name==="style"&&(d??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot use inline style attributes.",file:f.path},g.stop())},JSXOpeningElement(g){g.node.name.type==="JSXIdentifier"&&g.node.name.name.toLowerCase()==="style"&&(d??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot declare style elements.",file:f.path},g.stop())}}),d)return{ok:!1,error:d}}if(!kf.test(n))return Pn("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must be a .ts/.tsx source module.",n);let l=s.get(n);if(!l)return Pn("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must resolve to a controlled source file.",n);if(!Bv(l,r))return Pn("MATERIALIZATION_EXPORT_MISSING","Static prefab entry does not declare the manifest export.",n);for(let[f,m]of c)if(m.size!==1)return Pn("MATERIALIZATION_IMPORT_FORBIDDEN","Each component .i18n.json file must have exactly one same-name Client Component static importer.",f);return jv(n,a).size!==e.length?Pn("MATERIALIZATION_ENTRY_INVALID","Every controlled source file must be reachable from the entry module.",n):{ok:!0,data:{kind:"static-prefab-materialization",instanceName:"",generatedRoot:qa,instanceRoot:"",entry:{path:"",export:{kind:"default"}},files:[]}}}function Cf(e){if(!e.source.startsWith("./")&&!e.source.startsWith("../"))return e.source.startsWith("@/components/site/generated/")?{allowed:!1}:{allowed:e.allowedExternalImports.some(o=>o.endsWith("/")?e.source.startsWith(o):e.source===o)};if(e.source.includes("\\")||e.source.includes("\0"))return{allowed:!1};let t=Zt.posix.normalize(Zt.posix.join(Zt.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 Dv(e){let t=Zt.posix.dirname(e.importer),n=Zt.posix.dirname(e.imported),r=Zt.posix.basename(e.importer).replace(/\.tsx?$/,""),o=Zt.posix.basename(e.imported).slice(0,-Oi.length),i=`./${r}${Oi}`;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 Bv(e,t){for(let n of e.program.body){if(t.kind==="default"&&n.type==="ExportDefaultDeclaration")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 jv(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 Pn(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{file:n}:{}}}}function $v(e){let t=Af(e);return t===qa?t:null}function Vv(e){let t=e.trim().toLowerCase();return Cv.test(t)?t:null}function Pf(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 Iv.test(t)?t:null}function Af(e){if(!e||e.startsWith("/")||e.includes("\\"))return null;let t=Zt.posix.normalize(e);return t==="."||t.startsWith("../")||t.includes("/../")||t.includes("//")?null:t}function Kv(e){let t=Af(e);return!t||t!==e?null:t}function Tf(...e){return Zt.posix.join(...e)}function Rf(e){return new Set(e.map(t=>t.pathTemplate))}function Uv(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 Jv(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function wf(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 mc}from"node:crypto";import ac from"@babel/traverse";function ec(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}}import{createHash as Xv}from"node:crypto";import Ff from"node:path";import*as Df from"@babel/parser";import tc from"@babel/generator";import*as Ue from"@babel/types";var _f=typeof tc=="function"?tc:tc.default;function rc(e){let t=jf(e);if(t)return{ok:!1,error:t};let n=e.projection,r=sc(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=Hv(n,o),s={jsx:`<${e.component.localName} />`},a=zv(e);if(i){let d=nc(e);return d.ok?{ok:!0,plan:{kind:"route-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:e.placementKey,placementUnitKey:o.placementUnitKey,importStep:a,rewriteStep:{kind:"insert-root-expression",locator:d.locator,sourceHash:d.sourceHash,node:s,placement:o.relation,replaceOriginal:n.container.kind==="starter-placeholder"}}}:d.result}let c=o.containerSourceRange??n.container.sourceRange,l=o.containerSourceHash??(ic(c,n.container.sourceRange)?n.container.sourceHash:null);if(!c||!l)return zr("Route page composition does not expose a verifiable container boundary.");let u=Hr(c),f=Of(e.source,u,l,"Route page composition container");if(!f.ok)return f.result;let m=o.anchorSourceRange?Hr(o.anchorSourceRange):void 0;if(m){if(!o.anchorSourceHash)return zr("Route page composition placement does not expose a verifiable anchor boundary.");let d=Of(e.source,m,o.anchorSourceHash,"Route page composition anchor");if(!d.ok)return d.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:a,rewriteStep:{kind:"insert-child",parentLocator:u,node:s,placement:o.relation,...m?{anchorLocator:m}:{}}}}}function zv(e){let t=Qv(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 Di(e){if(e.locator.root.kind!=="expression"||e.locator.path?.length)return An(e.source,"Root expression rewrite requires an exact expression locator.");let t=kr(e.source,"value");if(!t.ok)return An(e.source,t.diagnostic.message);let n=se(t.ast,e.locator);if(!n.ok)return An(e.source,n.diagnostic.message);let r=n.match.path;if(!r.isExpression())return An(e.source,"Resolved value locator does not point to an expression.");let o=ir(e.source,r.node.start??null,r.node.end??null);if(!o||o!==e.expectedSourceHash)return An(e.source,"Root expression hash no longer matches the current source.");if(e.action.kind==="remove")return r.replaceWith(Ue.nullLiteral()),{ok:!0,source:_f(t.ast,{}).code};let i;try{i=Df.parseExpression(e.action.jsx,{plugins:["jsx","typescript"]})}catch(s){return An(e.source,s instanceof Error?s.message:String(s))}return!Ue.isJSXElement(i)&&!Ue.isJSXFragment(i)?An(e.source,"Root expression rewrite requires a JSX insertion expression."):(e.action.kind==="replace"?r.replaceWith(i):r.replaceWith(Wv(r.node,i,e.action.placement,e.action.replaceOriginal)),{ok:!0,source:_f(t.ast,{}).code})}function Wv(e,t,n,r){if(Ue.isNullLiteral(e)||r)return t;let o=Ue.isJSXFragment(e)?[...e.children]:[Ue.isJSXElement(e)?e:Ue.jsxExpressionContainer(e)],s=n==="before"||n==="prepend"?[t,...o]:[...o,t];return Ue.jsxFragment(Ue.jsxOpeningFragment(),Ue.jsxClosingFragment(),s)}function An(e,t){return{ok:!1,source:e,diagnostic:{message:t}}}function oc(e){let t=jf(e);if(t)return{ok:!1,error:t};let n=e.projection,r=$f(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(Gv(n,o)){let h=nc(e);return h.ok?e.operation==="remove-node"&&!Mf(n,o.placementUnitKey)?zr("The last editable page unit cannot be deleted."):e.operation==="move-node"?zr("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=Hr(o.sourceRange),a=Tt(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?[]:[Wr(a.diagnostic)]}};if(ir(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=nc(e);return h.ok?Mf(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}}}:zr("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||!Zv(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=sc(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 f=u.containerSourceRange;if(!f||!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 m=Hr(f),d=Tt(e.source,m);if(!d.ok||!d.match.node)return{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:d.ok===!1?d.diagnostic.message:"Route page composition target container could not be resolved.",diagnostics:d.ok?[]:[Wr(d.diagnostic)]}};if(ir(e.source,d.match.node.start??null,d.match.node.end??null)!==u.containerSourceHash)return Lf("Route page composition target container hash no longer matches the current source.");if(u.relation==="before"||u.relation==="after"){let h=u.anchorSourceRange,S=u.anchorSourceHash;if(!h||!S)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Route page composition target placement does not expose a verifiable anchor boundary.",diagnostics:[]}};let E=Hr(h),y=Tt(e.source,E);return!y.ok||!y.match.node?{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:y.ok===!1?y.diagnostic.message:"Route page composition target anchor could not be resolved.",diagnostics:y.ok?[]:[Wr(y.diagnostic)]}}:ir(e.source,y.match.node.start??null,y.match.node.end??null)!==S?Lf("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:m,anchorLocator:E,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:m,placement:u.relation}}}}function Mf(e,t){for(let n of e.placementUnitByKey.values())if(n.placementUnitKey!==t&&n.members.length>0)return!0;return!1}function Hv(e,t){let n=e.placementUnitByKey.get(t.placementUnitKey);return n&&e.container.kind!=="jsx-container"&&ic(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 Gv(e,t){return e.container.kind!=="jsx-container"&&ic(t.sourceRange,e.mutationTarget.sourceRange)&&t.sourceHash===e.mutationTarget.sourceHash}function nc(e){let t=e.projection.mutationTarget,n={kind:"value",root:{kind:"expression",sourceRange:t.sourceRange}},r=Tt(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?[]:[Wr(r.diagnostic)]}}}:ir(e.source,r.match.node.start??null,r.match.node.end??null)!==t.sourceHash?{ok:!1,result:Bf("Route mutation target hash no longer matches the current source.")}:{ok:!0,locator:n,sourceHash:t.sourceHash}}function Of(e,t,n,r){let o=Tt(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?[]:[Wr(o.diagnostic)]}}}:ir(e,o.match.node.start??null,o.match.node.end??null)!==n?{ok:!1,result:Bf(`${r} hash no longer matches the current source.`)}:{ok:!0}}function Bf(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function zr(e){return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:e,diagnostics:[]}}}function Lf(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function Wr(e){return{code:"UNSUPPORTED_PAGE_SHAPE",message:e.message,details:{astCode:e.code}}}function jf(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&&!Yv(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 Yv(e,t){return e.routeId===t.routeId&&e.effectiveTemplateId===t.effectiveTemplateId}function Zv(e,t){return e.routeId===t.routeId&&e.templateId===t.effectiveTemplateId}function Qv(e,t){let n=Ff.posix.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=Ff.posix.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function Hr(e){return{kind:"jsx-node",strategy:"source-range",sourceRange:e}}function ir(e,t,n){return t==null||n==null?null:`sha256:${Xv("sha256").update(e.slice(t,n)).digest("hex")}`}function ic(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}var qv=typeof ac=="function"?ac:ac.default;function Jf(e){if(!e.ast)return kt(e,[Ve("UNSUPPORTED_PAGE_SHAPE","SourceGraph entry AST is required",{reason:"parsed-ast-required"})]);let t=ak(e.ast);if(!t)return kt(e,[Ve("UNSUPPORTED_PAGE_SHAPE","Route default export must resolve to a local function component",{reason:"default-export-unresolved"})]);let n=lk(t);if(!n.ok)return kt(e,[n.diagnostic]);let r=n.expression;if(r.isIdentifier()){let o=dk(r,t);if(o.status==="resolved")r=o.expression;else if(o.status==="invalid")return kt(e,[Ve("UNSUPPORTED_PAGE_SHAPE","Route default export local binding is not a supported JSX root")])}if(pk(r,t))return kt(e,[Ve("INDIRECT_RETURN_ONLY","Route default export only returns through an indirect function boundary")]);if(r.isNullLiteral())return lc(e,t,"virtual-route-root",r);if(fk(r)){let o=yk({input:e,source:e.source,expression:r});return cc(e,t,o,{kind:"virtual-route-root",sourceKind:"atomic-expression"},r)}if(r.isConditionalExpression())return kt(e,[Ve("UNSUPPORTED_PAGE_SHAPE","Route conditional root contains an unsupported branch shape",{reason:"ambiguous-placement"})]);if(r.isJSXElement()&&!Me(r)&&!un(r)){let o=fc(r),i=Uf({input:e,containerKind:"virtual-route-root",sourceKind:"jsx-element",source:e.source,containerPath:r,members:[o]});return cc(e,t,i,{kind:"virtual-route-root",sourceKind:"jsx-element"},r)}if(r.isJSXElement()||r.isJSXFragment()){let o=gk(r);if(!o.ok)return kt(e,[o.diagnostic]);let i=sr(o.path);if(i.unsupported)return kt(e,[Ve("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);if(mk(e.source,r,i.members))return lc(e,t,"starter-placeholder",r);let s=r.isJSXFragment()||Me(r);if(i.members.length===0&&s)return lc(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=Uf({input:e,containerKind:a,sourceKind:c,source:e.source,containerPath:o.path,members:i.members});return cc(e,t,l,{kind:a,sourceKind:c},r)}return kt(e,[Ve("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")])}function sc(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:Ve("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:Ve("PLACEMENT_KEY_NOT_FOUND","Placement key was not found in the projected page composition",{placementKey:t})}}function $f(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:Ve("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:Ve("PLACEMENT_KEY_NOT_FOUND","Placement unit key was not found in the projected page composition",{placementUnitKey:t})}}function Xf(e){return e.ok?ek(e.projection):tk(e.projection)}function ek(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 f=u.members.flatMap((h,S)=>zf(e,u,h,S,e.container.placementKey)),m=f.filter(({member:h})=>h.isBusinessMember).map(({sourceMember:h})=>rk(l,h,u.independent)),d=f.length>0?f:[{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,d.map(({sourceMember:h})=>h)),o.set(l,m);let g=d[0]?.sourceMember.key??l;n.push({key:l,containerKey:g,businessMemberKeys:m.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:nk(e,a),sourceMembers:i,businessMembers:s,placementUnits:n,placements:c}}function tk(e){let t=e.diagnostics.map(ok);return{status:"unsupported",version:e.version,composition:e.composition,reason:ik(e.diagnostics),diagnostics:t}}function nk(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 zf(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)=>zf(e,t,a,c,i))]}function rk(e,t,n){return{key:`business:${e}:${t.key}`,sourceMemberKey:t.key,containerKey:e,label:t.label,isIndependent:n}}function ok(e){return{code:sk(e),message:e.message}}function ik(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 sk(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 ak(e){let t=null;return qv(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=ck(o.path);i&&(t=i,n.stop())}}),t}function ck(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 lk(e){let t=e.get("body");if(!t.isBlockStatement()){let s=Yr(t);return s?{ok:!0,expression:s}:{ok:!1,diagnostic:Ve("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:Ve("ROUTE_RETURN_NOT_FOUND","Route default export does not contain a proven return boundary")};if(!r.isReturnStatement())return{ok:!1,diagnostic:Ve("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(!uk(s))return{ok:!1,diagnostic:Ve("UNSUPPORTED_PAGE_SHAPE","Route guard return shape is not statically safe",{reason:"guard-shape"})};continue}if(Wf(s)||Hf(s))return{ok:!1,diagnostic:Ve("UNSUPPORTED_PAGE_SHAPE","Route default export contains unsupported control flow before the terminal return",{reason:"control-flow-return"})}}let o=r.get("argument"),i=Yr(o);return i?{ok:!0,expression:i}:{ok:!1,diagnostic:Ve("ROUTE_RETURN_NOT_FOUND","Route default export returns without a boundary expression",{reason:"bare-return"})}}function uk(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(Wf(o)||Hf(o))return null;return r}function Wf(e){return e.isForStatement()||e.isForInStatement()||e.isForOfStatement()||e.isWhileStatement()||e.isDoWhileStatement()||e.isSwitchStatement()||e.isTryStatement()||e.isWithStatement()}function Hf(e){let t=!1;return e.traverse({Function(n){n.skip()},ReturnStatement(){t=!0}}),t}function dk(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=Yr(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 fk(e){return e.isConditionalExpression()?Vf(Yr(e.get("consequent")))&&Vf(Yr(e.get("alternate"))):!1}function Vf(e){return!!(e&&(e.isJSXElement()||e.isJSXFragment()||e.isNullLiteral()))}function Yr(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 pk(e,t){if(e.isIdentifier())return Kf(e.node.name,t);if(e.isCallExpression()){let n=e.get("callee");if(n.isIdentifier())return Kf(n.node.name,t)}return!1}function Kf(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 mk(e,t,n){return e.includes("DESIGN_PLAN_REPLACE_ME")&&t.isJSXElement()&&n.length>0&&dc(t)}function dc(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(!dc(t))return!1;continue}if(t.isJSXElement()&&!dc(t))return!1}return!0}function gk(e){let t=e;if(e.isJSXFragment()||Me(e)){let r=Gr(e),o=r[0];if(r.length===1&&o?.isJSXElement()&&un(o))t=o;else return{ok:!0,path:t}}for(;t.isJSXElement()&&un(t);){let r=Gr(t);if(r.length!==1)return{ok:!0,path:t};let o=r[0];if(!o?.isJSXElement()||!un(o))return{ok:!0,path:t};if(Gr(o).length<=1)return{ok:!0,path:t};t=o}return{ok:!0,path:t}}function Gr(e){let t=[];for(let n of e.get("children"))if(!Array.isArray(n)){if(n.isJSXText()){n.node.value.trim()&&t.push(n);continue}if(n.isJSXExpressionContainer()){let r=n.get("expression");!r.isJSXEmptyExpression()&&!r.isNullLiteral()&&t.push(n);continue}if(n.isJSXFragment()){t.push(...Gr(n));continue}n.isJSXElement()&&(Me(n)?t.push(...Gr(n)):t.push(n))}return t}function sr(e){let t=[],n=!1;for(let r of e.get("children")){if(r.isJSXText()){if(!r.node.value.trim())continue;t.push({memberKey:pc(r.node.type,r.node.start,r.node.end),kind:"text",nodeType:r.node.type,sourceRange:yt(r.node.loc),businessMemberCount:0,parentSourceRange:yt(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=sr(o);n||=i.unsupported,t.push(...i.members);continue}if(o.isJSXElement()){let i=un(o)?sr(o):null;n||=i?.unsupported??!1,t.push({...fc(o,i?.members),sourceRange:yt(r.node.loc),parentSourceRange:yt(e.node.loc)});continue}if(o.isJSXSpreadChild()){n=!0;continue}t.push({memberKey:pc(o.node.type,o.node.start,o.node.end),kind:"atomic-expression",nodeType:o.node.type,sourceRange:yt(r.node.loc),businessMemberCount:1,parentSourceRange:yt(e.node.loc),children:[],isBusinessMember:!0,label:"atomic-expression"});continue}if(r.isJSXFragment()||r.isJSXElement()&&Me(r)){let o=sr(r);n||=o.unsupported,t.push(...o.members);continue}if(r.isJSXElement()){let o=un(r)?sr(r):null;n||=o?.unsupported??!1,t.push({...fc(r,o?.members),parentSourceRange:yt(e.node.loc)})}}return{members:t,unsupported:n}}function fc(e,t){let n=e.isJSXElement()&&un(e)?t??sr(e).members:[],r=e.isJSXElement()&&!un(e)&&!Me(e);return{memberKey:pc(e.node.type,e.node.start,e.node.end),kind:"jsx-element",nodeType:e.node.type,sourceRange:yt(e.node.loc),businessMemberCount:r?1:Gf(n),parentSourceRange:yt(e.parentPath?.node.loc),children:n,isBusinessMember:r,label:hk(e)}}function un(e){let t=e.node.openingElement.name;return t.type==="JSXIdentifier"&&t.name[0]===t.name[0]?.toLowerCase()}function hk(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 Gf(e){return e.reduce((t,n)=>t+n.businessMemberCount,0)}function Bi(e){return e.length===0?0:Math.max(1,Gf(e))}function Uf(e){let t=yt(e.containerPath.node.loc),n=gc(e.source,e.containerPath.node.start,e.containerPath.node.end),r=xt(e.input,e.containerKind,e.sourceKind,t),o=xt(e.input,e.containerKind,"placement-unit",t);return{placementKey:r,placementUnitKey:o,version:e.input.version,containerKey:r,independent:Bi(e.members)<=1,memberCount:Bi(e.members),sourceRange:t,sourceHash:n,relation:"append",containerSourceRange:t,containerSourceHash:n,anchorSourceRange:null,anchorSourceHash:null,members:e.members}}function yk(e){let t=yt(e.expression.node.loc),n=gc(e.source,e.expression.node.start,e.expression.node.end),r=xt(e.input,"virtual-route-root","atomic-expression",t),o=xt(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:xt(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 Yf(e,t){let n=yt(t.node.loc),r=gc(e.source,t.node.start,t.node.end);return!n||!r?null:{kind:"expression",documentVersion:e.version,sourceRange:n,sourceHash:r}}function cc(e,t,n,r,o){let i=Yf(e,o);if(!i)return kt(e,[Ve("UNSUPPORTED_PAGE_SHAPE","Route default export does not provide an exact mutation target",{reason:"mutation-target-unavailable"})]);let s=n.containerSourceRange??n.sourceRange,a=xk(e,n,s),c=ec(a),l={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:Qf(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 xk(e,t,n){if(t.members.length===0)return[t];let r=[],o=(l,u,f,m,d,g,h=n)=>({...t,placementKey:u,placementUnitKey:f,containerKey:t.placementKey,independent:Bi(g)<=1,memberCount:Bi(g),sourceRange:m,sourceHash:m?uc(e.source,m):null,relation:l,containerSourceRange:h,containerSourceHash:h?uc(e.source,h):null,anchorSourceRange:d,anchorSourceHash:d?uc(e.source,d):null,members:g}),i=t.placementKey,s=t.members.map(l=>xt(e,i,"placement-unit",l.sourceRange)),a=s[0]??t.placementUnitKey,c=s.at(-1)??t.placementUnitKey;r.push(o("prepend",xt(e,i,"prepend",n),a,n,null,[]));for(let l of t.members){let u=l.parentSourceRange??n,f=xt(e,i,"placement-unit",l.sourceRange);r.push(o("before",xt(e,f,"before",l.sourceRange),f,l.sourceRange,l.sourceRange,[l],u)),r.push(o("after",xt(e,f,"after",l.sourceRange),f,l.sourceRange,l.sourceRange,[l],u))}return r.push(o("append",i,c,n,null,[])),r}function lc(e,t,n,r){let o=Yf(e,r);if(!o)return kt(e,[Ve("UNSUPPORTED_PAGE_SHAPE","Route default export does not provide an exact mutation target",{reason:"mutation-target-unavailable"})]);let i=xt(e,n,"empty-container",void 0),s=xt(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=ec([a]),l={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:Qf(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 kt(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 Ve(e,t,n){return n===void 0?{code:e,message:t}:{code:e,message:t,details:n}}function xt(e,t,n,r){return Zf([e.route,e.entryFile,String(e.version),t,n,r?`${r.startLine}:${r.startColumn}-${r.endLine}:${r.endColumn}`:"no-range"])}function pc(e,t,n){return Zf(["member",e,String(t??-1),String(n??-1)])}function Zf(e){return`pc_${mc("sha256").update(e.join("\0")).digest("hex").slice(0,24)}`}function gc(e,t,n){return t==null||n==null?null:`sha256:${mc("sha256").update(e.slice(t,n)).digest("hex")}`}function uc(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:${mc("sha256").update(e.slice(r+t.startColumn,o+t.endColumn)).digest("hex")}`}function yt(e){return e?{startLine:e.start.line,startColumn:e.start.column,endLine:e.end.line,endColumn:e.end.column}:null}function Qf(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{PageTemplateIdSchema as Ak}from"@vcp-dev/contracts";import a_ from"node:fs";import l_ from"node:path";var Sk=/^page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function Zr(e){let t=e.map(r=>Pk(r.path)),n=Ek(t);return n?t.filter(r=>kk(n,r)).map(r=>({routeId:Ik(n,r),entryFile:r})).sort((r,o)=>r.routeId.localeCompare(o.routeId)):[]}function hc(e,t=""){let r=((e??"/").trim()||"/").split(/[?#]/,1)[0]||"/",o=r.startsWith("/")?r:`/${r}`,i=Nk(t),s=i&&(o===i||o.startsWith(`${i}/`))?o.slice(i.length)||"/":o,a=s.startsWith("/")?s:`/${s}`;return a==="/"?"/":a.replace(/\/+$/,"")}function Ek(e){return e.some(r=>r.startsWith("app/")&&!vk(r))?"app":e.some(r=>r.startsWith("src/app/"))?"src/app":null}function vk(e){return/^(?:src\/)?app\/(?:_vcp|\.vcp)/.test(e)}function kk(e,t){if(!t.startsWith(`${e}/`))return!1;let n=t.slice(t.lastIndexOf("/")+1);return Sk.test(n)?t.slice(e.length+1,-n.length-1).split("/").filter(Boolean).every(r=>!r.startsWith("_")&&!r.startsWith(".")):!1}function Ik(e,t){let n=t.slice(e.length+1).split("/").slice(0,-1).map(Rk).filter(r=>!!r);return n.length===0?"/":`/${n.join("/")}`}function Ck(e){return e.startsWith("(")&&e.endsWith(")")}function Rk(e){return!e||e.startsWith("@")||e.startsWith("_")||Ck(e)?null:wk(e)}function wk(e){return e.replace(/^\((?:\.|\.\.|\.\.\.)\)/,"")}function Nk(e){let t=e.trim();return!t||t==="/"?"":(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"")}function Pk(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}var Qr=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="PageTemplateManagedSourceError"}};function ot(e,t={}){throw new Qr("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Invalid page-template source (${e}): ${t.path??t.routeId??t.templateId??""}`,{reason:e,...t})}function yc(e){return Ak.safeParse(e).success||ot("invalid-template-id",{templateId:e}),Buffer.from(e,"utf8").toString("base64url")}function qf(e){/^[A-Za-z0-9_-]{1,255}$/.test(e)||ot("invalid-template-key",{path:e});let t;try{t=new TextDecoder("utf-8",{fatal:!0}).decode(Buffer.from(e,"base64url"))}catch{return ot("invalid-template-key",{path:e})}return yc(t)!==e&&ot("noncanonical-template-key",{path:e}),t}function Tk(e){let t=hc(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("(")||Fk(r)&&!ep(r)))&&ot("invalid-public-route",{routeId:e}),t}function Fk(e){return e.includes("[")||e.includes("]")}function ep(e){return/^\[\[\.\.\.[^\[\]]+\]\]$|^\[[^\[\]]+\]$/.test(e)}function tp(e){return e.some(ep)}function np(e,t,n="app"){n!=="app"&&n!=="src/app"&&ot("invalid-app-root");let r=Tk(e),o=yc(t),i=tp(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))&&ot("path-too-long",{path:a}),{appRoot:n,routeRoot:s,templateKey:o,templateEntryFile:a}}function rp(e){return/^(?:src\/)?app\/\.vcp\/page-templates\//.test(e)}function op(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===".")&&ot("invalid-file-path",{path:i}),n.has(i)&&ot("duplicate-file-path",{path:i}),n.set(i,o)}return n}function $i(e){let t=op(e.files),n=Zr([...t.keys()].map(i=>({path:i}))),r=new Map;for(let i of n){if(r.has(i.routeId))throw new Qr("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(!rp(i))continue;let s=/^(app|src\/app)\/\.vcp\/page-templates\/(.+)\/page\.tsx$/.exec(i);s||ot("candidate-must-be-single-page",{path:i});let a=s[1],c=s[2].split("/"),l=tp(c),u=l?c[0]:c.pop(),f=l?c.slice(1):c,m=qf(u),d=f.length?`/${f.join("/")}`:"/";np(d,m,a).templateEntryFile!==i&&ot("candidate-path-mismatch",{path:i,routeId:d});let h=r.get(d);(!h||!h.startsWith(`${a}/`))&&ot("canonical-entry-missing",{path:i,routeId:d}),o.push({routeId:d,templateId:m,entryFile:i,canonicalEntryFile:h,appRoot:a})}return o.sort((i,s)=>ji(i.routeId,s.routeId)||ji(i.templateId,s.templateId))}function ip(e){let t=op(e.files),n=$i({files:t}),r=Zr([...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)=>ji(o.context.routeId,i.context.routeId)||(o.context.effectiveTemplateId===void 0?-1:i.context.effectiveTemplateId===void 0?1:ji(o.context.effectiveTemplateId,i.context.effectiveTemplateId)))}function _k(e){let t=hc(e.selector.routeId),n=ip({files:e.files}),r=n.find(i=>i.context.routeId===t&&i.context.effectiveTemplateId===void 0);(!r||r.entryFile!==e.canonicalEntryFile)&&ot("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||ot("template-selection-not-found",{routeId:t,templateId:e.selector.templateId}),{...o,mode:e.selector.templateId===void 0?"direct":"candidate",effectiveEntryFile:o.entryFile}}function ji(e,t){return e<t?-1:e>t?1:0}import{HOME_PAGE_URL_PATH as zk}from"@vcp-dev/contracts";import{parse as uM}from"@babel/parser";import{parse as x_}from"@babel/parser";import{FormBlockIdSchema as S_,FormSpecV1Schema as E_}from"@vcp-dev/contracts";var qr="components/site/generated/forms",v_=`${qr}/vcp-form-runtime.tsx`,Vi="[A-Za-z0-9][A-Za-z0-9_-]{0,127}",k_=new RegExp(`^${qr}/form-(${Vi})\\.spec\\.ts$`),I_=new RegExp(`^${qr}/form-(${Vi})\\.tsx$`),C_=new RegExp(`^@/${qr}/form-(${Vi})$`),R_=new RegExp(`(?:^|/)${qr}/form-(${Vi})(?:\\.tsx?)?$`);var w_=Symbol("invalid-literal");import{createHash as A_}from"node:crypto";import{posix as F_}from"node:path";import{parse as M_}from"@babel/parser";import{FormSpecV1Schema as L_}from"@vcp-dev/contracts";var D_=Symbol("dynamic");import{parse as Mk}from"@babel/parser";function Ki(e){return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&typeof t.type=="string"):[]}var Ok=/^(?:src\/)?app\/(.*)page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function sp(e){let t=Ok.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 Lk(e){let t=e;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function ap(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function Dk(e){let t=e;for(;t&&(t.type==="TSAsExpression"||t.type==="TSSatisfiesExpression"||t.type==="ParenthesizedExpression");)t=t.expression??null;return t}function xc(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(xc);if(t?.type==="ObjectExpression"){let n={};for(let r of Ki(t.properties)){if(r.type!=="ObjectProperty"||r.computed)throw new Error("dynamic object property");let o=ap(r.key);if(!o)throw new Error("unsupported object key");n[o]=xc(r.value)}return n}throw new Error(`unsupported static value: ${t?.type??"unknown"}`)}function bc(e,t){let n=[],r=sp(t);if(r===null)return{found:!1,seo:null,diagnostics:n};let o;try{o=Mk(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 Ki(o.program.body)){let u=l.type==="ExportNamedDeclaration"?l.declaration:l;if(u?.type==="VariableDeclaration")for(let f of Ki(u.declarations)){let m=f.id;m?.type==="Identifier"&&m.name==="PAGE_SEO"&&(i=f.init)}}if(i==null)return{found:!1,seo:null,diagnostics:n};let s=Dk(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 Ki(s.properties)){if(l.type!=="ObjectProperty"||l.computed)continue;let u=ap(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 f=Lk(l.value);if(f===void 0){n.push({code:"page-seo.dynamic-field",message:`PAGE_SEO.${u} is not a static string; skipped`});continue}a[u]=f;continue}try{let f=xc(l.value);u==="meta_tags_json"&&f!==null&&typeof f=="object"&&!Array.isArray(f)?a.meta_tags_json=f:u==="schema_json"&&f!==null&&typeof f=="object"?a.schema_json=f:u==="breadcrumbs_json"&&Array.isArray(f)?a.breadcrumbs_json=f:n.push({code:"page-seo.dynamic-field",message:`PAGE_SEO.${u} has unsupported static shape; skipped`})}catch(f){n.push({code:"page-seo.dynamic-field",message:`PAGE_SEO.${u} is not a static JSON-like value; skipped: ${f instanceof Error?f.message:String(f)}`})}}}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 Bk}from"@babel/parser";var cp=["page","anchor","external","email","phone","group","file"],jk=["link","cta"],up=["description","badge","iconKey"],Sc=["label","targetType","href","role","openInNewTab","nofollow","children",...up],$k=new Set(Sc);function to(e){return Array.isArray(e)?e:[]}function eo(e){let t=e;return t?.type==="StringLiteral"&&typeof t.value=="string"?t.value:void 0}function Vk(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function lp(e){let t=e;return t?.type==="BooleanLiteral"&&typeof t.value=="boolean"?t.value:void 0}function Ec(e){let t=[],n;try{n=Bk(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 to(n.program.body)){let s=i.type==="ExportNamedDeclaration"?i.declaration:i;if(s?.type==="VariableDeclaration")for(let a of to(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 to(r.elements).forEach((i,s)=>{let a=dp(i,`NAV_ITEMS[${s}]`,t);a&&o.push(a)}),{items:o,diagnostics:t}}function dp(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 to(e.properties)){if(l.type!=="ObjectProperty"||l.computed)continue;let u=Vk(l.key);u&&(r[u]=l.value)}let o=eo(r.label),i=eo(r.targetType);if(!o)return n.push({severity:"fatal",path:`${t}.label`,message:"label must be a static string"}),null;if(!i||!cp.includes(i))return n.push({severity:"fatal",path:`${t}.targetType`,message:`targetType must be one of ${cp.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 up){if(r[l]===void 0)continue;let u=eo(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))$k.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 ${Sc.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=[];to(r.children.elements).forEach((u,f)=>{let m=dp(u,`${t}.children[${f}]`,n);m&&l.push(m)}),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=eo(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=eo(r.role);if(c!==void 0&&(jk.includes(c)?s.role=c:n.push({severity:"warning",path:`${t}.role`,message:"role ignored: not link/cta"})),r.openInNewTab!==void 0){let l=lp(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=lp(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 Kk}from"@babel/parser";function no(e){return Array.isArray(e)?e:[]}function fp(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression";)t=t.expression;return t?.type==="ArrayExpression"?t:void 0}function Uk(e){let t;try{t=Kk(e,{sourceType:"module",plugins:["typescript","jsx"],tokens:!0})}catch{return{status:"unsupported"}}let n=[];for(let o of no(t.program.body)){let i=o.type==="ExportNamedDeclaration"?o.declaration:o;if(i?.type==="VariableDeclaration")for(let s of no(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=fp(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 vc(e,t){let n=pp(t);if(!n)return{status:"unsupported",source:e};let r=Uk(e);if(r.status!=="ok")return{status:r.status,source:e};let o=r.array;if(Ec(e).diagnostics.some(({severity:l})=>l==="fatal"))return{status:"unsupported",source:e};let s=[],a=l=>{let u=no(l.elements);for(let[f,m]of u.entries()){if(Xk(m,n)){let g=u[f+1],h=u[f-1],S=m.start,E=m.end;if(typeof S!="number"||typeof E!="number")continue;if(g&&typeof g.start=="number")s.push({start:S,end:g.start});else if(h&&typeof h.end=="number")s.push({start:h.end,end:E});else{let y=/^\s*,/.exec(e.slice(E));s.push({start:S,end:y?E+y[0].length:E})}continue}let d=Jk(m);d&&a(d)}};if(a(o),s.length===0)return{status:"not_found",source:e};let c=e;for(let l of s.sort((u,f)=>f.start-u.start))c=c.slice(0,l.start)+c.slice(l.end);return{status:"removed",source:c,removedCount:s.length}}function Jk(e){if(e.type==="ObjectExpression")for(let t of no(e.properties)){if(t.type!=="ObjectProperty")continue;let n=t.key;if((n?.name??n?.value)==="children")return fp(t.value)}}function pp(e){let t=e.trim();return t.startsWith("/")?t==="/"?t:t.replace(/\/+$/,""):null}function Xk(e,t){if(e.type!=="ObjectExpression")return!1;let n,r;for(let o of no(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"&&pp(n??"")===t}import{estimateNavLabelWidth as W_}from"@vcp-dev/contracts";import{parse as Y_}from"@babel/parser";var Wk="components/site/generated/",ro=[".tsx",".ts",".jsx",".js"];function mp(e){if(e.expectedUrlPath===zk)return{ok:!1,code:"HOME_PAGE_LOCKED",message:"The homepage source is protected from deletion."};let t=new Set(Zr(Object.keys(e.files).map(h=>({path:h}))).map(h=>h.entryFile)),n=Object.entries(e.files).filter(([h,S])=>{let E=h.replace(/\\/g,"/");if(!t.has(E))return!1;let y=bc(S,E);return y.found&&y.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=$i({files:new Map(Object.entries(e.files))});for(let S of h)S.canonicalEntryFile===r&&o.add(S.entryFile)}catch(h){return{ok:!1,code:"SOURCE_DEPENDENCY_UNSAFE",message:h instanceof Error?h.message:"Invalid page template source."}}let i=Hk(e.files);if(!i.ok)return i.error;let s=i.graph,a=Qk(o,s),c=qk(o,a,s),l=[...a].filter(h=>!c.has(h)).sort((h,S)=>h.localeCompare(S)),u=[...o,...[...c].sort((h,S)=>h.localeCompare(S))],f=new Set(u),m=u.map(h=>({operation:"delete",file:h})),d=[],g=[];for(let[h,S]of Object.entries(e.files))if(!f.has(h)){if(S.includes("NAV_ITEMS")){let E=vc(S,e.expectedUrlPath);E.status==="removed"?(m.push({operation:"upsert",file:h,content:E.source}),d.push(h)):E.status==="unsupported"&&g.push(`unsupported_navigation:${h}`)}S.includes(e.expectedUrlPath)&&!S.includes("NAV_ITEMS")&&g.push(`preserved_link:${h}`)}return{ok:!0,edits:m,deletedFiles:u,updatedFiles:d,preservedSharedFiles:l,warnings:g}}function Hk(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")||!Gk(r))continue;let s=Ut(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(Yk(c))continue;let l=bn(r,c),u=Zk(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 Gk(e){let t=e.toLowerCase();return ro.some(n=>t.endsWith(n))}function Yk(e){return!!(/\.([a-z0-9]+)$/i.exec(e)&&!ro.some(n=>e.endsWith(n)))}function Zk(e,t){let n=e.replace(/\\/g,"/");return(ro.some(o=>n.endsWith(o))?[n]:[...ro.map(o=>`${n}${o}`),...ro.map(o=>`${n}/index${o}`)]).find(o=>t.has(o))??null}function Qk(e,t){let n=new Set,r=[...e].flatMap(o=>[...t.get(o)??[]]);for(;r.length>0;){let o=r.pop();!o.startsWith(Wk)||n.has(o)||(n.add(o),r.push(...t.get(o)??[]))}return n}function qk(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 mm from"@babel/parser";import*as pe from"@babel/types";import*as is from"node:path";import*as Ee from"@babel/types";function gp(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 Mt(e){if(e.path.isObjectPattern()||e.path.isArrayPattern())return Tn(e.path.node,e.identifier.name);if(e.path.isVariableDeclarator()){let n=e.path.node.id;if(Ee.isObjectPattern(n)||Ee.isArrayPattern(n))return Tn(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(tI(e.path,n))return!0}if(t.isFunction()||t.isVariableDeclarator())return!1;t=t.parentPath}return!1}function Tn(e,t,n=!1){return Ee.isIdentifier(e)?e.name===t&&n:Ee.isObjectPattern(e)?e.properties.some(r=>Ee.isObjectProperty(r)?Tn(r.value,t,n):Tn(r.argument,t,n)):Ee.isArrayPattern(e)?e.elements.some(r=>{if(!r)return!1;let o=Ee.isRestElement(r)?r.argument:r;return Tn(o,t,n)}):Ee.isAssignmentPattern(e)?Tn(e.left,t,!0):Ee.isRestElement(e)?Tn(e.argument,t,n):!1}function ar(e,t){if(e.path.isObjectPattern()){if(t){let r=It(e.path.node,t.base),[o,...i]=r??[];if(o?.kind==="property")return{propName:o.name,remainingPath:[...i,...t.path],hasDefault:Mt(e)}}return t?{propName:t.base,remainingPath:t.path,hasDefault:Mt(e)}:null}if(e.path.isVariableDeclarator()){let r=e.path.get("init");if(r?.isExpression()){let o=hp(r),i=!1,s=o?o.initBinding&&kc(o.initBinding)?(i=Mt(o.initBinding),[...o.initPathPrefix]):o.initBinding?(()=>{let c=ar(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=It(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||Mt(e)}}}}let n=oI(e);if(n){let r=eI(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||Mt(e)}}if(n.findParent(s=>s.isVariableDeclarator()))return null;let o=nI(e);if(o){let[s,...a]=o;return!s||s.kind!=="property"?null:{propName:s.name,remainingPath:[...a,...t?.path??[]],hasDefault:Mt(e)}}let i=oo(n.node);return i?{propName:i,remainingPath:t?.path??[],hasDefault:Mt(e)}:null}if(kc(e)){let[r,...o]=t?.path??[];return!r||r.kind!=="property"?null:{propName:r.name,remainingPath:o,hasDefault:Mt(e)}}return null}function eI(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=hp(r);if(!o)return null;let{initBinding:i,initPathPrefix:s}=o;if(!i)return null;let a=!1,c=kc(i)?(a=Mt(i),[...s]):(()=>{let u=ar(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=It(n.node.id,t.identifier.name);return l?{path:[...c,...l],hasDefault:a||Mt(t)}:null}function hp(e){if(e.isIdentifier())return{initBinding:e.scope.getBinding(e.node.name),initPathPrefix:[]};if(!e.isMemberExpression())return null;let t=iI(e.node);return t?{initBinding:e.scope.getBinding(t.base),initPathPrefix:t.path}:null}function kc(e){return e.path.isIdentifier()&&e.path.key===0&&Array.isArray(e.path.container)&&e.path.parentPath?.isFunction()===!0}function tI(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function nI(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=It(i.node,t);if(a)return a}return null}function yp(e,t,n){if(e.path.isVariableDeclarator()){let a=e.path.get("id");if(!Array.isArray(a)&&(a.isObjectPattern()||a.isArrayPattern())){let c=Ui(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=oo(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=rI(e);if(!r)return null;let o=r.parentPath;if(!o?.isObjectProperty())return null;let i=oo(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 Ui(e,t){if(e.isObjectPattern()){for(let n of e.get("properties"))if(n.isObjectProperty()){let r=oo(n.node),o=n.get("value");if(o.isAssignmentPattern()){let i=o.get("left"),s=o.get("right");if(r&&!Array.isArray(i)&&It(i.node,t)&&!Array.isArray(s)&&s.isExpression())return{propName:r,expressionPath:s}}if(!Array.isArray(o)&&(o.isObjectPattern()||o.isArrayPattern())){let i=Ui(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=Ui(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=Ui(r,t);if(o)return o}}return null}function It(e,t,n=[]){if(Ee.isIdentifier(e))return e.name===t?n:null;if(Ee.isObjectPattern(e)){for(let r of e.properties)if(Ee.isObjectProperty(r)){let o=oo(r);if(!o)continue;let i=It(r.value,t,[...n,{kind:"property",name:o}]);if(i)return i}else if(Ee.isRestElement(r)){let o=It(r.argument,t,n);if(o)return o}}if(Ee.isArrayPattern(e))for(let r=0;r<e.elements.length;r+=1){let o=e.elements[r];if(!o)continue;let i=Ee.isRestElement(o)?o.argument:o,s=It(i,t,[...n,{kind:"index",index:r}]);if(s)return s}return Ee.isAssignmentPattern(e)?It(e.left,t,n):null}function rI(e){if(!e.path.isIdentifier())return null;let t=e.path.parentPath;return t?.isAssignmentPattern()&&t.node.left===e.path.node?t:null}function oI(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 oo(e){return e.computed?null:Ee.isIdentifier(e.key)?e.key.name:Ee.isStringLiteral(e.key)?e.key.value:null}function iI(e){let t=[],n=e;for(;Ee.isMemberExpression(n);){if(n.computed)if(Ee.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(Ee.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(Ee.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return Ee.isIdentifier(n)?{base:n.name,path:t}:null}import*as vp from"@babel/parser";import Rc from"@babel/traverse";import*as cr from"@babel/types";import*as ae from"@babel/types";function zi(e,t=[]){if(e.isIdentifier()){let n=e.scope.getBinding(e.node.name);return n?Ji(n,t):null}if(e.isMemberExpression()){let n=dI(e.node),r=sI(e.node);if(!n||r===null)return null;let o=e.scope.getBinding(n);return o?Ji(o,[...r,...t]):null}return e.isAwaitExpression()||Cc(e.node)?dn(pI(e.node),t,"awaited or fetched expression"):null}function sI(e){let t=[],n=e;for(;ae.isMemberExpression(n);){if(n.computed)if(ae.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(ae.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(ae.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return ae.isIdentifier(n)?t:null}function Ji(e,t=[],n){let r=aI(e,t);if(r)return r;let o=cI(e,t);if(o)return o;let i=lI(e,t,n);return i||null}function so(e){return e?.kind==="api-source"}function aI(e,t){if(e.path.isVariableDeclarator()&&ae.isIdentifier(e.path.node.id)){let s=e.path.get("init");if(s?.isCallExpression()&&Ic(s.node)&&t[0]?.kind==="property"&&t[0].name==="data")return dn(e.identifier.name,t,"query hook result.data binding")}if(e.path.isVariableDeclarator()&&ae.isObjectPattern(e.path.node.id)){let s=e.path.node.id.properties.find(c=>ae.isObjectProperty(c)&&Sp(c)==="data"&&io(c.value,e.identifier.name)),a=e.path.get("init");if(s&&a?.isCallExpression()&&Ic(a.node))return dn(e.identifier.name,t,"query hook data binding")}let n=uI(e);if(!n||Sp(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()||!Ic(i.node)?null:dn(e.identifier.name,t,"query hook data binding")}function cI(e,t){if(e.path.isVariableDeclarator()&&ae.isArrayPattern(e.path.node.id)){let a=e.path.get("init");if(!a?.isCallExpression()||!bp(a.node))return null;let[c,l]=e.path.node.id.elements;return!ae.isIdentifier(c)||c.name!==e.identifier.name||!ae.isIdentifier(l)?null:xp(e,l.name)?dn(e.identifier.name,t,"state setter is updated by API data"):null}if(!e.path.isIdentifier())return null;let n=e.path.parentPath;if(!n?.isArrayPattern())return null;let r=n.parentPath;if(!r?.isVariableDeclarator())return null;let o=r.get("init");if(!o?.isCallExpression()||!bp(o.node)||n.node.elements.findIndex(a=>a===e.path.node)!==0)return null;let s=n.node.elements[1];return ae.isIdentifier(s)&&xp(e,s.name)?dn(e.identifier.name,t,"state setter is updated by API data"):null}function lI(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()?dn(e.identifier.name,t,"awaited binding result"):Cc(o.node,n)?dn(e.identifier.name,t,"fetch-backed binding result"):null:null}function uI(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 io(e,t){return ae.isIdentifier(e)?e.name===t:ae.isAssignmentPattern(e)?io(e.left,t):ae.isObjectPattern(e)?e.properties.some(n=>ae.isObjectProperty(n)?io(n.value,t):io(n.argument,t)):ae.isArrayPattern(e)?e.elements.some(n=>!!n&&io(ae.isRestElement(n)?n.argument:n,t)):!1}function xp(e,t){let n=!1,r=!1;return e.scope.path.traverse({CallExpression(i){Cc(i.node)&&(n=!0),(fI(i.node.callee,t)||i.node.arguments.some(s=>ae.isIdentifier(s)&&s.name===t))&&(r=!0)}}),n&&r}function Ic(e){let t=Wi(e.callee);return t==="useQuery"||t==="useSWR"||t==="useSuspenseQuery"}function bp(e){return Wi(e.callee)==="useState"}function Cc(e,t){let n=t?.get(e);if(n!==void 0)return n;let r=Xi(e,o=>ae.isCallExpression(o)&&Wi(o.callee)==="fetch");return t?.set(e,r),r}function dI(e){let t=e;for(;ae.isMemberExpression(t);)t=t.object;return ae.isIdentifier(t)?t.name:null}function Sp(e){return e.computed?null:ae.isIdentifier(e.key)?e.key.name:ae.isStringLiteral(e.key)?e.key.value:null}function Wi(e){return ae.isIdentifier(e)?e.name:ae.isMemberExpression(e)&&ae.isIdentifier(e.property)?e.property.name:null}function fI(e,t){return Xi(e,n=>ae.isIdentifier(n)&&n.name===t)}function Xi(e,t){if(t(e))return!0;let n=ae.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(ae.isNode(i)&&Xi(i,t))return!0;continue}if(ae.isNode(o)&&Xi(o,t))return!0}return!1}function pI(e){return ae.isIdentifier(e)?e.name:ae.isCallExpression(e)?Wi(e.callee)??"api":ae.isAwaitExpression(e)?"awaited-api":"api"}function dn(e,t,n){return{kind:"api-source",readonly:!0,sourceId:e,displayPath:mI(e,t),reason:n}}function mI(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}var kp=typeof Rc=="function"?Rc:Rc.default;function Ip(e,t){let n=Rp(e);if(!n)return{allowed:!0};let r=!1;return kp(n,{CallExpression(o){if(!wp(o.node,t.sourceRange)||!gI(o.node))return;let i=o.get("callee");if(!i.isMemberExpression())return;let s=i.get("object");Array.isArray(s)||!s.isExpression()||so(zi(s))&&(r=!0,o.stop())}}),r?{allowed:!1,reason:"Cannot add data-backed items to a dynamic API list"}:{allowed:!0}}function Cp(e,t){let n=Rp(e);if(!n)return{allowed:!0};let r=!1;return kp(n,{JSXExpressionContainer(o){wp(o.node,t.sourceRange)&&(cr.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 Rp(e){try{return vp.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function gI(e){let t=e.callee;return cr.isMemberExpression(t)&&cr.isIdentifier(t.property)&&t.property.name==="map"}function wp(e,t){let n=e.loc;return n?Ep({line:n.start.line,column:n.start.column},{line:t.startLine,column:t.startColumn})>=0&&Ep({line:n.end.line,column:n.end.column},{line:t.endLine,column:t.endColumn})<=0:!1}function Ep(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 X from"@babel/types";import*as Np from"@babel/parser";import wc from"@babel/traverse";import*as Fe from"@babel/types";import*as lr from"node:path";var Ct=typeof wc=="function"?wc:wc.default;function Je(e){try{return Np.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function Nc(e){return e.computed?Fe.isStringLiteral(e.key)||Fe.isNumericLiteral(e.key)?String(e.key.value):null:hI(e.key)}function hI(e){return Fe.isIdentifier(e)?e.name:Fe.isStringLiteral(e)||Fe.isNumericLiteral(e)?String(e.value):null}function Fn(e){return Fe.isParenthesizedExpression(e)||Fe.isTSAsExpression(e)||Fe.isTSSatisfiesExpression(e)||Fe.isTSNonNullExpression(e)||Fe.isTSTypeAssertion(e)?Fn(e.expression):Fe.isExpression(e)?e:null}function Pc(e){if(Fe.isIdentifier(e))return[e.name];if((Fe.isMemberExpression(e)||Fe.isOptionalMemberExpression(e))&&!e.computed&&Fe.isIdentifier(e.property)){let t=Fn(e.object),n=t?Pc(t):null;return n?[...n,e.property.name]:null}return null}function _n(e,t){return t.startsWith("@/")?t.slice(2).replace(/\\/g,"/"):t.startsWith(".")?lr.normalize(lr.join(lr.dirname(e),t)).replace(/\\/g,"/"):t}function ct(e,t){return Hi(e)===Hi(t)}function Hi(e){let t=ur(e);return t.endsWith("/index")?t.slice(0,-6):t}function ur(e){return e.replace(/\.(tsx|ts|jsx|js)$/,"")}function Tp(e,t,n){let r=Op(e,t);if(Lp(e,r),Dp(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 Ct(e,{JSXElement(s){Vp(s,r)&&o.push(s)}}),o.length!==1?{ok:!1,reason:"Cannot move prop-backed repeat child without a single unambiguous component call site"}:Gi(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 Fp(e,t){let n=new Map,r=i=>{let s=dr(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 yI(i,n))o=r(s)||o}return[...n.values()]}function yI(e,t){let n=[],r=xI(e,t);for(let o of e.ast.program.body){if(X.isExportDefaultDeclaration(o)&&X.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=ao(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(X.isExportNamedDeclaration(o)&&o.source&&typeof o.source.value=="string"){let i=_n(e.file,o.source.value);for(let s of o.specifiers){if(X.isExportNamespaceSpecifier(s)){let l=fn(s.exported);for(let u of t.values())ct(u.file,i)&&n.push({file:e.file,namespace:Ac(l,u.namespace),exportName:u.exportName});continue}if(!X.isExportSpecifier(s))continue;let a=fn(s.local),c=[...t.values()].filter(l=>ct(l.file,i)&&Mn(l.namespace,a));if(c.length>0){let l=fn(s.exported);for(let u of c){let f=ao(u.namespace,a,l);f&&n.push({file:e.file,namespace:f,exportName:u.exportName})}continue}t.has(dr({file:i,exportName:a}))&&n.push({file:e.file,exportName:fn(s.exported)})}continue}if(X.isExportNamedDeclaration(o)&&!o.source){for(let i of o.specifiers){if(!X.isExportSpecifier(i))continue;let s=fn(i.local),a=r.get(s)??[];if(a.length>0){let c=fn(i.exported);n.push({file:e.file,exportName:c});for(let l of a){let u=ao(l.namespace,s,c);u&&n.push({file:e.file,namespace:u,exportName:l.exportName})}}}continue}if(X.isExportAllDeclaration(o)&&typeof o.source.value=="string"){let i=_n(e.file,o.source.value),s=o.exported;if(s){let a=fn(s);for(let c of t.values())ct(c.file,i)&&n.push({file:e.file,namespace:Ac(a,c.namespace),exportName:c.exportName});continue}for(let a of t.values())ct(a.file,i)&&(a.namespace||a.exportName!=="default")&&n.push({file:e.file,namespace:a.namespace,exportName:a.exportName})}}return n}function Ac(e,t){return t?`${e}.${t}`:e}function Mn(e,t){return e===t||e?.startsWith(`${t}.`)===!0}function ao(e,t,n){return!Mn(e,t)||!e?null:e===t?n:`${n}${e.slice(t.length)}`}function xI(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(!X.isImportDeclaration(i)||typeof i.source.value!="string")continue;let s=_n(e.file,i.source.value);for(let a of i.specifiers){if(X.isImportDefaultSpecifier(a)){let c=t.get(dr({file:s,exportName:"default"}));c&&r(a.local.name,c);let l=[...t.values()].filter(u=>ct(u.file,s)&&Mn(u.namespace,"default"));for(let u of l){let f=ao(u.namespace,"default",a.local.name);f&&r(a.local.name,{...u,namespace:f})}continue}if(X.isImportSpecifier(a)){let c=fn(a.imported),l=[...t.values()].filter(f=>ct(f.file,s)&&Mn(f.namespace,c));for(let f of l)r(a.local.name,f);let u=t.get(dr({file:s,exportName:c}));u&&r(a.local.name,u);continue}if(X.isImportNamespaceSpecifier(a))for(let c of t.values())ct(c.file,s)&&r(a.local.name,{...c,namespace:Ac(a.local.name,c.namespace)})}}let o=!0;for(;o;){o=!1;for(let i of e.ast.program.body)if(X.isVariableDeclaration(i))for(let s of i.declarations){if(!X.isIdentifier(s.id)||!s.init)continue;let a=Fn(s.init);if(!a||!X.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(dr));for(let f of c){let m=ao(f.namespace,a.name,s.id.name),d=m?{...f,namespace:m}:f,g=dr(d);u.has(g)||(r(s.id.name,d),u.add(g),o=!0)}}}return n}function dr(e){let t=e.namespace?`${e.namespace}.${e.exportName}`:e.exportName;return`${Hi(e.file)}#${t}`}function fn(e){return X.isIdentifier(e)?e.name:e.value}function _p(e,t){for(let n of e.program.body){if(X.isExportDefaultDeclaration(n)){let o=n.declaration;if((X.isFunctionDeclaration(o)||X.isClassDeclaration(o))&&o.id?.name===t)return{exportName:"default"};if(X.isIdentifier(o)&&o.name===t)return{exportName:"default"}}if(!X.isExportNamedDeclaration(n))continue;let r=n.declaration;if((X.isFunctionDeclaration(r)||X.isClassDeclaration(r))&&r.id?.name===t)return{exportName:t};if(X.isVariableDeclaration(r)){for(let o of r.declarations)if(X.isIdentifier(o.id,{name:t}))return{exportName:t}}for(let o of n.specifiers){if(!X.isExportSpecifier(o)||o.local.name!==t)continue;return{exportName:X.isIdentifier(o.exported)?o.exported.name:o.exported.value}}}return null}function Fc(e){let t=bI(e),n=[],r=Dp(e.ast,t);return Ct(e.ast,{JSXElement(o){ct(e.file,e.sourceFile)&&Gi(o)===e.sourceComponent||Vp(o,t)&&n.push({file:e.file,path:o})}}),{callSites:n,hasUnsafeReference:r}}function Mp(){return{localBindings:new Set,namespaceMembers:new Map,hasUnsupportedAlias:!1}}function Op(e,t){let n=Mp();return Ct(e,{Program(r){let o=r.scope.getBinding(t);o&&n.localBindings.add(o),r.stop()}}),n}function bI(e){let t=Mp();return ct(e.file,e.sourceFile)&&SI(t,Op(e.ast,e.sourceComponent)),Ct(e.ast,{ImportDeclaration(n){let r=n.node,o=r.source.value;if(typeof o!="string")return;let i=_n(e.file,o),s=e.componentIdentities.filter(a=>ct(a.file,i));if(s.length!==0)for(let a of r.specifiers){let c=n.scope.getBinding(a.local.name);if(c){if(X.isImportDefaultSpecifier(a)&&s.some(l=>l.exportName==="default")&&t.localBindings.add(c),X.isImportDefaultSpecifier(a)){let l=s.filter(u=>Mn(u.namespace,"default"));if(l.length>0){let u=t.namespaceMembers.get(c)??new Set;for(let f of l){let m=Ap(f,"default");m&&u.add(m)}t.namespaceMembers.set(c,u)}continue}if(X.isImportSpecifier(a)){let l=X.isIdentifier(a.imported)?a.imported.name:a.imported.value,u=s.filter(f=>Mn(f.namespace,l));if(u.length>0){let f=t.namespaceMembers.get(c)??new Set;for(let m of u){let d=Ap(m,l);d&&f.add(d)}t.namespaceMembers.set(c,f);continue}s.some(f=>!f.namespace&&f.exportName===l)&&t.localBindings.add(c);continue}if(X.isImportNamespaceSpecifier(a))for(let l of s){let u=l.namespace?`${l.namespace}.${l.exportName}`:l.exportName,f=t.namespaceMembers.get(c)??new Set;f.add(u),t.namespaceMembers.set(c,f)}}}}}),Lp(e.ast,t),t}function SI(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 Lp(e,t){Ct(e,{VariableDeclarator(n){if(!n.node.init)return;let r=Fn(n.node.init);if(r){if(X.isIdentifier(n.node.id)){let o=On(r,t,n),i=n.scope.getBinding(n.node.id.name);o&&i&&Tc(t,i,o);return}if(X.isObjectPattern(n.node.id)){let o=On(r,t,n);o?.unsupported||o?.local?t.hasUnsupportedAlias=!0:o&&o.namespaceMembers.size>0&&$p(n.node.id,o.namespaceMembers,t,n)}}}})}function Dp(e,t){if(t.hasUnsupportedAlias)return!0;let n=!1;return Ct(e,{ReferencedIdentifier(r){if(n){r.stop();return}EI(r)||!r.isIdentifier()||!Bp(r,t)||vI(r,t)||kI(r)||(n=!0,r.stop())}}),n}function EI(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 Bp(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)&&On(r.node,t,r)?r:null}function vI(e,t){let n=e.findParent(c=>c.isVariableDeclarator());if(!n?.isVariableDeclarator())return!1;let r=n.get("init");if(!r?.isExpression()||!Pp(e,r))return!1;let o=Bp(e,t);if(!o)return!1;if(Fn(r.node)===o.node)return!!On(r.node,t,r);let s=e.findParent(c=>c.isObjectProperty());if(!s?.isObjectProperty())return!1;let a=s.get("value");return a.isExpression()&&Pp(e,a)&&!!On(a.node,t,a)}function kI(e){let t=e.parentPath;return t?.isExportDefaultDeclaration()&&t.node.declaration===e.node?!0:!!(t?.isExportSpecifier()&&t.node.local===e.node)}function Pp(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function On(e,t,n){let r=Fn(e);if(!r)return null;if(X.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(X.isObjectExpression(r))return II(r,t,n);let o=Pc(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?jp(s,o.slice(1).join(".")):null}function II(e,t,n){let r=new Set,o=!1;for(let i of e.properties){if(!X.isObjectProperty(i))continue;let s=Nc(i);if(!s||!X.isExpression(i.value)){X.isExpression(i.value)&&(o||=On(i.value,t,n)!==null);continue}let a=On(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 jp(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 Tc(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 $p(e,t,n,r){for(let o of e.properties){if(X.isRestElement(o)){if(X.isIdentifier(o.argument)){let c=r.scope.getBinding(o.argument.name);c&&Tc(n,c,{local:!1,namespaceMembers:new Set(t),unsupported:!1})}else n.hasUnsupportedAlias=!0;continue}if(!X.isObjectProperty(o))continue;let i=Nc(o);if(!i){n.hasUnsupportedAlias=!0;continue}let s=jp(t,i);if(!s)continue;n.hasUnsupportedAlias||=s.unsupported;let a=X.isAssignmentPattern(o.value)?o.value.left:o.value;if(X.isIdentifier(a)){let c=r.scope.getBinding(a.name);c&&Tc(n,c,s);continue}if(X.isObjectPattern(a)&&s.namespaceMembers.size>0){$p(a,s.namespaceMembers,n,r);continue}n.hasUnsupportedAlias=!0}}function Ap(e,t){if(!Mn(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 Vp(e,t){let n=e.node.openingElement.name;if(X.isJSXIdentifier(n)){let o=e.scope.getBinding(n.name);return!!(o&&t.localBindings.has(o))}let r=Kp(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 Kp(e){if(X.isJSXIdentifier(e))return[e.name];if(X.isJSXMemberExpression(e)){let t=Kp(e.object);return t?[...t,e.property.name]:null}return null}function Gi(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()&&X.isIdentifier(n.node.id))return n.node.id.name}return null}function Up(e,t){let n=Je(e);if(!n||!t.tag||!t.importedFrom||!t.exportName)return Number.POSITIVE_INFINITY;let r=Fc({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 xe(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 ye(e){return typeof e.start=="number"&&typeof e.end=="number"?{start:e.start,end:e.end}:null}function Ot(e,t){let n=ye(e);return!!(n&<(t,n))}function lt(e,t){return t.start>=e.start&&t.end<=e.end}function bt(e,t){let n=se(e,xe(t));return n.ok&&n.match.path.isJSXElement()?n.match.path:Yi(e,t)}function fr(e,t){let n=ye(t);return n?e.slice(n.start,n.end):""}function Jp(e,t){return e.start===t.start&&e.end===t.end}function Yi(e,t){let n=null;return Ct(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 Zi(e,t){return _c(e,t).length>0}function Qi(e,t){let n=ye(e.node),r=ye(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()&&!CI(o,n,r)))return!0;o=o.parentPath}return!1}function CI(e,t,n){let r=ye(e.node.consequent);if(r&<(r,t)&&!lt(r,n))return!1;let o=e.node.alternate?ye(e.node.alternate):null;return!(o&<(o,t)&&!lt(o,n))}function _c(e,t){let n=ye(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=ye(o.node.consequent),a=ye(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()&&Mc(o.node.operator)){let s=ye(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 Mc(e){return e==="&&"||e==="||"||e==="??"}function Xp(e,t){let n=ye(e.consequent);if(n&<(n,t))return n;let r=ye(e.alternate);return r&<(r,t)?r:null}function zp(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=>ur(a.file)));if(!t.has(ur(e.sourceFile))||!t.has(ur(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(ur(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=_p(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=Je(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=Fp(r,{file:e.sourceFile,exportName:n.exportName}),i=[];for(let a of r){let c=Fc({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!ct(s.file,e.targetFile)||Gi(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 TI}from"@vcp-dev/contracts";function qi(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 co();let a=s.target,c=a.locator;if(a.sourceKind==="repeat-template"){let l=o?.instanceIndex;if(l===void 0)return co();let u=RI(a,l,o?.instanceCount);if(!u)return co();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"?co():{ok:!0,target:{kind:"jsx-attribute"}}}function co(){return{ok:!1,code:"unsupported-binding",reason:"Property does not have a safe typed binding write target for this scope and operation"}}function RI(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 Lt from"@babel/types";import{SiteEditSetPropsParamsSchema as wI}from"@vcp-dev/contracts";function Wp(e){let t=e.changes??(e.change?[e.change]:[]);if(!wI.safeParse({kind:"set-props",scope:"selection",changes:t}).success)return lo("invalid-change","Repeat property changes are invalid");if(t.length!==1||t[0].name!==e.target.propertyName)return lo("target-mismatch","A repeat property plan must contain exactly one change for its target property");let r=t[0];if(r.operation==="remove"&&e.target.propertyState==="missing")return{ok:!0,steps:[]};let o=we(e.source,"value");if(!o.ok)return lo("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=se(o.ast,a);if(!c.ok||!c.match.path.isObjectExpression())return lo("unsupported-object",`Repeat item ${s} is not a writable object expression`);let l=s===e.target.sourceItemIndex?NI(r):PI(c.match.path.node,r.name);if(!l)return lo("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 NI(e){return e.operation==="set"?{kind:"value",value:e.value}:{kind:"undefined"}}function PI(e,t){let n=e.properties.filter(i=>Lt.isObjectProperty(i)&&AI(i.key)===t);if(n.length>1)return null;let r=n[0];if(!r)return{kind:"undefined"};if(!Lt.isExpression(r.value))return null;let o=_t(r.value);return o.status==="undefined"?{kind:"undefined"}:o.status!=="resolved"?null:{kind:"value",value:o.value}}function AI(e){return Lt.isIdentifier(e)?e.name:Lt.isStringLiteral(e)?e.value:Lt.isNumericLiteral(e)?String(e.value):null}function lo(e,t){return{ok:!1,errorCode:e,reason:t}}function Hp(e){if(e.change.name!=="className"&&e.change.name!=="class")return uo("unsupported-owner",`No specialized property owner is available for '${e.change.name}'`);let t=e.classNameSource;if(!t||t.filePath!==e.node.file)return uo("owner-source-unavailable","className source details are unavailable for the selected node");if(e.change.name==="class"&&t.sourceKind==="missing")return uo("owner-source-unavailable","The class alias requires an existing className source");if(t.sourceKind==="expression")return uo("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 uo("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 uo(e,t){return{ok:!1,errorCode:e,reason:t}}async function Yp(e){let t=TI.safeParse({kind:"set-props",scope:e.scope,changes:e.changes});if(!t.success)return pn("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 pn("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 FI(e,r);if(o){if(!o.ok)return pn("owner-plan-failed",o.reason);Gp(n,o.steps);continue}let i=await e.getPropertyState(e.node.key,r.name,e.selectionRef);if(!i)return pn("missing-property-state",`No authoritative property state is available for '${r.name}'`);if(i.status==="blocked")return pn("readonly-property",i.diagnostic?.message??`Property '${r.name}' is not writable`);if(OI(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=qi({state:i,scope:e.scope,operation:r.operation,selectionRef:e.selectionRef,repeatTarget:s});if(!a.ok)return pn(a.code,a.reason);let c=a.target;if(c.kind==="value-binding"&&r.operation==="set"){Oc(n,{type:"update-value",order:n.length,file:c.file,locator:c.locator,value:r.value});continue}if(c.kind==="repeat-property"){let l=Wp({source:e.getFileContent(c.target.sourceFile),target:c.target,changes:[r]});if(!l.ok)return pn("repeat-target-failed",l.reason);Gp(n,l.steps);continue}Oc(n,{type:"set-property-changes",order:n.length,file:e.node.file,locator:_I(e.node),scope:e.scope,changes:[r]})}return n.forEach((r,o)=>{r.order=o}),MI(n)?pn("step-conflict","Property changes resolve to conflicting write steps"):{ok:!0,steps:n}}async function FI(e,t){return t.name!=="className"&&t.name!=="class"?null:Hp({node:e.node,change:t,classNameSource:e.classNameSource})}function _I(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 MI(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 Gp(e,t){for(let n of t)Oc(e,{...n,order:e.length})}function Oc(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 OI(e,t){if(t.operation!=="set"||e.status!=="direct")return!1;let n=e.attribute?.resolution;return n?.status==="resolved"?Lc(n.value,t.value):e.attribute?.source===null&&e.attribute.value===t.value}function Lc(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)=>Lc(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=>Lc(n[i],r[i]))}return!1}function pn(e,t){return{ok:!1,errorCode:e,reason:t}}import*as mr from"@babel/types";import*as G from"@babel/types";function Dc(e,t,n){let r=bt(t,n);return r?Dt(e,r):null}function Dt(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(!G.isIdentifier(l)||l.name!=="map"||c.computed)return null;let u=a.get("object"),f=fr(e,u.node),m=r.node.params.map(h=>fr(e,h)),d=ye(i.node),g=ye(r.node);return!f||m.some(h=>h.length===0)||!d||!g?null:{callStart:d.start,callEnd:d.end,callbackStart:g.start,callbackEnd:g.end,collectionExpression:f,callbackParams:m,mapOperator:G.isOptionalMemberExpression(c)&&c.optional?"?.map":".map",collectionNeedsParens:es(u.node),callbackPath:r,collectionPath:u}}function fo(e,t){return!!(e&&t&&e.callStart===t.callStart&&e.callEnd===t.callEnd&&e.callbackStart===t.callbackStart&&e.callbackEnd===t.callbackEnd)}function LI(e,t){let n=ye(e.node);return n?DI(t).some(r=>{let o=ye(r);return r===e.node||!!(o&&o.start===n.start&&o.end===n.end)}):!1}function DI(e){let t=e.callbackPath.node.body;return G.isBlockStatement(t)?mn(t.body):gn(t)}function mn(e){let t=[];for(let n of e){if(G.isReturnStatement(n)){n.argument&&t.push(...gn(n.argument));continue}if(G.isBlockStatement(n)){t.push(...mn(n.body));continue}if(G.isIfStatement(n)){let r=G.isBlockStatement(n.consequent)?n.consequent.body:[n.consequent];if(t.push(...mn(r)),n.alternate){let o=G.isBlockStatement(n.alternate)?n.alternate.body:[n.alternate];t.push(...mn(o))}continue}if(G.isSwitchStatement(n)){for(let r of n.cases)t.push(...mn(r.consequent));continue}G.isTryStatement(n)&&(t.push(...mn(n.block.body)),n.handler&&t.push(...mn(n.handler.body.body)),n.finalizer&&t.push(...mn(n.finalizer.body)))}return t}function gn(e){return G.isJSXElement(e)?BI(e)?Zp(e.children):[e]:G.isJSXFragment(e)?Zp(e.children):G.isParenthesizedExpression(e)||G.isTSAsExpression(e)||G.isTSSatisfiesExpression(e)||G.isTSNonNullExpression(e)||G.isTSTypeAssertion(e)?gn(e.expression):G.isConditionalExpression(e)?[...gn(e.consequent),...gn(e.alternate)]:G.isLogicalExpression(e)&&Mc(e.operator)?gn(e.right):[]}function Zp(e){return e.flatMap(t=>G.isJSXElement(t)||G.isJSXFragment(t)?gn(t):G.isJSXExpressionContainer(t)&&(G.isJSXElement(t.expression)||G.isJSXFragment(t.expression)||G.isConditionalExpression(t.expression)||G.isLogicalExpression(t.expression))?gn(t.expression):[])}function BI(e){let t=e.openingElement.name;return G.isJSXIdentifier(t)?t.name==="Fragment":G.isJSXMemberExpression(t)&&t.property.name==="Fragment"}function Qp(e,t){return!!(e&&t&&e.callbackStart<t.callbackStart&&e.callbackEnd>t.callbackEnd)}function es(e){return!(G.isIdentifier(e)||G.isThisExpression(e)||G.isMemberExpression(e)||G.isOptionalMemberExpression(e)||G.isCallExpression(e)||G.isOptionalCallExpression(e))}function qp(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(G.isMemberExpression(n)||G.isOptionalMemberExpression(n))&&G.isIdentifier(n.property)&&n.property.name==="map"&&!n.computed}function pr(e,t){let n=Je(e);if(!n)return t.isRepeatItemRoot===!0;let r=se(n,xe(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:Yi(n,t);if(!o)return t.isRepeatItemRoot===!0;let i=Dt(e,o);return i?LI(o,i):t.isRepeatItemRoot===!0}function em(e,t){let n=Je(e);if(!n)return!1;let r=se(n,xe(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:Yi(n,t);return o?!!o.findParent(i=>{if(!i.isCallExpression()&&!i.isOptionalCallExpression())return!1;let s=i.node.callee;return(G.isMemberExpression(s)||G.isOptionalMemberExpression(s))&&G.isIdentifier(s.property)&&s.property.name==="map"}):!1}import*as Ie from"@babel/types";function Bc(e){if(Ie.isJSXIdentifier(e))return/^[A-Z]/.test(e.name)?e.name:null;if(Ie.isJSXMemberExpression(e)){let t=e;for(;Ie.isJSXMemberExpression(t);)t=t.object;return t.name}return null}function jI(e,t){let n=ye(e.node);if(!n)return[];let r=new Set,o=(i,s)=>{let a=s.scope.getBinding(i);!a||Ot(a.path.node,n)||hn(a,i,t)||r.add(i)};return e.traverse({ReferencedIdentifier(i){o(i.node.name,i)},JSXOpeningElement(i){let s=Bc(i.node.name);s&&o(s,i)}}),[...r].sort()}function jc(e,t,n){let r=Je(e);if(!r)return{ok:!0};let o=se(r,xe(t));if(!o.ok||!o.match.path.isJSXElement())return{ok:!0};let i=se(r,xe(n));if(!i.ok||!i.match.path.isJSXElement())return{ok:!0};let s=Tr(o.match.path,i.match.path);if(Zi(s,i.match.path))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let a=jI(s,i.match.path);return a.length>0?{ok:!1,bindingNames:a}:{ok:!0}}function nm(e){let t=e;for(;Ie.isTSQualifiedName(t);)t=t.left;return Ie.isIdentifier(t)?t.name:null}function po(e,t){e.isIdentifier()&&e.isReferencedIdentifier()&&t(e),e.traverse({ReferencedIdentifier(n){n.isIdentifier()&&t(n)}})}function ts(e){let t=[],n=r=>{if(r){if(Ie.isIdentifier(r)){t.push(r.name);return}if(Ie.isObjectPattern(r)){for(let o of r.properties){if(Ie.isRestElement(o)){n(o.argument);continue}Ie.isObjectProperty(o)&&n(o.value)}return}if(Ie.isArrayPattern(r)){for(let o of r.elements)n(o);return}if(Ie.isAssignmentPattern(r)){n(r.left);return}if(Ie.isRestElement(r)){n(r.argument);return}Ie.isTSParameterProperty(r)&&n(r.parameter)}};return n(e),t}function $c(e,t){let n=ye(e.node),r=ye(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=tm(e),i=tm(t);if(!o||!i||!Jp(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=Xp(s.node,n);if(a&&!lt(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=ye(s.node.right);if(a&<(a,n)&&!lt(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())&&qp(s)){let a=ye(s.node.body)??ye(s.node);if(a&&!lt(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 tm(e){let t=e;for(;t;){if(t.isReturnStatement())return t.node.argument?ye(t.node.argument):null;if(t.isArrowFunctionExpression()&&(Ie.isJSXElement(t.node.body)||Ie.isJSXFragment(t.node.body)||Ie.isConditionalExpression(t.node.body)||Ie.isLogicalExpression(t.node.body)))return ye(t.node.body);t=t.parentPath}return null}function hn(e,t,n){return n.scope.getBinding(t)===e}function Vc(e,t,n,r={}){if(!r.preserveConditionalBoundary&&Zi(e,t))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let o=ye(e.node);if(!o)return{ok:!0};let i=new Set(n.callbackPath.node.params.flatMap(c=>ts(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||Ot(u.path.node,o)||i.has(u.path.node)||hn(u,c,t)||s.add(c)};return e.traverse({ReferencedIdentifier(c){a(c.node.name,c)},JSXOpeningElement(c){let l=Bc(c.node.name);l&&a(l,c)}}),s.size>0?{ok:!1,bindingNames:[...s].sort()}:{ok:!0}}function Kc(e,t,n){let r=ye(e.node);if(!r)return{ok:!0};let o=new Set(n.callbackPath.node.params.flatMap(s=>ts(s)).map(s=>n.callbackPath.scope.getBinding(s)?.path.node).filter(Boolean)),i=new Set;return po(e,s=>{let a=s.scope.getBinding(s.node.name);!a||Ot(a.path.node,r)||o.has(a.path.node)||hn(a,s.node.name,t)||i.add(s.node.name)}),i.size>0?{ok:!1,bindingNames:[...i].sort()}:{ok:!0}}function rm(e,t){let n=new Set(e.callbackPath.node.params.flatMap(a=>ts(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)||hn(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(mr.isIdentifier(l))o(l.name,c);else{let u=nm(l);u&&o(u,c)}}});return r.size>0?{ok:!1,bindingNames:[...r].sort()}:{ok:!0}}function Uc(e,t){let n=ye(e.node),r=new Set;return po(e,o=>{let i=o.scope.getBinding(o.node.name);i&&(n&&Ot(i.path.node,n)||hn(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 om(e){let t=[];for(let n of e.callbackPath.node.params){if(mr.isIdentifier(n)){t.push(n.name);continue}if(mr.isRestElement(n)&&mr.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 im(e,t){return{...e,callbackParams:t}}function Jc(e,t){return`${e.collectionNeedsParens?`(${e.collectionExpression})`:e.collectionExpression}${e.mapOperator}((${e.callbackParams.join(", ")}) => ${t})`}function mo(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 sm(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 Ln(e){return{file:e.file,component:e.component}}function $I(e){return e.target.kind==="node"?e.target.key:null}function VI(e){return"kind"in e}function ns(e){return!VI(e)}function Gc(e,t){let n=is.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=is.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function Xc(e,t){let n=e.getFileContent(t.file);if(!n)return;let r=Tt(n,xe(t));if(r.ok)return n.slice(r.match.start,r.match.end)}function Zc(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 KI(e){if(e.isNumericLiteral())return!0;if(!e.isUnaryExpression({operator:"-"}))return!1;let t=e.get("argument");return!Array.isArray(t)&&t.isNumericLiteral()}function UI(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 zc(e){return e==="Cannot edit repeat-backed child node structure with a generic node operation"}function JI(e){let t=Tp(e.ast,e.sourceNode.component,e.targetParent.component);if(!t.ok)return{ok:!1,reason:t.reason};let n=$c(t.path,e.targetParentPath);if(!n.ok)return{ok:!1,reason:n.reason};let r=XI({source:e.source,sourceContext:e.sourceContext,callSitePath:t.path,targetParentPath:e.targetParentPath});if(!r.ok)return r;let o=gm(r.collectionExpression);return{ok:!0,context:{...e.sourceContext,collectionExpression:r.collectionExpression,collectionNeedsParens:o?es(o):!0}}}function XI(e){let t=ye(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||Ot(a.path.node,t))return;let c=HI(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=YI(e.callSitePath,c.propName,e.source);if(!l.ok){o=l.reason;return}let u=zI(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 f=Uc(l.expressionPath,e.targetParentPath);if(!f.ok){o=f.reason??`Cannot move prop-backed repeat child because the mapped prop source is not visible at the target: ${f.bindingNames.join(", ")}`;return}n.set(`${c.range.start}:${c.range.end}`,{...c.range,text:u});return}hn(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:ZI(e.source,t,[...n.values()])}}function zI(e,t){if(t.length===0)return e;let n=gm(e);if(!n)return null;let r=es(n)?`(${e})`:e;for(let o of t){if(o.kind==="property"){r=WI(o.name)?`${r}.${o.name}`:`${r}[${JSON.stringify(o.name)}]`;continue}r=`${r}[${o.index}]`}return r}function WI(e){return/^[$A-Z_a-z][$\w]*$/.test(e)}function HI(e,t,n){let r=GI(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=ar(t,o);if(!i)return null;let s=r?.range??ye(e.node);return s?{propName:i.propName,remainingPath:i.remainingPath,hasDefault:i.hasDefault,range:s}:null}function GI(e,t){let n=e.parentPath;if(!n||!n.isMemberExpression()&&!n.isOptionalMemberExpression()||n.node.object!==e.node||!Ot(n.node,t)||n.node.computed||!pe.isIdentifier(n.node.property))return null;let r=ye(n.node);return r?{propertyName:n.node.property.name,range:r}:null}function YI(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()&&pe.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=fr(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 ZI(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 gm(e){try{let n=mm.parse(`const __VD_EXPR__ = (${e});`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0],r=pe.isVariableDeclaration(n)?n.declarations[0]?.init:null;return r&&pe.isExpression(r)?r:null}catch{return null}}function QI(e){let t=ye(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||Ot(s.path.node,t))return;let a=am(s,e.sourceFile,e.targetFile);if(a){let c=e.targetParentPath.scope.getBinding(a.localName);if(c){let u=am(c,e.targetFile,e.targetFile);(!u||u.moduleFile!==a.moduleFile||!qI(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 po(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 qI(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 am(e,t,n){let r=eC(e),o=r?.parentPath;if(!r||!o?.isImportDeclaration())return null;let i=o.node.source.value;if(typeof i!="string")return null;let s=_n(t,i),a=i.startsWith(".")?Gc(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=pe.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 eC(e){let t=e.path;for(;t&&!t.isImportDeclaration();){if(t.isImportSpecifier()||t.isImportDefaultSpecifier()||t.isImportNamespaceSpecifier())return t;t=t.parentPath}return null}function cm(e,t,n,r){let o=_c(t,n);if(o.length===0)return{sourceJsx:r,conditionPaths:[]};let i=r,s=[];for(let a of o){let c=fr(e,a.conditionPath.node);if(!c)return{sourceJsx:r,conditionPaths:[]};let l=tC(a.conditionPath,c);if(s.push(a.conditionPath),a.kind==="logical"){i=`${l} ${a.operator} ${rC(i)}`;continue}i=a.branch==="consequent"?`${l} ? ${i} : null`:`${l} ? null : ${i}`}return{sourceJsx:i,conditionPaths:s}}function tC(e,t){return nC(e.node)?t:`(${t})`}function nC(e){return pe.isIdentifier(e)||pe.isThisExpression(e)||pe.isSuper(e)||pe.isMemberExpression(e)||pe.isOptionalMemberExpression(e)||pe.isCallExpression(e)||pe.isOptionalCallExpression(e)||pe.isBooleanLiteral(e)||pe.isNumericLiteral(e)||pe.isStringLiteral(e)||pe.isNullLiteral(e)||pe.isUnaryExpression(e)}function rC(e){return e.trim().startsWith("<")?e:`(${e})`}var oC={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 rs(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=oC[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 iC(e,t){for(let n of e.program.body){if(!pe.isImportDeclaration(n)||n.source.value!==t)continue;let r=n.specifiers.find(o=>pe.isImportDefaultSpecifier(o));if(r&&pe.isImportDefaultSpecifier(r))return r.local.name}return null}function sC(e,t,n){for(let r of e.program.body){if(!pe.isImportDeclaration(r)||r.source.value!==t)continue;let o=r.specifiers.find(i=>pe.isImportSpecifier(i)&&(pe.isIdentifier(i.imported)?i.imported.name:i.imported.value)===n);if(o&&pe.isImportSpecifier(o))return o.local.name}return null}function lm(e){let t=new Set;return Ct(e,{Program(n){for(let r of Object.keys(n.scope.bindings))t.add(r);n.stop()}}),t}function um(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n+=1;return`${e}${n}`}function aC(e,t){if(!e.component)return{localName:"Component"};let n=e.component,r=Zc(e),o=Je(t);if(n.exportName!=="default"){let a=o?sC(o,n.source,n.exportName):null;if(a)return{localName:a};let c=o?um(r,lm(o)):r;return{localName:c,importStep:Wc(e,c)}}if(!o)return{localName:r,importStep:Wc(e,r)};let i=iC(o,n.source);if(i)return{localName:i};let s=um(r,lm(o));return{localName:s,importStep:Wc(e,s)}}function cC(e,t){if(e.kind==="native-tag")return e.text?`<${e.tag}>${e.text}</${e.tag}>`:`<${e.tag} />`;let n=t??Zc(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 lC(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?uC(e.props):void 0;return{kind:e.kind,component:{source:e.component.source,exportName:e.component.exportName},...t?{props:t}:{}}}function uC(e){return Object.fromEntries(Object.entries(e).filter(t=>Yc(t[1])))}function Yc(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(Yc):typeof e=="object"?Object.values(e).every(Yc):!1}function Wc(e,t=Zc(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 dm(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 dC(e,t,n){let r=e;for(;r;){if(r===t)return!0;r=n.getNode(r)?.parentKey}return!1}function gr(e,t){return`Operation kind '${e}' does not match params.kind '${t}'`}function Qc(e,t=e.path){return{kind:"value",root:e.root,path:t&&t.length>0?t:void 0,expectedRange:e.expectedRange}}function go(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:Qc(e,t.slice(0,n)),index:r.index}}return null}function Hc(e,t){return e.locator?e.collectionPathMap?.[t]?Qc(e.locator,e.collectionPathMap[t]):go(e.locator)?pC(e.locator,mC(t,e.collectionIndexMap)):null:null}function fC(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:hm(o,t)}function hm(e,t){let[n,...r]=e;if(!n)return t;if(n.kind!=="property")return;let o=hm(r,t);return o===void 0?void 0:{[n.name]:o}}function pC(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},Qc(e,i)}return null}function mC(e,t){return t?.[e]??e}function fm(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 gC(e,t){return hC(e.root,t.root)&&xC(e.path??[],t.path??[])}function hC(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&&yC(e.sourceRange,t.sourceRange)}}function yC(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function xC(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 os=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:gr(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:gr(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:gr(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:gr(t.kind,t.params.kind)};let r=t;if(!ns(r.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};let o=dm(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:gr(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:gr(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=$I(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):pm(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 pm(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:xe(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?Yp({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),f=r.attributes?.find(d=>d.name===c);if((await this.graph.getPropertyState?.(r.key,c,i))?.status==="blocked"||!u&&f?.source)return{ok:!1,errorCode:"capability-denied",reason:`apply-style-draft cannot overwrite a derived or unresolved property '${c}'`};if(!(typeof f?.resolvedValue=="string"&&f.resolvedValue===l||f?.source===null&&f.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 d=u.locator;if(u.sourceKind==="repeat-template"&&typeof i?.instanceIndex=="number"){let g=Hc(u,i.instanceIndex);if(!g)return{ok:!1,errorCode:"invalid-params",reason:"apply-style-draft could not resolve the selected repeat item"};d=g}s.push({order:n+s.length,file:u.file,type:"update-value",locator:d,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:xe(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=Hc(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:xe(t),segmentIndex:n,newText:r}]}}coerceTextValueForValueTarget(t,n,r,o="update-text"){let i=this.graph.getFileContent(t),s=Je(i);if(!s)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not inspect the value source`};let a=se(s,n);if(!a.ok)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not resolve the value source`};if(!KI(a.match.path))return{ok:!0,value:r};let c=UI(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=Hc(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=Je(this.graph.getFileContent(t));if(!o)return!1;let i=se(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 f=i;if(f?.kind==="value-binding"&&f.locator){let m=go(f.locator);if(m)return this.buildPlan(t,n,[{order:0,file:f.file,type:"remove-bound-array-item",locator:m.locator,index:m.index}],o)}return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed node removal requires a writable array target"}}let s=mo(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:xe(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||Up(n,t)>1)return null;let r=Gc(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(!ns(n.params.position))return{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=mo(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 f=await this.planRepeatBackedInsertChild(t,n,r,o);if(f)return f;let m=this.getRepeatBackedTemplateStructureReason(r);if(m)return{ok:!1,errorCode:"unsupported-operation",reason:m};let d=Ip(this.graph.getFileContent(r.file),r);if(!d.allowed)return{ok:!1,errorCode:"unsupported-operation",reason:d.reason??"Cannot insert child into this node"};let g=rs(r,n.params.node);if(g)return{ok:!1,errorCode:"unsupported-operation",reason:g};let h=[],S=0,E=n.params.node.kind==="component-call"?aC(n.params.node,this.graph.getFileContent(r.file)):void 0,y=E?.importStep;return y&&h.push({order:S++,file:r.file,type:"add-import",moduleSpecifier:y.moduleSpecifier,imports:y.imports}),h.push({order:S++,file:r.file,type:"insert-child",parentLocator:xe(r),node:{jsx:cC(n.params.node,E?.localName)},placement:n.params.position.relation,anchorLocator:i?xe(i):void 0}),this.buildPlan(t,n,h,o)}async planExternalBackedInsertChild(t,n,r,o,i,s){if(!ns(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:lC(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(!ns(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(f=>f.isRepeatItemRoot&&f.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=go(a.locator);if(!c)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child requires an array-backed target"};let l=fC(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"?fm(0,a.collectionIndexMap):fm(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=mo(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 pr(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:")||em(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&&pr(this.graph.getFileContent(r.file),r)||r.file!==o.file)return null;let c=this.graph.getFileContent(r.file),l=Je(c);if(!l)return null;let u=bt(l,r),f=bt(l,o);if(!u||!f)return null;let m=Dt(c,u),d=Dt(c,f);if(!fo(m,d))return null;if(a&&(s==="before"||s==="after")){let h=bt(l,a),S=h?Dt(c,h):null;if(!fo(m,S))return null}if(Qi(u,f))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child across statement-level conditional branches"};let g=jc(c,r,o);return g.ok?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:xe(r),targetParentLocator:xe(o),placement:s,anchorLocator:a?xe(a):void 0,selectionContext:Ln(o)}],i):{ok:!1,errorCode:"unsupported-operation",reason:g.reason??`Cannot move node because it depends on bindings outside the target scope: ${g.bindingNames.join(", ")}`}}planRepeatTemplateHoistMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&pr(this.graph.getFileContent(r.file),r)||r.file!==o.file)return null;let c=this.graph.getFileContent(r.file),l=Je(c);if(!l)return null;let u=bt(l,r),f=bt(l,o);if(!u||!f)return null;let m=Dt(c,u);if(!m)return null;let d=Dt(c,f);if(fo(m,d))return null;if(d&&!Qp(d,m))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child into a different repeat template"};if(a&&(s==="before"||s==="after")){let v=Dc(c,l,a);if(d&&!fo(d,v)||!d&&v)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 v=rs(o,{kind:"native-tag",tag:r.tag});if(v)return{ok:!1,errorCode:"unsupported-operation",reason:v}}let g=Xc(this.graph,r);if(!g)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(Qi(u,f))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let h=cm(c,u,f,g);for(let v of h.conditionPaths){let C=Kc(v,f,m);if(!C.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its condition depends on bindings outside the target scope: ${C.bindingNames.join(", ")}`}}let S=Vc(u,f,m,{preserveConditionalBoundary:h.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 E=rm(m,f);if(!E.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its callback parameters depend on bindings outside the target scope: ${E.bindingNames.join(", ")}`};let y=m;if(r.component!==o.component){let v=JI({source:c,ast:l,sourceContext:m,sourceNode:r,targetParent:o,targetParentPath:f});if(!v.ok)return{ok:!1,errorCode:"unsupported-operation",reason:v.reason};y=v.context}else{let v=Uc(m.collectionPath,f);if(!v.ok)return{ok:!1,errorCode:"unsupported-operation",reason:v.reason??`Cannot move repeat-backed child because the repeat collection is not visible at the target: ${v.bindingNames.join(", ")}`}}return this.buildPlan(t,n,[{order:0,file:r.file,type:"move-repeat-template-child",locator:xe(r),targetParentLocator:xe(o),placement:s,anchorLocator:a?xe(a):void 0,repeatExpression:Jc(y,h.sourceJsx),selectionContext:Ln(o)}],i)}planCrossFileRepeatTemplateHoistMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&pr(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=Je(c),f=Je(l);if(!u||!f)return null;let m=zp({knownSourceFiles:this.graph.getKnownSourceFiles?.(),routeEntryFiles:this.graph.getRouteEntryFiles?.(),sourceAst:u,sourceFile:r.file,targetFile:o.file,sourceComponent:r.component,targetComponent:o.component});if(!m.ok)return{ok:!1,errorCode:"unsupported-operation",reason:m.reason};let d=bt(u,r),g=bt(f,o);if(!d||!g)return null;let h=$c(m.callSitePath,g);if(!h.ok)return{ok:!1,errorCode:"unsupported-operation",reason:h.reason};let S=Dt(c,d);if(!S)return null;if(Dt(l,g))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child into a different repeat template"};if(a&&(s==="before"||s==="after")&&Dc(l,f,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 _=rs(o,{kind:"native-tag",tag:r.tag});if(_)return{ok:!1,errorCode:"unsupported-operation",reason:_}}let y=Xc(this.graph,r);if(!y)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(Qi(d,g))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let v=cm(c,d,g,y);for(let _ of v.conditionPaths){let D=Kc(_,g,S);if(!D.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its condition depends on bindings outside the target scope: ${D.bindingNames.join(", ")}`}}let C=Vc(d,g,S,{preserveConditionalBoundary:v.conditionPaths.length>0});if(!C.ok)return{ok:!1,errorCode:"unsupported-operation",reason:C.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${C.bindingNames.join(", ")}`};let N=QI({sourceFile:r.file,targetFile:o.file,sourceContext:S,targetParentPath:g});if(!N.ok)return{ok:!1,errorCode:"unsupported-operation",reason:N.reason};let A=om(S);if(!A.ok)return{ok:!1,errorCode:"unsupported-operation",reason:A.reason};let R=im(S,A.callbackParams),F=[{order:0,file:r.file,type:"remove-node",locator:xe(r),removeWhitespace:!0}];for(let _ of N.imports)F.push({order:F.length,file:o.file,type:"add-import",moduleSpecifier:_.moduleSpecifier,imports:_.imports});return F.push({order:F.length,file:o.file,type:"insert-jsx-expression-child",parentLocator:xe(o),expression:Jc(R,v.sourceJsx),placement:s,anchorLocator:a?xe(a):void 0,selectionContext:Ln(o)}),this.buildPlan(t,n,F,i)}async planMoveNode(t,n,r,o){if(!o.canMove)return{ok:!1,errorCode:"capability-denied",reason:"Cannot move this node"};if("kind"in n.params.target&&n.params.target.kind==="source-sibling"){let v=n.params.target,C=this.graph.getNode(v.anchorKey);if(!C||r.file!==C.file||r.component!==C.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 A=this.graph.getFileContent(r.file),R=Je(A),F=R?bt(R,r):null,_=R?bt(R,C):null,D=F?.parentPath,L=_?.parentPath;if(!F||!_||!D||!L||D.node!==L.node||!D.isJSXFragment()&&!(D.isJSXElement()&&Me(D)))return{ok:!1,errorCode:"unsupported-operation",reason:"Source sibling move requires two direct children of the same transparent Fragment"};let oe=D.node.loc;return oe?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:xe(r),targetParentLocator:{kind:"jsx-node",strategy:"source-range",sourceRange:{startLine:oe.start.line,startColumn:oe.start.column,endLine:oe.end.line,endColumn:oe.end.column}},placement:v.relation,anchorLocator:xe(C),selectionContext:Ln(r)}],o):{ok:!1,errorCode:"locator-miss",reason:"Source Fragment has no stable source range"}}let i=dm(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(dC(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 v=n.params.target.relation,C=i.anchorNode&&(v==="before"||v==="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:v,anchorSourceId:C?.kind==="external-entry"?C.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,f=i.anchorNode,m=this.graph.getTextProvenance?.(r.key,0)??null,d=mo(r,c,m);if(d&&!zc(d)&&!sm(r,s,c,m))return{ok:!1,errorCode:"unsupported-operation",reason:d};if(r.isRepeatItemRoot&&f?.isRepeatItemRoot&&r.repeatOwnerKey&&r.repeatOwnerKey===f.repeatOwnerKey&&(u==="before"||u==="after")){let v=c,C=await this.graph.getTextWriteTarget(f.key,0);if(v?.kind==="value-binding"&&C?.kind==="value-binding"&&v.locator&&C.locator){let N=go(v.locator),A=go(C.locator);if(N&&A&&v.file===C.file&&gC(N.locator,A.locator)){let R=N.index,F=A.index,_=u==="before"?F-(R<F?1:0):F+(R<F?0:1);return this.buildPlan(t,n,[{order:0,file:v.file,type:"move-array-item",locator:N.locator,fromIndex:R,toIndex:_}],o)}}}if(r.isRepeatItemRoot&&pr(this.graph.getFileContent(r.file),r))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed item outside its collection"};let g=this.getRepeatBackedTemplateStructureReason(r),h=zc(d)?d:g;if(h&&zc(h)){let v=this.planRepeatTemplateInternalMove(t,n,r,s,o,u,f);if(v)return v;let C=this.planRepeatTemplateHoistMove(t,n,r,s,o,u,f);if(C)return C;let N=this.planCrossFileRepeatTemplateHoistMove(t,n,r,s,o,u,f);return N||{ok:!1,errorCode:"unsupported-operation",reason:h}}if(g)return{ok:!1,errorCode:"unsupported-operation",reason:g};let S=await this.getUpstreamBackedDescendantReason(r);if(S)return{ok:!1,errorCode:"unsupported-operation",reason:S};if(r.tag&&r.tag.toLowerCase()===r.tag){let v=rs(s,{kind:"native-tag",tag:r.tag});if(v)return{ok:!1,errorCode:"unsupported-operation",reason:v}}if(l)return this.planCrossFileMove(t,n,r,s,o,u,f);let E=jc(this.graph.getFileContent(r.file),r,s);if(!E.ok)return{ok:!1,errorCode:"unsupported-operation",reason:E.reason??`Cannot move node because it depends on bindings outside the target scope: ${E.bindingNames.join(", ")}`};let y=[{order:0,file:r.file,type:"move-node",locator:xe(r),targetParentLocator:xe(s),placement:u,anchorLocator:f?xe(f):void 0,selectionContext:Ln(s)}];return this.buildPlan(t,n,y,o)}planCrossFileMove(t,n,r,o,i,s,a){let c=[],l=0,u=this.graph.getFileContent(r.file),f=Xc(this.graph,r)??`<${r.component} />`,m=Cp(u,r);if(!m.allowed)return{ok:!1,errorCode:"unsupported-operation",reason:m.reason??"Cannot move subtree across files"};if(c.push({order:l++,file:r.file,type:"remove-node",locator:xe(r),removeWhitespace:!0}),r.importedFrom&&r.exportName){let g=r.tag??r.component,S={moduleSpecifier:Gc(o.file,r.importedFrom),imports:r.exportName==="default"?[{kind:"default",local:g}]:[{kind:"named",imported:r.exportName,local:g===r.exportName?void 0:g}]};c.push({order:l++,file:o.file,type:"add-import",moduleSpecifier:S.moduleSpecifier,imports:S.imports}),c.push({order:l++,file:o.file,type:"insert-child",parentLocator:xe(o),node:{jsx:f},placement:s,anchorLocator:a?xe(a):void 0,selectionContext:Ln(o)})}else c.push({order:l++,file:o.file,type:"insert-child",parentLocator:xe(o),node:{jsx:f},placement:s,anchorLocator:a?xe(a):void 0,selectionContext:Ln(o)});let d=this.buildRemoveComponentImportStep(r,u);return d&&c.push({...d,order:l++}),this.buildPlan(t,n,c,i)}buildPlan(t,n,r,o){let s=[...new Set(r.map(a=>a.file))].map(a=>({file:a,content:this.graph.getFileContent(a),version:this.graph.getFileVersion(a),exists:!0,sha256:ke(this.graph.getFileContent(a))}));return{ok:!0,plan:{operationId:t,kind:n.kind,target:n.target,documentVersion:n.documentVersion,steps:r,preSnapshots:s,validatedCapability:o}}}};function pm(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 rl from"@babel/generator";import{parse as _C}from"@babel/parser";import ol from"@babel/traverse";import*as w from"@babel/types";import*as jt from"@babel/types";import qc from"@babel/generator";import*as ve from"@babel/types";var bC=typeof qc=="function"?qc:qc.default,SC=/(?:token|secret|key|password|authorization|cookie|signature|credential)/i,EC=/^((?:https?:)?\/\/)[^/@\s]+@/i,vC=/(\/(?:token|secret|api[-_]?key|password|credential|signature)\/)[^/?#]+/gi;function xm(e,t){let n=Bt(e.callee);if(!n)return null;if(n==="fetch")return el(e.arguments[0],"GET",t,["fetch call"]);if(n.startsWith("axios.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(ym(r))return el(e.arguments[0],r,t,["axios client contract"])}if(n.startsWith("ky.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(ym(r))return el(e.arguments[0],r,t,["ky client contract"])}return null}function el(e,t,n,r){if(!e||ve.isSpreadElement(e)||ve.isJSXNamespacedName(e))return RC(t,n,r,"missing url argument");let o=ho(e);return{sourceKind:CC(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 ho(e){if(ve.isStringLiteral(e))return ss(e.value);if(ve.isTemplateLiteral(e))return ss(kC(e));if(ve.isBinaryExpression(e)&&e.operator==="+"){let t=ho(e.left),n=ho(e.right);return!t&&!n?void 0:ss(`${t??tl(e.left)}${n??tl(e.right)}`)}if(ve.isMemberExpression(e)){let t=bm(e);if(t)return`env:${t}`}if(!(ve.isCallExpression(e)&&Bt(e.callee)==="new URL")){if(ve.isNewExpression(e)&&ve.isIdentifier(e.callee,{name:"URL"})){let[t,n]=e.arguments,r=t&&!ve.isSpreadElement(t)?ho(t):void 0,o=n&&!ve.isSpreadElement(n)?ho(n):void 0;return o&&r?ss(`${o} + ${r}`):r??o}if(ve.isIdentifier(e))return`:${e.name}`}}function kC(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+=tl(r))}return t}function tl(e){if(ve.isIdentifier(e))return`:${e.name}`;if(ve.isMemberExpression(e)){let t=bm(e);if(t)return`env:${t}`}return`:${IC(e)}`}function IC(e){return bC(e,{comments:!1}).code.replace(/[^a-zA-Z0-9_$]+/g,"_").replace(/^_+|_+$/g,"")||"param"}function ss(e){let[t]=e.split("#"),[n,r]=t.split("?"),o=n.replace(EC,"$1<redacted>@").replace(vC,"$1<redacted>");if(!r)return o;let i=r.split("&").map(s=>{let[a]=s.split("=");return a?SC.test(a)?`${a}=<redacted>`:`${a}=:${a}`:""}).filter(Boolean).join("&");return i?`${o}?${i}`:o}function CC(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 RC(e,t,n,r){return{sourceKind:"unknown-api",method:e,confidence:"partial",evidence:[{file:t.file,reason:[...n,r].join("; ")}]}}function ym(e){return["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(e)}function bm(e){return!ve.isMemberExpression(e.object)||!ve.isIdentifier(e.object.object,{name:"process"})||!wC(e.object.property,"env")?null:ve.isIdentifier(e.property)?e.property.name:ve.isStringLiteral(e.property)?e.property.value:null}function wC(e,t){return ve.isIdentifier(e)&&e.name===t}function Bt(e){if(ve.isIdentifier(e))return e.name;if(ve.isMemberExpression(e)){let t=Bt(e.object),n=ve.isIdentifier(e.property)?e.property.name:ve.isStringLiteral(e.property)?e.property.value:null;if(t&&n)return`${t}.${n}`}return null}var NC=new Set(["list","listStrict","get","getStrict","getByUrl","getByUrlStrict","schema","categories"]),PC=new Set(["getConfig","submit"]);function Sm(e,t){let n=AC(Bt(e.callee),t);if(!n)return null;let r="cms.collections.";if(n.startsWith(r)){let i=n.slice(r.length);if(!NC.has(i))return null;let s=nl(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(!PC.has(i))return null;let s=nl(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=nl(e,0)??TC(e,0,"path")??"/cms/:path",s=FC(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 AC(e,t){let n=e?.indexOf(".")??-1;if(!e||n<1)return e;let r=t.imports?.get(e.slice(0,n));return r?.importedName==="collections"&&/(?:^|\/)lib\/cms\/collections(?:\.js)?$/.test(r.source)?`cms.collections${e.slice(n)}`:e}function Em(e,t){let n=Bt(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 vm(e){let t=Bt(e.callee);return typeof t=="string"&&t.startsWith("cms.field.")}function nl(e,t){let n=e.arguments[t];return jt.isStringLiteral(n)?n.value:null}function TC(e,t,n){let r=e.arguments[t];if(!jt.isObjectExpression(r))return null;for(let o of r.properties)if(jt.isObjectProperty(o)&&!o.computed&&(jt.isIdentifier(o.key)&&o.key.name===n||jt.isStringLiteral(o.key)&&o.key.value===n)&&jt.isStringLiteral(o.value))return o.value.value;return null}function FC(e){return/^\/collections\/([^/]+)(?:\/|$)/.exec(e)?.[1]??null}function km(e=4096){if(!Number.isSafeInteger(e)||e<1)throw new RangeError("Re-export relation capacity must be positive.");let t=new Map;return{resolve(n,r){let o=JSON.stringify([n.fromFile,n.exportName,n.targetFile,n.maxImportDepth]),i=t.get(o);if(i)return i;let s=r();return t.size>=e&&t.delete(t.keys().next().value),t.set(o,s),s.catch(()=>{t.get(o)===s&&t.delete(o)}),s}}}var Tm=typeof ol=="function"?ol:ol.default,YO=typeof rl=="function"?rl:rl.default,Fm=new WeakMap;function _m(e){let t=new Map;return Fm.set(t,new Map([...e].map(n=>[n.file,n]))),t}var MC={maxFunctionDepth:8,maxImportDepth:6},OC=new Set(["src","href","alt","poster","content","title","aria-label"]),Im=new WeakMap;function LC(e,t,n){let r=Im.get(t.fileCache);r||(r=new WeakMap,Im.set(t.fileCache,r));let o=r.get(e);if(!o){o={imported:[],local:new Map};let u=0;for(let f of e.elements.values()){let m={element:f,order:u++};f.importedFrom&&f.exportName&&o.imported.push(m);let d=o.local.get(f.sourceFile);d||(d=new Map,o.local.set(f.sourceFile,d));let g=d.get(f.tag)??[];g.push(m),d.set(f.tag,g)}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],f=i[l];u&&(!f||u.order<f.order)?(a.push(u.element),c++):f&&(!u||f.order<u.order)?(a.push(f.element),l++):(a.push(u.element),c++,l++)}return a}async function Mm(e){let t=e.fileCache??new Map,n=cl(e.file,e.source,t),r={file:e.file,analysis:n,readFile:e.readFile,exists:e.exists,fileCache:t,options:{...MC,...e.options},variableCache:new Map,functionDepth:0,importDepth:0,paramSources:new Map,resolvingVariables:new Set,resolvingComponentProps:new Set,scopeVariables:Gm(n,e.element.componentName)};await Om(e.element.componentName,e.graph,r);let o=[];o.push(...await VC(e.element,e.graph,r),...await KC(e.element,e.graph,r));for(let s of e.element.textSegments){let a=await UC(s,e.element,e.graph,r);a&&o.push(ls(a,"text","children"))}for(let s of e.element.attributes??[]){let a=$C(s,e.element);if(!a)continue;let c=await jm(s.source,e.element,e.graph,r);c&&o.push(ls(c,a,s.name))}let i=oR(o).sort(Wm);return{hasDynamicData:i.length>0,bindings:i}}async function Om(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 LC(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 DC(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 f=await Bm(l.sourceFile,n);if(!f)continue;let m=ds(f,n,{importDepth:n.importDepth+1});m.paramSources.clear(),m.scopeVariables=Gm(f,l.componentName),await Om(l.componentName,t,m);let d=await BC(l,m);for(let[g,h]of d){if(!h)continue;let S=a.get(g)??[];S.push(h),a.set(g,S)}}finally{n.resolvingComponentProps.delete(u)}}}let c=new Map;for(let[l,u]of a){let f=Xm(u);f.length===1&&c.set(l,f[0])}jC(o,c,n)}var Cm=new WeakMap;function DC(e,t,n,r){let o=Cm.get(r.fileCache);return o||(o=km(),Cm.set(r.fileCache,o)),o.resolve({fromFile:e,exportName:t,targetFile:n,maxImportDepth:r.options.maxImportDepth},()=>Lm(e,t,n,r))}async function Lm(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 Bm(e,r))?.imports.get(t);if(!s||!Nt(s.source))return!1;let a=await Qm(e,s.source,r.exists);return a?a===n?!0:Lm(a,s.importedName,n,r,o):!1}async function BC(e,t){let n=new Map,r=t.analysis.jsxElementsByRange.get(Dm(e.sourceRange));if(r)for(let i of r.openingElement.attributes)!w.isJSXAttribute(i)||!w.isJSXIdentifier(i.name)||!w.isJSXExpressionContainer(i.value)||!w.isExpression(i.value.expression)||n.set(i.name.name,i.value.expression);let o=new Map;for(let[i,s]of n){let a=await je(s,t);a&&o.set(i,a)}return o}function Dm(e){return`${e.startLine}:${e.startColumn}:${e.endLine}:${e.endColumn}`}async function Bm(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 cl(e,r,t.fileCache)}function jC(e,t,n){if(w.isIdentifier(e)){t.size>0&&n.paramSources.set(e.name,al(Object.fromEntries(t),n.file));return}if(w.isObjectPattern(e))for(let r of e.properties){if(!w.isObjectProperty(r)||r.computed||!w.isIdentifier(r.key))continue;let o=t.get(r.key.name);if(!o)continue;let i=w.isAssignmentPattern(r.value)?r.value.left:r.value;w.isIdentifier(i)&&n.paramSources.set(i.name,ze(o))}}function $C(e,t){return e.name==="dangerouslySetInnerHTML"?"richtext":OC.has(e.name)?"attribute":t.importedFrom||/^[A-Z]/.test(t.tag)?"component-prop":null}async function VC(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 us(i.collectionSource,n);s&&r.push(ls(Dn(s),"repeat-region",i.collectionExpression))}return r}async function KC(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 us(i.conditionSource,n);s&&r.push(ls(Dn(s),"conditional-region",i.conditionExpression))}return r}async function UC(e,t,n,r){return jm(e.source,t,n,r)}async function jm(e,t,n,r){let o=await JC(e,t,n,r);return o||us(e,r)}async function JC(e,t,n,r){if(!e)return null;let o=XC(e.base,t,n);if(!o)return null;let i=await us(o.collectionSource,r);return i?So(i,e.path,!0):null}function XC(e,t,n){let r=t.identity.key;for(;r;){for(let o of n.regions){if(o.kind!=="repeat-region"||!o.childKeys.includes(r))continue;let i=o.sourceCandidates?.find(s=>s.kind==="repeat-template"&&s.itemParamName===e);if(i)return i}r=n.elements.get(r)?.parentKey??null}return null}async function us(e,t){if(!e)return null;let n=await $m(e.base,t);return n?So(n,e.path,!1):null}async function $m(e,t){let n=t.paramSources.get(e);if(n)return ze(n);if(t.variableCache.has(e))return iR(t.variableCache.get(e)??null);if(t.resolvingVariables.has(e))return null;t.resolvingVariables.add(e);let r=await zC(e,t);if(r)return t.variableCache.set(e,ze(r)),t.resolvingVariables.delete(e),r;let o=t.scopeVariables?.get(e)??t.analysis.variables.get(e);if(o){let s=await je(o,t);return t.variableCache.set(e,s?ze(s):null),t.resolvingVariables.delete(e),s}let i=t.analysis.imports.get(e);if(i&&t.importDepth<t.options.maxImportDepth){let s=await Ym(i,t);if(s){let a=ds(s,t,{importDepth:t.importDepth+1}),c=Zm(i,s);if(c){let f=(await Bn(c,[],a)).returnSource;return t.variableCache.set(e,f?ze(f):null),t.resolvingVariables.delete(e),f}let l=s.variables.get(i.importedName);if(l){let u=await je(l,a);return t.variableCache.set(e,u?ze(u):null),t.resolvingVariables.delete(e),u}}}return t.variableCache.set(e,null),t.resolvingVariables.delete(e),null}async function zC(e,t){let n=t.analysis.stateSetters.get(e);if(!n)return null;let r=[];Tm(t.analysis.ast,{CallExpression(o){if(w.isIdentifier(o.node.callee,{name:n})){let i=o.node.arguments[0];w.isExpression(i)&&r.push(i);return}o.node.arguments.some(i=>w.isIdentifier(i)&&i.name===n)&&r.push(o.node)}});for(let o of r){let i=await je(o,t);if(i)return i}return null}async function je(e,t){if(w.isIdentifier(e))return $m(e.name,t);if(w.isMemberExpression(e)||w.isOptionalMemberExpression(e)){let n=w.isMemberExpression(e)?Em(e,{file:t.file}):null;if(n)return Jm(n);let r=await WC(e,t);if(!r)return null;let o=nR(e);return So(r,o,!1)}if(w.isAwaitExpression(e))return w.isExpression(e.argument)?je(e.argument,t):null;if(w.isCallExpression(e))return Vm(e,t);if(w.isObjectExpression(e)){let n=await Km(e,t);return Object.keys(n).length>0?al(n,t.file):null}if(w.isConditionalExpression(e)){let n=await je(e.consequent,t),r=await je(e.alternate,t);return bo(wm(n,r))}if(w.isLogicalExpression(e)){let n=await je(e.left,t),r=await je(e.right,t);return bo(wm(n,r))}return w.isTSAsExpression(e)||w.isTSSatisfiesExpression(e)||w.isTSNonNullExpression(e)||w.isTypeCastExpression(e)||w.isParenthesizedExpression(e)?je(e.expression,t):null}async function WC(e,t){let n=e;for(;w.isMemberExpression(n)||w.isOptionalMemberExpression(n);)n=n.object;return w.isExpression(n)?je(n,t):null}async function Vm(e,t){let n=Sm(e,{file:t.file,imports:t.analysis.imports});if(n)return Jm(n);if(vm(e)){let f=e.arguments[0];if(f&&w.isExpression(f))return bo(await je(f,t))}let r=await HC(e,t);if(r)return r;let o=xm(e,{file:t.file});if(o)return{sourceKind:o.sourceKind,sourceType:"api-field",endpointPattern:o.endpointPattern,valuePath:o.valuePath,confidence:o.confidence,readonly:!0,evidence:o.evidence};let i=await ZC(e,t);if(i)return i;let s=await QC(e,t);if(s)return s;let a=await qC(e,t);if(a)return a;let c=await eR(e,t);if(c)return c;let l=[];for(let f of e.arguments)if(w.isExpression(f)){let m=await je(f,t);m&&l.push(m)}let u=Xm(l);return u.length===1?bo(u[0]):null}async function HC(e,t){let n=Bt(e.callee);if(n!=="useQuery"&&n!=="useSuspenseQuery"&&n!=="useInfiniteQuery"&&n!=="useSWR")return null;if(n==="useSWR"){let i=YC(e.arguments[0],t.file,"SWR key"),s=e.arguments[1];if(w.isIdentifier(s)){let a=await xo(s.name,t);if(a)return(await Bn(a.node,i?[i]:[],a.context)).returnSource??i}return i}let r=e.arguments[0];if(!w.isObjectExpression(r))return as(t.file,`${n} without static options`);let o=GC(r,"queryFn");if(!o)return as(t.file,`${n} without queryFn`);if(w.isIdentifier(o)){let i=await xo(o.name,t);return i?(await Bn(i.node,[],i.context)).returnSource:as(t.file,`${n} queryFn unresolved`)}return w.isArrowFunctionExpression(o)||w.isFunctionExpression(o)?(await Bn(o,[],t)).returnSource:w.isCallExpression(o)?Vm(o,t):null}function GC(e,t){for(let n of e.properties){if(!w.isObjectProperty(n)||!w.isExpression(n.value))continue;if(Um(n)===t)return n.value}return null}function YC(e,t,n){return w.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 ZC(e,t){if(!w.isMemberExpression(e.callee)||!w.isIdentifier(e.callee.property))return null;let n=e.callee.property.name;if(!["map","filter","slice","sort","toSorted"].includes(n))return null;let r=w.isExpression(e.callee.object)?await je(e.callee.object,t):null;if(!r)return null;if(n!=="map")return Dn(r);let o=e.arguments[0];if(w.isIdentifier(o)){let i=await xo(o.name,t);if(!i)return Dn(r);let s=await Bn(i.node,[r],i.context);return{...Dn(r),...s.objectReturnMap??s.returnSource?.fieldMap?{fieldMap:s.objectReturnMap??s.returnSource.fieldMap}:{}}}if(w.isArrowFunctionExpression(o)||w.isFunctionExpression(o)){let i=await Bn(o,[r],t);return{...Dn(r),...i.objectReturnMap??i.returnSource?.fieldMap?{fieldMap:i.objectReturnMap??i.returnSource.fieldMap}:{}}}return Dn(r)}async function QC(e,t){return!w.isMemberExpression(e.callee)||!w.isIdentifier(e.callee.property,{name:"json"})||!w.isExpression(e.callee.object)?null:je(e.callee.object,t)}async function qC(e,t){return!w.isMemberExpression(e.callee)||!w.isIdentifier(e.callee.property,{name:"then"})||!w.isExpression(e.callee.object)?null:bo(await je(e.callee.object,t))}async function eR(e,t){if(!w.isIdentifier(e.callee))return null;let n=await xo(e.callee.name,t);if(!n)return null;let r=[];for(let i of e.arguments){if(!w.isExpression(i)){r.push(as(t.file,`unsupported argument for ${e.callee.name}`));continue}let s=await je(i,t);r.push(s)}return(await Bn(n.node,r,n.context)).returnSource}async function xo(e,t){let n=t.analysis.functions.get(e);if(n)return{node:n,context:t};let r=t.analysis.imports.get(e);if(!r||t.importDepth>=t.options.maxImportDepth)return null;let o=await Ym(r,t);if(!o)return null;let i=ds(o,t,{importDepth:t.importDepth+1}),s=Zm(r,o);return s?{node:s,context:i}:xo(r.importedName,i)}async function Bn(e,t,n){if(n.functionDepth>=n.options.maxFunctionDepth)return{returnSource:null};let r=ds(n.analysis,n,{functionDepth:n.functionDepth+1});r.scopeVariables=n.analysis.functionVariables.get(e),e.params.forEach((c,l)=>{let u=t[l];u&&il(c,rR(u),r)});let o=tR(e),i=null,s,a=!1;for(let c of o){if(w.isObjectExpression(c)){s={...s??{},...await Km(c,r)},i=i??al(s,n.file);continue}let l=await je(c,r);if(l){if(!i){i=l;continue}let u=sl(i,l);if(!u){a=!0,i=null;continue}i=u}}return{returnSource:a?null:i,...s?{objectReturnMap:s}:{}}}function il(e,t,n){if(w.isIdentifier(e)){n.paramSources.set(e.name,ze(t));return}if(w.isAssignmentPattern(e)){il(e.left,t,n);return}if(w.isObjectPattern(e))for(let r of e.properties){if(!w.isObjectProperty(r)||r.computed||!w.isIdentifier(r.key))continue;let o=So(t,[{kind:"property",name:r.key.name}],!0),i=w.isAssignmentPattern(r.value)?r.value.left:r.value;il(i,o,n)}}function tR(e){if(w.isArrowFunctionExpression(e)&&w.isExpression(e.body))return[e.body];let t=[],n=e.body;if(!w.isBlockStatement(n))return t;let r=o=>{if(w.isFunction(o)&&o!==e)return;if(w.isReturnStatement(o)){o.argument&&w.isExpression(o.argument)&&t.push(o.argument);return}let i=w.VISITOR_KEYS[o.type];for(let s of i??[]){let a=o[s];if(Array.isArray(a))for(let c of a)w.isNode(c)&&r(c);else w.isNode(a)&&r(a)}};return r(n),t}async function Km(e,t){let n={};for(let r of e.properties){if(!w.isObjectProperty(r))continue;let o=Um(r);if(!o||!w.isExpression(r.value))continue;let i=await je(r.value,t);i&&(n[o]=i)}return n}function Um(e){return w.isIdentifier(e.key)&&!e.computed?e.key.name:w.isStringLiteral(e.key)?e.key.value:null}function nR(e){let t=[],n=e;for(;w.isMemberExpression(n)||w.isOptionalMemberExpression(n);){let r=n.property;n.computed?w.isStringLiteral(r)?t.unshift({kind:"property",name:r.value}):w.isNumericLiteral(r)&&t.unshift({kind:"index",index:r.value}):w.isIdentifier(r)&&t.unshift({kind:"property",name:r.name}),n=n.object}return w.isIdentifier(n),t}function So(e,t,n){if(t.length===0)return ze(e);let r=t[0];if(r?.kind==="property"&&e.fieldMap?.[r.name])return So(e.fieldMap[r.name],t.slice(1),n);let o=ze(e);if(o.sourceType==="cms-field"){let i=t.filter(s=>s.kind==="property").map(s=>s.name);return i[0]==="data"&&i[1]==="items"?(o.valuePath=yo(o.valuePath,"data.items[]"),o.cmsFieldRoot=!1,o):i[0]==="fields"?(o.fieldPath=yo(o.fieldPath,i.slice(1).join(".")),o.cmsFieldRoot=!0,o):o.cmsFieldRoot||n||o.fieldMap?(o.fieldPath=yo(o.fieldPath,i.join(".")),o):(o.valuePath=yo(o.valuePath,Rm(t)),o)}return o.valuePath=yo(o.valuePath,Rm(t)),o}function Rm(e){return e.map(t=>t.kind==="property"?t.name:`[${t.index}]`).join(".").replace(/\.\[/g,"[")}function yo(e,t){return t?e?t.startsWith("[")?`${e}${t}`:`${e}.${t}`:t:e}function Jm(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 Dn(e){let t=ze(e);return t.sourceType==="cms-field"&&!t.valuePath&&(t.valuePath="items[]"),t}function rR(e){let t=ze(e);return t.valuePath=void 0,t.sourceType==="cms-field"&&(t.cmsFieldRoot=!1),t}function bo(e){return e?{...ze(e),confidence:e.confidence==="unknown"?"unknown":"safe-derived",evidence:[...e.evidence,{file:e.evidence[0]?.file??"unknown",reason:"safe derived expression"}]}:null}function wm(e,t){return e?t?sl(e,t):ze(e):t?ze(t):null}function sl(e,t){if(cs(e)!==cs(t))return null;let n=Hm(e.confidence,t.confidence)<=0?e.confidence:t.confidence;return{...e,confidence:n,evidence:[...e.evidence,...t.evidence]}}function Xm(e){let t=new Map;for(let n of e){let r=cs(n),o=t.get(r);t.set(r,o?sl(o,n):ze(n))}return[...t.values()]}function cs(e){let t=e.fieldMap?Object.fromEntries(Object.entries(e.fieldMap).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>[n,cs(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 al(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 as(e,t){return{sourceKind:"unknown-api",sourceType:"api-field",confidence:"unknown",readonly:!0,evidence:[{file:e,reason:t}]}}function ls(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 zm(e){let t=[...e].sort(Wm),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 oR(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 Wm(e,t){return Nm(e.targetKind)-Nm(t.targetKind)||Hm(e.confidence,t.confidence)||Pm(e.sourceKind)-Pm(t.sourceKind)||e.targetName.localeCompare(t.targetName)}function Nm(e){return{"repeat-region":0,"conditional-region":1,text:2,richtext:3,attribute:4,"component-prop":5}[e]}function Pm(e){return e.startsWith("vcp-cms-")?0:e==="site-api-route"?1:e==="external-api"?2:3}function Hm(e,t){let n={exact:0,"safe-derived":1,partial:2,unknown:3};return n[e]-n[t]}function cl(e,t,n){let r=n.get(e);if(r?.source===t)return r;let o=Fm.get(n)?.get(e),i=o?.source===t?o.ast:_C(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,jsxElementsByRange:new Map,functionVariables:new WeakMap};return Tm(i,{JSXElement(a){let c=a.node.loc;if(!c)return;let l=Dm({startLine:c.start.line,startColumn:c.start.column,endLine:c.end.line,endColumn:c.end.column});s.jsxElementsByRange.has(l)||s.jsxElementsByRange.set(l,a.node)},ImportDeclaration(a){let c=a.node.source.value;for(let l of a.node.specifiers)w.isImportSpecifier(l)&&w.isIdentifier(l.local)?s.imports.set(l.local.name,{source:c,importedName:w.isIdentifier(l.imported)?l.imported.name:l.imported.value,localName:l.local.name,isDefault:!1}):w.isImportDefaultSpecifier(l)&&s.imports.set(l.local.name,{source:c,importedName:"default",localName:l.local.name,isDefault:!0})},FunctionDeclaration(a){a.node.id?.name&&s.functions.set(a.node.id.name,a.node)},VariableDeclarator(a){let c=a.getFunctionParent(),l=c&&(w.isFunctionDeclaration(c.node)||w.isFunctionExpression(c.node)||w.isArrowFunctionExpression(c.node))?c.node:null,u=l?s.functionVariables.get(l)??new Map:s.variables;l&&!s.functionVariables.has(l)&&s.functionVariables.set(l,u);for(let f of hr(a.node.id))u.set(f,w.isExpression(a.node.init)?a.node.init:null);if(w.isArrayPattern(a.node.id)&&w.isCallExpression(a.node.init)&&Bt(a.node.init.callee)==="useState"){let[f,m]=a.node.id.elements;w.isIdentifier(f)&&w.isIdentifier(m)&&s.stateSetters.set(f.name,m.name)}w.isIdentifier(a.node.id)&&Am(a.node.init)&&s.functions.set(a.node.id.name,a.node.init)},ExportNamedDeclaration(a){let c=a.node.declaration,l=a.node.source?.value;if(l)for(let u of a.node.specifiers){if(!w.isExportSpecifier(u))continue;let f=w.isIdentifier(u.exported)?u.exported.name:u.exported.value,m=u.local.name;s.imports.set(f,{source:l,importedName:m,localName:f,isDefault:m==="default"})}if(w.isFunctionDeclaration(c)&&c.id?.name&&s.functions.set(c.id.name,c),w.isVariableDeclaration(c))for(let u of c.declarations)w.isIdentifier(u.id)&&Am(u.init)&&s.functions.set(u.id.name,u.init)},ExportDefaultDeclaration(a){let c=a.node.declaration;if((w.isFunctionDeclaration(c)||w.isFunctionExpression(c)||w.isArrowFunctionExpression(c))&&s.functions.set("default",c),w.isIdentifier(c)){let l=s.functions.get(c.name);l&&s.functions.set("default",l)}}}),n.set(e,s),s}function hr(e){return!e||w.isVoidPattern(e)?[]:w.isIdentifier(e)?[e.name]:w.isObjectPattern(e)?e.properties.flatMap(t=>w.isObjectProperty(t)?hr(t.value):hr(t.argument)):w.isArrayPattern(e)?e.elements.flatMap(t=>t?hr(w.isRestElement(t)?t.argument:t):[]):w.isAssignmentPattern(e)?hr(e.left):w.isRestElement(e)?hr(e.argument):[]}function Am(e){return w.isFunctionExpression(e)||w.isArrowFunctionExpression(e)}function Gm(e,t){let n=e.functions.get(t)??e.functions.get("default");return n?e.functionVariables.get(n):void 0}async function Ym(e,t){let n=await Qm(t.file,e.source,t.exists);if(!n)return null;let r=await t.readFile(n);return cl(n,r,t.fileCache)}function Zm(e,t){return e.isDefault?t.functions.get("default")??t.functions.get(e.localName)??null:t.functions.get(e.importedName)??null}async function Qm(e,t,n){return Nt(t)?Sn(e,t,n):null}function ds(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),resolvingVariables:new Set,resolvingComponentProps:t.resolvingComponentProps,scopeVariables:e===t.analysis?t.scopeVariables:void 0}}function iR(e){return e?ze(e):null}function ze(e){return{...e,evidence:e.evidence.map(t=>({...t})),...e.fieldMap?{fieldMap:Object.fromEntries(Object.entries(e.fieldMap).map(([t,n])=>[t,ze(n)]))}:{}}}import*as ul from"@babel/parser";import ll from"@babel/traverse";import*as Y from"@babel/types";import{classifySiteEditPropertyName as sR}from"@vcp-dev/contracts";var dl=typeof ll=="function"?ll:ll.default;function fl(e){let t=sR(e.propertyName);if(t.owner!=="generic")return ut("invalid-property",t.diagnostic?.message??`Property '${e.propertyName}' is not a generic property`);let n=e.selectionRef;if(!n)return ut("missing-selection-ref","A repeat property target requires a complete selection reference");if(n.key!==e.element.identity.key)return ut("selection-mismatch","Selection reference does not identify the requested element");if(n.instanceIndex===void 0)return ut("missing-instance-index","A repeat property target requires an instance index");let r;try{r=ul.parse(e.source,{sourceType:"module",plugins:["typescript","jsx"]})}catch(S){return ut("repeat-not-found",`Unable to parse repeat source: ${S instanceof Error?S.message:String(S)}`)}let o=aR(r,e.element.sourceRange);if(!o)return ut("repeat-not-found","The selected element is not inside a supported map repeat");if(!Y.isIdentifier(o.callback.params[0]))return ut("unsupported-callback","Repeat property materialization requires an identifier callback item");let i=cR(r,o.collection,e.file,e.sources);if(!i)return ut("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[S,E]of s.elements.entries()){if(!E||!Y.isObjectExpression(E)||!og(E))return ut("unsafe-collection","Repeat materialization requires an array of local static objects without spreads");let y=[{kind:"index",index:S}];l.push(y),u.push({kind:"value",root:a.root,path:y})}let f=u.length;if(n.instanceCount!==void 0&&n.instanceCount!==f)return ut("count-mismatch",`Selection reports ${n.instanceCount} instances but the source collection has ${f}`);let m=n.instanceIndex;if(m>=f)return ut("index-out-of-range",`Selected repeat instance ${m} is outside the source collection`);let d=s.elements[m];if(!d||!Y.isObjectExpression(d))return ut("unsafe-collection","Selected repeat item is not an object");let g=mR(e.element,e.propertyName),h=fR(d,e.propertyName);return h?{ok:!0,sourceFile:c,templateFile:e.file,collectionLocator:a,parentObjectLocators:u,selectedParentObjectLocator:u[m],sourceItemIndex:m,sourceItemPath:l[m],collectionIndexMap:Array.from({length:f},(S,E)=>E),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:pR(d,e.propertyName),...g?{property:g}:{},selectionRef:n}:ut("unsafe-property-source",`Property '${e.propertyName}' has a dynamic or unsupported source in the repeat item`)}function aR(e,t){let n=[];return dl(e,{CallExpression(r){let o=qm(r.node);o&&tg(o.callback,t)&&n.push({...o,span:eg(r.node)})},OptionalCallExpression(r){let o=qm(r.node);o&&tg(o.callback,t)&&n.push({...o,span:eg(r.node)})}}),n.sort((r,o)=>r.span-o.span),n[0]??null}function qm(e){let t=e.callee;if(!Y.isMemberExpression(t)&&!Y.isOptionalMemberExpression(t)||t.computed||!Y.isIdentifier(t.property)||t.property.name!=="map"||!Y.isExpression(t.object))return null;let n=e.arguments[0];return!n||!Y.isExpression(n)||!Y.isArrowFunctionExpression(n)&&!Y.isFunctionExpression(n)?null:{collection:t.object,callback:n}}function cR(e,t,n,r){let o=Eo(t);if(o&&Y.isArrayExpression(o))return{array:o,locator:{kind:"value",root:{kind:"expression",sourceRange:sg(o)}},sourceFile:n};if(!Y.isIdentifier(t))return null;let i=[];if(dl(e,{VariableDeclarator(s){Y.isIdentifier(s.node.id)&&s.node.id.name===t.name&&s.node.init&&i.push(s.node)}}),i.length===1){let s=Eo(i[0].init);return!s||!Y.isArrayExpression(s)?null:{array:s,locator:{kind:"value",root:{kind:"binding",name:t.name}},sourceFile:n}}return lR(e,t.name,n,r)}function lR(e,t,n,r){if(!r)return null;for(let o of e.program.body){if(!Y.isImportDeclaration(o))continue;let i=o.specifiers.find(m=>m.local.name===t);if(!i||!Y.isStringLiteral(o.source)||!Y.isImportSpecifier(i))continue;let s=dR(n,o.source.value,r);if(!s)return null;let a=Y.isIdentifier(i.imported)?i.imported.name:i.imported.value,c=r.get(s);if(c===void 0)return null;let l;try{l=ul.parse(c,{sourceType:"module",plugins:["typescript","jsx"]})}catch{return null}let u=uR(l,a),f=u?Eo(u):null;return!f||!Y.isArrayExpression(f)?null:{array:f,locator:{kind:"value",root:{kind:"binding",name:a}},sourceFile:s}}return null}function uR(e,t){let n=null;return dl(e,{VariableDeclarator(r){n||!Y.isIdentifier(r.node.id)||r.node.id.name!==t||!r.node.init||!Y.isExpression(r.node.init)||(n=r.node.init)}}),n}function dR(e,t,n){let r=bn(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 Eo(e){return Y.isParenthesizedExpression(e)?Eo(e.expression):Y.isTSAsExpression(e)?rg(e.typeAnnotation)?Eo(e.expression):null:Y.isTSSatisfiesExpression(e)?null:e}function rg(e){return Y.isTSTypeReference(e)&&Y.isIdentifier(e.typeName)&&e.typeName.name==="const"}function og(e){return e.properties.every(t=>!Y.isObjectProperty(t)||t.computed||!Y.isExpression(t.value)?!1:fs(t.value))}function fs(e){if(Y.isTSAsExpression(e)&&rg(e.typeAnnotation))return fs(e.expression);if(Y.isTSSatisfiesExpression(e))return!1;if(Y.isArrayExpression(e))return e.elements.every(n=>!n||Y.isSpreadElement(n)||!Y.isExpression(n)?!1:fs(n));if(Y.isObjectExpression(e))return og(e);let t=_t(e);return t.status==="resolved"||t.status==="undefined"}function fR(e,t){let n=e.properties.filter(o=>Y.isObjectProperty(o)&&ig(o.key)===t);if(n.length>1)return null;let r=n[0];return r?Y.isExpression(r.value)?fs(r.value)?"static":Y.isIdentifier(r.value)||Y.isMemberExpression(r.value)?"binding":null:null:"missing"}function pR(e,t){let n=e.properties.filter(o=>Y.isObjectProperty(o)&&ig(o.key)===t);if(n.length>1)return{status:"unresolved"};let r=n[0];return!r||!Y.isExpression(r.value)?{status:"undefined"}:_t(r.value)}function mR(e,t){let n=e.attributes?.filter(r=>r.name===t)??[];return n.length===1?n[0]:void 0}function ig(e){return Y.isIdentifier(e)?e.name:Y.isStringLiteral(e)?e.value:Y.isNumericLiteral(e)?String(e.value):null}function sg(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 eg(e){return e.start==null||e.end==null?Number.MAX_SAFE_INTEGER:e.end-e.start}function tg(e,t){let n=sg(e);return ng(n.startLine,n.startColumn,t.startLine,t.startColumn)<=0&&ng(n.endLine,n.endColumn,t.endLine,t.endColumn)>=0}function ng(e,t,n,r){return e===n?t-r:e-n}function ut(e,t){return{ok:!1,errorCode:e,reason:t}}import{classifySiteEditPropertyName as ew}from"@vcp-dev/contracts";import*as Z from"@babel/types";import Ro from"node:path";import*as V from"@babel/types";import*as fg from"@babel/parser";import pl from"@babel/traverse";import*as ne from"@babel/types";function ms(e,t){let n=[],r=e;for(;ne.isMemberExpression(r);){if(r.computed)if(ne.isNumericLiteral(r.property))n.unshift({kind:"index",index:r.property.value});else if(ne.isStringLiteral(r.property))n.unshift({kind:"property",name:r.property.value});else return null;else{if(!ne.isIdentifier(r.property))return null;n.unshift({kind:"property",name:r.property.name})}r=r.object}return!ne.isIdentifier(r)||r.name!==t?null:n}function ag(e){if(ne.isIdentifier(e))return{base:e.name,path:[]};if(!ne.isMemberExpression(e))return null;let t=[],n=e;for(;ne.isMemberExpression(n);){if(n.computed)if(ne.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(ne.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else{if(!ne.isIdentifier(n.property))return null;t.unshift({kind:"property",name:n.property.name})}n=n.object}return ne.isIdentifier(n)?{base:n.name,path:t}:null}function qe(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 $t=Symbol("not-closed-literal");function ps(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:$t;case"TSAsExpression":case"TSSatisfiesExpression":case"TSNonNullExpression":return ps(e.expression);case"ArrayExpression":{let t=[];for(let n of e.elements){if(!n||ne.isSpreadElement(n))return $t;let r=ps(n);if(r===$t)return $t;t.push(r)}return t}case"ObjectExpression":{let t={};for(let n of e.properties){if(!ne.isObjectProperty(n)||n.computed||n.shorthand||!ne.isExpression(n.value))return $t;let r=ne.isIdentifier(n.key)?n.key.name:ne.isStringLiteral(n.key)?n.key.value:null;if(!r)return $t;let o=ps(n.value);if(o===$t)return $t;t[r]=o}return t}default:return $t}}function cg(e){let{resolveBindingTarget:t}=e;async function n(i,s,a,c,l,u,f){let m=ps(i);if(m!==$t)return m;if(!ne.isTemplateLiteral(i)){if(ne.isTSAsExpression(i)||ne.isTSSatisfiesExpression(i)||ne.isTSNonNullExpression(i))return await n(i.expression,s,a,c,l,u,f);if(ne.isIdentifier(i)){let d=s.getBinding(i.name);if(!d)return;let g=await t({currentFile:a,binding:d,readFile:c,exists:l,fileCache:u,visited:f});return g?.kind==="static"?g.value:void 0}if(ne.isArrayExpression(i)){let d=[];for(let g of i.elements){if(!g||ne.isSpreadElement(g))return;let h=await r(g,s,a,c,l,u,f);if(h===void 0)return;d.push(h)}return d}if(ne.isObjectExpression(i)){let d={};for(let g of i.properties){if(!ne.isObjectProperty(g)||g.computed)return;let h=null;if(ne.isIdentifier(g.key)?h=g.key.name:ne.isStringLiteral(g.key)&&(h=g.key.value),!h)return;if(g.shorthand){if(!ne.isIdentifier(g.value))return;let E=await r(g.value,s,a,c,l,u,f);if(E===void 0)return;d[h]=E;continue}if(!ne.isExpression(g.value))return;let S=await r(g.value,s,a,c,l,u,f);S!==void 0&&(d[h]=S)}return d}if(ne.isMemberExpression(i)){let d=await o(i,s,a,c,l,u,f);if(!d)return;let g=s.getBinding(d.base);if(!g)return;let h=await t({currentFile:a,binding:g,readFile:c,exists:l,fileCache:u,visited:f});return!h||h.kind!=="static"?void 0:qe(h.value,d.path)}}}async function r(i,s,a,c,l,u,f){if(!ne.isSpreadElement(i))return await n(i,s,a,c,l,u,f)}async function o(i,s,a,c,l,u,f){if(ne.isIdentifier(i))return{base:i.name,path:[]};if(!ne.isMemberExpression(i))return null;let m=[],d=i;for(;ne.isMemberExpression(d);){if(d.computed){let g=d.property;if(ne.isNumericLiteral(g))m.unshift({kind:"index",index:g.value});else if(ne.isStringLiteral(g))m.unshift({kind:"property",name:g.value});else{let h=ne.isExpression(g)?await n(g,s,a,c,l,u,f):void 0;if(typeof h=="string")m.unshift({kind:"property",name:h});else if(Number.isInteger(h))m.unshift({kind:"index",index:h});else return null}}else{if(!ne.isIdentifier(d.property))return null;m.unshift({kind:"property",name:d.property.name})}d=d.object}return ne.isIdentifier(d)?{base:d.name,path:m}:null}return{normalizeExpressionWithScope:o,evaluateStaticExpression:n}}var pg=typeof pl=="function"?pl:pl.default,lg=new WeakMap;function mg(e){try{return fg.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function gs(e,t,n){let r=e.get(t);if(r?.source===n)return r.ast;let o=mg(n);return e.set(t,{source:n,ast:o}),o}function hs(e,t){return gl(vo(e).expressionRanges,t,!1)}function gg(e,t){return vo(e).exactExpressions.get(hg(t))??null}function ml(e,t){return gl(vo(e).jsxRanges,t,!0)}function vo(e){let t=lg.get(e);if(t)return t;let n={expressions:[],expressionRanges:[],jsxRanges:[],exactExpressions:new Map};return pg(e,{Expression(r){let o=r;n.expressions.push(o);let i=ug(o,n.expressions.length-1);if(!i)return;n.expressionRanges.push(i);let s=hg(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=ug(r,n.jsxRanges.length);o&&n.jsxRanges.push(o)}}),n.expressionRanges.sort(dg),n.jsxRanges.sort(dg),lg.set(e,n),n}function ug(e,t){let n=ko(e.node);return n?{path:e,range:n,traversalIndex:t,span:(e.node.end??0)-(e.node.start??0)}:null}function hg(e){return`${e.startLine}:${e.startColumn}:${e.endLine}:${e.endColumn}`}function dg(e,t){return e.range.startLine-t.range.startLine||e.range.startColumn-t.range.startColumn||e.traversalIndex-t.traversalIndex}function gl(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 ko(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 yr(e,t){if(t)return hl(e,t);let n=ag(e);return n?n.path.reduce((r,o)=>o.kind==="property"?`${r}.${o.name}`:`${r}[${o.index}]`,n.base):""}function hl(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function Io(e,t,n){let r=null,o=Number.POSITIVE_INFINITY;for(let i of vo(e).expressions){if(hl(i.node,t)!==n)continue;let s=(i.node.end??0)-(i.node.start??0);s<=o&&(r=i,o=s)}return r}function yg(e,t,n,r){return gl(vo(e).expressionRanges,r,!0,o=>hl(o.node,t)===n)}function xr(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}function Co(e){let t=null;if(pg(e,{Program(n){t=n.scope,n.stop()}}),!t)throw new Error("Unable to determine program scope");return t}async function Vt(e,t,n){let r=n.get(e);if(r)return r;let o=await t(e),i=mg(o),s={source:o,ast:i};return n.set(e,s),s}function gR(e){return V.isIdentifier(e.callee)&&(e.callee.name==="useState"||e.callee.name==="useReducer")?e.callee.name:V.isMemberExpression(e.callee)&&V.isIdentifier(e.callee.property)&&(e.callee.property.name==="useState"||e.callee.property.name==="useReducer")?e.callee.property.name:null}function hR(e){if(!V.isNewExpression(e)||!V.isIdentifier(e.callee,{name:"Proxy"})||e.arguments.length!==2||!V.isIdentifier(e.arguments[0])||!V.isObjectExpression(e.arguments[1])||e.arguments[1].properties.length!==1)return null;let[t]=e.arguments[1].properties;if(!V.isObjectMethod(t)||t.kind!=="method"||t.computed||t.async||t.generator||!V.isIdentifier(t.key,{name:"get"})||t.params.length!==3||!t.params.every(V.isIdentifier)||t.body.body.length!==2)return null;let[n,r,o]=t.params,[i,s]=t.body.body;if(V.isIfStatement(i)&&V.isBlockStatement(i.consequent)&&i.consequent.body.length!==1)return null;let a=V.isIfStatement(i)?i.test:null,c=a&&V.isLogicalExpression(a,{operator:"&&"})?a.right:null,l=V.isIfStatement(i)?V.isBlockStatement(i.consequent)?i.consequent.body[0]:i.consequent:null,u=V.isReturnStatement(s)?s.argument:null;return!a||!V.isLogicalExpression(a,{operator:"&&"})||!V.isBinaryExpression(a.left,{operator:"==="})||!V.isUnaryExpression(a.left.left,{operator:"typeof"})||!V.isIdentifier(a.left.left.argument,{name:r.name})||!V.isStringLiteral(a.left.right,{value:"string"})||!V.isUnaryExpression(c,{operator:"!"})||!V.isBinaryExpression(c.argument,{operator:"in"})||!V.isIdentifier(c.argument.left,{name:r.name})||!V.isIdentifier(c.argument.right,{name:n.name})||!V.isReturnStatement(l)||!V.isIfStatement(i)||i.alternate||!V.isCallExpression(u)||!V.isMemberExpression(u.callee)||!V.isIdentifier(u.callee.object,{name:"Reflect"})||!V.isIdentifier(u.callee.property,{name:"get"})||u.arguments.length!==3||!V.isIdentifier(u.arguments[0],{name:n.name})||!V.isIdentifier(u.arguments[1],{name:r.name})||!V.isIdentifier(u.arguments[2],{name:o.name})?null:e.arguments[0].name}function yR(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()||!V.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 xR(e,t){let n=yR(e.path);if(!n)return null;let r=ar(e,t);return r?{...n,...r}:null}function bR(e,t,n,r){return e.importedFrom===t?r?e.exportName===r:!0:e.sourceFile===t&&e.tag===n}function yl(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 xl(e,t){for(let n of e.program.body){if(t==="default"&&V.isExportDefaultDeclaration(n))return V.isExpression(n.declaration)?{kind:"default-expression",expression:n.declaration}:(V.isFunctionDeclaration(n.declaration)||V.isClassDeclaration(n.declaration))&&n.declaration.id?{kind:"default-binding",name:n.declaration.id.name}:null;if(V.isExportNamedDeclaration(n)){if(n.declaration){if(V.isVariableDeclaration(n.declaration)){for(let r of n.declaration.declarations)if(V.isIdentifier(r.id)&&r.id.name===t)return{kind:"local-binding",name:r.id.name}}if((V.isFunctionDeclaration(n.declaration)||V.isClassDeclaration(n.declaration))&&n.declaration.id&&n.declaration.id.name===t)return{kind:"local-binding",name:t}}for(let r of n.specifiers)if((V.isIdentifier(r.exported)?r.exported.name:r.exported.value)===t&&V.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 xg(e){let{resolveExternalExpression:t,resolveCollectionCallTarget:n,evaluateStaticExpression:r,resolveSourceInfoProvenance:o,buildExpressionSourceInfo:i}=e;async function s(d){let{currentFile:g,binding:h,readFile:S,exists:E,fileCache:y,visited:v}=d,C=`${g}::${h.kind}::${h.identifier.name}`;if(v.has(C))return null;v.add(C);try{let N=await a({currentFile:g,binding:h,readFile:S,exists:E,fileCache:y,visited:v});if(N)return N;if(h.path.isImportSpecifier()||h.path.isImportDefaultSpecifier())return await f({currentFile:g,binding:h,readFile:S,exists:E,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,fileCache:y,visited:v});if(h.kind==="param")return null;if(h.path.isVariableDeclarator()){let A=h.path.node.init;if(!A||!V.isExpression(A))return null;let R=hR(A);if(R&&!h.path.scope.getBinding("Proxy")&&!h.path.scope.getBinding("Reflect")){let D=h.path.scope.getBinding(R),L=D?await s({...d,binding:D}):null;if(L?.kind==="static"&&L.value!==null&&!Array.isArray(L.value)&&typeof L.value=="object")return L}let F=h.path.get("init");if(F&&!Array.isArray(F)&&F.isExpression()){let D=await t({currentFile:g,expressionPath:F,readFile:S,exists:E,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:y,visited:v});if(D)return D;if(F.isCallExpression()){let L=await n({currentFile:g,callPath:F,readFile:S,exists:E,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:y,visited:v});if(L)return L}}let _=await r(A,h.path.scope,g,S,E,y,v);return _===void 0?null:{kind:"static",file:g,root:{kind:"binding",name:h.identifier.name},value:_,sourceKind:"binding"}}if(h.path.isIdentifier()&&h.path.parentPath?.isExportDefaultDeclaration()){let A=h.path.parentPath.node.declaration;if(!V.isExpression(A))return null;let R=await r(A,h.path.scope,g,S,E,y,v);return R===void 0?null:{kind:"static",file:g,root:{kind:"binding",name:h.identifier.name},value:R,sourceKind:"binding"}}return null}finally{v.delete(C)}}async function a(d){let{currentFile:g,binding:h,readFile:S,exists:E,fileCache:y,visited:v}=d;if(!h.path.isVariableDeclarator()||!h.path.get("id").isArrayPattern())return null;let C=h.path,N=C.node.init;if(!N||!V.isCallExpression(N))return null;let A=gR(N);if(!A||!V.isArrayPattern(C.node.id)||C.node.id.elements.findIndex(L=>V.isIdentifier(L)&&L.name===h.identifier.name)!==0)return null;let F=A==="useReducer"?1:0,_=N.arguments[F];if(!_||!V.isExpression(_))return null;let D=await r(_,C.scope,g,S,E,y,v);return D===void 0?null:{kind:"static",file:g,root:{kind:"hook-state",name:h.identifier.name,hook:A},value:D,sourceKind:"binding"}}async function c(d){let g=xR(d.binding,d.sourceInfo);if(!g||!d.graph)return null;let h=[...d.graph.elements.values()].filter(A=>bR(A,d.currentFile,g.componentName,g.exportName));if(h.length!==1)return null;let S=h[0],E=S.attributes?.find(A=>A.name===g.propName);if(E&&!E.source){let A=await l({caller:S,propName:g.propName,remainingPath:g.remainingPath,readFile:d.readFile,fileCache:d.fileCache});if(A)return yl(A,{componentName:g.componentName,propName:g.propName,file:S.sourceFile})}if(!E?.source){let A=await u({caller:S,propName:g.propName,remainingPath:g.remainingPath,readFile:d.readFile,exists:d.exists,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:d.fileCache,visited:d.visited});if(A)return yl(A,{componentName:g.componentName,propName:g.propName,file:S.sourceFile});let R=yp(d.binding,g.componentName,g.propName);if(!R||R.propName!==g.propName)return null;let F=await r(R.expressionPath.node,R.expressionPath.scope,d.currentFile,d.readFile,d.exists,d.fileCache,d.visited);if(F===void 0)return null;let _=g.remainingPath;return _.length>0&&qe(F,_)===void 0?null:{kind:"value",file:d.currentFile,root:{kind:"binding",name:g.propName},path:_,sourceKind:"binding",semanticKind:"component-prop",displayExpression:R.displayPath,chainPrefix:[{kind:"component-prop",file:d.currentFile,displayName:R.displayPath,canEditHere:!0}],editMode:"upstream",diagnostics:[]}}let y=await Vt(S.sourceFile,d.readFile,d.fileCache);if(!y.ast)return null;let v=yg(y.ast,y.source,E.source.expression,E.sourceRange)??Io(y.ast,y.source,E.source.expression);if(!v)return null;let C={...E.source,expression:xr(E.source.expression,g.remainingPath),path:[...E.source.path,...g.remainingPath]},N=await o({currentFile:S.sourceFile,expressionPath:v,sourceInfo:C,readFile:d.readFile,exists:d.exists,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:d.fileCache,visited:d.visited});return N?yl(N.kind==="external"?N:{...N,displayExpression:C.expression},{componentName:g.componentName,propName:g.propName,file:S.sourceFile}):null}async function l(d){let g=await Vt(d.caller.sourceFile,d.readFile,d.fileCache);if(!g.ast)return null;let h=ml(g.ast,d.caller.sourceRange);if(!h)return null;let S=h.get("openingElement").get("attributes").find(C=>C.isJSXAttribute()&&C.node.name.type==="JSXIdentifier"&&C.node.name.name===d.propName);if(!S?.isJSXAttribute())return null;let E=S.get("value"),y=E.isStringLiteral()?E:E.isJSXExpressionContainer()?E.get("expression"):null;if(!y?.isExpression())return null;let v=ko(y.node);return v?{kind:"value",file:d.caller.sourceFile,root:{kind:"expression",sourceRange:v},path:d.remainingPath,sourceKind:"binding",semanticKind:"component-prop",displayExpression:d.propName,editMode:"upstream",diagnostics:[]}:null}async function u(d){let g=await Vt(d.caller.sourceFile,d.readFile,d.fileCache);if(!g.ast)return null;let h=ml(g.ast,d.caller.sourceRange);if(!h)return null;let S=h.get("openingElement");for(let E of S.get("attributes")){if(!E.isJSXSpreadAttribute())continue;let y=E.get("argument");if(!y.isExpression())continue;let v=await i({expression:y.node,scope:y.scope,source:g.source,currentFile:d.caller.sourceFile,readFile:d.readFile,exists:d.exists,fileCache:d.fileCache,visited:d.visited});if(!v)continue;let C=[{kind:"property",name:d.propName},...d.remainingPath],N={...v,expression:xr(v.expression,C),path:[...v.path,...C]},A=await o({currentFile:d.caller.sourceFile,expressionPath:y,sourceInfo:N,readFile:d.readFile,exists:d.exists,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:d.fileCache,visited:d.visited});if(A)return A.kind==="external"?A:{...A,displayExpression:N.expression}}return null}async function f(d){let{currentFile:g,binding:h,readFile:S,exists:E,fileCache:y,visited:v}=d,C=h.path.parentPath;if(!C||!C.isImportDeclaration())return null;let N=C.node.source.value;if(typeof N!="string")return null;let A=await Sn(g,N,E);if(!A)return null;if(h.path.isImportDefaultSpecifier()){let oe=await Vt(A,S,y),me=oe.ast?xl(oe.ast,"default"):null,ee=await m({file:A,exportName:"default",readFile:S,exists:E,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:y,visited:v});return!ee||ee.kind!=="static"?null:{kind:"static",file:me?.kind==="default-expression"?ee.file:A,root:me?.kind==="default-expression"?ee.root:{kind:"default-export"},value:ee.value,sourceKind:"imported-binding"}}if(!h.path.isImportSpecifier())return null;let R=h.path.node.imported,F=V.isIdentifier(R)?R.name:R.value,_=await Vt(A,S,y),D=_.ast?xl(_.ast,F):null,L=await m({file:A,exportName:F,readFile:S,exists:E,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:y,visited:v});return L?L.kind==="external"?L:{kind:"static",file:D?.kind==="re-export"?L.file:A,root:D?.kind==="re-export"||L.root.kind==="binding"&&L.root.name!==D?.name?L.root:{kind:"named-export",name:F},value:L.value,sourceKind:"imported-binding"}:null}async function m(d){let{file:g,exportName:h,readFile:S,exists:E,fileCache:y,visited:v}=d,C=`export::${g}::${h}`;if(!v.has(C)){v.add(C);try{let N=await Vt(g,S,y);if(!N.ast)return;let A=xl(N.ast,h);if(!A)return;if(A.kind==="default-expression"){let D=A.expression;if(!D||!V.isIdentifier(D))return;let L=Co(N.ast).getBinding(D.name);return L?await s({currentFile:g,binding:L,readFile:S,exists:E,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:y,visited:v})??void 0:void 0}if(A.kind==="re-export"){if(!A.source||!A.name)return;let D=await Sn(g,A.source,E);return D?m({...d,file:D,exportName:A.name}):void 0}let R=A.name;if(!R)return;let F=Co(N.ast).getBinding(R);return F?await s({currentFile:g,binding:F,readFile:S,exists:E,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:y,visited:v})??void 0:void 0}finally{v.delete(C)}}}return{resolveExportValue:m,resolveComponentPropBinding:c,resolveBindingTarget:s}}import*as H from"@babel/types";function Sl(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=It(o,t);if(!i)return null;let s=r.parentPath;return!s||!s.isCallExpression()||!SR(s,r)?null:{callPath:s,basePath:i}}function SR(e,t){let n=e.node.callee;return!H.isMemberExpression(n)||!H.isIdentifier(n.property)||n.property.name!=="map"?!1:e.node.arguments.some(r=>r===t.node)}function Eg(e,t){let n=e.get("callee");if(!n.isMemberExpression())return null;let r=n.get("object");return Array.isArray(r)||!r.isExpression()?null:zi(r,t)}function bg(e,t){return e?H.isNumericLiteral(e)&&Number.isInteger(e.value)?e.value:null:t}function Sg(e,t,n,r,o){let i=H.isExpression(e.body)?e.body:e.body.body.find(a=>H.isReturnStatement(a))?.argument;if(!i||!H.isExpression(i))return;let s=bl(i,t,n,r,o);return typeof s=="number"?s:void 0}function bl(e,t,n,r,o){if(H.isNumericLiteral(e)||H.isStringLiteral(e)||H.isBooleanLiteral(e))return e.value;if(H.isIdentifier(e))return e.name===t?r:e.name===n?o:void 0;if(H.isMemberExpression(e)){let i=ms(e,t);if(i)return qe(r,i);let s=ms(e,n);return s?qe(o,s):void 0}if(H.isBinaryExpression(e)&&e.operator==="-"){let i=H.isExpression(e.left)?bl(e.left,t,n,r,o):void 0,s=H.isExpression(e.right)?bl(e.right,t,n,r,o):void 0;return typeof i=="number"&&typeof s=="number"?i-s:void 0}}function ER(e){if(H.isExpression(e.body))return e.body;for(let t of e.body.body)if(H.isReturnStatement(t)&&t.argument&&H.isExpression(t.argument))return t.argument;return null}function vR(e,t,n){let r=jn(e,t,n);return typeof r=="boolean"?r:void 0}function jn(e,t,n){if(H.isStringLiteral(e)||H.isNumericLiteral(e)||H.isBooleanLiteral(e))return e.value;if(H.isNullLiteral(e))return null;if(H.isIdentifier(e))return e.name===t?n:void 0;if(H.isMemberExpression(e)){let r=ms(e,t);return r?qe(n,r):void 0}if(H.isUnaryExpression(e)&&e.operator==="!"){let r=jn(e.argument,t,n);return r===void 0?void 0:!r}if(H.isLogicalExpression(e)){let r=jn(e.left,t,n);if(r===void 0)return;if(e.operator==="&&")return r&&jn(e.right,t,n);if(e.operator==="||")return r||jn(e.right,t,n)}if(H.isBinaryExpression(e)){let r=H.isExpression(e.left)?jn(e.left,t,n):void 0,o=H.isExpression(e.right)?jn(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 vg(e){let t=[],n=e;for(;H.isMemberExpression(n)||H.isOptionalMemberExpression(n);){let r=n.property;if(n.computed)if(H.isNumericLiteral(r))t.unshift({kind:"index",index:r.value});else if(H.isStringLiteral(r))t.unshift({kind:"property",name:r.value});else if(H.isExpression(r))t.unshift({kind:"dynamic",expression:r});else return null;else if(H.isIdentifier(r))t.unshift({kind:"property",name:r.name});else return null;n=n.object}return H.isIdentifier(n)?{base:n.name,segments:t}:null}function kg(e){return e.some(t=>t.kind==="dynamic")}function kR(e){return typeof e=="string"?{kind:"property",name:e}:Number.isInteger(e)?{kind:"index",index:e}:null}function Ig(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 IR(e,t){let n=[],r=[];for(let o of t){let i=qe(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 Cg(e){let{resolveBindingTarget:t,evaluateStaticExpression:n,buildExpressionSourceInfo:r,resolveSourceInfoProvenance:o}=e;async function i(d){let{currentFile:g,callPath:h,readFile:S,exists:E,fileCache:y,visited:v}=d,C=h.node.callee;if(!H.isMemberExpression(C)||!H.isIdentifier(C.property)||C.property.name!=="map")return null;let N=h.get("callee");if(!N.isMemberExpression())return null;let A=N.get("object");if(Array.isArray(A)||!A.isExpression())return null;let R=await s({currentFile:g,expressionPath:A,readFile:S,exists:E,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:y,visited:v});return!R||!Array.isArray(R.value)||R.value.length===0?null:R}async function s(d){let{currentFile:g,expressionPath:h,readFile:S,exists:E,fileCache:y,visited:v}=d;if(h.isIdentifier()){let C=h.scope.getBinding(h.node.name);if(!C)return null;let N=await t({currentFile:g,binding:C,readFile:S,exists:E,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:y,visited:v});return N?.kind==="static"?N:null}if(h.isCallExpression())return c({currentFile:g,callPath:h,readFile:S,exists:E,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:y,visited:v});if(h.isTSAsExpression()||h.isTSSatisfiesExpression()||h.isTSNonNullExpression()){let C=h.get("expression");if(!Array.isArray(C)&&C.isExpression())return s({...d,expressionPath:C})}if(h.isArrayExpression()){let C=ko(h.node);if(!C)return null;let N=await n(h.node,h.scope,g,S,E,y,v);return Array.isArray(N)?{kind:"static",file:g,root:{kind:"expression",sourceRange:C},value:N,sourceKind:"binding"}:null}if(h.isMemberExpression()){let C=await r({expression:h.node,scope:h.scope,currentFile:g,readFile:S,exists:E,fileCache:y,visited:v});if(!C)return null;let N=await o({currentFile:g,expressionPath:h,sourceInfo:C,readFile:S,exists:E,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:y,visited:v});if(!N||N.kind==="external")return null;let A=await a({currentFile:g,expressionPath:h,provenance:N,readFile:S,exists:E,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:y,visited:v});if(!A||A.kind!=="static")return null;if(N.collectionPathMap?.length){let F=IR(A.value,N.collectionPathMap);if(F)return{kind:"static",file:N.file,root:N.root,value:F.value,sourceKind:N.sourceKind,collectionPathMap:F.collectionPathMap}}let R=qe(A.value,N.path);return Array.isArray(R)?{kind:"static",file:N.file,root:N.root,value:R,sourceKind:N.sourceKind,pathPrefix:N.path,collectionIndexMap:N.collectionIndexMap,collectionPathMap:N.collectionPathMap}:null}return null}async function a(d){let{provenance:g}=d;if(g.root.kind==="binding"){let y=d.expressionPath.scope.getBinding(g.root.name);if(!y&&g.file!==d.currentFile){let v=await Vt(g.file,d.readFile,d.fileCache);y=v.ast?Co(v.ast).getBinding(g.root.name):void 0}return y?await t({currentFile:g.file,binding:y,readFile:d.readFile,exists:d.exists,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:d.fileCache,visited:d.visited}):null}if(g.root.kind!=="expression")return null;let h=await Vt(g.file,d.readFile,d.fileCache);if(!h.ast)return null;let S=gg(h.ast,g.root.sourceRange);if(!S)return null;let E=await n(S.node,S.scope,g.file,d.readFile,d.exists,d.fileCache,d.visited);return E===void 0?null:{kind:"static",file:g.file,root:g.root,value:E,sourceKind:g.sourceKind}}async function c(d){return await l(d)??await u(d)??await f(d)}async function l(d){let{callPath:g}=d,h=g.node.callee;if(!H.isMemberExpression(h)||!H.isIdentifier(h.property)||h.property.name!=="filter")return null;let S=g.get("callee");if(!S.isMemberExpression())return null;let E=S.get("object");if(Array.isArray(E)||!E.isExpression())return null;let y=await s({currentFile:d.currentFile,expressionPath:E,readFile:d.readFile,exists:d.exists,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:d.fileCache,visited:d.visited});if(!y||!Array.isArray(y.value))return null;let[v]=g.node.arguments;if(!H.isArrowFunctionExpression(v)&&!H.isFunctionExpression(v))return null;let C=v.params[0];if(!H.isIdentifier(C))return null;let N=ER(v);if(!N)return null;let A=[],R=[],F=[];for(let[_,D]of y.value.entries()){let L=vR(N,C.name,D);if(typeof L!="boolean")return null;if(L){A.push(D),R.push(y.collectionIndexMap?.[_]??_);let oe=y.collectionPathMap?.[_];oe&&F.push(oe)}}return{...y,value:A,pathPrefix:y.pathPrefix,collectionIndexMap:R,...F.length>0?{collectionPathMap:F}:{}}}async function u(d){let{callPath:g}=d,h=g.node.callee;if(!H.isMemberExpression(h)||!H.isIdentifier(h.property)||h.property.name!=="slice")return null;let S=g.get("callee");if(!S.isMemberExpression())return null;let E=S.get("object");if(Array.isArray(E)||!E.isExpression())return null;let y=await s({currentFile:d.currentFile,expressionPath:E,readFile:d.readFile,exists:d.exists,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:d.fileCache,visited:d.visited});if(!y||!Array.isArray(y.value))return null;let[v,C]=g.node.arguments,N=bg(v,0),A=bg(C,y.value.length);if(N===null||A===null)return null;let R=Math.max(0,N<0?y.value.length+N:N),F=Math.max(0,A<0?y.value.length+A:A),_=y.value.map((L,oe)=>y.collectionIndexMap?.[oe]??oe).slice(R,F),D=y.collectionPathMap?.slice(R,F);return{...y,value:y.value.slice(R,F),pathPrefix:y.pathPrefix,collectionIndexMap:_,...D?{collectionPathMap:D}:{}}}async function f(d){let{callPath:g}=d,h=g.node.callee;if(!H.isMemberExpression(h)||!H.isIdentifier(h.property)||h.property.name!=="sort"&&h.property.name!=="toSorted")return null;let S=g.get("callee");if(!S.isMemberExpression())return null;let E=S.get("object");if(Array.isArray(E)||!E.isExpression())return null;let y=await s({currentFile:d.currentFile,expressionPath:E,readFile:d.readFile,exists:d.exists,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:d.fileCache,visited:d.visited});if(!y||!Array.isArray(y.value))return null;let[v]=g.node.arguments;if(!H.isArrowFunctionExpression(v)&&!H.isFunctionExpression(v))return null;let[C,N]=v.params;if(!H.isIdentifier(C)||!H.isIdentifier(N))return null;let A=y.value.map((F,_)=>({value:F,sourceIndex:y.collectionIndexMap?.[_]??_,originalIndex:_})),R=[...A];for(let F of A)for(let _ of A)if(Sg(v,C.name,N.name,F.value,_.value)===void 0)return null;return R.sort((F,_)=>{let D=Sg(v,C.name,N.name,F.value,_.value)??0;return D===0?F.originalIndex-_.originalIndex:D}),{...y,value:R.map(F=>F.value),pathPrefix:y.pathPrefix,collectionIndexMap:R.map(F=>F.sourceIndex),...y.collectionPathMap?{collectionPathMap:R.map(F=>y.collectionPathMap?.[F.originalIndex]).filter(F=>!!F)}:{}}}async function m(d){let g=null,h,S=[];for(let y of d.segments){if(y.kind!=="dynamic")continue;let v=await r({expression:y.expression,scope:d.expressionPath.scope,source:d.fileCache.get(d.currentFile)?.source,currentFile:d.currentFile,readFile:d.readFile,exists:d.exists,fileCache:d.fileCache,visited:d.visited});if(!v)return null;let C=Sl(d.expressionPath,v.base);if(!C)return null;let N=await i({currentFile:d.currentFile,callPath:C.callPath,readFile:d.readFile,exists:d.exists,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:d.fileCache,visited:d.visited});if(!N||!Array.isArray(N.value))return null;let A=N.value.map((R,F)=>{let _=qe(N.value,[{kind:"index",index:F},...C.basePath,...v.path]);return kR(_)});if(A.some(R=>R===null)||g!==null&&g!==A.length)return null;g=A.length,h??=N.collectionIndexMap,S.push(A)}if(g===null||g===0)return null;let E=[];for(let y=0;y<g;y+=1){let v=[...d.rootPath],C=0;for(let N of d.segments){if(N.kind==="dynamic"){let A=S[C]?.[y];if(!A)return null;v.push(A),C+=1;continue}v.push({...N})}E.push(v)}return{...h?{collectionIndexMap:h}:{},collectionPathMap:E}}return{resolveRepeatCollectionTarget:i,resolveCollectionCallTarget:c,resolveDynamicMemberPathMap:m}}var{normalizeExpressionWithScope:CR,evaluateStaticExpression:ys}=cg({resolveBindingTarget:e=>xs(e)}),{resolveRepeatCollectionTarget:RR,resolveCollectionCallTarget:wR,resolveDynamicMemberPathMap:NR}=Cg({resolveBindingTarget:e=>xs(e),evaluateStaticExpression:ys,buildExpressionSourceInfo:Kt,resolveSourceInfoProvenance:St}),{resolveExportValue:PR,resolveComponentPropBinding:AR,resolveBindingTarget:xs}=xg({resolveExternalExpression:wl,resolveCollectionCallTarget:wR,evaluateStaticExpression:ys,resolveSourceInfoProvenance:St,buildExpressionSourceInfo:Kt});function Mg(e){return new Map([...e].map(t=>[t.file,{source:t.source,ast:t.ast}]))}var Rg=new WeakMap;function TR(e){let t=Rg.get(e);return t||(t=new WeakMap,Rg.set(e,t)),t}function wg(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 Og(e){let{file:t,source:n,segment:r,readFile:o,exists:i}=e,s=e.fileCache??new Map,a=gs(s,t,n);if(!a)return null;let c=hs(a,r.sourceRange);if(!c)return null;let l=await Kt({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:o,exists:i,fileCache:s,visited:new Set});if(!l){let m=await Tl({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 m?kl(m,yr(c.node,n)):null}let u=new Set,f=await qR({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 f?kl(f,l.expression):null}async function br(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=gs(i,t,n);if(!s)return null;let a=e.sourceRange?hs(s,e.sourceRange):e.expression!==void 0?Io(s,n,e.expression):null;if(!a)return null;let c=bs(a);if(!c.isIdentifier()&&!c.isMemberExpression())return null;let l=new Set,u=await Kt({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:r,exists:o,fileCache:i,visited:l}),f=u?await St({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 Ug({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 kl(f,e.expression??yr(c.node,n))}async function Rl(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=gs(i,t,n);if(!s)return dt("unsupported-expression","Unable to parse source for provenance resolution");let a=new Set;return e.target.kind==="text-segment"?FR({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}):_R({file:t,source:n,ast:s,candidate:e.target.candidate,readFile:r,exists:o,graph:e.graph,fileCache:i,visited:a})}async function Kt(e){if(Z.isIdentifier(e.expression))return{kind:"identifier",expression:e.expression.name,base:e.expression.name,path:[]};if(!Z.isMemberExpression(e.expression))return null;let t=await CR(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:yr(e.expression,e.source),base:t.base,path:t.path}:null}function kl(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 FR(e){let{file:t,source:n,ast:r,segment:o,readFile:i,exists:s,fileCache:a,visited:c}=e,l=hs(r,o.sourceRange),u=l?await Kt({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 Ng(t,o.value);let m=await Tl({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 m?m.kind==="external"?_g(t,m):Cl(t,yr(l.node,n),m):MR({expression:l.node,scope:l.scope,currentFile:t,source:n,readFile:i,exists:s,fileCache:a,visited:c,functionCallContracts:e.functionCallContracts})}if(!l)return dt("unsupported-expression","Unable to locate text expression for provenance resolution");let f=await St({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(!f){let m=Il(l.node);if(m)return dt(m.code,m.message);let d=l.scope.getBinding(u.base);if(d?.path.isVariableDeclarator()){let g=Il(d.path.node.init);if(g)return dt(g.code,g.message)}return d?.path.isVariableDeclarator()&&Z.isCallExpression(d.path.node.init)?OR("unsupported-expression",$g(d.path.node.init,e.functionCallContracts)):dt("unsupported-expression",`Unable to resolve provenance for expression "${u.expression}"`)}return f.kind==="external"?_g(t,f):Cl(t,u.expression,f)}async function _R(e){let{file:t,source:n,ast:r,candidate:o,readFile:i,exists:s,fileCache:a,visited:c}=e;if(!o.conditionSource)return dt("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let l=Io(r,n,o.conditionExpression);if(!l)return dt("conditional-branch-unresolved",`Unable to locate conditional expression "${o.conditionExpression}"`);let u=await St({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 dt("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);if(u.kind==="external")return dt("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let f=Cl(t,o.conditionExpression,u);return f.finalSource?{...f,finalSource:{...f.finalSource,kind:"conditional-branch",displayPath:o.conditionExpression},chain:[...f.chain,{kind:"conditional-branch",file:u.file,displayName:o.conditionExpression,canEditHere:!0}]}:f}function Ng(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 MR(e){let t=await Dg(e);if(t.length===0)return dt("unsupported-expression",`Unsupported expression type: ${e.expression.type}`);if(LR(e.expression))return Lg(t);if(jg(e.expression))return dt("unsupported-expression","i18n helpers require a static message id string");if(Z.isMemberExpression(e.expression)&&e.expression.computed&&!Z.isNumericLiteral(e.expression.property)&&!Z.isStringLiteral(e.expression.property))return dt("dynamic-key","Computed member expressions are not supported for provenance resolution");let[n]=t;return dt(n.code,n.message)}function dt(e,t){return{finalSource:null,chain:[],confidence:"unknown",editMode:"unsupported",diagnostics:[{code:e,message:t}]}}function OR(e,t){return Lg([{code:e,message:t}])}function Lg(e){return{finalSource:null,chain:[],confidence:"partial",editMode:"readonly",diagnostics:e}}function LR(e){return Z.isCallExpression(e)||Z.isConditionalExpression(e)||Z.isLogicalExpression(e)||Z.isBinaryExpression(e)}function wo(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 Dg(e){let{expression:t,scope:n,currentFile:r,readFile:o,exists:i,fileCache:s,visited:a,functionCallContracts:c}=e,l=Il(t);if(l)return[l];if(Z.isCallExpression(t))return[{code:"unsupported-expression",message:$g(t,c)}];if(Z.isMemberExpression(t)&&t.computed){let u=t.property;if(!Z.isNumericLiteral(u)&&!Z.isStringLiteral(u)){if(!Z.isExpression(u))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}];let m=await ys(u,n,r,o,i,s,a);if(typeof m!="string"&&!Number.isInteger(m))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}]}}return Z.isBinaryExpression(t)?wo([...await El(t.left,t.right,e),{code:"unsupported-expression",message:"Mixed expressions are recognized but remain readonly until a safer composition editing strategy is available"}]):Z.isLogicalExpression(t)?wo([...await El(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"}]):Z.isConditionalExpression(t)?wo([...await El(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 Il(e){return jg(e)?Pg("i18n helpers require a static message id string"):VR(e)?Pg("CMS helpers require static entry id and field path string arguments"):null}async function El(...e){let t=e[e.length-1],n=e.slice(0,-1),r=[];for(let o of n)r.push(...await Dg({...t,expression:o}));return r}function DR(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:[BR(e.sourceType)]}}async function wl(e){for(let n of XR){if(!Ag(e.expressionPath,n.helperNames))continue;let r=await n.resolve(e);if(r)return Fg(Tg(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(!Ag(e.expressionPath,n.helperNames))continue;let r=await n.resolve(t);if(r)return Fg(Tg(r),e.externalAdapters)}return null}function BR(e){return{code:"missing-adapter",message:`No external adapter is registered for ${e}`}}function jR(e){return{code:"external-source-readonly",message:e}}function Pg(e){return{code:"unsupported-expression",message:e}}function Nl(e){return!e||!Z.isCallExpression(e)?null:Z.isIdentifier(e.callee)?e.callee.name:Z.isMemberExpression(e.callee)&&!e.callee.computed&&Z.isIdentifier(e.callee.object)&&Z.isIdentifier(e.callee.property)?`${e.callee.object.name}.${e.callee.property.name}`:null}function Ag(e,t){if(!t||t.length===0)return!0;let n=Nl(e.node);return n?t.includes(n):!1}function Tg(e){return"match"in e?{match:e.match,editMode:e.editMode,diagnostics:wo(e.diagnostics??[])}:{match:e,diagnostics:[]}}function Fg(e,t){let n=DR(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:wo([...e.diagnostics,...e.editMode==="readonly"||n.editMode==="readonly"?n.diagnostics:[]])}}function $R(e){if(!e.isCallExpression())return null;let t=e.node.callee;if(!Z.isIdentifier(t)||t.name!=="getCmsField")return null;let[n,r]=e.node.arguments;if(!n||!r||!Z.isStringLiteral(n)||!Z.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 VR(e){return!!e&&Z.isCallExpression(e)&&Z.isIdentifier(e.callee)&&e.callee.name==="getCmsField"&&(e.arguments.length<2||!Z.isStringLiteral(e.arguments[0])||!Z.isStringLiteral(e.arguments[1]))}function Bg(e){if(!(!e||!Z.isCallExpression(e))){if(Z.isIdentifier(e.callee)&&e.callee.name==="t"){let[t]=e.arguments;return t&&Z.isStringLiteral(t)?t.value:null}if(Z.isMemberExpression(e.callee)&&!e.callee.computed&&Z.isIdentifier(e.callee.object)&&e.callee.object.name==="intl"&&Z.isIdentifier(e.callee.property)&&e.callee.property.name==="formatMessage"){let[t]=e.arguments;if(!t||!Z.isObjectExpression(t))return null;for(let n of t.properties)if(Z.isObjectProperty(n)&&!n.computed&&(Z.isIdentifier(n.key)&&n.key.name==="id"||Z.isStringLiteral(n.key)&&n.key.value==="id")&&Z.isStringLiteral(n.value))return n.value.value;return null}}}function jg(e){return Bg(e)===null}async function KR(e,t,n){let r=new Set,o=Ro.posix.dirname(e);for(;r.add(o),!(o==="."||o==="/");){let i=Ro.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"]:[Ro.posix.join(i,"locales"),Ro.posix.join(i,"messages")];for(let a of s){let c=Ro.posix.join(a,`${t}.json`);if(await n(c))return c}}return null}async function UR(e){let t=Bg(e.expressionPath.node);if(typeof t!="string"||t.length===0)return null;let n="en",r=await KR(e.currentFile,n,e.exists);return r?{sourceType:"i18n-message",sourceId:`${n}:${t}`,file:r,displayPath:t}:null}async function JR(e){if(!e.expressionPath.isCallExpression())return null;let t=e.expressionPath.node.callee;if(!Z.isIdentifier(t)||t.name!=="apiField")return null;let[n,r]=e.expressionPath.node.arguments;if(!n||!Z.isExpression(n))return null;let o=await ys(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:[jR("API mapping transforms must stay readonly until a reversible mapping strategy is registered")]}:i}var XR=[{helperNames:["getCmsField"],resolve:({expressionPath:e})=>$R(e)},{helperNames:["apiField"],resolve:e=>JR(e)},{helperNames:["t","intl.formatMessage"],resolve:({currentFile:e,expressionPath:t,exists:n})=>UR({currentFile:e,expressionPath:t,exists:n})}];function Pl(e){return{...e,editMode:"readonly",diagnostics:[{code:"unsupported-expression",message:"Derived display values are readonly because no identity-preserving write target exists"}]}}function _g(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 Cl(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=QR(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 zR=[{helperName:"formatPrice",purity:"pure",sourceArgIndex:0},{helperName:"formatDate",purity:"pure",sourceArgIndex:0},{helperName:"pickLabel",purity:"pure",sourceArgIndex:0}];function Al(e,t){let n=[...zR,...t??[]];for(let r=n.length-1;r>=0;r-=1){let o=n[r];if(o?.helperName===e)return o}return null}function $g(e,t){let n=e.callee;return Z.isIdentifier(n)&&Al(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 Tl(e){let t=await wl(e);if(t)return t;let n=await Vg({...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 Kt({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 St({...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 YR(e)}async function Vg(e){let t=await Rt({...e,allowComposed:!1});if(t?.kind!=="source")return null;let n=bs(e.expressionPath);return n.isIdentifier()||n.isMemberExpression()?t.provenance:Pl(t.provenance)}async function Rt(e){let t=bs(e.expressionPath),n=GR(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 Kt({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 St({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 Kt({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 St({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 Rt({...e,expressionPath:r,allowComposed:!0}),a=await Rt({...e,expressionPath:o,allowComposed:!1}),c=await Rt({...e,expressionPath:i,allowComposed:!1});return vl(s,a,c)}if(t.isCallExpression())return WR({...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 Rt({...e,expressionPath:r,allowComposed:!0}),s=await Rt({...e,expressionPath:o,allowComposed:!0});return vl(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 Rt({...e,expressionPath:r,allowComposed:!0}),s=await Rt({...e,expressionPath:o,allowComposed:!0});return vl(i,s)}if(t.isUnaryExpression()){let r=t.get("argument");return Array.isArray(r)||!r.isExpression()?null:Rt({...e,expressionPath:r,allowComposed:!0})}return null}finally{n&&e.visited.delete(n)}}function bs(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 WR(e){let t=Nl(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:Rt({...e,expressionPath:r,allowComposed:!1})}let n=e.expressionPath.get("callee");if(n.isMemberExpression()&&!n.node.computed){let r=n.node.property;if(Z.isIdentifier(r)&&(r.name==="toFixed"||r.name==="toString")){let o=n.get("object");return Array.isArray(o)||!o.isExpression()?null:Rt({...e,expressionPath:o,allowComposed:!1})}}return null}function vl(...e){let t=null;for(let n of e){if(!n)return null;if(n.kind!=="none"){if(!t){t=n.provenance;continue}if(!HR(t,n.provenance))return null}}return t?{kind:"source",provenance:t}:{kind:"none"}}function HR(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 GR(e,t){return t.start==null||t.end==null?null:`safe-derived:${e}:${t.start}:${t.end}`}async function YR(e){if(!e.expressionPath.isCallExpression())return null;let t=Nl(e.expressionPath.node);if(!t)return null;let n=Al(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 Kg({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?Pl(i):null}async function Kg(e){let t=await wl({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 Kt({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 St({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 Tl({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 ZR(e){if(!e.binding.path.isVariableDeclarator())return null;let t=e.binding.path.node.init;if(!t||!Z.isCallExpression(t))return null;let n=t.callee;if(!Z.isIdentifier(n))return null;let r=Al(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 Kg({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?Pl(a):null}function QR(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=xr(t,e.path);return{sourceId:o,displayPath:o}}async function qR(e){let t=e.segment.source;return t?St({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 St(e){let t=e.sourceInfo,n=Sl(e.expressionPath,t.base);if(n){let l=await RR({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=Eg(n.callPath,[...n.basePath,...t.path]);return so(h)?wg(e.currentFile,h.sourceId,h.displayPath):null}let u=Ig(l,[...n.basePath,...t.path]),f=l.collectionIndexMap?.[0]??0,m=[...l.pathPrefix??[],{kind:"index",index:f},...n.basePath,...t.path],d=[{kind:"index",index:0},...n.basePath,...t.path];return qe(l.value,d)===void 0?null:{kind:"value",file:l.file,root:l.root,path:u?.[0]??m,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 f=await Sn(e.currentFile,u.node.source.value,e.exists);if(!f)return null;let m=await PR({file:f,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(!m||m.kind==="external")return null;let d=t.path.slice(1);return qe(m.value,d)===void 0?null:{kind:"value",file:m.file,root:m.root,path:d,sourceKind:"imported-binding",collectionIndexMap:m.collectionIndexMap}}let o=gp(r);if(o){let l=o.expressionPath,u=await Kt({expression:l.node,scope:l.scope,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(u){let f=await St({...e,expressionPath:l,sourceInfo:{...u,expression:xr(u.expression,t.path),path:[...u.path,...t.path]}});if(f)return f}else if(r.constant){let f=`dynamic-alias:${e.currentFile}:${l.node.start}`;if(e.visited.has(f))return null;e.visited.add(f);try{let m=await Ug({...e,expressionPath:bs(l),memberSuffix:t.path});if(m?.kind==="value")return m}finally{e.visited.delete(f)}}if(t.path.length===0){let f=await Vg({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(f)return f}}if(r.kind==="param")return AR({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 ZR({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=Ji(r,t.path,TR(e.fileCache));if(so(s))return wg(e.currentFile,s.sourceId,s.displayPath);let a=await xs({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:qe(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 Ug(e){let t=vg(e.expressionPath.node);if(!t||!kg(t.segments))return null;let n=await St({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 NR({...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 xs({...e,binding:i}):null;if(s?.kind!=="static"||o.some(a=>qe(s.value,a.slice(n.path.length))===void 0))return null}return{...n,path:o[0]??n.path,sourceKind:"repeat-template",displayExpression:yr(e.expressionPath.node,e.fileCache.get(e.currentFile)?.source),...r.collectionIndexMap?{collectionIndexMap:r.collectionIndexMap}:{},collectionPathMap:o}}async function Jg(e){let t=ew(e.propertyName);if(t.owner==="blocked")return yn(t.owner,t.diagnostic);if(t.owner==="class-name-source"||t.owner==="style")return yn(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 yn("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 nw(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 yn("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}:yn("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?yn("generic",{code:"remove-exposes-spread",message:`Removing '${e.propertyName}' would expose an earlier spread source`}):tw(e,s.attribute)}async function tw(e,t){if(t.resolution&&t.resolution.status!=="resolved"&&!t.source){let r=await br({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}}:yn("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 br({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"?yn("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 nw(e,t){let n=t.source?.expression;if(!n)return;let r=await br({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:rw(r,e.propertyName)}}function rw(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 yn(e,t){return{status:"blocked",owner:e,...t?{diagnostic:t}:{}}}function Xg(e){let{key:t,element:n,graph:r,provenances:o}=e,i=iw(t,n,r),s=i?.tag??($n(n.tag)?n.tag:n.componentName),a=i?.identity.key??zg(n,r)??t,c=cw(i),l=lw(t,n,r,o,i),u=ow(t,n,r,o,a);return{componentName:s,instanceKey:a,templateOwner:aw(i??n,s),...c.length>0?{variantKeys:c}:{},...l.length>0?{slotKeys:l}:{},editableStrategy:u,impactScope:uw(u),alternativeStrategies:dw(u)}}function ow(e,t,n,r,o){for(let i of r.values())if(i?.editMode==="upstream")return"upstream";return Fl(e,n)?"instance":!$n(t.tag)&&t.sourceFile!==n.routeId&&o!==e?"template":"instance"}function zg(e,t){if($n(e.tag))return e.identity.key;let n=[...t.elements.values()].filter(r=>r.importedFrom===e.sourceFile&&sw(r,e.componentName));return n.length!==1?null:n[0].identity.key}function iw(e,t,n){if($n(t.tag))return t;let r=Fl(e,n);if(r)return r;let o=zg(t,n);return o?n.elements.get(o)??null:null}function sw(e,t){return e.exportName===t||e.tag===t||e.exportName==="default"}function aw(e,t){return $n(e.tag)&&e.importedFrom?`${e.importedFrom}#${t}`:`${e.sourceFile}#${t}`}function cw(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 lw(e,t,n,r,o){let i=new Set,s=Fl(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&&$n(t.tag)&&t.childKeys.length>0&&i.add("children"),[...i]}function Fl(e,t){let n=t.elements.get(e)?.parentKey??null;for(;n;){let r=t.elements.get(n);if(!r)break;if($n(r.tag))return r;n=r.parentKey}return null}function $n(e){return/^[A-Z]/.test(e)}function uw(e){switch(e){case"template":return"component-template";case"upstream":return"upstream-source";default:return"current-instance"}}function dw(e){switch(e){case"template":return["instance"];case"upstream":return["template"];default:return["template"]}}function Gg(e){let t=e.isRepeat??(e.graph?Sw(e.element,e.graph):!1),n=e.propertyProvenance??new Map,r=e.repeatTargets??new Map,o=bw(e.element.attributes??[]),i=[...r.values()].some(u=>u.ok),s=o.map(u=>fw({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,f)=>u.order-f.order).map(u=>({raw:u.raw,sourceRange:Ew(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 fw(e){let{attribute:t,provenance:n,repeatTarget:r}=e,o=e.selectionRef?.instanceIndex!==void 0&&r?.ok===!0?r:null,i=pw(t,n,e.isRepeat),s=["selection","template"].map(S=>({scope:S,result:qi({state:n,scope:S,operation:"set",selectionRef:e.selectionRef,isRepeat:e.isRepeat,repeatTarget:r})})),a=s.find(({result:S})=>S.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=mw(t,n,l,e.isRepeat),f=c?yw(c,e.element,t.name):void 0,m=s.filter(({result:S})=>S.ok).map(({scope:S})=>S),d=m.length>0?hw(n,o,e.element):"unsupported",g=o?"repeat-item":e.isRepeat?"repeat-template":"node",h=xw(t,n,r);if(m.length===0&&h.length===0){let S=s.find(({result:E})=>!E.ok)?.result;S&&!S.ok&&h.push({code:S.code,message:S.reason})}return{name:t.name,source:i,resolution:u,editMode:d,sourceScope:g,allowedWriteScopes:m,...f?{effectiveWriteTarget:f}:{},diagnostics:h}}function pw(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 mw(e,t,n,r){return n?Wg(n.selectedResolution):t?.status==="blocked"?{status:"unresolved"}:r&&t?.status==="binding"?{status:"unresolved"}:Wg(gw(e))}function gw(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 Wg(e){return!e||e.status==="unresolved"?{status:"unresolved"}:e.status==="undefined"?{status:"undefined"}:{status:"resolved",value:e.value}}function hw(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 yw(e,t,n){return e.kind==="repeat-property"?{kind:"value-path",file:e.target.sourceFile,isProxy:e.target.sourceFile!==t.sourceFile,displayPath:Hg({...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:Hg(e.locator)}:{kind:"jsx-node",file:t.sourceFile,isProxy:!1,displayPath:t.componentName+" > "+n}}function xw(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 bw(e){let t=new Set;return e.filter(n=>t.has(n.name)?!1:(t.add(n.name),!0))}function Sw(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 Hg(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 Ew(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 vw(e){return e==="api-field"||e==="cms-field"||e==="i18n-message"||e==="config-entry"}var kw=160;function Yg(e,t,n,r={}){let o=er(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 Zg(e,t,n,r,o,i,s,a,c,l,u){let f=er(t),m=t.elements.get(e),d=n.nodes.get(e),g=r.get(e);if(!m||!d||!g)throw new Error(`Node not found: ${e}`);let h=nh(m.textSegments,s),S=rh(e,t,m,g,h),E=h?ww(h):void 0,y=Nw(i,h),v=m.textSegments.map(R=>({index:R.index,value:R.value,editable:oh(R,g,s?.get(R.index)??null),source:o.get(R.index)??null})),C=eh(m,t),N=m.childKeys.map(R=>{let F=t.elements.get(R);return F?{key:R,tag:F.tag,label:F.tag}:null}).filter(R=>R!==null),A=[];if(m.parentKey){let R=t.elements.get(m.parentKey);if(R)for(let F of R.childKeys){if(F===e)continue;let _=t.elements.get(F);_&&A.push({key:F,tag:_.tag,label:_.tag})}}return{composition:f,key:e,tag:m.tag,componentName:m.componentName,sourceFile:m.sourceFile,sourceLocator:qg(m),label:m.tag,capabilities:S,writeTarget:i,effectiveWriteTarget:y,provenanceChain:E,componentSemantic:c,styleSource:l,conditional:a,...u?{dynamicData:u}:{},textSegments:v,boundaryKind:m.boundaryKind,isOpaque:m.isOpaque,ancestors:C,children:N,siblings:A}}function Qg(e,t,n,r,o,i,s,a){let c=er(t),l=t.elements.get(e),u=n.nodes.get(e),f=r.get(e);if(!l||!u||!f)throw new Error(`Node not found: ${e}`);let m=nh(l.textSegments,i),d=Iw(l);return{composition:c,key:e,tag:l.tag,...d?{linkSourceKind:d}:{},componentName:l.componentName,sourceFile:l.sourceFile,sourceLocator:qg(l),label:l.tag,capabilities:rh(e,t,l,f,m),provenanceChain:m?{editMode:m.editMode,diagnostics:m.diagnostics.map(g=>({code:g.code,message:g.message}))}:void 0,...s?{dynamicData:s}:{},...a?{properties:a}:{},textSegments:l.textSegments.map(g=>{let h=o.get(g.index);return{index:g.index,editable:oh(g,f,i?.get(g.index)??null),source:h?{kind:h.kind}:null}}),boundaryKind:l.boundaryKind,isOpaque:l.isOpaque,ancestors:eh(l,t)}}function Iw(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 qg(e){return{sourceFile:e.sourceFile,componentName:e.componentName,openingElementRange:Cw(e.sourceRange),structuralPath:e.identity.structuralPath,...Rw(e.textSegments)}}function eh(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 Cw(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function Rw(e){let t=e.map(n=>n.value.trim()).filter(Boolean).join(" ").replace(/\s+/g," ").trim();return t?{textPreview:t.slice(0,kw)}:{}}function th(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 nh(e,t){if(!t)return null;for(let n of e){let r=t.get(n.index);if(r)return r}return null}function rh(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&&ih(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 oh(e,t,n){return!e.editable||!t.canUpdateText?!1:n?ih(n.editMode):!0}function ih(e){return e==="direct"||e==="proxy"||e==="upstream"}function ww(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 Nw(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}:vw(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 _l=["set-class-name-source","apply-style-draft"];function sh(e){let t=e.attributes?.find(n=>n.name==="className");if(!t)return{kind:"class-name-source",className:"",sourceKind:"missing",editable:!0,operationBoundary:_l,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:_l,sourcePath:n}}return{kind:"class-name-source",className:t.value,sourceKind:t.resolvedValue===void 0?"static-attribute":"static-expression",editable:!0,operationBoundary:_l}}function ah(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}),ch(i,r,o,t,e)}}return{nodes:t,rootKeys:[...e.rootKeys]}}function ch(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}),ch(s,t,n,r,o))}}import lh from"node:path";function Ol(){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 dh(e,t,n){let r=[],o=new Set;for(let i of e.intents){let s=Fw(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 Ss(e){let t=()=>Pw(e);return e.mutex?e.mutex.runExclusive(t):t()}async function Pw(e){let t=await dh(e.plan,e.overlay,e.exists);if(!t.ok)return{ok:!1,stage:"precheck",reason:t.reason,error:t,recoveryRequired:!1};let n=Aw(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 Ml({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 Ml({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 Ml({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 uh("swap",l,"Live state swap failed after durable publish.")}try{await e.finalizeCandidate?.(c)}catch(l){return uh("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 Aw(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 Ml(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:Tw(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 uh(e,t,n){return{ok:!1,stage:e,reason:n,error:t,recoveryRequired:!0}}function Tw(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 Fw(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)||lh.isAbsolute(e))return{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`};let t=lh.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 _w=50,Mw=8*1024*1024;function gh(e,t={}){let n=[],r=[],o=t.externalAdapters??[],i=Math.max(0,t.maxUndoEntries??_w),s=Math.max(0,t.maxUndoBytes??Mw);return{prepareRewritePlan:a,execute:c,executeFilePlan:l,undo:u,redo:f};async function a(R){let F=[...R.steps].sort((ee,ce)=>ee.order-ce.order),_=F.filter(ee=>ee.type!=="invoke-external-adapter");if(_.length!==F.length)return{ok:!1,errorCode:"unsupported-operation",reason:"External adapter writes require a transactional prepare/commit/rollback contract."};let D=new Set(_.map(ee=>ee.file)),L=await y(D),oe=new Map(L.map(ee=>[ee.file,ee.exists===!1?"":ee.content])),me;for(let ee of _){let ce=mh(ee,oe.get(ee.file)??"");if(!ce.ok)return{ok:!1,errorCode:ce.errorCode,reason:ce.reason};oe.set(ee.file,ce.source),me=ce.selectionRef??me}return{ok:!0,filePlan:{operationId:R.operationId,kind:"source-edit",target:R.target,documentVersion:R.documentVersion,conflictPolicy:"compare-and-swap",edits:[...oe].map(([ee,ce])=>({operation:"upsert",file:ee,content:ce,baseContentHash:L.find(_e=>_e.file===ee)?.sha256??null}))},...me?{selectionRef:me}:{}}}async function c(R){let F=[...R.steps].sort((_e,Qt)=>_e.order-Qt.order),_=F.filter(_e=>_e.type!=="invoke-external-adapter"),D=F.filter(_e=>_e.type==="invoke-external-adapter"),L=new Set(_.map(_e=>_e.file));if(_.length>0&&D.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(_.length===0)return S(R,D);let oe=await y(L),me=new Map;for(let _e of oe)me.set(_e.file,_e.exists===!1?"":_e.content);let ee;for(let _e of _){let Qt=me.get(_e.file)??"",qt=mh(_e,Qt);if(!qt.ok)return{ok:!1,operationId:R.operationId,errorCode:qt.errorCode,reason:qt.reason,rolledBack:!1};me.set(_e.file,qt.source),qt.selectionRef&&(ee=qt.selectionRef)}let ce=await C([...me].map(([_e,Qt])=>({file:_e,content:Qt,exists:!0,version:0,sha256:ke(Qt)})),oe);return ce.ok===!1?{ok:!1,operationId:R.operationId,errorCode:ce.rolledBack?"writeback-failed":"rollback-failed",reason:ce.reason,rolledBack:ce.rolledBack}:(n.push({operationId:R.operationId,preSnapshots:oe,postSnapshots:ce.snapshots,plan:R}),m(),r.length=0,{ok:!0,operationId:R.operationId,kind:R.kind,target:R.target,resultVersion:Math.max(...ce.snapshots.map(_e=>_e.version)),affectedFiles:[...L],...ee?{selectionRef:ee}:{}})}async function l(R){let F=new Set(R.edits.map(ce=>ce.file)),_=await y(F),D=E(R,_);if(D)return{ok:!1,operationId:R.operationId,errorCode:"stale-version",reason:D.reason,affectedFiles:[D.file],rolledBack:!1};let L=new Map(_.map(ce=>[ce.file,ce])),oe=R.edits.find(ce=>ce.operation==="create-only"&&L.get(ce.file)?.exists!==!1);if(oe)return{ok:!1,operationId:R.operationId,errorCode:"stale-version",reason:`MATERIALIZATION_INSTANCE_CONFLICT: create-only target already exists: ${oe.file}`,affectedFiles:[oe.file],rolledBack:!1};let me=R.edits.map(ce=>ce.operation==="delete"?{file:ce.file,content:"",exists:!1,version:0}:{file:ce.file,content:ce.content,exists:!0,version:0,sha256:ke(ce.content)}),ee=await C(me,_,new Set(R.edits.filter(ce=>ce.operation==="create-only").map(ce=>ce.file)));return ee.ok===!1?{ok:!1,operationId:R.operationId,errorCode:ee.rolledBack?"writeback-failed":"rollback-failed",reason:ee.reason,rolledBack:ee.rolledBack}:(n.push({operationId:R.operationId,preSnapshots:_,postSnapshots:ee.snapshots,plan:{operationId:R.operationId,kind:R.kind,target:R.target,documentVersion:R.documentVersion,steps:[],preSnapshots:_}}),m(),r.length=0,{ok:!0,operationId:R.operationId,kind:R.kind,target:R.target,resultVersion:Math.max(...ee.snapshots.map(ce=>ce.version)),affectedFiles:[...F]})}async function u(){let R=n.at(-1);if(!R)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to undo"};let F=await C(R.preSnapshots,R.postSnapshots);return F.ok===!1?{ok:!1,operationId:R.operationId,errorCode:F.rolledBack?"writeback-failed":"rollback-failed",reason:F.reason,rolledBack:F.rolledBack}:(n.pop(),r.push(R),{ok:!0,operationId:R.operationId,kind:R.plan.kind,target:R.plan.target,resultVersion:Math.max(...F.snapshots.map(_=>_.version)),affectedFiles:R.preSnapshots.map(_=>_.file)})}async function f(){let R=r.at(-1);if(!R)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to redo"};let F=await C(R.postSnapshots,R.preSnapshots);return F.ok===!1?{ok:!1,operationId:R.operationId,errorCode:F.rolledBack?"writeback-failed":"rollback-failed",reason:F.reason,rolledBack:F.rolledBack}:(r.pop(),n.push(R),m(),{ok:!0,operationId:R.operationId,kind:R.plan.kind,target:R.plan.target,resultVersion:Math.max(...F.snapshots.map(_=>_.version)),affectedFiles:R.postSnapshots.map(_=>_.file)})}function m(){for(;n.length>i;)n.shift();for(;n.length>0&&d()>s;)n.shift()}function d(){return n.reduce((R,F)=>R+g(F),0)}function g(R){return h(R.preSnapshots)+h(R.postSnapshots)}function h(R){return R.reduce((F,_)=>F+_.file.length+_.content.length,0)}async function S(R,F){let _=[];for(let D of F){let L=D.capability??"write-text",oe=o.find(ee=>ee.sourceType===D.sourceType&&(D.adapterId===void 0||ee.adapterId===D.adapterId)&&(ee.capabilities===void 0||ee.capabilities.includes(L)));if(!oe)return{ok:!1,operationId:R.operationId,errorCode:"unsupported-operation",reason:`No external adapter registered for ${D.sourceType}`,rolledBack:!1};let me=await oe.execute(D);if(!me.ok)return{ok:!1,operationId:R.operationId,errorCode:"writeback-failed",reason:me.reason??`External adapter failed for ${D.sourceType}`,rolledBack:!1};_.push(D.file)}return{ok:!0,operationId:R.operationId,kind:R.kind,target:R.target,resultVersion:0,affectedFiles:_}}function E(R,F){if(R.conflictPolicy!=="compare-and-swap")return null;let _=new Map(F.map(D=>[D.file,D]));for(let D of R.edits){if(D.operation==="create-only")continue;if(D.baseContentHash===void 0)return{file:D.file,reason:`Source file ${D.file} is missing baseContentHash. Reopen the file before saving.`};let L=_.get(D.file),oe=D.baseContentHash;if(oe===null){if(L?.exists!==!1)return{file:D.file,reason:`Source file ${D.file} was created or changed before save.`};continue}if(!oe)return{file:D.file,reason:`Source file ${D.file} is missing baseContentHash. Reopen the file before saving.`};if(L?.exists===!1||L?.sha256!==oe)return{file:D.file,reason:`Source file ${D.file} changed before save. Reload or explicitly overwrite the newer version.`}}return null}async function y(R){let F=[];for(let _ of R)F.push(await v(_));return F}async function v(R){if(!await e.exists(R))return{file:R,content:"",version:0,exists:!1};let _=Math.max(1,e.getVersion(R)),D=await e.readFile(R);return{file:R,content:D,version:_,exists:!0,sha256:ke(D)}}async function C(R,F,_=new Set){let D=[];try{for(let L of R){if(_.has(L.file)){if(!e.createExclusive)throw new Error("Create-only write requires atomic exclusive-create support.");await e.createExclusive(L.file,L.content)}else await N(L);let oe=e.bumpVersion(L.file);D.push(L.file),L.version=oe}}catch(L){let oe=await A(F.filter(ee=>D.includes(ee.file)));if(oe.ok===!1)return{ok:!1,reason:`Writeback failed, then rollback failed for ${oe.failedFiles.join(", ")}: ${ph(L)}`,rolledBack:!1,instanceConflict:fh(L)};let me=fh(L);return{ok:!1,reason:`${me?"MATERIALIZATION_INSTANCE_CONFLICT: ":""}Writeback failed and committed files were restored: ${ph(L)}`,rolledBack:!0,instanceConflict:me}}return{ok:!0,snapshots:R.map(Ow)}}async function N(R){if(R.exists===!1){await e.deleteFile(R.file);return}await e.writeFile(R.file,R.content)}async function A(R){let F=[];for(let _ of R)try{await N(_),e.bumpVersion(_.file)}catch{F.push(_.file)}return F.length===0?{ok:!0}:{ok:!1,failedFiles:F}}}function fh(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="EEXIST"}function Ow(e){let t=e.exists!==!1;return{file:e.file,content:t?e.content:"",version:e.version,exists:t,...t?{sha256:ke(e.content)}:{}}}function ph(e){return e instanceof Error?e.message:String(e)}function mh(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 We(Qn({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-import":return We(qn({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-node":return We(Hn({source:t,locator:e.locator,removeWhitespace:e.removeWhitespace}));case"insert-child":return We(Gn({source:t,locator:e.parentLocator,node:e.node,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"update-text":return We(ei({source:t,locator:e.locator,segmentIndex:e.segmentIndex,newText:e.newText}));case"update-value":return We(_r({source:t,locator:e.locator,next:e.value}));case"update-array-item":return We(_r({source:t,locator:e.locator,next:e.value}));case"insert-bound-array-item":return We(ai({source:t,locator:e.locator,index:e.index,value:e.value}));case"insert-jsx-expression-child":return We(ni({source:t,locator:e.parentLocator,expression:e.expression,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"remove-bound-array-item":return We(ci({source:t,locator:e.locator,index:e.index}));case"move-array-item":return We(li({source:t,locator:e.locator,fromIndex:e.fromIndex,toIndex:e.toIndex}));case"move-node":return We(Yn({source:t,locator:e.locator,targetParentLocator:e.targetParentLocator,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"move-repeat-template-child":return We(ri({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 Lw(e,t);case"set-property-changes":return We(oi({source:t,locator:e.locator,changes:e.changes}));case"set-link-target":return We(ii({source:t,locator:e.locator,link:e.link,changes:e.changes}));case"set-property-binding":return We(si({source:t,locator:e.locator,name:e.name,object:e.object,property:e.property}));case"upsert-object-property":return We(di({source:t,objectLocator:e.locator,name:e.name,value:e.value}));default:return{ok:!1,reason:`Unknown step type: ${e.type}`,errorCode:"unknown"}}}function Lw(e,t){let{request:n}=e;if(n.newAttrRaw!==null&&!hd(n.newAttrRaw))return{ok:!1,reason:"newAttrRaw must be a valid JSX className attribute.",errorCode:"invalid-params"};let r=n.oldAttrRange!==null&&n.oldAttrRaw!==null,o=n.openingElementRange.start,i=n.openingElementRange.end,s=t.slice(o,i);if(!(Number.isInteger(o)&&Number.isInteger(i)&&o>=0&&i>o&&i<=t.length&&s.startsWith("<")&&s.endsWith(">")&&!s.startsWith("</")&&(n.oldAttrRange===null||n.oldAttrRange.start>=o&&n.oldAttrRange.end<=i)))return{ok:!1,reason:"The opening element range changed before className save.",errorCode:"stale-version"};if(!r&&n.expectedVersion.contentHash!==ke(t))return{ok:!1,reason:"The source file changed before className save.",errorCode:"stale-version"};if(n.oldAttrRange){if(t.slice(n.oldAttrRange.start,n.oldAttrRange.end)!==n.oldAttrRaw)return{ok:!1,reason:"The className attribute changed before save.",errorCode:"stale-version"}}else if(n.oldAttrRaw!==null)return{ok:!1,reason:"The className attribute range no longer matches.",errorCode:"stale-version"};return{ok:!0,source:gd({source:t,oldAttrRange:n.oldAttrRange,openingElementRange:n.openingElementRange,newAttrRaw:n.newAttrRaw})}}function We(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 Es,SiteEditCompositionContextSchema as Dw,SiteEditCompositionSelectorSchema as Bw}from"@vcp-dev/contracts";var Ze=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="SiteEditCompositionError"}};function hh(e,t){throw new Ze("INVALID_COMPOSITION",e,{value:t})}function vs(e){let t=Dw.safeParse(e);return t.success?t.data:hh("Invalid SiteEditCompositionContext.",e)}function yh(e){let t=[],n=new Map,r=new Map;for(let l of e.compositions){let u=vs(l?.context);if(typeof l.entryFile!="string"||!l.entryFile)throw new Ze("INVALID_COMPOSITION","A registered composition must have a non-empty entryFile.");let f=Es(u);if(n.has(f))throw new Ze("DUPLICATE_COMPOSITION",`Composition key ${f} is registered more than once.`,{key:f,context:u});let m=r.get(l.entryFile);if(m)throw new Ze("DUPLICATE_COMPOSITION",`Entry file ${l.entryFile} is registered more than once.`,{entryFile:l.entryFile,context:m});let d={context:u,entryFile:l.entryFile,key:f};t.push(d),n.set(f,d),r.set(l.entryFile,f)}if(t.length===0)throw new Ze("INVALID_COMPOSITION","At least one composition must be registered.");let o=new Map;for(let l of e.initialDocumentVersions??[]){let u=vs(l?.composition);if(!Number.isInteger(l?.version)||(l?.version??-1)<0)throw new Ze("INVALID_INITIAL_DOCUMENT_VERSION","Initial document version must be a non-negative integer.",{context:u,version:l?.version});let f=Es(u);if(!n.has(f))throw new Ze("UNKNOWN_COMPOSITION","Initial document version references an unregistered composition.",{context:u,key:f});if(o.has(f))throw new Ze("DUPLICATE_COMPOSITION","Initial document versions must contain each composition at most once.",{context:u,key:f});o.set(f,l.version)}function i(l){let u=Bw.safeParse(l);if(!u.success)return hh("Invalid SiteEditCompositionSelector.",l);let f=t.filter(({context:m})=>m.routeId===u.data.routeId&&(u.data.templateId===void 0?m.effectiveTemplateId===void 0:m.effectiveTemplateId===u.data.templateId));if(f.length===1)return f[0];throw f.length>1?new Ze("AMBIGUOUS_COMPOSITION","The composition selector matches multiple registered contexts.",{selector:u.data}):new Ze("UNKNOWN_COMPOSITION","The composition selector is not registered.",{selector:u.data})}function s(l){let u=vs(l),f=Es(u),m=n.get(f);if(!m)throw new Ze("UNKNOWN_COMPOSITION","The composition context is not registered.",{context:u,key:f});return m}function a(l){let u=vs(l?.context);if(typeof l.entryFile!="string"||!l.entryFile)throw new Ze("INVALID_COMPOSITION","A registered composition must have a non-empty entryFile.");let f=Es(u),m=n.get(f);if(m){if(m.entryFile===l.entryFile)return m;throw new Ze("DUPLICATE_COMPOSITION",`Composition key ${f} is registered more than once.`,{key:f,context:u})}let d=[...n.values()].find(h=>h.entryFile===l.entryFile);if(d)throw new Ze("DUPLICATE_COMPOSITION",`Entry file ${l.entryFile} is registered more than once.`,{entryFile:l.entryFile,context:d.context});let g={context:u,entryFile:l.entryFile,key:f};return t.push(g),n.set(f,g),g}function c(l){let u=n.get(l);if(!u)return;n.delete(l);let f=t.findIndex(m=>m.key===l);return f>=0&&t.splice(f,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 Ll(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}}}import{composeSiteEditRepeatInstanceKey as jw,stripSiteEditRepeatInstanceKeys as xh}from"@vcp-dev/contracts";function bh(e){let t=new Map,n=new Map,r=new Map;for(let o of e.entries){t.set(o.key,o);let i=xh(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 $w(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 ks(e){return e?.map(t=>({...t}))}function Dl(e,t){if(t===null||e?.kind!=="value-binding"||e.sourceKind!=="repeat-template")return e;let n=e.collectionIndexMap?.[t]??t,r=ks(e.collectionPathMap?.[t])??ks(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:ks(e.path),locator:e.locator?{...e.locator,path:r}:e.locator,collectionIndexMap:e.collectionIndexMap?[...e.collectionIndexMap]:void 0,collectionPathMap:e.collectionPathMap?.map(o=>ks(o)??[])}}function Sh(e,t,n){let r=new Set;for(let d of t.regions)if(d.kind==="repeat-region")for(let g of d.childKeys)r.add(g);if(r.size===0)return e;let o=new Map(e.entries.map(d=>[d.key,d])),i=[],s=new Map,a=(d,g)=>jw(d,g),c=(d,g,h)=>{let S=o.get(d);if(!S)return a(d,h);let E=a(d,h),y={...S,key:E,parentKey:g,childKeys:[]};return i.push(y),y.childKeys=S.childKeys.flatMap(v=>l(v,h,E)),E},l=(d,g,h)=>{if(!r.has(d))return[c(d,h,g)];let S=f(d,g),E=[];for(let y=0;y<S;y+=1)E.push(c(d,h,[...g,y]));return E},u=Array.from(new Set([...e.rootKeys,...e.entries.filter(d=>d.parentKey===null).map(d=>d.key)]));for(let d of u){if(!r.has(d)){c(d,null,[]);continue}let g=f(d,[]);for(let h=0;h<g;h+=1)c(d,null,[h])}return{...e,rootKeys:[...e.rootKeys],entries:i};function f(d,g){let h=new Set;for(let S of m(d)){let E=n.get(S);if(E){for(let y of[...E.textTargets.values(),...E.elementPropertyTargets.values()])if(!(y?.kind!=="value-binding"||y.sourceKind!=="repeat-template"))for(let v of Vw(y))v.length<=g.length||Kw(v,g)&&h.add(v[g.length])}}return h.size>0?h.size:$w(n.get(d))}function m(d){let g=s.get(d);if(g)return g;let h=[d],S=o.get(d);for(let E of S?.childKeys??[])h.push(...m(E));return s.set(d,h),h}}function Eh(e){let t=e.parts.at(-1);return typeof t?.repeatIndex=="number"?t.repeatIndex:null}function vh(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((xh(s.key)??s.key)===n){if(s.key===t)return i;i+=1}return null}function Vw(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 Kw(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 kh(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 Ih(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 Ch(e){return{path:e.path,code:e.code,message:e.message,...e.details?{details:JSON.parse(JSON.stringify(e.details))}:{}}}function Uw(e){return e.map(t=>`${t.code} (${t.path}): ${t.message}`).join("; ")}var No=class extends Error{constructor(t){let n=t.map(Ch);super(Uw(n)),this.name="RouteBuildDiagnosticsError",this.diagnostics=n}};function Rh(e,t){let n=t instanceof Error&&t.message?t.message:String(t);return t instanceof No?{routeId:e,message:n,diagnostics:t.diagnostics.map(Ch)}:{routeId:e,message:n}}function Bl(e){return e.map(({routeId:t,message:n})=>`${t}: ${n}`).join("; ")}function jl(e,t){let n=new Map(e);for(let r of t)n.delete(r);return n}function Sr(e,t){e.clear();for(let[n,r]of t)e.set(n,r)}function wh(e,t){for(let n of t){if(n.exists===!1){e.delete(n.file);continue}e.set(n.file,n.content)}}function $l(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 Nh(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 Zw=/^(?:src\/)?app\/.*\/?page\.[cm]?[jt]sx?$/,Qw=["layout.tsx","layout.ts","layout.jsx","layout.js","layout.mjs","layout.cjs"],Ph=32,Ah=256;function qw(e){return{expectedIndexDigest:e.digest,publishedIndexDigest:e.digest,publishedCursor:e.cursor,publishedCurrentId:e.currentId}}var Th={maxEntries:50,maxBytes:8*1024*1024};function eN(){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 pi(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 tN(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 nN(){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>Th.maxEntries||rN(e)>Th.maxBytes;)e.shift()}}function rN(e){return e.reduce((t,n)=>t+oN(n),0)}function oN(e){return Fh(e.preSnapshots)+Fh(e.postSnapshots)+iN(e.provenance)}function iN(e){return e?new TextEncoder().encode(JSON.stringify(e)).byteLength:0}function Fh(e){return e.reduce((t,n)=>t+n.file.length+n.content.length,0)}function _h(e,t){return{key:Xw(e),composition:e,routeId:e.routeId,entryFile:t,graph:null,topology:null,capabilities:null,document: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 Cs=class extends Error{constructor(t){super(t.reason),this.result=t}},Vn=class extends Error{constructor(t){super(Bl(t)),this.failedRoutes=t}};function Mh(e,t){if(!e)return;let n=[...t];if(n.some(o=>o?.entries.some(i=>i.key===e.key)))return e;let r=it(e.key)??e.key;for(let o of n){let i=o?.entries.find(s=>(it(s.key)??s.key)===r);if(i)return{...e,key:i.key}}return e}function sN(e,t,n){if(!n)return;let r=it(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 aN=/\.(?:[cm]?[jt]sx?)$/i,cN=/\.json$/i,lN=/\.(?:css|scss|sass)$/i,uN=/\.mdx$/i,dN=/\.ya?ml$/i;function fN(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 pN(e){return{kind:e.isProxy?"component-proxy":"jsx-node",file:e.file,componentName:e.componentName,isProxy:e.isProxy}}function mN(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=$h(await e.listFiles(i)),a=new Map(s.files.map(l=>[l.path,l]));for(let[l,u]of n)if(gN(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 gN(e,t){return t.length===0?!0:t.some(n=>e===n||e.startsWith(`${n}/`))}function $h(e){return Array.isArray(e)?{files:e}:e}function hN(e){if(!Ww(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!==Gw||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=zw(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(aN.test(e.path)){let t=Pt({source:e.content,profile:vn({filePath:e.path,source:e.content})});if(!t.ok)return{ok:!1,errorCode:"ast-error",message:t.diagnostic.message,details:{path:e.path}}}if(cN.test(e.path))try{JSON.parse(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`JSON parse failed: ${et(t)}`,details:{path:e.path}}}if(lN.test(e.path)){let t=Oh({content:e.content,path:e.path,profile:"css"});if(!t.ok)return t}if(uN.test(e.path)){let t=Oh({content:e.content,path:e.path,profile:"mdx"});if(!t.ok)return t}if(dN.test(e.path))try{Yw(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`YAML parse failed: ${et(t)}`,details:{path:e.path}}}return{ok:!0}}function Oh({content:e,path:t,profile:n}){let r=[],o=null,i=!1,s=!1,a=!1,c=!1,l=!0;for(let f=0;f<e.length;f+=1){let m=e[f]??"",d=e[f+1]??"";if(n==="mdx"&&l&&e.startsWith("```",f)){c=!c;let g=e.indexOf(`
|
|
1
|
+
import*as py from"@babel/parser";import*as Ge from"@babel/types";import*as tn from"node:path";var Bs=[".tsx",".ts",".jsx",".js"],my=Bs.map(e=>`/index${e}`),gy=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 au(e){let t=e.replace(/[?#].*$/,""),n=/\.([a-z0-9]+)$/i.exec(t);return n!==null&&gy.has(n[1].toLowerCase())}function cu(e){let t=[];for(let n of e.program.body)Ge.isImportDeclaration(n)&&typeof n.source.value=="string"&&Nt(n.source.value)&&t.push(n.source.value),Ge.isExportNamedDeclaration(n)&&n.source&&typeof n.source.value=="string"&&Nt(n.source.value)&&t.push(n.source.value),Ge.isExportAllDeclaration(n)&&typeof n.source.value=="string"&&Nt(n.source.value)&&t.push(n.source.value);return Ge.traverseFast(e.program,n=>{let r=Ge.isImportExpression(n)?n.source:Ge.isCallExpression(n)&&Ge.isImport(n.callee)?n.arguments[0]:null;Ge.isStringLiteral(r)&&Nt(r.value)&&t.push(r.value)}),t}function Nt(e){return e.startsWith("./")||e.startsWith("../")||e.startsWith("@/")}function bn(e,t){if(t.startsWith("@/"))return t.slice(2).replace(/\\/g,"/");let n=tn.dirname(e);return tn.join(n,t).replace(/\\/g,"/")}async function hy(e,t){if(Bs.some(n=>e.endsWith(n))&&await t(e))return e;for(let n of Bs){let r=`${e}${n}`;if(await t(r))return r}for(let n of my){let r=`${e}${n}`;if(await t(r))return r}return null}async function Sn(e,t,n){let r=await Oo(e,t,n);return r.ok?r.path:null}async function Oo(e,t,n){let r=bn(e,t);try{if(!yy(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 hy(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 yy(e,t,n){if(!Nt(t)||t.includes("\0")||t.includes("\\")||tn.posix.isAbsolute(n))return!1;let r=tn.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!tn.posix.isAbsolute(e)}import{createHash as by}from"node:crypto";import*as lu from"@babel/parser";function En(e,t,n,r){return{code:e,message:t,locatorKind:n,details:r}}function J(e,t,n,r,o){return{ok:!1,source:e,diagnostic:En(t,n,r,o)}}function js(e,t,n,r,o){return{ok:!1,source:e,diagnostic:En(t,n,r,o)}}var xy={"tsx-module":["jsx","typescript"],"ts-module":["typescript"],"next-app-entry":["jsx","typescript"]};function Pt(e){let{source:t,profile:n}=e;try{return{ok:!0,ast:lu.parse(t,{sourceType:"module",plugins:xy[n]})}}catch(r){return{ok:!1,source:t,diagnostic:En("parse-failed",`AST parse failed: ${r instanceof Error?r.message:String(r)}`)}}}function $s(e,t){return Pt({source:e,profile:uu(t.kind)})}function kr(e,t){return Pt({source:e,profile:uu(t)})}function uu(e){return"next-app-entry"}function vn(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 Ut=(e,t)=>{let n=Pt({source:t,profile:vn({filePath:e,source:t})});return n.ok?{ok:!0,module:{file:e,source:t,sourceHash:`sha256:${by("sha256").update(t).digest("hex")}`,ast:n.ast,imports:cu(n.ast).map(r=>({specifier:r}))}}:{ok:!1,diagnostic:{path:e,code:"parse-failed",message:n.diagnostic.message}}};function Sy(e,t){return Ut(e,t)}function Ey(e,t){return bn(e,t)}import{COMPONENT_I18N_FILE_SUFFIX as vy,parseComponentI18nResourcesJson as ky,resolveSiteTextDirection as Iy,SiteLocaleSchema as Cy}from"@vcp-dev/contracts";var Ry=["i18next","react-i18next"],wy="components/ui/site-locale-provider.tsx",Ny="components/ui/component-i18n-provider.tsx",du="app/layout.tsx";async function Lo(e){let t=e.files.filter(m=>m.path.endsWith(vy));if(t.length===0)return{ok:!0};for(let m of["package.json",du,wy,Ny])if(!await e.exists(m))return nn(`Target snapshot is missing required i18n host file: ${m}`);let n;try{n=JSON.parse(await e.readFile("package.json"))}catch{return nn("Target snapshot package.json is invalid.")}let r=fu(n)&&fu(n.dependencies)?n.dependencies:{},o=Ry.filter(m=>typeof r[m]!="string"||r[m].trim().length===0);if(o.length>0)return nn(`Target snapshot must already declare: ${o.join(", ")}.`);let i=await e.readFile(du),s=Vs(i,"html","lang"),a=Vs(i,"html","dir"),c=Vs(i,"SiteLocaleProvider","locale"),l=Cy.safeParse(s);if(!l.success||!a||!c||s!==c||a!==Iy(l.data))return nn("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 nn("Target snapshot root layout is not wired to SiteLocaleProvider.");let u=l.data;if(e.targetLocale&&e.targetLocale!==u)return nn("Target snapshot locale does not match the authoritative site language.");let f=u.split("-")[0];for(let m of t){let d=ky(m.content);if(!d.success)return nn(`Component i18n resource is invalid: ${m.path}.`);if(!e.deferTargetLocale&&!Object.hasOwn(d.data,u)&&!Object.hasOwn(d.data,f))return nn(`Component i18n resource ${m.path} has no locale for ${u} or ${f}.`)}return{ok:!0}}function Vs(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 fu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function nn(e){return{ok:!1,message:e}}import Us from"@babel/generator";import*as xu from"@babel/parser";import Js from"@babel/traverse";import*as Re from"@babel/types";import{computeSiteEditSourceIdentityKey as Ay}from"@vcp-dev/contracts";var pu="data-vcp-ui-component",Do="components/ui";function Jt(e){if(!e)return!1;let t=Ks(e);return t===Do||t.startsWith(`${Do}/`)||t.includes(`/${Do}/`)||t.endsWith(`/${Do}`)}function kn(e,t){return e?e.startsWith("@/")||e.startsWith("~/")?Jt(e.slice(2)):e.startsWith("./")||e.startsWith("../")?Jt(Ks(`${Py(t)}/${e}`)):Jt(e):!1}function Ks(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 Py(e){let t=Ks(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}import{stripSiteEditRepeatInstanceKeys as oP}from"@vcp-dev/contracts";import{isSiteEditRuntimeContainerTag as sP,isSiteEditRuntimeTextTag as aP}from"@vcp-dev/contracts/site-edit-runtime-capability";var mu={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 Ty=typeof Us=="function"?Us:Us.default,Fy=typeof Js=="function"?Js:Js.default,_y=new Set(["base","body","head","html","link","meta","noscript","script","style","template","title"]),My="suppressHydrationWarning",Oy=new Set(["SiteEditBootstrap"]);function Ly(e){let t=jy(e.file,e.projectRoot);if(!By(e.source)||Jt(t))return{code:e.source,elements:[]};let n=e.attributes??mu,r=xu.parse(e.source,{sourceType:"module",plugins:["jsx","typescript"]}),o=[],i=Vy(r,t);return Fy(r,{JSXElement(s){let a=s.node.openingElement,c=a.name;if(!Uy(c)||bu(a,n.key))return;let l=Xy(s)??"default",u=Wy(s),f=Ay(t,l,u),m=jo(c)??"unknown",d=$y(c)?"jsx":"component-call";if(d==="component-call"&&!zy(s.node.children)&&Oy.has(m))return;let g=d==="component-call"&&Ky(m,i);Jy(a,n.key,f),g&&gu(a,pu),Dy(s)&&gu(a,My),o.push({key:f,tag:m,componentName:l,sourceFile:t,sourceKind:d})}}),o.length===0?{code:e.source,elements:o}:{code:Ty(r,{jsescOption:{minimal:!0}}).code,elements:o}}function Dy(e){return!e.findParent(t=>t.isJSXElement())}function By(e){return/(?:^|[=(:,?;\[{>&|\n\r]|return\s+)\s*<(?:[A-Za-z][\w.:-]*|>)(?:\s|>|\/)/m.test(e)}function jy(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 $y(e){return Re.isJSXIdentifier(e)&&/^[a-z]/.test(e.name)}function jo(e){return Re.isJSXIdentifier(e)?e.name:Re.isJSXMemberExpression(e)?Eu(e):null}function Vy(e,t){let n=new Set;for(let r of e.program.body)if(!(!Re.isImportDeclaration(r)||!kn(r.source.value,t)))for(let o of r.specifiers)n.add(o.local.name);return n}function Ky(e,t){let n=e.split(".")[0]??e;return t.has(n)}function Uy(e){let t=jo(e);return!t||t==="Fragment"||t.endsWith(".Fragment")?!1:!_y.has(t)}function bu(e,t){return e.attributes.some(n=>Re.isJSXAttribute(n)&&Re.isJSXIdentifier(n.name,{name:t}))}function Jy(e,t,n){Su(e,Re.jsxAttribute(Re.jsxIdentifier(t),Re.stringLiteral(n)))}function gu(e,t){bu(e,t)||Su(e,Re.jsxAttribute(Re.jsxIdentifier(t),null))}function Su(e,t){let n=e.attributes.findIndex(r=>Re.isJSXSpreadAttribute(r));if(n>=0){e.attributes.splice(n,0,t);return}e.attributes.push(t)}function Eu(e){return`${Re.isJSXIdentifier(e.object)?e.object.name:Eu(e.object)}.${e.property.name}`}function Xy(e){let t=e;for(;t;){if(t.isFunctionDeclaration()||t.isClassDeclaration())return t.node.id?.name??null;if(t.isVariableDeclarator()&&Re.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 zy(e){return e.some(t=>Re.isJSXElement(t)||Re.isJSXFragment(t))}var hu=new WeakMap,Bo=new WeakMap,Xs=new WeakMap;function Wy(e){let t=hu.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=Hy(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return hu.set(e.node,o),o}function Hy(e){let t=jo(e.node.openingElement.name);return!t||t==="Fragment"||t.endsWith(".Fragment")?null:/^[A-Z]/.test(t)?`component:${t}#${yu(e,t)}`:`${t}#${yu(e,t)}`}function yu(e,t){let n=vu(e)??e.getFunctionParent();if(!n)return 0;let r=Xs.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=Xs.get(n.node);o||(o=new Map,Xs.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()?$o(n):Gy(n);for(let c of a)if(jo(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 Gy(e){let t=Bo.get(e.node);if(t)return t;let n=[];return e.traverse({JSXElement(r){r.getFunctionParent()?.node===e.node&&!vu(r)&&n.push(r)}}),Bo.set(e.node,n),n}function vu(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 $o(e){let t=Bo.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(...$o(o));continue}o.isJSXExpressionContainer()&&n.push(...In(o.get("expression")))}return Bo.set(e.node,n),n}function In(e){if(e.isJSXElement())return[e];if(e.isJSXFragment())return $o(e);if(e.isParenthesizedExpression())return In(e.get("expression"));if(e.isLogicalExpression()&&e.node.operator==="&&")return In(e.get("right"));if(e.isConditionalExpression())return[...In(e.get("consequent")),...In(e.get("alternate"))];if(e.isCallExpression()&&Zy(e.node)){let t=e.get("arguments")[0];return Yy(t)}return[]}function Yy(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return[t];if(t.isJSXFragment())return $o(t);if(t.isParenthesizedExpression())return In(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?In(r):[]}return[]}function Zy(e){return Re.isMemberExpression(e.callee)&&Re.isIdentifier(e.callee.property)&&e.callee.property.name==="map"}import{SiteEditOperationRequestSchema as MN,SiteEditPatchPlanSchema as ON}from"@vcp-dev/contracts";function Cn(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 Vo(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 Ko(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}:{}})),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 Uo(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:Qy(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 Jo(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:Cn(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 Qy(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 Jw,computeSiteEditCompositionKey as Xw,getSiteEditSourceDeleteProtectionReason as zw,isSiteEditTextSourcePath as Ww,parseSiteEditRepeatInstanceKey as Hw,SITE_EDIT_SOURCE_DELETE_CAPABILITY as Gw,stripSiteEditRepeatInstanceKeys as it}from"@vcp-dev/contracts";import Is from"node:path";import{parse as Yw}from"yaml";import Ys from"node:path";import{TextDecoder as ex}from"node:util";import{SITE_EDIT_SOURCE_ALLOWED_APP_FILES as Iu,SITE_EDIT_SOURCE_ALLOWED_DIRS as Cu,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as Ru,SiteEditCompositionContextSchema as tx,SiteEditSourceFileResponseSchema as zs,SiteEditSourceLocationSchema as nx,SiteEditSourcePathSchema as Xo,SiteEditSourceTreeResponseSchema as rx,isSiteEditTextSourcePath as ox}from"@vcp-dev/contracts";import{createHash as qy}from"node:crypto";var Ir=class{constructor(t){this.original=new Map,this.files=new Map,this.versions=new Map;for(let n of t)this.original.set(n.path,n.content),this.files.set(n.path,n.content),this.versions.set(n.path,n.version??1)}async readFile(t){let n=this.files.get(t);if(n===void 0)throw new Error(`Snapshot file not found: ${t}`);return n}async readFileBytes(t){return Buffer.from(await this.readFile(t),"utf8")}async getFileInfo(t){let n=this.files.get(t);return n===void 0?null:{path:t,sizeBytes:Buffer.byteLength(n,"utf8")}}async writeFile(t,n){this.files.set(t,n)}async createExclusive(t,n){if(this.files.has(t))throw Object.assign(new Error(`Snapshot file already exists: ${t}`),{code:"EEXIST"});this.files.set(t,n)}async deleteFile(t){this.files.delete(t)}async exists(t){return this.files.has(t)}async listFiles(t={}){let n=t.roots??[],r=[...this.files.keys()].filter(a=>n.length===0?!0:n.some(c=>a===c||a.startsWith(`${c}/`))),o=[],i=new Set,s=0;for(let a of r.sort()){let c=Buffer.byteLength(this.files.get(a)??"","utf8"),l=a.split("/").length;if(t.maxDepth!==void 0&&l>t.maxDepth){i.add("max-depth");continue}if(t.maxFiles!==void 0&&o.length>=t.maxFiles){i.add("max-files");break}if(t.maxTotalBytes!==void 0&&s+c>t.maxTotalBytes){i.add("max-total-bytes");break}o.push({path:a,sizeBytes:c}),s+=c}return i.size>0?{files:o,truncated:{reasons:[...i]}}:{files:o}}getVersion(t){return this.versions.get(t)??0}bumpVersion(t){let n=this.getVersion(t)+1;return this.versions.set(t,n),n}getChangedFiles(){let t=new Set([...this.original.keys(),...this.files.keys()]),n=[];for(let r of[...t].sort()){let o=this.original.get(r),i=this.files.get(r);o!==i&&n.push({path:r,before:o,after:i})}return n}};function ke(e){return`sha256:${qy("sha256").update(e).digest("hex")}`}var ix=[...Ru,...Iu,...Cu];function Zs(e){if(!e.composition)throw new Error("Composition unavailable for source access policy.");return tx.parse(e.composition)}var Ws=2e3,Hs=12,Gs=24*1024*1024,ku=512*1024,sx=new Set(["image/avif","image/gif","image/jpeg","image/png","image/webp","image/x-icon"]),ax={".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"},cx={".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"},lx=new ex("utf-8",{fatal:!0});async function zo(e,t={}){let n=Zs(t),{files:r,truncated:o}=await hx(e,t),i=bx(r.map(s=>s.metadata));return rx.parse({composition:n,nodes:i,defaultPath:Sx(r.map(s=>s.metadata)),totalFiles:r.length,...o?{truncated:o}:{}})}async function Wo(e,t,n={}){let r=Zs(n),o=Xo.parse(t.path),i=await dx(e,o,n);if(!i)throw new Error(`Source file not found: ${o}`);if(qs(o)){let a=Pu(o),c=await px(e,{path:o,sizeBytes:i.sizeBytes,mimeType:a});return zs.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:i.sizeBytes,mimeType:a,readonly:!0,...c})}let s=await Qs(e,o);return s.ok?zs.parse({composition:r,path:o,kind:"text",language:Au(o),sizeBytes:s.sizeBytes,contentHash:ke(s.content),readonly:!1,content:s.content}):zs.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:s.sizeBytes,mimeType:"application/octet-stream",readonly:!0,previewUnavailableReason:"unsupported-mime"})}async function Qs(e,t){if(e.readFileBytes){let o=await e.readFileBytes(t),i=ux(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 ux(e){if(e.includes(0))return null;try{return lx.decode(e)}catch{return null}}async function dx(e,t,n){if(!mx(t,n))return null;let r=await fx(e,t);return r?{path:t,sizeBytes:r.sizeBytes}:null}async function fx(e,t){if(e.getFileInfo)return e.getFileInfo(t);if(e.listFiles){let o=wu(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(qs(t))return{path:t,sizeBytes:0};let n=await e.readFile(t);return{path:t,sizeBytes:Buffer.byteLength(n,"utf8")}}async function px(e,t){if(!sx.has(t.mimeType))return{previewUnavailableReason:"unsupported-mime"};if(t.sizeBytes>ku)return{previewUnavailableReason:"too-large"};if(!e.readFileBytes)return{previewUnavailableReason:"bytes-unavailable"};let n=await e.readFileBytes(t.path);return n.byteLength>ku?{previewUnavailableReason:"too-large"}:{contentBase64:Buffer.from(n).toString("base64")}}function mx(e,t){return Ru.some(n=>n===e)||Iu.some(n=>n===e)||Cu.some(n=>e===n||e.startsWith(`${n}/`))?!0:!e.startsWith("app/")&&!e.startsWith("src/app/")?!1:(t.routeEntryFiles??[]).some(n=>{let r=Xo.safeParse(n);return r.success&&r.data===e})}function Ho(e,t){if(!t.sourceLocator)throw new Error(`Source location not available for key: ${e.key}`);return nx.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 wu(e){return Array.isArray(e)?{files:e}:e}function gx(e){return["max-files","max-depth","max-total-bytes"].filter(n=>e.includes(n))}async function hx(e,t){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let n=wu(await e.listFiles({roots:yx(t),maxFiles:Ws+1,maxDepth:Hs,maxTotalBytes:Gs+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=Xo.safeParse(a.path);if(!c.success)continue;let l=c.data;if(l.split("/").length>Hs){o.add("max-depth");continue}if(r.size>=Ws){o.add("max-files");break}if(i+a.sizeBytes>Gs){o.add("max-total-bytes");break}r.set(l,{path:l,sizeBytes:a.sizeBytes,metadata:xx(l,a.sizeBytes,Zs(t))}),i+=a.sizeBytes}return{files:[...r.values()].sort((a,c)=>a.path.localeCompare(c.path)),...o.size>0?{truncated:{reasons:gx([...o]),maxFiles:Ws,maxDepth:Hs,maxTotalBytes:Gs}}:{}}}function yx(e){let t=new Set(ix);for(let n of e.routeEntryFiles??[]){let r=Xo.safeParse(n);r.success&&(r.data.startsWith("app/")||r.data.startsWith("src/app/"))&&t.add(r.data)}return[...t]}function xx(e,t,n){return qs(e)?{composition:n,path:e,kind:"binary",language:null,sizeBytes:t,mimeType:Pu(e),readonly:!0}:{composition:n,path:e,kind:"text",language:Au(e),sizeBytes:t,readonly:!1}}function bx(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 Nu(t)}function Nu(e){return e.map(t=>t.kind==="directory"?{...t,children:Nu(t.children)}:t).sort((t,n)=>t.kind!==n.kind?t.kind==="directory"?-1:1:t.name.localeCompare(n.name))}function Sx(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 qs(e){return!ox(e)}function Pu(e){let t=Ys.posix.extname(e).toLowerCase();return!t&&Ys.posix.basename(e).toLowerCase()==="favicon"?"image/x-icon":ax[t]??"application/octet-stream"}function Au(e){let t=Ys.posix.extname(e).toLowerCase();return cx[t]??"plaintext"}import ea from"@babel/traverse";import*as At from"@babel/types";function Me(e){if(e.isJSXFragment())return!0;if(!e.isJSXElement())return!1;let t=e.node.openingElement.name;if(At.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(At.isIdentifier(s)&&s.name==="Fragment"||At.isStringLiteral(s)&&s.value==="Fragment")&&Tu(i.parentPath)}if(!At.isJSXMemberExpression(t)||!At.isJSXIdentifier(t.property)||t.property.name!=="Fragment"||!At.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())&&Tu(r.parentPath)}function Tu(e){return e?.isImportDeclaration()===!0&&e.node.source.value==="react"}var rn=typeof ea=="function"?ea:ea.default,Go=new WeakMap,Yo=new WeakMap;function Tt(e,t){let n=$s(e,t);if(!n.ok)return js(e,n.diagnostic.code,n.diagnostic.message,t.kind);let r=se(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}}:js(e,r.diagnostic.code,r.diagnostic.message,t.kind,r.diagnostic.details)}function se(e,t){return t.kind==="jsx-node"?Ou(e,t):t.kind==="jsx-attribute"?Rx(e,t):t.kind==="value"?wx(e,t):t.kind==="expression"?Nx(e,t):t.kind==="directive"?Px(e,t):t.kind==="export"?Ax(e,t):{ok:!1,diagnostic:En("unsupported-syntax",`Unsupported locator kind: ${t.kind}`)}}function Ou(e,t){return t.strategy==="source-range"?Ex(e,t):vx(e,t)}function Ex(e,t){let n=null;if(rn(e,{JSXElement(o){if(!Rn(o.node,t.sourceRange))return;let i=De("jsx-node",o);if(i){if(!n){n=i;return}i.end-i.start<n.end-n.start&&(n=i)}},JSXFragment(o){if(!Rn(o.node,t.sourceRange))return;let i=De("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXExpressionContainer(o){if(!Rn(o.node,t.sourceRange))return;let i=De("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXText(o){if(!Rn(o.node,t.sourceRange))return;let i=De("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)}}),!n)return Be("jsx-node","locator-miss","JSX node not found for source-range locator");let r=n;return t.expectedIdentity&&!Kx(r.path,t.expectedIdentity)?Be("jsx-node","locator-miss","JSX node failed expected identity validation"):{ok:!0,match:r}}function vx(e,t){if(t.structuralPath===""){let r=Ix(e,t.component);if(r){let o=Cx(r);if(o)return o}}let n=null;return rn(e,{JSXElement(r){if(Rr(r)!==t.component||na(r)!==t.structuralPath)return;let i=De("jsx-node",r);i&&(n=i,r.stop())},JSXFragment(r){if(Rr(r)!==t.component||na(r)!==t.structuralPath)return;let i=De("jsx-node",r);i&&(n=i,r.stop())}}),!n&&t.expectedRange&&(n=kx(e,t.component,t.expectedRange)),n?{ok:!0,match:n}:Be("jsx-node","locator-miss","JSX node not found for structural-path locator")}function kx(e,t,n){let r=null;return rn(e,{JSXElement(o){if(Rr(o)!==t||!Rn(o.node,n))return;let i=De("jsx-node",o);i&&(r=i,o.stop())},JSXFragment(o){if(Rr(o)!==t||!Rn(o.node,n))return;let i=De("jsx-node",o);i&&(r=i,o.stop())}}),r}function Ix(e,t){let n=null;return rn(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 Cx(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 Be("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}return null}return(t.isParenthesizedExpression()?t.get("expression"):t).isJSXFragment()?Be("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 Be("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}}}return null}function Rx(e,t){let n=Ou(e,t.element);if(!n.ok)return n;let s=n.match.path.get("openingElement").get("attributes").find(c=>Ux(c,t.name));if(!s||!s.isJSXAttribute())return Be("jsx-attribute","locator-miss",`JSX attribute '${t.name}' not found`);let a=De("jsx-attribute",s);return a?{ok:!0,match:a}:Be("jsx-attribute","locator-miss",`JSX attribute '${t.name}' has no source range`)}function wx(e,t){let n=Tx(e,t);if(!n.ok)return n;let r=Fx(n.match.path,t.path??[]);return r.ok?t.expectedRange&&!zt(r.match.path.node.loc,t.expectedRange)?Be("value","locator-miss","Resolved value does not match expected range"):{ok:!0,match:r.match}:r}function Nx(e,t){let n=null;return rn(e,{Identifier(r){if(!Bx(r))return;let o=_u(r);if(!o||!Mu(o,t))return;let i=De("expression",r);i&&(t.expectedRange&&!zt(r.node.loc,t.expectedRange)||(n=i,r.stop()))},MemberExpression(r){let o=_u(r);if(!o||!Mu(o,t))return;let i=De("expression",r);i&&(t.expectedRange&&!zt(r.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:Be("expression","locator-miss","Expression not found")}function Px(e,t){let n=null;return rn(e,{Program(r){let i=r.get("directives").find(a=>a.node.value.value===t.value);if(!i||t.expectedRange&&!zt(i.node.loc,t.expectedRange))return;let s=De("directive",i);s&&(n=s,r.stop())}}),n?{ok:!0,match:n}:Be("directive","locator-miss",`Directive '${t.value}' not found`)}function Ax(e,t){let n=null;return rn(e,{ExportNamedDeclaration(r){if(t.exportKind==="generate-metadata"){let c=r.get("declaration");if(c.isFunctionDeclaration()&&c.node.id?.name==="generateMetadata"){let m=De("export",c);if(!m||t.expectedRange&&!zt(c.node.loc,t.expectedRange))return;n=m,r.stop();return}if(!c.isVariableDeclaration())return;let l=ra(c,"generateMetadata");if(!l||!l.isVariableDeclarator())return;let u=l.get("init");if(!u.node)return;let f=De("export",u);if(!f||t.expectedRange&&!zt(u.node.loc,t.expectedRange))return;n=f,r.stop();return}let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=ra(o,t.exportKind==="named"?t.name:"metadata");if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node||t.expectedRange&&!zt(s.node.loc,t.expectedRange))return;let a=De("export",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(t.exportKind!=="default")return;let o=r.get("declaration"),i=De("export",o);i&&(t.expectedRange&&!zt(o.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:Be("export","export-not-found",`Export '${Vx(t)}' not found`)}function Tx(e,t){let n=null;return rn(e,{Expression(r){if(n||t.root.kind!=="expression"||!Rn(r.node,t.root.sourceRange))return;let o=De("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 d=r.get("init");if(!d.node)return;let g=De("value",d);if(!g)return;n=g,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(d=>d?.type==="Identifier"&&d.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,f=r.get(`init.arguments.${u}`);if(!f||Array.isArray(f)||!f.node)return;let m=De("value",f);m&&(n=m,r.stop())},ExportNamedDeclaration(r){if(n||t.root.kind!=="named-export")return;let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=ra(o,t.root.name);if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node)return;let a=De("value",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(n||t.root.kind!=="default-export")return;let o=r.get("declaration"),i=De("value",o);i&&(n=i,r.stop())}}),n?{ok:!0,match:n}:Be("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 Fx(e,t){let n=ta(e);for(let o of t){if(n=ta(n),o.kind==="property"){if(!n.isObjectExpression())return Be("value","unsupported-syntax","Property path requires object expression");let a=n.get("properties");if(a.some(l=>!l.isObjectProperty()))return Be("value","unsupported-syntax","Spread properties are not supported");let c=a.find(l=>Jx(l,o.name));if(!c||!c.isObjectProperty())return Be("value","property-not-found",`Property '${o.name}' not found`);n=c.get("value");continue}if(!n.isArrayExpression())return Be("value","unsupported-syntax","Array index path requires array expression");let i=n.get("elements");if(i.some(a=>a.node?.type==="SpreadElement"))return Be("value","unsupported-syntax","Spread array elements are not supported");let s=i[o.index];if(!s?.node)return Be("value","array-index-out-of-range",`Array index ${o.index} is out of range`);n=s}n=ta(n);let r=De("value",n);return r?{ok:!0,match:r}:Be("value","locator-miss","Resolved value has no source range")}function ta(e){let t=e;for(;t.isTSAsExpression()||t.isTSSatisfiesExpression()||t.isTSNonNullExpression();)t=t.get("expression");return t}function De(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 Rn(e,t){return zt(e.loc,t)}function zt(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 na(e){let t=[],n=e,r=e.node;for(;n;){if(n.isJSXElement()){if(!Me(n)){let o=Du(n.node.openingElement);o&&(/^[A-Z]/.test(o)?t.unshift(`component:${o}#${Fu(n,o)}`):t.unshift(`${o}#${Fu(n,o)}`))}}else n.isJSXFragment()&&n.node===r&&t.unshift("fragment");if(!n.parentPath||Lx(n.parentPath)&&!Dx(n.parentPath))break;n=n.parentPath}return t.join("/")}function Fu(e,t){let n=Lu(e)??e.getFunctionParent();if(!n)return 0;let r=Go.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=0,i=Go.get(n.node)?.get(t);if(!i){let a=Go.get(n.node);a||(a=new Map,Go.set(n.node,a)),i=new WeakMap,a.set(t,i)}let s=n.isJSXElement()||n.isJSXFragment()?Cr(n):_x(n);for(let a of s)if(Du(a.node.openingElement)===t){if(i.set(a.node,o),a.node===e.node)return o;o++}return i.get(e.node)??0}function _x(e){let t=Yo.get(e.node);if(t)return t;let n=[];return e.traverse({JSXElement(r){r.getFunctionParent()?.node===e.node&&!Lu(r)&&n.push(r)}}),Yo.set(e.node,n),n}function Lu(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(Me(t)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function Cr(e){let t=Yo.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(Me(o)){n.push(...Cr(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...Cr(o));continue}o.isJSXExpressionContainer()&&n.push(...Xt(o.get("expression")))}return Yo.set(e.node,n),n}function Xt(e){if(e.isJSXElement())return Me(e)?Cr(e):[e];if(e.isJSXFragment())return Cr(e);if(e.isParenthesizedExpression())return Xt(e.get("expression"));if(e.isLogicalExpression()&&Mx(e.node.operator))return Xt(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(...Xt(c))}if(s.isReturnStatement()){let a=s.get("argument");a.isExpression()&&i.push(...Xt(a));break}}return i}else if(o.node&&o.isExpression())return Xt(o)}}}}return e.isConditionalExpression()?[...Xt(e.get("consequent")),...Xt(e.get("alternate"))]:e.isArrayExpression()?e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:Xt(t)):[]}function Mx(e){return e==="&&"||e==="||"||e==="??"}function Du(e){return e.name.type==="JSXIdentifier"?e.name.name:e.name.type==="JSXMemberExpression"?Ox(e.name):null}function Ox(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 Rr(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 Lx(e){return!!(e.isFunctionDeclaration()||e.isFunctionExpression()||e.isArrowFunctionExpression())}function Dx(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 Bx(e){return!(!e.isExpression()||e.parentPath?.isMemberExpression({property:e.node}))}function _u(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 Mu(e,t){return e.base===t.base&&jx(e.path,t.path??[])}function jx(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 $x(e){return e.key.type==="Identifier"?e.key.name:e.key.type==="StringLiteral"?e.key.value:null}function Vx(e){return e.exportKind==="named"?e.name:e.exportKind}function Be(e,t,n,r){return{ok:!1,diagnostic:En(t,n,e,r)}}function Kx(e,t){return Rr(e)!==t.component?!1:na(e)===t.structuralPath}function Ux(e,t){return!e.isJSXAttribute()||e.node.name.type!=="JSXIdentifier"?!1:e.node.name.name===t}function ra(e,t){return e.get("declarations").find(n=>!n.isVariableDeclarator()||n.node.id.type!=="Identifier"?!1:n.node.id.name===t)}function Jx(e,t){return e.isObjectProperty()?$x(e.node)===t:!1}import*as ju from"@babel/parser";import{arrayExpression as Gx,booleanLiteral as Yx,identifier as Zx,jsxAttribute as Qx,jsxExpressionContainer as qx,jsxIdentifier as eb,nullLiteral as tb,numericLiteral as nb,objectExpression as rb,objectProperty as ob,stringLiteral as ia}from"@babel/types";import oa from"@babel/generator";var Xx=typeof oa=="function"?oa:oa.default;function zx(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 Wx(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 Hx(e,t){return e.split(`
|
|
3
|
+
`).map(r=>Wx(r,t)).join(`
|
|
4
|
+
`)}function Zo(e){let{ast:t,source:n}=e;try{let r=zx(n),i=Xx(t,{comments:!0,jsescOption:{minimal:!0,quotes:"single"}},n).code;return r!=="2"&&(i=Hx(i,r)),{ok:!0,source:i}}catch(r){return J(n,"printer-failed",`AST print failed: ${r instanceof Error?r.message:String(r)}`)}}function Bu(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 wr(e,t,n){return{ok:!0,source:t,operation:{type:n.kind,nodeId:n.target,kind:n.kind,target:n.target,beforeSourceHash:Bu(e),afterSourceHash:Bu(t),inverse:n.inverse}}}function he(e,t,n){let r=Zo({ast:e,source:t});return r.ok?wr(t,r.source,n):r}function we(e,t){let n=kr(e,t);return n.ok?{ok:!0,ast:n.ast}:{ok:!1,result:{ok:!1,source:e,diagnostic:n.diagnostic}}}function Qo(e,t){return Zo({ast:e,source:t})}function ib(e,t,n){let r=se(e,t);return r.ok?{ok:!0,match:r.match}:{ok:!1,result:{ok:!1,source:n,diagnostic:r.diagnostic}}}function Wn(e,t,n){let r=ib(e,t,n);return r.ok?r.match.path.isJSXElement()?r:{ok:!1,result:J(n,"unsupported-syntax","JSX locator must resolve to JSXElement","jsx-node")}:r}function on(e){return typeof e=="string"?ia(e):typeof e=="number"?nb(e):typeof e=="boolean"?Yx(e):e===null?tb():Array.isArray(e)?Gx(e.map(t=>on(t))):rb(Object.entries(e).map(([t,n])=>{let r=ob(sa(t),on(n));return t==="__proto__"&&(r.computed=!0),r}))}function sb(e){return typeof e=="string"?ia(e):qx(on(e))}function Nr(e,t){return Qx(eb(e),sb(t))}function qo(e,t){try{let r=ju.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:J(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:J(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function sa(e){return/^[$A-Z_][0-9A-Z_$]*$/i.test(e)?Zx(e):ia(e)}function ei(e){let{source:t,locator:n,segmentIndex:r,newText:o}=e,i=we(t,"jsx-node");if(!i.ok)return i.result;let s=se(i.ast,n);if(!s.ok)return{ok:!1,source:t,diagnostic:s.diagnostic};let c=ab(s.match.path)[r];if(!c)return J(t,"locator-miss",`Text segment ${r} not found`,"jsx-node");switch(c.kind){case"jsx-text":c.path.node.value=cb(c.path.node.value,o);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,c.path.node.quasis[l].value.cooked=o;break}}return he(i.ast,t,{kind:"update-text",target:"jsx-node",inverse:"restore-text"})}function ab(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=lb(r.get("expression"));o.length>0&&t.push(...o)}}return t}function cb(e,t){let n=e.match(/^\s*/)?.[0]??"",r=e.match(/\s*$/)?.[0]??"";return`${n}${t.trim()}${r}`}function lb(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&&t.push({kind:"template-literal",path:e,quasiIndex:r});if(t.length>0)return t}return e.isCallExpression()?[]:[]}import{nullLiteral as aa}from"@babel/types";function Hn(e){let{source:t,locator:n}=e,r=we(t,"jsx-node");if(!r.ok)return r.result;let o=se(r.ast,n);return o.ok?(ub(o.match.path),he(r.ast,t,{kind:"remove-node",target:"jsx-node",inverse:"insert-child"})):{ok:!1,source:t,diagnostic:o.diagnostic}}function ub(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(aa());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(aa());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(aa());return}e.remove()}import{cloneNode as db}from"@babel/types";function ti(e){let t=we(e.source,"jsx-node");if(!t.ok)return t.result;let n=se(t.ast,e.locator);if(!n.ok)return{ok:!1,source:e.source,diagnostic:n.diagnostic};let r=qo(e.source,e.node.jsx);return r.ok?(n.match.path.replaceWith(db(r.node,!0)),he(t.ast,e.source,{kind:"replace-node",target:"jsx-node",inverse:"replace-node"})):r.result}import{cloneNode as vb}from"@babel/types";import ca from"@babel/traverse";import*as Q from"@babel/types";function Pr(e,t,n){return`${e}::${t}::${n}`}var K={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 fb=typeof ca=="function"?ca:ca.default;function mt(e,t,n,r){if(!e.ok)return e;let o=pt(n,t);if(!o)return e;let i=pb(t,o,r);return i?{...e,selectionRef:i}:e}function pb(e,t,n){let r=mb(e,t);if(!r)return;let o=n.sourceLocator?$u(n.sourceLocator):void 0,i=n.targetParentLocator?$u(n.targetParentLocator):void 0,s=n.file??i?.file??o?.file,a=n.component??hb(r)??i?.component??o?.component;if(!(!s||!a))return{key:Pr(s,a,yb(r))}}function $u(e){return e.strategy==="structural-path"?{file:e.file,component:e.component,structuralPath:e.structuralPath}:e.expectedIdentity}function mb(e,t){let n=zu(e,t);return!n||n.node.type!=="JSXElement"?null:n}function zu(e,t){let n=null;return fb(e,{JSXElement(r){r.node===t&&(n=r,r.stop())},JSXFragment(r){r.node===t&&(n=r,r.stop())}}),n}function pt(e,t){if(!e)return null;if(Q.isJSXElement(e))return Eb(t,e)?Vu(e.children,t):e;if(Q.isJSXFragment(e))return Vu(e.children,t);if(Q.isJSXExpressionContainer(e)||Q.isParenthesizedExpression(e)||Q.isTSAsExpression(e)||Q.isTSSatisfiesExpression(e)||Q.isTSTypeAssertion(e)||Q.isTSNonNullExpression(e))return pt(e.expression,t);if(Q.isLogicalExpression(e))return pt(e.right,t);if(Q.isConditionalExpression(e))return pt(e.consequent,t)??pt(e.alternate,t);if(Q.isCallExpression(e)||Q.isOptionalCallExpression(e))return Wu(e)?gb(e.arguments[0],t):null;if(Q.isArrayExpression(e))for(let n of e.elements){if(!n)continue;let r=pt(n,t);if(r)return r}return null}function Vu(e,t){for(let n of e){let r=pt(n,t);if(r)return r}return null}function gb(e,t){return!e||!Q.isArrowFunctionExpression(e)&&!Q.isFunctionExpression(e)?null:Q.isBlockStatement(e.body)?Ar(e.body.body,t):pt(e.body,t)}function Ar(e,t){for(let n of e){if(Q.isReturnStatement(n)){let r=pt(n.argument,t);if(r)return r;continue}if(Q.isBlockStatement(n)){let r=Ar(n.body,t);if(r)return r;continue}if(Q.isIfStatement(n)){let r=Ku(n.consequent,t);if(r)return r;let o=n.alternate?Ku(n.alternate,t):null;if(o)return o;continue}if(Q.isSwitchStatement(n))for(let r of n.cases){let o=Ar(r.consequent,t);if(o)return o}}return null}function Ku(e,t){return Q.isBlockStatement(e)?Ar(e.body,t):Ar([e],t)}function hb(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(Q.isFunctionDeclaration(n))return n.id?.name??"default"}if(t.isVariableDeclarator()&&Q.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 Uu=new WeakMap,Ju=new WeakMap,la=new WeakMap;function yb(e){let t=Uu.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=xb(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return Uu.set(e.node,o),o}function xb(e){let t=Hu(e.node.openingElement.name);return!t||Me(e)?null:/^[A-Z]/.test(t)?`component:${t}#${Xu(e,t)}`:`${t}#${Xu(e,t)}`}function Xu(e,t){let n=bb(e);if(!n)return 0;let r=la.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=la.get(n.node);o||(o=new Map,la.set(n.node,o));let i=o.get(t);i||(i=new WeakMap,o.set(t,i));let s=0;for(let a of wn(n))if(Hu(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 bb(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(Me(t)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function wn(e){let t=Ju.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(Me(o)){n.push(...wn(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...wn(o));continue}o.isJSXExpressionContainer()&&n.push(...Ft(o.get("expression")))}return Ju.set(e.node,n),n}function Ft(e){if(e.isJSXElement())return Me(e)?wn(e):[e];if(e.isJSXFragment())return wn(e);if(e.isParenthesizedExpression())return Ft(e.get("expression"));if(e.isLogicalExpression())return Ft(e.get("right"));if(e.isConditionalExpression())return[...Ft(e.get("consequent")),...Ft(e.get("alternate"))];if(e.isArrayExpression())return e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:Ft(t));if((e.isCallExpression()||e.isOptionalCallExpression())&&Wu(e.node)){let t=e.get("arguments"),n=Array.isArray(t)?t[0]:void 0;return n?Sb(n):[]}return[]}function Sb(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return Me(t)?wn(t):[t];if(t.isJSXFragment())return wn(t);if(t.isParenthesizedExpression())return Ft(t.get("expression"));if(t.isLogicalExpression()||t.isConditionalExpression())return Ft(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(...Ft(s))}if(!r.isReturnStatement())continue;let o=r.get("argument");return o.node&&n.push(...Ft(o)),n}return n}function Wu(e){let t=e.callee;return(Q.isMemberExpression(t)||Q.isOptionalMemberExpression(t))&&Q.isIdentifier(t.property)&&t.property.name==="map"&&!t.computed}function Eb(e,t){let n=zu(e,t);return n?Me(n):!1}function Hu(e){return Q.isJSXIdentifier(e)?e.name:Q.isJSXMemberExpression(e)?Gu(e):Q.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function Gu(e){return`${Q.isJSXIdentifier(e.object)?e.object.name:Gu(e.object)}.${e.property.name}`}function sn(e,t){if(t.parentPath===e&&t.listKey==="children"&&ua(e))return e;if(!t.parentPath||t.listKey!=="children")return null;let n=t.parentPath;if(!ua(n))return null;let r=n;for(;r&&r!==e;){if(!ua(r)||!Me(r)||r.listKey!=="children")return null;r=r.parentPath}return r===e?n:null}function ua(e){return e.isJSXElement()||e.isJSXFragment()}function Gn(e){let{source:t,locator:n,node:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=we(t,"jsx-node");if(!a.ok)return a.result;let c=se(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};if(!c.match.path.isJSXElement()&&!c.match.path.isJSXFragment())return J(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 v=c.match.path.node;if(!v.closingElement||v.openingElement.selfClosing)return J(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=qo(t,r.jsx);if(!u.ok)return u.result;let f=vb(u.node,!0),m=l.node.children,d={...s,targetParentLocator:n},g=v=>s?mt(v,a.ast,f,d):v;if(o==="append")return m.push(f),g(he(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return m.unshift(f),g(he(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(!i)return J(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let h=se(a.ast,i);if(!h.ok)return{ok:!1,source:t,diagnostic:h.diagnostic};let S=sn(c.match.path,h.match.path);if(!S)return J(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");l=S;let E=l.node.children,y=E.findIndex(v=>v===h.match.path.node);return y===-1?J(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(E.splice(o==="before"?y:y+1,0,f),g(he(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"})))}import*as Yu from"@babel/parser";import{cloneNode as kb}from"@babel/types";function ni(e){let{source:t,locator:n,expression:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=we(t,"jsx-node");if(!a.ok)return a.result;let c=Ib(t,r);if(!c.ok)return c.result;let l=se(a.ast,n);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return J(t,"unsupported-syntax","insert-jsx-expression-child target must be a JSXElement or JSXFragment","jsx-node");if(l.match.path.isJSXElement()){let E=l.match.path.node;if(!E.closingElement||E.openingElement.selfClosing)return J(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=l.match.path,f=null;if(i){let E=se(a.ast,i);if(!E.ok)return{ok:!1,source:t,diagnostic:E.diagnostic};let y=sn(l.match.path,E.match.path);if(!y)return J(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=y,f=E.match.path.node}else if(o==="before"||o==="after")return J(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let m=kb(c.node,!0),d=u.node.children,g={...s,targetParentLocator:n},h=E=>s?mt(E,a.ast,m,g):E;if(o==="append")return d.push(m),h(he(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return d.unshift(m),h(he(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));let S=d.findIndex(E=>E===f);return S===-1?J(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(d.splice(o==="before"?S:S+1,0,m),h(he(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"})))}function Ib(e,t){try{let r=Yu.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:J(e,"unsupported-syntax","Expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:J(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}import{cloneNode as Cb,nullLiteral as da}from"@babel/types";import*as an from"@babel/types";import*as Zu from"@babel/types";function Tr(e,t){let n=e.parentPath;if(!n?.isConditionalExpression()||e.key!=="consequent"||!Zu.isNullLiteral(n.node.alternate))return e;let r=n.parentPath;return!r?.isJSXExpressionContainer()||r.parentPath?.node!==t.node||r.listKey!=="children"?e:r}function Yn(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=we(t,"jsx-node");if(!a.ok)return a.result;let c=se(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};let l=se(a.ast,r);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return J(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 v=l.match.path.node;if(!v.closingElement||v.openingElement.selfClosing)return J(t,"self-closing-element","Cannot move child into self-closing element","jsx-node")}let f=null;if(i){let v=se(a.ast,i);if(!v.ok)return{ok:!1,source:t,diagnostic:v.diagnostic};let C=v.match.path.isJSXElement()?Tr(v.match.path,l.match.path):v.match.path,N=sn(l.match.path,C);if(!N)return J(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=N,f=C}else if(o==="before"||o==="after")return J(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let m=f&&typeof f.key=="number"?f.key:-1;if(f&&m===-1)return J(t,"locator-miss","Anchor node does not exist in target parent","jsx-node");let d=c.match.path.isJSXElement()?Tr(c.match.path,l.match.path):c.match.path,g=Cb(d.node,!0);if(!an.isJSXElement(g)&&!an.isJSXExpressionContainer(g)&&!an.isJSXFragment(g)&&!an.isJSXText(g))return J(t,"unsupported-syntax","move-node source must resolve to a JSX child","jsx-node");let h=d.parentPath?.node===u.node&&typeof d.key=="number"?d.key:-1;if(f&&d.parentPath?.node===f.parentPath?.node&&d.key===f.key)return J(t,"invalid-parent-child-relation","Cannot move a node relative to itself","jsx-node");Rb(d);let S=u.node.children,E={...s,sourceLocator:n,targetParentLocator:r};if(o==="append")return S.push(g),mt(Qo(a.ast,t),a.ast,g,E);if(o==="prepend")return S.unshift(g),mt(Qo(a.ast,t),a.ast,g,E);let y=m-(h!==-1&&h<m?1:0);return S.splice(o==="before"?y:y+1,0,g),mt(Qo(a.ast,t),a.ast,g,E)}function Rb(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(da());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(da());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(da());return}e.remove()}import*as Qu from"@babel/parser";import{cloneNode as wb,nullLiteral as fa}from"@babel/types";function ri(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,repeatExpression:s,selectionContext:a}=e,c=we(t,"jsx-node");if(!c.ok)return c.result;let l=Nb(t,s);if(!l.ok)return l.result;let u=se(c.ast,n);if(!u.ok)return{ok:!1,source:t,diagnostic:u.diagnostic};let f=se(c.ast,r);if(!f.ok)return{ok:!1,source:t,diagnostic:f.diagnostic};if(!f.match.path.isJSXElement()&&!f.match.path.isJSXFragment())return J(t,"unsupported-syntax","move-repeat-template-child target parent must be a JSXElement or JSXFragment","jsx-node");if(f.match.path.isJSXElement()){let v=f.match.path.node;if(!v.closingElement||v.openingElement.selfClosing)return J(t,"self-closing-element","Cannot move repeat child into self-closing element","jsx-node")}let m=f.match.path,d=null;if(i){let v=se(c.ast,i);if(!v.ok)return{ok:!1,source:t,diagnostic:v.diagnostic};let C=sn(f.match.path,v.match.path);if(!C)return J(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");m=C,d=v.match.path.node}else if(o==="before"||o==="after")return J(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");if(!u.match.path.isJSXElement())return J(t,"unsupported-syntax","move-repeat-template-child source must be a JSXElement","jsx-node");let g=m.node,h=wb(l.node,!0);Pb(u.match.path);let S={...a,sourceLocator:n,targetParentLocator:r},E=g.children;if(o==="append")return E.push(h),mt(he(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,h,S);if(o==="prepend")return E.unshift(h),mt(he(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,h,S);let y=E.findIndex(v=>v===d);return y===-1?J(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(E.splice(o==="before"?y:y+1,0,h),mt(he(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,h,S))}function Nb(e,t){try{let r=Qu.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:J(e,"unsupported-syntax","Repeat expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:J(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function Pb(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(fa());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(fa());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(fa());return}e.remove()}import{SiteEditSetPropsParamsSchema as Ab,classifySiteEditPropertyName as Tb}from"@vcp-dev/contracts";import*as Zn from"@babel/types";function oi(e){let t=Ab.safeParse({kind:"set-props",scope:"selection",changes:e.changes});if(!t.success)return J(e.source,"unsupported-syntax","Invalid typed JSX property changes","jsx-node",{issues:t.error.issues});let n=we(e.source,"jsx-node");if(!n.ok)return n.result;let r=Wn(n.ast,e.locator,e.source);if(!r.ok)return r.result;for(let a of t.data.changes){let c=Tb(a.name);if(c.owner!=="generic")return J(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(Zn.isJSXAttribute),s=new Map;for(let a of i){let c=Fb(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 J(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=Nr(a.name,a.value).value;c?c.value=l:o.attributes.push(Nr(a.name,a.value))}return he(n.ast,e.source,{kind:"set-props",target:"jsx-node",inverse:"set-props"})}function Fb(e){return Zn.isJSXIdentifier(e.name)?e.name.name:Zn.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:null}import{SiteEditOperationParamsSchema as _b}from"@vcp-dev/contracts";import*as z from"@babel/types";var qu=["prefetch","replace","scroll","locale","onNavigate"],Mb=/^on(?:Click|DoubleClick|AuxClick|MouseDown|MouseUp|PointerDown|PointerUp|TouchStart|TouchEnd|KeyDown|KeyUp|ContextMenu)(?:Capture)?$/;function Ob(e){let t=e;for(;t;){if(t.isJSXElement()&&t.node.openingElement.attributes.some(n=>z.isJSXAttribute(n)&&z.isJSXIdentifier(n.name)&&Mb.test(n.name.name)))return!0;t=t.parentPath}return!1}function ii(e){let t=we(e.source,"jsx-node");if(!t.ok)return t.result;let n=Wn(t.ast,e.locator,e.source);if(!n.ok)return n.result;let r=_b.safeParse({kind:"set-link-target",scope:"selection",link:e.link,changes:e.changes});if(!r.success||r.data.kind!=="set-link-target")return Wt(e.source,"Invalid typed link-target changes");let o=n.match.path,i=o.node,s=i.openingElement,a=Kb(s.name);if(!a)return Wt(e.source,"Unsupported JSX link tag");if(s.attributes.some(z.isJSXSpreadAttribute))return Wt(e.source,"Link elements with spread props cannot be transformed safely");let c=new Map;for(let g of s.attributes){if(!z.isJSXAttribute(g))continue;let h=ma(g);if(!h)return Wt(e.source,"Unsupported JSX attribute name");let S=c.get(h)??[];S.push(g),c.set(h,S)}if([...c.values()].some(g=>g.length>1))return Wt(e.source,"Duplicate JSX attributes cannot be transformed safely");let l=c.get("href")?.[0];if(l&&!Vb(l))return Wt(e.source,"Dynamic link href cannot be transformed safely");let u=a==="a",f=u?null:Bb(o,s.name);if(!u&&!f)return Wt(e.source,"Only native anchors and imported next/link components are supported");if(e.link.kind==="none"&&Ob(o))return Wt(e.source,"A link with an active event handler in its JSX ancestry cannot become an inert anchor");let m=null;if(e.link.kind==="internal-route")if(f)m=a;else{let g=jb(t.ast,o);if(!g.ok)return Wt(e.source,g.reason);m=g.localName}if(f&&e.link.kind!=="internal-route"){let g=z.jsxIdentifier("a");s.name=g,i.closingElement&&(i.closingElement.name=z.jsxIdentifier("a")),$b(t.ast,f,o)}else m&&u&&(s.name=z.jsxIdentifier(m),i.closingElement&&(i.closingElement.name=z.jsxIdentifier(m)));let d=new Set;return e.link.kind==="none"?(d.add("href"),d.add("target"),d.add("rel"),qu.forEach(g=>d.add(g))):(d.add("href"),e.link.kind==="native-link"&&qu.forEach(g=>d.add(g))),s.attributes=s.attributes.filter(g=>{if(!z.isJSXAttribute(g))return!0;let h=ma(g);return!h||!d.has(h)}),e.link.kind!=="none"&&s.attributes.push(z.jsxAttribute(z.jsxIdentifier("href"),z.stringLiteral(e.link.href))),Lb(s,e.changes),he(t.ast,e.source,{kind:"set-link-target",target:"jsx-node",inverse:"set-link-target"})}function Lb(e,t){for(let n of t){let r=e.attributes.find(s=>z.isJSXAttribute(s)&&ma(s)===n.name);if(n.operation==="remove"){e.attributes=e.attributes.filter(s=>s!==r);continue}let o=typeof n.value=="string"?z.stringLiteral(n.value):z.jsxExpressionContainer(pa(n.value)),i=z.jsxAttribute(z.jsxIdentifier(n.name),o);r&&z.isJSXAttribute(r)?r.value=i.value:e.attributes.push(i)}}function pa(e){return e===null?z.nullLiteral():typeof e=="string"?z.stringLiteral(e):typeof e=="number"?z.numericLiteral(e):typeof e=="boolean"?z.booleanLiteral(e):Array.isArray(e)?z.arrayExpression(e.map(t=>pa(t))):typeof e=="object"?z.objectExpression(Object.entries(e).map(([t,n])=>z.objectProperty(z.isValidIdentifier(t)?z.identifier(t):z.stringLiteral(t),pa(n)))):z.nullLiteral()}function Db(e){return z.isImportDefaultSpecifier(e)||z.isImportSpecifier(e)&&e.importKind!=="type"&&(z.isIdentifier(e.imported,{name:"default"})||z.isStringLiteral(e.imported,{value:"default"}))}function ed(e){return!e.parentPath?.isImportDeclaration()||e.parentPath.node.importKind==="type"?!1:e.isImportDefaultSpecifier()||e.isImportSpecifier()&&e.node.importKind!=="type"&&(z.isIdentifier(e.node.imported,{name:"default"})||z.isStringLiteral(e.node.imported,{value:"default"}))}function Bb(e,t){if(!z.isJSXIdentifier(t))return null;let n=e.scope.getBinding(t.name);if(!n||!ed(n.path))return null;let r=n.path.parentPath;return!r?.isImportDeclaration()||r.node.source.value!=="next/link"?null:t.name}function jb(e,t){let n=e.program.body.filter(c=>z.isImportDeclaration(c)&&c.source.value==="next/link"&&c.importKind!=="type"),r=n[0],o=n.flatMap(c=>c.specifiers).find(Db);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=z.importDefaultSpecifier(z.identifier(s));if(r)r.specifiers.unshift(a);else{let c=z.importDeclaration([a],z.stringLiteral("next/link")),l=0;for(;l<e.program.body.length&&z.isImportDeclaration(e.program.body[l]);)l+=1;e.program.body.splice(l,0,c)}return{ok:!0,localName:s}}function $b(e,t,n){let r=n.scope.getProgramParent();r.crawl();let o=r.getBinding(t);if(!o||!ed(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 Vb(e){return!e.value||z.isStringLiteral(e.value)}function Kb(e){return z.isJSXIdentifier(e)?e.name:null}function ma(e){return z.isJSXIdentifier(e.name)?e.name.name:null}function Wt(e,t){return J(e,"unsupported-syntax",t,"jsx-node")}import*as Ke from"@babel/types";import{classifySiteEditPropertyName as td}from"@vcp-dev/contracts";function si(e){let t=td(e.name),n=td(e.property);if(t.owner!=="generic"||n.owner!=="generic")return J(e.source,"unsupported-syntax","Property binding is only available for generic properties","jsx-node");if(!nd(e.object))return J(e.source,"unsupported-syntax","Property binding object must be a single identifier","jsx-node");if(e.property.length===0)return J(e.source,"unsupported-syntax","Property binding requires a non-empty property name","jsx-node");let r=we(e.source,"jsx-node");if(!r.ok)return r.result;let o=Wn(r.ast,e.locator,e.source);if(!o.ok)return o.result;let i=o.match.path.node.openingElement,s=i.attributes.filter(l=>Ke.isJSXAttribute(l)&&Jb(l)===e.name);if(s.length>1)return J(e.source,"unsupported-syntax",`JSX attribute '${e.name}' has multiple sources`,"jsx-node");let a=Ub(e.object,e.property),c=s[0];if(c)c.value=Ke.jsxExpressionContainer(a);else{let l=Nr(e.name,"");l.value=Ke.jsxExpressionContainer(a),i.attributes.push(l)}return he(r.ast,e.source,{kind:"set-property-binding",target:"jsx-node",inverse:"restore-property-binding"})}function Ub(e,t){return nd(t)?Ke.memberExpression(Ke.identifier(e),Ke.identifier(t)):Ke.memberExpression(Ke.identifier(e),Ke.stringLiteral(t),!0)}function nd(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(e)}function Jb(e){return Ke.isJSXIdentifier(e.name)?e.name.name:Ke.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:null}import{getBindingIdentifiers as zb,identifier as Fr,importDeclaration as Wb,importDefaultSpecifier as Hb,importNamespaceSpecifier as Gb,importSpecifier as Yb,isImportDefaultSpecifier as rd,isImportNamespaceSpecifier as od,isImportSpecifier as id,stringLiteral as Zb}from"@babel/types";function Qn(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(S=>!sS(S));if(o!==-1){let S=r[o],E=S&&typeof S=="object"&&"kind"in S?S.kind:void 0;return J(t,"unsupported-syntax",`Unsupported import spec kind: ${String(E)}`)}let i=rS(r);if(!i.ok)return J(t,"unsupported-syntax",i.message);let s=we(t);if(!s.ok)return s.result;let{ast:a}=s,c=a.program,l=c.body.filter(S=>S.type==="ImportDeclaration"&&S.source.value===n),u=new Set(l.flatMap(S=>S.specifiers.flatMap(E=>{let y=aS(S,E);return y?[y]:[]}))),f=i.imports.filter(S=>!u.has(dd(S)));if(f.length===0)return wr(t,t,{kind:"add-import",target:"import",inverse:"remove-import"});let m=oS(c.body),d=f.find(S=>m.has(ga(S)));if(d)return J(t,"unsupported-syntax",`Import local binding already exists: ${ga(d)}`);let g=nS(f);if(g.reduce((S,E)=>S+E.length,0)!==f.length)return J(t,"unsupported-syntax","Unsupported import specifier grouping");for(let S of g){if(!ld(ad(S)))return J(t,"unsupported-syntax","Unsupported import specifier combination");let E=l.find(y=>Qb(y,S));if(E)qb(E,S);else{let y=Wb(sd(S),Zb(n));iS(c.body,y),l.push(y)}}return he(a,t,{kind:"add-import",target:"import",inverse:"remove-import"})}function Qb(e,t){return e.importKind==="type"?!1:ld(tS(eS(e),ad(t)))}function qb(e,t){let n=!1,r=new Set(e.specifiers.map(o=>ha(o)));for(let o of sd(t)){let i=ha(o);r.has(i)||(e.specifiers.push(o),r.add(i),n=!0)}return ud(e.specifiers),{changed:n}}function sd(e){let t=e.map(n=>{switch(n.kind){case"named":return Yb(n.local?Fr(n.local):Fr(n.imported),Fr(n.imported));case"default":return Hb(Fr(n.local));case"namespace":return Gb(Fr(n.local));default:return n}});return ud(t),t}function ad(e){let t=cd();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 eS(e){let t=cd();for(let n of e.specifiers)rd(n)?t.defaultLocals.add(n.local.name):od(n)?t.namespaceLocals.add(n.local.name):t.hasNamed=!0;return t}function cd(){return{defaultLocals:new Set,hasNamed:!1,namespaceLocals:new Set}}function tS(e,t){return{defaultLocals:new Set([...e.defaultLocals,...t.defaultLocals]),hasNamed:e.hasNamed||t.hasNamed,namespaceLocals:new Set([...e.namespaceLocals,...t.namespaceLocals])}}function ld(e){return e.defaultLocals.size>1||e.namespaceLocals.size>1?!1:!(e.hasNamed&&e.namespaceLocals.size>0)}function ud(e){let t=[...e.filter(n=>rd(n)),...e.filter(n=>od(n)),...e.filter(n=>id(n))];e.splice(0,e.length,...t)}function nS(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 rS(e){let t=new Map,n=new Map;for(let r of e){let o=dd(r);if(t.has(o))continue;let i=ga(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 oS(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(zb(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 iS(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 sS(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 dd(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 ga(e){return e.kind==="named"?e.local??e.imported:e.local}function aS(e,t){return e.importKind==="type"||id(t)&&t.importKind==="type"?null:ha(t)}function ha(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 qn(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(u=>!lS(u));if(o!==-1){let u=r[o],f=u&&typeof u=="object"&&"kind"in u?u.kind:void 0;return J(t,"unsupported-syntax",`Unsupported remove import spec kind: ${String(f)}`)}let i=we(t);if(!i.ok)return i.result;let{ast:s}=i,a=s.program,c=a.body.findIndex(u=>u.type==="ImportDeclaration"&&u.source.value===n);if(c===-1)return wr(t,t,{kind:"remove-import",target:"import",inverse:"add-import"});let l=a.body[c];return r.length===0?(a.body.splice(c,1),he(s,t,{kind:"remove-import",target:"import",inverse:"add-import"})):(l.specifiers=l.specifiers.filter(u=>!r.some(f=>cS(u,f))),l.specifiers.length===0&&a.body.splice(c,1),he(s,t,{kind:"remove-import",target:"import",inverse:"add-import"}))}function cS(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 lS(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 _r(e){let{source:t,locator:n,next:r}=e,o=ui(t,n);return o.ok?(o.path.replaceWith(on(r)),he(o.ast,t,{kind:"update-value",target:"value",inverse:"restore-value"})):o.result}function ai(e){let{source:t,locator:n,index:r,value:o}=e,i=ui(t,n);return i.ok?i.path.isArrayExpression()?i.path.node.elements.some(s=>s?.type==="SpreadElement")?J(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>i.path.node.elements.length?J(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(i.path.node.elements.splice(r,0,on(o)),he(i.ast,t,{kind:"insert-array-element",target:"value",inverse:"remove-array-element"})):J(t,"unsupported-syntax","Array operations require array expression target","value"):i.result}function ci(e){let{source:t,locator:n,index:r}=e,o=ui(t,n);return o.ok?o.path.isArrayExpression()?o.path.node.elements.some(i=>i?.type==="SpreadElement")?J(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>=o.path.node.elements.length?J(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(o.path.node.elements.splice(r,1),he(o.ast,t,{kind:"remove-array-element",target:"value",inverse:"insert-array-element"})):J(t,"unsupported-syntax","Array operations require array expression target","value"):o.result}function li(e){let{source:t,locator:n,fromIndex:r,toIndex:o}=e,i=ui(t,n);if(!i.ok)return i.result;if(!i.path.isArrayExpression())return J(t,"unsupported-syntax","Array operations require array expression target","value");if(i.path.node.elements.some(c=>c?.type==="SpreadElement"))return J(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 J(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),he(i.ast,t,{kind:"move-array-element",target:"value",inverse:"move-array-element-back"})}function ui(e,t){let n=we(e,"value");if(!n.ok)return{ok:!1,result:n.result};let r=se(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 Xe from"@babel/types";function di(e){let t=we(e.source,"value");if(!t.ok)return t.result;let n=se(t.ast,e.objectLocator);if(!n.ok)return{ok:!1,source:e.source,diagnostic:n.diagnostic};if(!n.match.path.isObjectExpression())return J(e.source,"unsupported-syntax","Object property upsert requires an ObjectExpression parent","value");let r=n.match.path.node;if(r.properties.some(a=>Xe.isSpreadElement(a)||Xe.isObjectProperty(a)&&a.computed))return J(e.source,"unsupported-syntax","Object property upsert does not support spreads or computed keys","value");let o=r.properties.filter(a=>Xe.isObjectProperty(a)&&uS(a.key)===e.name);if(o.length>1)return J(e.source,"unsupported-syntax",`Object property '${e.name}' has multiple sources`,"value");let i=e.value.kind==="undefined"?Xe.unaryExpression("void",Xe.numericLiteral(0)):on(e.value.value),s=o[0];if(s)s.value=i,s.shorthand=!1;else{let a=Xe.objectProperty(sa(e.name),i);e.name==="__proto__"&&(a.computed=!0),r.properties.push(a)}return he(t.ast,e.source,{kind:"upsert-object-property",target:"value",inverse:"restore-object-property"})}function uS(e){return Xe.isIdentifier(e)?e.name:Xe.isStringLiteral(e)?e.value:Xe.isNumericLiteral(e)?String(e.value):null}import{isSiteEditRuntimeContainerTag as dS,isSiteEditRuntimeVoidElementTag as fS}from"@vcp-dev/contracts/site-edit-runtime-capability";function er(e){if(!e.composition)throw new Error("Composition unavailable for render source graph.");return e.composition}function pS(e,t,n){let r=er(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(C=>({kind:C.kind,message:C.reason})),a=i.isOpaque,l=o.parentKey===null&&i.componentName==="Page",u=i.tag.toLowerCase(),f=i.tag!==u,m=!f&&fS(u),d=f||dS(u),g=f&&i.childKeys.length>0&&!i.isPublicUiComponent,h=i.textSegments.length>0&&i.textSegments.some(C=>C.editable);m&&!s.some(C=>C.kind==="void-element")&&s.push({kind:"void-element",message:`Element '${i.tag}' is void: children cannot be inserted`}),!m&&!d&&!s.some(C=>C.kind==="void-element")&&s.push({kind:"void-element",message:`Element '${i.tag}' cannot contain structured children`});let S=h&&(!a||i.importedFrom==="next/link"),E=!i.isPublicUiComponent&&!m&&d&&(!a||g);return{composition:r,key:e,canUpdateText:S,canInsertChild:E,canMove:!l,canRemove:!l,constraints:s}}function fd(e,t){let n=new Map;for(let r of e.nodes.keys())n.set(r,pS(r,e,t));return n}function ya(e){let t=e.route.graph.elements.get(e.key);if(!t)return{key:e.key,composition:e.route.composition,filePath:"",componentName:"",sourceKind:"missing",attrRaw:null,valueRaw:null,attrRange:null,openingElementRange:{start:0,end:0},version:{documentVersion:e.route.graph.version,contentHash:ke(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Key not found: ${e.key}`}]};let n=mS(e.route.source,t);if(!n)return{key:e.key,composition:e.route.composition,filePath:t.sourceFile,componentName:t.componentName,sourceKind:"missing",attrRaw:null,valueRaw:null,attrRange:null,openingElementRange:{start:0,end:0},version:{documentVersion:e.route.graph.version,contentHash:ke(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Unable to locate JSX element for key ${t.identity.key}`}]};let r=n.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:md(r),version:{documentVersion:e.route.graph.version,contentHash:ke(e.route.source)}};if(!o)return{...i,sourceKind:"missing",attrRaw:null,valueRaw:null,attrRange:null,diagnostics:[{code:"missing-class-name",message:"No className attribute is present on this element."}]};let s=o.value,a=s?.type==="StringLiteral"?"stringLiteral":"expression";return{...i,sourceKind:a,attrRaw:pd(e.route.source,o),valueRaw:s?pd(e.route.source,s):null,attrRange:md(o),diagnostics:[]}}function gd(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 mS(e,t){let n=Pt({source:e,profile:vn({filePath:t.sourceFile,source:e})});if(!n.ok)return null;let r=se(n.ast,{kind:"jsx-node",strategy:"structural-path",file:t.identity.file,component:t.identity.component,structuralPath:t.identity.structuralPath,expectedRange:gS(t.sourceRange)});return!r.ok||r.match.node.type!=="JSXElement"?null:r.match.node}function hd(e){let t=Pt({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 pd(e,t){return t.start==null||t.end==null?"":e.slice(t.start,t.end)}function md(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 gS(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function yd(){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 hS}from"node:crypto";import fi from"node:fs/promises";import xa from"node:path";import{setTimeout as yS}from"node:timers/promises";var xS={async mkdir(e,t){await fi.mkdir(e,t)},async writeFile(e,t,n){await fi.writeFile(e,t,n)},async rename(e,t){await fi.rename(e,t)},async rm(e,t){await fi.rm(e,t)}},bS=new Set(["EACCES","EBUSY","EPERM"]),SS=[10,20,40,80,160];async function ES(e,t,n){for(let r of SS)try{await e.rename(t,n);return}catch(o){if(!vS(o))throw o;await yS(r)}await e.rename(t,n)}function vS(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&bS.has(e.code)}async function pi(e,t,n=xS){let r=xa.dirname(e),o=xa.basename(e),i=xa.join(r,`.${o}.${process.pid}.${hS()}.tmp`),s=!1;try{await n.mkdir(r,{recursive:!0}),await n.writeFile(i,t,"utf8"),await ES(n,i,e),s=!0}finally{if(!s)try{await n.rm(i,{force:!0})}catch{}}}import ba from"@babel/traverse";import*as k from"@babel/types";import*as fe from"@babel/types";function _t(e,t={}){if(fe.isTSAsExpression(e)||fe.isTSSatisfiesExpression(e)||fe.isTSNonNullExpression(e)||fe.isTypeCastExpression(e)||fe.isParenthesizedExpression(e))return _t(e.expression,t);if(fe.isStringLiteral(e))return{status:"resolved",value:e.value};if(fe.isNumericLiteral(e))return Number.isFinite(e.value)?{status:"resolved",value:e.value}:{status:"unresolved"};if(fe.isBooleanLiteral(e))return{status:"resolved",value:e.value};if(fe.isNullLiteral(e))return{status:"resolved",value:null};if(fe.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(fe.isIdentifier(e))return e.name==="undefined"&&!t.resolveIdentifier?{status:"undefined"}:t.resolveIdentifier?.(e.name)??{status:"unresolved"};if(fe.isUnaryExpression(e)&&e.operator==="void"&&fe.isNumericLiteral(e.argument)&&e.argument.value===0)return{status:"undefined"};if(fe.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||fe.isSpreadElement(r))return{status:"unresolved"};let o=_t(r,t);if(o.status!=="resolved")return{status:"unresolved"};n.push(o.value)}return{status:"resolved",value:n}}if(fe.isObjectExpression(e)){let n=Object.create(null);for(let r of e.properties){if(!fe.isObjectProperty(r)||r.computed||!fe.isExpression(r.value))return{status:"unresolved"};let o=kS(r.key);if(o===null)return{status:"unresolved"};let i=_t(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 fe.isMemberExpression(e)||fe.isOptionalMemberExpression(e)?t.resolveMember?.(e)??{status:"unresolved"}:{status:"unresolved"}}function kS(e){return fe.isIdentifier(e)?e.name:fe.isStringLiteral(e)?e.value:fe.isNumericLiteral(e)?String(e.value):null}var IS=typeof ba=="function"?ba:ba.default;function Ye(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 CS(e){return/^[A-Z]/.test(e)}function Ia(e){let t=e.openingElement;return k.isJSXIdentifier(t.name)?t.name.name==="Fragment":k.isJSXMemberExpression(t.name)?t.name.property.name==="Fragment":!1}function nr(e){return k.isJSXFragment(e)}function bd(e){return k.isJSXIdentifier(e.name)?e.name.name:k.isJSXMemberExpression(e.name)?Sd(e.name):k.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:"unknown"}function Sd(e){return k.isJSXIdentifier(e.object)?`${e.object.name}.${e.property.name}`:k.isJSXMemberExpression(e.object)?`${Sd(e.object)}.${e.property.name}`:e.property.name}function RS(e){return e.split(".")[0]??e}function wS(e){let t=e;for(;t;){let n=t.node;if(k.isFunctionDeclaration(n)&&n.id||k.isVariableDeclarator(n)&&k.isIdentifier(n.id))return n.id.name;if(k.isExportDefaultDeclaration(n)){let r=n.declaration;if(k.isFunctionDeclaration(r)&&r.id)return r.id.name;if(k.isFunctionDeclaration(r)&&!r.id)return"default"}t=t.parentPath}return null}function NS(){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 PS(e){let t=new Map;for(let n of e.program.body){if(!k.isImportDeclaration(n))continue;let r=n.source.value;for(let o of n.specifiers)if(k.isImportDefaultSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"default"});else if(k.isImportNamespaceSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"*"});else if(k.isImportSpecifier(o)){let i=k.isIdentifier(o.imported)?o.imported.name:o.imported.value;t.set(o.local.name,{specifier:r,exportName:i})}}return t}function Ht(e,t=[]){if(k.isIdentifier(e))return t.push(e.name),t;if(k.isObjectPattern(e)){for(let n of e.properties)k.isObjectProperty(n)?Ht(n.value,t):k.isRestElement(n)&&Ht(n.argument,t);return t}if(k.isArrayPattern(e)){for(let n of e.elements)n&&(k.isRestElement(n)?Ht(n.argument,t):Ht(n,t));return t}return k.isAssignmentPattern(e)?(Ht(e.left,t),t):(k.isRestElement(e)&&Ht(e.argument,t),t)}function Et(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function Mr(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 AS(e,t,n){e.set(t,{resolved:!0,value:n})}function Ca(e,t){e.set(t,{resolved:!1})}function Ed(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 $e(e,t,n){if(k.isTSAsExpression(e)||k.isTSSatisfiesExpression(e)||k.isTSNonNullExpression(e)||k.isTypeCastExpression(e)||k.isParenthesizedExpression(e))return $e(e.expression,t,n);if(k.isLogicalExpression(e))return mi([$e(e.left,t,n),$e(e.right,t,n)]);if(k.isBinaryExpression(e))return mi([k.isExpression(e.left)?$e(e.left,t,n):null,k.isExpression(e.right)?$e(e.right,t,n):null]);if(k.isConditionalExpression(e))return mi([$e(e.consequent,t,n),$e(e.alternate,t,n)]);if(k.isTemplateLiteral(e))return mi(e.expressions.filter(k.isExpression).map(i=>$e(i,t,n)));if(k.isIdentifier(e))return{kind:"identifier",expression:e.name,base:e.name,path:[]};if(!k.isMemberExpression(e)&&!k.isOptionalMemberExpression(e))return null;let r=[],o=e;for(;k.isMemberExpression(o)||k.isOptionalMemberExpression(o);){if(o.computed)if(k.isNumericLiteral(o.property))r.unshift({kind:"index",index:o.property.value});else if(k.isStringLiteral(o.property))r.unshift({kind:"property",name:o.property.value});else if(n&&k.isExpression(o.property)){let i=cn(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(!k.isIdentifier(o.property))return null;r.unshift({kind:"property",name:o.property.name})}o=o.object}return k.isIdentifier(o)?{kind:r.some(i=>i.kind==="index")?"index-expression":"member-expression",expression:Et(e,t),base:o.name,path:r}:null}function mi(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 cn(e,t){if(k.isStringLiteral(e)||k.isNumericLiteral(e)||k.isBooleanLiteral(e))return e.value;if(k.isNullLiteral(e))return null;if(k.isTemplateLiteral(e))return e.expressions.length===0&&e.quasis.length===1?e.quasis[0].value.cooked??e.quasis[0].value.raw:void 0;if(k.isIdentifier(e)){let n=Mr(e.name,t.valueScopes);return n.kind==="resolved"?n.value:void 0}if(k.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||k.isSpreadElement(r))return;let o=cn(r,t);if(o===void 0)return;n.push(o)}return n}if(k.isObjectExpression(e)){let n={};for(let r of e.properties){if(!k.isObjectProperty(r)||r.computed||!k.isExpression(r.value))return;let o=null;if(k.isIdentifier(r.key)?o=r.key.name:k.isStringLiteral(r.key)&&(o=r.key.value),!o)return;let i;if(r.shorthand){if(!k.isIdentifier(r.value))return;let s=Mr(r.value.name,t.valueScopes);if(s.kind!=="resolved")return;i=s.value}else i=cn(r.value,t);if(i===void 0)return;n[o]=i}return n}if(k.isMemberExpression(e)){let n=$e(e,"",t);if(!n)return;let r=Mr(n.base,t.valueScopes);if(r.kind!=="resolved")return;let o=Ed(r.value,n.path);return o.kind==="resolved"?o.value:void 0}if(k.isCallExpression(e))return kd(e,t)??void 0}function vd(e,t,n){let r=$e(e,n,t);if(!r)return k.isMemberExpression(e)||k.isBinaryExpression(e)||k.isLogicalExpression(e)||k.isConditionalExpression(e)||k.isCallExpression(e)?{value:Et(e,n),source:null}:null;let o=Mr(r.base,t.valueScopes),i=r.kind==="identifier"?o:o.kind==="resolved"?Ed(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 Sa(e,t,n,r,o,i){return{file:e,componentName:t,elements:n,regions:r,ordinalTracker:NS(),parentStack:[],valueScopes:i,importMap:o}}function va(e,t,n){for(let r of e)for(let o of r.declarations){for(let s of Ht(o.id))Ca(n,s);if(!k.isIdentifier(o.id)||!o.init||!k.isExpression(o.init))continue;let i=cn(o.init,t);i!==void 0&&AS(n,o.id.name,i)}}function TS(e){let t=[];for(let n of e){if(k.isVariableDeclaration(n)){t.push(n);continue}k.isExportNamedDeclaration(n)&&n.declaration&&k.isVariableDeclaration(n.declaration)&&t.push(n.declaration)}return t}function FS(e,t,n){let r=[],o=0;for(let i of e)if(k.isJSXText(i)){let s=i.value.trim();s&&r.push({index:o++,value:s,sourceRange:Ye(i),editable:!0,source:null})}else if(k.isJSXExpressionContainer(i)&&k.isStringLiteral(i.expression))r.push({index:o++,value:i.expression.value,sourceRange:Ye(i),editable:!0,source:null});else if(k.isJSXExpressionContainer(i)&&k.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:Ye(i),editable:!0,source:null}):r.push({index:o++,value:Et(s,n),sourceRange:Ye(i),editable:!0,source:$e(s,n,t)})}else if(k.isJSXExpressionContainer(i)&&k.isExpression(i.expression)){let s=vd(i.expression,t,n);s&&r.push({index:o++,value:s.value,sourceRange:Ye(i),editable:!0,source:s.source})}return r}function _S(e,t,n){let r=[];for(let[o,i]of e.attributes.entries()){if(!k.isJSXAttribute(i))continue;let s=OS(i.name);if(!s)continue;let a=Et(i,n);if(k.isStringLiteral(i.value)){r.push({name:s,value:i.value.value,sourceRange:Ye(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:Ye(i),source:null,syntaxKind:"boolean-shorthand",raw:a,order:o,resolution:{status:"resolved",value:!0},resolvedValue:!0});continue}if(k.isJSXExpressionContainer(i.value)&&k.isExpression(i.value.expression)){let c=cn(i.value.expression,t);if(s==="className"){let d=typeof c=="string"?c:c===void 0?kd(i.value.expression,t):null;if(d){r.push({name:s,value:d,sourceRange:Ye(i),source:null,resolvedValue:d,syntaxKind:"expression",raw:a,order:o,resolution:{status:"resolved",value:d}});continue}}let l=vd(i.value.expression,t,n);if(c!==void 0){r.push({name:s,value:KS(c),sourceRange:Ye(i),source:$e(i.value.expression,n,t),resolvedValue:c,syntaxKind:"expression",raw:a,order:o,resolution:{status:"resolved",value:c}});continue}let u=LS(i.value.expression,t),f=$e(i.value.expression,n,t),m=l?.value??Et(i.value.expression,n);r.push({name:s,value:u.status==="undefined"?"undefined":m,sourceRange:Ye(i),source:l?.source??f,syntaxKind:"expression",raw:a,order:o,resolution:u})}}return r}function MS(e,t,n){return e.attributes.flatMap((r,o)=>!k.isJSXSpreadAttribute(r)||!k.isExpression(r.argument)?[]:[{raw:Et(r.argument,n),sourceRange:Ye(r),order:o,source:$e(r.argument,n,t)}])}function OS(e){return k.isJSXIdentifier(e)?e.name:k.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function LS(e,t){return _t(e,{resolveIdentifier(n){let r=Mr(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=cn(n,t);return r===void 0?{status:"unresolved"}:{status:"resolved",value:r}}})}function kd(e,t){let n=tr(e,t);return n&&n.map(o=>o.trim()).filter(Boolean).join(" ")||null}function tr(e,t){if(k.isStringLiteral(e))return[e.value];if(k.isTemplateLiteral(e))return e.expressions.length>0?null:[e.quasis.map(n=>n.value.cooked??"").join("")];if(k.isNullLiteral(e))return[];if(k.isBooleanLiteral(e))return e.value?null:[];if(k.isIdentifier(e)||k.isMemberExpression(e)){if(k.isIdentifier(e)&&e.name==="undefined")return[];let n=cn(e,t);return typeof n=="string"?[n]:null}if(k.isConditionalExpression(e)){let n=tr(e.consequent,t),r=tr(e.alternate,t);return!n||!r?null:[...n,...r]}if(k.isLogicalExpression(e)){if(e.operator!=="&&")return null;let n=cn(e.left,t);return n===!1||n===null?[]:tr(e.right,t)}if(k.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||k.isSpreadElement(r))return null;let o=tr(r,t);if(!o)return null;n.push(...o)}return n}if(k.isObjectExpression(e)){let n=[];for(let r of e.properties){if(!k.isObjectProperty(r))return null;let o=BS(r.key);if(!o)return null;n.push(o)}return n}if(k.isCallExpression(e)){let n=DS(e.callee);if(!n||!["cn","clsx","twMerge"].includes(n))return null;let r=[];for(let o of e.arguments){if(!k.isExpression(o))return null;let i=tr(o,t);if(!i)return null;r.push(...i)}return r}return null}function DS(e){return k.isIdentifier(e)?e.name:k.isMemberExpression(e)&&k.isIdentifier(e.property)?e.property.name:null}function BS(e){return k.isIdentifier(e)?e.name:k.isStringLiteral(e)?e.value:null}function jS(e,t){let n=e.attributes.find(r=>k.isJSXAttribute(r)&&k.isJSXIdentifier(r.name)&&r.name.name===t);return!n||!k.isJSXAttribute(n)||!k.isJSXExpressionContainer(n.value)?null:n.value.expression}function $S(e,t){for(let n of t){let r=jS(e,n);if(r)return r}return null}function VS(e){return k.isJSXIdentifier(e.name)?e.name.name:null}function KS(e){return e===null?"null":typeof e=="boolean"?e?"true":"false":JSON.stringify(e)}function US(e){if(!k.isCallExpression(e)&&!k.isOptionalCallExpression(e))return null;let t=e.callee;return!k.isMemberExpression(t)&&!k.isOptionalMemberExpression(t)||!k.isIdentifier(t.property)||t.property.name!=="map"||t.computed||!k.isExpression(t.object)?null:{call:e,collection:t.object,callback:e.arguments[0]}}function Ea(e){return k.isArrowFunctionExpression(e)||k.isFunctionExpression(e)}function JS(e){return e==="render"||e==="itemRender"||e==="rowRender"||e==="children"}function XS(e){return e==="empty"||e==="emptyRender"||e==="loading"||e==="loadingRender"||e==="error"||e==="errorRender"||e==="fallback"||e==="headerRender"||e==="footerRender"}function xd(e,t,n,r){if(!e||!k.isExpression(e))return null;let o={kind:"repeat-template",collectionExpression:Et(e,n),collectionSource:$e(e,n,r)};if(t){let i=t.params[0],s=t.params[1];k.isIdentifier(i)&&(o.itemParamName=i.name),k.isIdentifier(s)&&(o.indexParamName=s.name)}return o}function Gt(e,t,n){if(!e)return[];if(k.isJSXElement(e)){if(Ia(e))return bi(e.children,t,n);let r=yi(e,t,n);return r?[r]:[]}return nr(e)?xi(e,t,n):k.isParenthesizedExpression(e)?Gt(e.expression,t,n):k.isExpression(e)?Si(e,t,n):[]}function gi(e,t,n){let r=new Map;for(let o of e.params)for(let i of Ht(o))Ca(r,i);t.valueScopes.push(r);try{if(!k.isBlockStatement(e.body))return Gt(e.body,t,n);let o=new Map;t.valueScopes.push(o);try{return Id(e.body.body,t,n)}finally{t.valueScopes.pop()}}finally{t.valueScopes.pop()}}function Id(e,t,n){let r=[];for(let o of e){if(k.isVariableDeclaration(o)){let i=t.valueScopes[t.valueScopes.length-1];if(i){va([o],t,i);for(let s of o.declarations)k.isIdentifier(s.id)&&(k.isJSXElement(s.init)||k.isJSXFragment(s.init))&&r.push(...Gt(s.init,t,n))}continue}r.push(...ka(o,t,n))}return r}function ka(e,t,n){if(k.isReturnStatement(e))return e.argument?Gt(e.argument,t,n):[];if(k.isBlockStatement(e))return Nn(e.body,t,n);if(k.isIfStatement(e)){let r=k.isBlockStatement(e.consequent)?Nn(e.consequent.body,t,n):ka(e.consequent,t,n),o=e.alternate?k.isBlockStatement(e.alternate)?Nn(e.alternate.body,t,n):ka(e.alternate,t,n):[];return[...r,...o]}if(k.isSwitchStatement(e))return Nn(e.cases.flatMap(r=>r.consequent),t,n);if(k.isTryStatement(e)){let r=Nn(e.block.body,t,n);return e.handler&&r.push(...Nn(e.handler.body.body,t,n)),e.finalizer&&r.push(...Nn(e.finalizer.body,t,n)),r}return[]}function Nn(e,t,n){let r=new Map;t.valueScopes.push(r);try{return Id(e,t,n)}finally{t.valueScopes.pop()}}function hi(e,t,n,r,o,i){o.length!==0&&e.regions.push({kind:t,ownerKey:n,childKeys:o,sourceRange:Ye(r),sourceCandidates:i&&i.length>0?i:void 0})}function zS(e,t,n,r){let o=$S(e.openingElement,["items","dataSource","data"]),i={key:t,tag:bd(e.openingElement)};n.parentStack.push(i);try{for(let s of e.openingElement.attributes){if(!k.isJSXAttribute(s))continue;let a=VS(s);if(!a||!k.isJSXExpressionContainer(s.value))continue;let c=s.value.expression;if(!k.isJSXEmptyExpression(c)){if(JS(a)&&Ea(c)){let l=gi(c,n,r),u=xd(o,c,r,n);hi(n,"repeat-region",t,s,l,u?[u]:void 0);continue}if(XS(a)){let l=Ea(c)?gi(c,n,r):Gt(c,n,r);hi(n,"conditional-region",t,s,l)}}}if(o)for(let s of e.children){if(!k.isJSXExpressionContainer(s)||!Ea(s.expression))continue;let a=gi(s.expression,n,r),c=xd(o,s.expression,r,n);hi(n,"repeat-region",t,s,a,c?[c]:void 0)}}finally{n.parentStack.pop()}}function yi(e,t,n){let r=bd(e.openingElement);if(r==="Fragment"||Ia(e))return bi(e.children,t,n),null;let o=t.parentStack[t.parentStack.length-1]??null,i=o?.key??null,s=CS(r),a;if(s){let C=t.ordinalTracker.getOrdinal(i,r);a=`component:${r}#${C}`}else{let C=t.ordinalTracker.getOrdinal(i,r);a=`${r}#${C}`}let c=o?t.elements.get(o.key)?.identity.structuralPath:void 0,l=c?`${c}/${a}`:a,u=Pr(t.file,t.componentName,l),f={file:t.file,component:t.componentName,structuralPath:l,key:u},m=s?"component-boundary":null,d=FS(e.children,t,n),g=_S(e.openingElement,t,n),h=MS(e.openingElement,t,n),S,E,y=!1;if(s){let C=t.importMap.get(r)??t.importMap.get(RS(r));C&&(S=C.specifier,E=C.exportName,y=kn(C.specifier,t.file))}let v={identity:f,tag:r,componentName:t.componentName,sourceFile:t.file,sourceRange:Ye(e),parentKey:i,childKeys:[],textSegments:d,attributes:g.length>0?g:void 0,attributeSpreads:h.length>0?h:void 0,boundaryKind:m,isOpaque:s,...y?{isPublicUiComponent:!0}:{},importedFrom:S,exportName:E};return t.elements.set(u,v),i&&t.elements.has(i)&&t.elements.get(i).childKeys.push(u),zS(e,u,t,n),(!s||e.children.length>0)&&(t.parentStack.push({key:u,tag:r}),WS(e.children,t,n),t.parentStack.pop()),u}function xi(e,t,n){return bi(e.children,t,n)}function bi(e,t,n){let r=[];for(let o of e)if(k.isJSXElement(o))if(Ia(o))r.push(...bi(o.children,t,n));else{let i=yi(o,t,n);i&&r.push(i)}else nr(o)?r.push(...xi(o,t,n)):k.isJSXExpressionContainer(o)&&r.push(...Si(o.expression,t,n));return r}function WS(e,t,n){for(let r of e)k.isJSXElement(r)?yi(r,t,n):nr(r)?xi(r,t,n):k.isJSXExpressionContainer(r)&&Si(r.expression,t,n)}function HS(e){return e==="&&"||e==="||"||e==="??"}function Si(e,t,n){if(k.isJSXEmptyExpression(e))return[];let r=US(e);if(r){let o=r.call,i=t.parentStack[t.parentStack.length-1]??null,s=[],a=r.callback,c={kind:"repeat-template",collectionExpression:Et(r.collection,n),collectionSource:$e(r.collection,n,t)};if(k.isArrowFunctionExpression(a)||k.isFunctionExpression(a)){let u=a.params[0],f=a.params[1];k.isIdentifier(u)&&(c.itemParamName=u.name),k.isIdentifier(f)&&(c.indexParamName=f.name)}s.push(c);let l={kind:"repeat-region",ownerKey:i?.key??"",childKeys:[],sourceRange:Ye(o),sourceCandidates:s.length>0?s:void 0};return t.regions.push(l),(k.isArrowFunctionExpression(a)||k.isFunctionExpression(a))&&l.childKeys.push(...gi(a,t,n)),l.childKeys}if(k.isConditionalExpression(e)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:Et(e.test,n),conditionSource:$e(e.test,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:Ye(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...Gt(e.consequent,t,n)),s.childKeys.push(...Gt(e.alternate,t,n)),s.childKeys}if(k.isLogicalExpression(e)&&HS(e.operator)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:Et(e.left,n),conditionSource:$e(e.left,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:Ye(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...Gt(e.right,t,n)),s.childKeys}if(k.isParenthesizedExpression(e))return Si(e.expression,t,n);if(k.isJSXElement(e)){let o=yi(e,t,n);return o?[o]:[]}return nr(e)?xi(e,t,n):[]}function GS(e){let t=e.argument;return t&&(k.isExpression(t)||nr(t))?t:null}function Or(e,t){let n=[];for(let r of e){if(k.isReturnStatement(r)){let o=GS(r);o&&n.push({argument:o,statement:r,condition:t});continue}if(k.isIfStatement(r)){let o=k.isBlockStatement(r.consequent)?r.consequent.body:[r.consequent];if(n.push(...Or(o,r.test)),r.alternate){let i=k.isBlockStatement(r.alternate)?r.alternate.body:[r.alternate];n.push(...Or(i,r.test))}continue}if(k.isSwitchStatement(r))for(let o of r.cases){let i=o.test?k.binaryExpression("===",r.discriminant,o.test):r.discriminant;n.push(...Or(o.consequent,i))}}return n}function Cd(e){return{routeId:e,rootKeys:[],elements:new Map,regions:[],fileIndex:new Map,version:1,diagnostics:[]}}function Rd(e){let{file:t,source:n,ast:r}=e,o=e.imports.map(f=>f.specifier),i=new Map,s=[],a=[],c=new Map,l=PS(r);IS(r,{"FunctionDeclaration|FunctionExpression|ArrowFunctionExpression"(f){let m=wS(f);if(!m)return;let d=f.node,g=[];if(k.isArrowFunctionExpression(d))k.isExpression(d.body)||nr(d.body)?g=[{argument:d.body,statement:k.returnStatement(k.isExpression(d.body)?d.body:null)}]:k.isBlockStatement(d.body)&&(g=Or(d.body.body));else{let C=d.body;k.isBlockStatement(C)&&(g=Or(C.body))}if(g.length===0){f.skip();return}let h=new Map;va(TS(r.program.body),Sa(t,m,i,s,l,[h]),h);let S=new Map;for(let C of d.params)for(let N of Ht(C))Ca(S,N);let E=k.isBlockStatement(d.body)?d.body.body:[],y=g[0]?.statement??null;for(let C of E){if(y&&C===y)break;k.isVariableDeclaration(C)&&va([C],Sa(t,m,i,s,l,[h,S]),S)}let v=Sa(t,m,i,s,l,[h,S]);for(let C of g){let N=Gt(C.argument,v,n);for(let A of N)a.includes(A)||a.push(A);if(C.condition){let A={kind:"conditional-branch",conditionExpression:Et(C.condition,n),conditionSource:$e(C.condition,n,v)};hi(v,"conditional-region","",C.statement,N,[A])}}f.skip()}});let u=[...i.keys()];return u.length>0&&c.set(t,u),{graph:{routeId:t,rootKeys:a,elements:i,regions:s,fileIndex:c,version:1,diagnostics:[]},localImports:o}}function Ra(e,t,n,r){return[...e.map(o=>({...o})),{fromFile:t,specifier:n,targetPath:r}]}function Ei(e,t,n){return{...e,details:{...e.details??{},entryFile:t,importStack:n.map(r=>({...r}))}}}async function YS(e,t){if(e.length===0)return[];if(e.length===1)return[await t(e[0])];let n=new Array(e.length),r=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 wd(e,t,n,r,o={}){let i=o.maxDepth??10,s=o.version??1,a=o.parseModule??Ut,c=new Map,l=new Map,u=new Map,f=[],m=new Set,d=E=>{let y=`${E.path}\0${E.code}\0${E.message}\0${JSON.stringify(E.details??{})}`;m.has(y)||(m.add(y),f.push(E))},g=[{file:e,source:t,depth:0,diagnosticEntryFile:e,importStack:[]},...(o.additionalEntries??[]).map(E=>({file:E.file,source:E.source,depth:0,diagnosticEntryFile:E.file,importStack:[]}))],h=new Set;for(;g.length>0;){let E=g.shift(),{file:y,source:v,depth:C,diagnosticEntryFile:N,importStack:A}=E;if(h.has(y))continue;h.add(y),c.set(y,v);let R=a(y,v);if(!R.ok){d(Ei(R.diagnostic,N,A));continue}u.set(y,R.module);let{graph:F,localImports:_}=o.validationOnly&&C<i?{graph:Cd(y),localImports:R.module.imports.map(L=>L.specifier)}:Rd(R.module);for(let L of F.elements.values())if(L.importedFrom&&Nt(L.importedFrom)){let oe=L.importedFrom,me=await Oo(y,oe,r);me.ok?(L.importedFrom=me.path,Jt(me.path)&&(L.isPublicUiComponent=!0)):kn(oe,y)||d(Ei(me.diagnostic,N,Ra(A,y,oe,me.diagnostic.path)))}if(l.set(y,F),C>=i)continue;let D=await YS(_,async L=>{if(au(L))return null;let oe=await Oo(y,L,r);if(!oe.ok)return kn(L,y)?null:{diagnostic:Ei(oe.diagnostic,N,Ra(A,y,L,oe.diagnostic.path))};let me=oe.path;if(h.has(me)||Jt(me))return null;let ee=Ra(A,y,L,me);try{let ce=await n(me);return{entry:{file:me,source:ce,depth:C+1,diagnosticEntryFile:N,importStack:ee}}}catch(ce){return{diagnostic:Ei({path:me,code:"import-read-failed",message:`Failed to read imported file: ${me}`,details:{fromFile:y,specifier:L,reason:ce instanceof Error?ce.message:String(ce)}},N,ee)}}});for(let L of D)L&&"entry"in L?g.push(L.entry):L&&d(L.diagnostic)}let S=ZS(e,l,s,(o.additionalEntries??[]).map(E=>E.file));return S.diagnostics=f,{graph:S,allSources:c,diagnostics:f,parsedModules:u,entryModule:u.get(e)??null}}function ZS(e,t,n,r=[]){let o=new Map,i=[],s=new Map,a=[];for(let[c,l]of t){for(let[u,f]of l.elements)o.set(u,f);for(let u of l.regions)i.push(u);for(let[u,f]of l.fileIndex){let m=s.get(u)??[];s.set(u,[...m,...f])}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}}import{SiteEditHistoryProvenanceSchema as RE}from"@vcp-dev/contracts";import{createHash as QS,randomUUID as La}from"node:crypto";import Oe from"node:fs/promises";import Le from"node:path";var Dd=new WeakMap;function rr(e){return Dd.get(e)?.()??e.readIndex()}var gt=1,Na=1,qS=2,eE="index.json",tE="recovery.json",nE="transaction-journal.json",rE="document-version.json",Ii={maxEntries:100,maxSessionBytes:512*1024*1024,maxEntryBytes:128*1024*1024},te={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"},re=class extends Error{constructor(t,n,r){super(n),this.name="FileHistoryStoreError",this.code=t,r?.cause!==void 0&&(this.cause=r.cause)}};function Yt(){return{entries:new Map,blobSizes:new Map}}function vi(e,t){let n={entries:new Map,blobs:new Map,objectBytes:0};for(let r of e)Bd(n,r,t);return n}function Bd(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 jd(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 $d(e,t={}){let n=SE(e),r=IE(t.limits),o=wa(n),i=EE(n),s=await nt(i),a=await nt(o)||s;a||(await fE(n),await pE(n)),a||await CE(n);let c=Yt(),l=await Ri(n,c),u=new Set(a?(await Ti(n)).map(y=>y.stageId):[]);a||await Fd(n,l.entryIds,c);let f=l.digest,m=vi(l.entryIds,c),d=async y=>{let{index:v,sizeBytes:C}=await $r(n);if(Wd(v,y),v.digest!==f){let N=Yt();await Jd(n,v.entryIds,N,C),m=vi(v.entryIds,N),f=v.digest}return{...Fi(v),totalBytes:m.objectBytes+C}},g=async y=>{Da(y),await d(),await Ad(n,m,[y.entryId],y.blobIds,y.stageId),await Ci(n,y.stageId)},h=async(y,v)=>{let C=await d(v);Kd(y,C.entryIds.length);let N=Yt();for(let A of C.entryIds.slice(Math.min(C.cursor,y)+1,Math.max(C.cursor,y)+1))await Dr(n,A,N);return C},S=async()=>{if(await nt(o)||s)throw new re(te.RECOVERY_PENDING,"history store requires explicit recovery before accepting writes")},E={rootDir:n,recoveryRequired:a,async readDocumentVersion(){return Od(n)},async writeDocumentVersion(y){if(await S(),!Number.isInteger(y)||y<0)throw new re(te.INVALID_SCHEMA,"document version must be a non-negative integer");let v=await Od(n);y<=v||await Lr(Zd(n),{schemaVersion:1,version:Math.max(v,y)})},async stageAppend(y,v={}){await S();let C=await sE(y,r),N={schemaVersion:Na,stageId:La(),entryId:C.entryId,blobIds:C.blobs.map(A=>A.digest)};try{await aE(n,C),await lE(n,N,v.durableManifest!==!1)}catch(A){try{await g(N)}catch(R){throw new re(te.INDEX_CORRUPT,"staged history cleanup failed after preparation error",{cause:R})}throw A}return{stageId:N.stageId,entryId:N.entryId,blobIds:N.blobIds}},async discardStage(y){await S(),Ta(y);let v=await Pa(n,y);v&&await g(v)},async previewStagedAppend(y,v){await S();let C=await d(v);return(await Nd(n,r,y,C,m)).transition},async previewCursor(y,v){await S();let C=await h(y,v);return Vd(C,C.entryIds,y)},async publishStagedAppend(y,v,C){if(await S(),Ni(y,"entryId"),C){Ta(C);let _=await Pa(n,C);if(!_||_.entryId!==y)throw new re(te.INVALID_SCHEMA,"history stage does not match the published entry")}let N=await d(v),A=m,R=await Nd(n,r,y,N,A),F=await Md({rootDir:n,previousDigest:R.current.digest,entryIds:R.entryIds,cursor:R.cursor,readback:async()=>_d(n,R.usage),afterWrite:async()=>{C?await Ci(n,C):await dE(n,y),await Ad(n,R.usage,[...A.entries.keys()].filter(_=>!R.usage.entries.has(_)),[...A.blobs.keys()].filter(_=>!R.usage.blobs.has(_)))}});return m=R.usage,f=F.digest,F},async append(y){await S();let v=await d(),C=await E.stageAppend(y);try{return await E.publishStagedAppend(C.entryId,v.digest,C.stageId)}catch(N){throw await E.discardStage(C.stageId),N}},async readEntry(y){return Ni(y,"entryId"),Dr(n,y)},async readBlob(y){Ni(y,"blobId");let v=await qd(n,y),C=await Br(v,te.NOT_FOUND,"blob");return Yd(C,y,v),C},async readIndex(){let y=Yt(),v=await Ri(n,y);return m=vi(v.entryIds,y),f=v.digest,v},async readStatus(){let y=await wi(n);return{canUndo:y.undoIds.length>0,canRedo:y.redoIds.length>0,undoDepth:y.undoIds.length,redoDepth:y.redoIds.length,cursor:y.cursor,recoveryRequired:await nt(o)||await nt(i)}},async readUndoRedoIds(){let y=await wi(n);return{undoIds:y.undoIds,redoIds:y.redoIds,currentId:y.currentId}},async setCursor(y,v){await S();let C=await h(y,v),N=await Md({rootDir:n,previousDigest:C.digest,entryIds:C.entryIds,cursor:y,readback:async()=>_d(n,m)});return f=N.digest,N},async markRecoveryRequired(y){await nt(o)||await Lr(wa(n),{schemaVersion:gt,reason:vE(y),createdAt:new Date().toISOString()})},async clearRecoveryRequired(){await Oe.rm(wa(n),{force:!0})},async readTransactionJournal(){return await nt(i)?ki(i):null},async writeTransactionJournal(y){await S(),Qd(y);try{await Lr(i,y)}catch(C){let N=await ki(i).catch(()=>null);if(N&&Buffer.from(rt(N)).equals(Buffer.from(rt(y))))return;throw N?new re(te.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous",{cause:C}):C}let v=await ki(i);if(!Buffer.from(rt(v)).equals(Buffer.from(rt(y))))throw new re(te.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous")},async clearTransactionJournal(y){let v=await nt(i)?await ki(i):null;if(v&&v.transactionId!==y)throw new re(te.INVALID_SCHEMA,"transaction journal changed concurrently");try{await Oe.rm(i,{force:!0})}catch(C){if(!await nt(i))return;throw C}if(await nt(i))throw new re(te.INDEX_CORRUPT,"transaction journal clear outcome is ambiguous");s=!1},async cleanupTmp(){await S();for(let C of u)await Ci(n,C),u.delete(C);await mE(n);let y=Yt(),v=await Ri(n,y);await Fd(n,v.entryIds,y),m=vi(v.entryIds,y),f=v.digest}};return Dd.set(E,()=>wi(n)),E}async function Nd(e,t,n,r,o){Ni(n,"entryId");let i=Yt(),s=await Dr(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))jd(a,u);Bd(a,s.id,i),c.push(s.id);let l=cE(c,t,a);return{current:r,entryIds:l.entryIds,cursor:l.cursor,usage:a,transition:Vd(r,l.entryIds,l.cursor)}}function Vd(e,t,n){return Kd(n,t.length),{expectedIndexDigest:e.digest,publishedIndexDigest:oE(t,n),publishedCursor:n,publishedCurrentId:t[n]??null}}function oE(e,t){return ln(rt({schemaVersion:gt,entryIds:e,cursor:t}))}function Kd(e,t){if(!Number.isInteger(e)||e<-1||e>=t)throw new re(te.INVALID_SCHEMA,`history cursor is out of bounds: ${e}`)}function iE(e){if(!vt(e))return!1;let t=e.publishedCursor,n=e.publishedCurrentId;return!at(e.expectedIndexDigest)||!at(e.publishedIndexDigest)||!Number.isInteger(t)||t<-1||n!==null&&!at(n)?!1:t===-1?n===null:at(n)}async function sE(e,t){if(!e.kind.trim())throw new re(te.INVALID_JSON,"history entry kind must not be empty");let n=[],r=[];for(let c of e.blobs??[]){if(!c.name.trim())throw new re(te.INVALID_JSON,"history blob name must not be empty");let l=bE(c.data),u=ln(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:gt,kind:e.kind,manifest:e.manifest,blobs:r},i=rt({...o}),s=ln(i),a=i.byteLength+n.reduce((c,l)=>c+l.sizeBytes,0);if(a>t.maxEntryBytes)throw new re(te.CAPACITY_EXCEEDED,`history entry exceeds maxEntryBytes (${a} > ${t.maxEntryBytes})`);return{entryBody:o,entryId:s,blobs:n}}async function aE(e,t){let n=Va(e,t.entryId),r={id:t.entryId,...t.entryBody},o=[...t.blobs.map(a=>Pd(Ka(e,a.digest),a.bytes,{kind:"blob",digest:a.digest},Ja(e,a.digest))),Pd(n,rt(r),{kind:"entry",digest:t.entryId},Ua(e,t.entryId))],s=(await Promise.allSettled(o)).find(a=>a.status==="rejected");if(s)throw s.reason}async function Pd(e,t,n,r){let o=await Ma(e)??(r?await Ma(r):null);if(o!==null){if(Buffer.compare(o,t)!==0)throw new re(n.kind==="blob"?te.BLOB_CORRUPT:te.ENTRY_CORRUPT,`${n.kind} content mismatch for ${n.digest}`);return}await Hd(e,t)}function cE(e,t,n){let r=[...e],o=r.length-1;for(;;){if(n.objectBytes+rt(zd(r,o)).byteLength<=t.maxSessionBytes&&r.length<=t.maxEntries)return{entryIds:r,cursor:o};if(o<=0||r.length===0)throw new re(te.CAPACITY_EXCEEDED,"history store exceeds capacity limits and the current entry cannot be trimmed");jd(n,r.shift()),o-=1}}async function lE(e,t,n){Da(t);let r=$a(e,t.stageId);if(n){await Lr(r,t);return}await xE(r,t)}async function Pa(e,t){let n=await Ma($a(e,t));if(n===null)return null;let r=Vr(Buffer.from(n).toString("utf8"),`history stage ${t}`),o=Da(r);if(o.stageId!==t)throw new re(te.INVALID_SCHEMA,`history stage id mismatch: ${t}`);return o}async function Ti(e){let t=[];for(let n of await Ai(ja(e))){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);Ta(r);let o=await Pa(e,r);o&&t.push(o)}return t}async function Ad(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 Ti(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 Td(Va(e,a),Ua(e,a));for(let a of new Set(r))!t.blobs.has(a)&&!s.has(a)&&await Td(Ka(e,a),Ja(e,a));await Oa(Kr(e)),await Oa(Ur(e))}async function Ci(e,t){await Aa($a(e,t)),await uE(e)}async function uE(e){try{await Oe.rmdir(ja(e))}catch(t){if(Jr(t)||vt(t)&&t.code==="ENOTEMPTY")return;throw t}}async function dE(e,t){for(let n of await Ti(e))n.entryId===t&&await Ci(e,n.stageId)}async function Aa(e){if(await Oe.rm(e,{force:!0}),await nt(e))throw new re(te.INDEX_CORRUPT,`unable to remove staged history object: ${e}`)}async function Td(e,t){await Aa(e),await Aa(t)}function Da(e){if(!vt(e)||e.schemaVersion!==Na||typeof e.stageId!="string"||!Ud(e.stageId)||!at(e.entryId))throw new re(te.INVALID_SCHEMA,"history stage schema is invalid");let t=Gd(e.blobIds,"history stage blobIds");return{schemaVersion:Na,stageId:e.stageId,entryId:e.entryId,blobIds:t}}function Ta(e){if(!Ud(e))throw new re(te.INVALID_PATH,"history stageId must be a UUID")}function Ud(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 Fd(e,t,n=Yt()){let r=new Set(t),o=new Set;for(let l of t){let u=await Dr(e,l,n);for(let f of u.blobs)o.add(f.digest)}for(let l of await Ti(e)){r.add(l.entryId);for(let u of l.blobIds)o.add(u)}let i=Kr(e),s=await Ai(i);for(let l of s){if(!l.endsWith(".json"))continue;let u=Ld(l.slice(0,-5));u&&!r.has(u)&&await Pi(Le.join(i,l))}let a=Ur(e),c=await Ai(a);for(let l of c){let u=Ld(l);u&&!o.has(u)&&await Pi(Le.join(a,l))}}async function Ri(e,t=Yt()){let{index:n,sizeBytes:r}=await $r(e),{totalBytes:o}=await Jd(e,n.entryIds,t,r);return{...Fi(n),totalBytes:o}}async function _d(e,t){let{index:n,sizeBytes:r}=await $r(e);return{...Fi(n),totalBytes:t.objectBytes+r}}async function $r(e){let t=Ba(e),n=await Br(t,te.NOT_FOUND,"index"),r=Vr(Buffer.from(n).toString("utf8"),"index");return{index:gE(r),sizeBytes:n.byteLength}}async function wi(e){return Fi((await $r(e)).index)}function Fi(e){let t=[...e.entryIds],n=t.slice(0,e.cursor+1).reverse(),r=t.slice(e.cursor+1);return{schemaVersion:gt,digest:e.digest,entryIds:t,cursor:e.cursor,currentId:t[e.cursor]??null,undoIds:n,redoIds:r}}async function Jd(e,t,n,r){let o=0,i=new Set;o+=r??(await $r(e)).sizeBytes;for(let s of new Set(t)){let a=await Dr(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 Dr(e,t,n=Yt()){let r=n.entries.get(t);if(r)return r.entry;let o=await kE(e,t),i=await Br(o,te.NOT_FOUND,"entry"),s=Vr(Buffer.from(i).toString("utf8"),`entry ${t}`),a=hE(s);if(a.id!==t)throw new re(te.ENTRY_CORRUPT,`entry id mismatch for ${t}`);if(ln(rt({schemaVersion:a.schemaVersion,kind:a.kind,manifest:a.manifest,blobs:a.blobs}))!==t)throw new re(te.ENTRY_CORRUPT,`entry hash mismatch for ${t}`);for(let l of a.blobs){if(n.blobSizes.has(l.digest))continue;let u=await qd(e,l.digest),f=await Br(u,te.NOT_FOUND,"blob");Yd(f,l.digest,u),n.blobSizes.set(l.digest,f.byteLength)}return n.entries.set(t,{entry:a,sizeBytes:i.byteLength}),a}async function Xd(e,t,n){await Lr(Ba(e),zd(t,n))}function zd(e,t){return{schemaVersion:gt,digest:ln(rt({schemaVersion:gt,entryIds:e,cursor:t})),entryIds:e,cursor:t}}function Wd(e,t){if(t!==void 0&&e.digest!==t)throw new re(te.INVALID_SCHEMA,`history index changed concurrently (expected ${t}, current ${e.digest})`)}async function Md(e){Wd(await wi(e.rootDir),e.previousDigest);let t=ln(rt({schemaVersion:gt,entryIds:e.entryIds,cursor:e.cursor}));try{await Xd(e.rootDir,e.entryIds,e.cursor),await e.afterWrite?.();let n=await e.readback();if(n.digest!==t)throw new re(te.INDEX_CORRUPT,"history index readback did not match the published transition");return n}catch(n){let r=await Ri(e.rootDir).catch(()=>null);if(r?.digest===t)return r;throw r?.digest===e.previousDigest?n:new re(te.INDEX_CORRUPT,"history index publish outcome is ambiguous",{cause:n})}}async function fE(e){await Oe.mkdir(e,{recursive:!0}),await Oe.mkdir(Kr(e),{recursive:!0}),await Oe.mkdir(Ur(e),{recursive:!0}),await Oe.mkdir(jr(e),{recursive:!0})}async function pE(e){await Oe.rm(jr(e),{recursive:!0,force:!0}),await Oe.mkdir(jr(e),{recursive:!0})}async function mE(e){let t=jr(e);await Oe.mkdir(t,{recursive:!0});for(let n of await Ai(t))n!=="stages"&&await Oe.rm(Le.join(t,n),{recursive:!0,force:!0})}function gE(e){if(!vt(e))throw new re(te.INDEX_CORRUPT,"index.json must be an object");if(e.schemaVersion!==gt)throw new re(te.INVALID_SCHEMA,`unsupported index schemaVersion: ${String(e.schemaVersion)}`);let t=Gd(e.entryIds,"index.entryIds"),n=e.cursor;if(!Number.isInteger(n)||n<-1||n>=t.length)throw new re(te.INDEX_CORRUPT,"index cursor is out of bounds");let r=n,o=e.digest;if(!at(o))throw new re(te.INDEX_CORRUPT,"index digest is invalid");let i=ln(rt({schemaVersion:gt,entryIds:t,cursor:r}));if(o!==i)throw new re(te.INDEX_CORRUPT,"index digest mismatch");return{schemaVersion:gt,digest:o,entryIds:t,cursor:r}}function hE(e){if(!vt(e))throw new re(te.ENTRY_CORRUPT,"entry must be an object");if(e.schemaVersion!==gt)throw new re(te.INVALID_SCHEMA,`unsupported entry schemaVersion: ${String(e.schemaVersion)}`);let t=e.id;if(!at(t))throw new re(te.ENTRY_CORRUPT,"entry id is invalid");let n=e.kind;if(typeof n!="string"||n.trim().length===0)throw new re(te.ENTRY_CORRUPT,"entry kind is invalid");let r=_a(e.manifest,"entry.manifest"),o=yE(e.blobs);return{id:t,schemaVersion:gt,kind:n,manifest:r,blobs:o}}function yE(e){if(!Array.isArray(e))throw new re(te.ENTRY_CORRUPT,"entry blobs must be an array");return e.map((t,n)=>{if(!vt(t))throw new re(te.ENTRY_CORRUPT,`entry blob ref ${n} must be an object`);let r=t.name;if(typeof r!="string"||r.trim().length===0)throw new re(te.ENTRY_CORRUPT,`entry blob ref ${n} name is invalid`);let o=t.digest;if(!at(o))throw new re(te.ENTRY_CORRUPT,`entry blob ref ${n} digest is invalid`);let i=t.sizeBytes;if(!Number.isInteger(i)||i<0)throw new re(te.ENTRY_CORRUPT,`entry blob ref ${n} sizeBytes is invalid`);return{name:r,digest:o,sizeBytes:i}})}async function Lr(e,t){await Hd(e,rt(t))}async function xE(e,t){let n=Le.dirname(e),r=Le.basename(e),o=Le.join(n,`.${r}.${process.pid}.${La()}.tmp`);await Oe.mkdir(n,{recursive:!0});try{await Oe.writeFile(o,rt(t),{flag:"wx"}),await Oe.rename(o,e)}finally{await Pi(o)}}async function Hd(e,t){let n=Le.dirname(e),r=Le.basename(e),o=Le.join(n,`.${r}.${process.pid}.${La()}.tmp`);await Oe.mkdir(n,{recursive:!0});try{let i=await Oe.open(o,"wx");try{await i.writeFile(t),await i.sync()}finally{await i.close()}await Oe.rename(o,e),await Oa(n)}finally{await Pi(o)}}function rt(e){return Buffer.from(JSON.stringify(Fa(e)),"utf8")}function Fa(e){if(Array.isArray(e))return e.map(t=>Fa(t));if(vt(e)){let t={};for(let n of Object.keys(e).sort())t[n]=Fa(e[n]);return t}return e}function Vr(e,t){try{return JSON.parse(e)}catch(n){throw new re(te.INVALID_JSON,`${t} is not valid JSON`,{cause:n})}}function _a(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=>_a(n,t));if(vt(e)){let n={};for(let[r,o]of Object.entries(e))n[r]=_a(o,t);return n}break}throw new re(te.INVALID_JSON,`${t} must be JSON-serializable`)}function Gd(e,t){if(!Array.isArray(e))throw new re(te.INDEX_CORRUPT,`${t} must be an array`);return e.map((n,r)=>{if(!at(n))throw new re(te.INDEX_CORRUPT,`${t}[${r}] is invalid`);return n})}function Ni(e,t){if(!at(e))throw new re(te.INVALID_PATH,`${t} must be a sha256 digest`)}function at(e){return typeof e=="string"&&/^sha256:[a-f0-9]{64}$/u.test(e)}function ln(e){return`sha256:${QS("sha256").update(e).digest("hex")}`}function bE(e){return typeof e=="string"?Buffer.from(e,"utf8"):Buffer.from(e)}async function Br(e,t,n){try{return await Oe.readFile(e)}catch(r){throw new re(t,`${n} not found: ${e}`,{cause:r})}}async function Ma(e){try{return await Oe.readFile(e)}catch(t){if(Jr(t))return null;throw t}}function Yd(e,t,n){if(ln(e)!==t)throw new re(te.BLOB_CORRUPT,`blob hash mismatch for ${n}`)}async function nt(e){try{return await Oe.access(e),!0}catch(t){if(Jr(t))return!1;throw t}}async function Pi(e){try{await Oe.rm(e,{force:!0,recursive:!0})}catch{}}async function Oa(e){try{let t=await Oe.open(e,"r");try{await t.sync()}finally{await t.close()}}catch{}}async function Ai(e){try{return await Oe.readdir(e)}catch(t){if(Jr(t))return[];throw t}}function SE(e){if(typeof e!="string"||e.trim().length===0)throw new re(te.INVALID_ROOT,"history store rootDir must be a non-empty string");return Le.resolve(e)}function Ba(e){return Le.join(e,eE)}function wa(e){return Le.join(e,tE)}function EE(e){return Le.join(e,nE)}function Zd(e){return Le.join(e,rE)}async function Od(e){try{let t=await Oe.readFile(Zd(e),"utf8"),n=Vr(t,"document version");if(!vt(n)||n.schemaVersion!==1||!Number.isInteger(n.version)||n.version<0)throw new re(te.INVALID_SCHEMA,"document version schema is invalid");return n.version}catch(t){if(Jr(t))return 0;throw t}}async function ki(e){let t=await Br(e,te.RECOVERY_PENDING,"transaction journal"),n=Vr(Buffer.from(t).toString("utf8"),"transaction journal");return Qd(n),n}function Qd(e){if(!vt(e)||e.schemaVersion!==qS||typeof e.transactionId!="string"||e.transactionId.length===0||typeof e.operationId!="string"||e.operationId.length===0||!["prepared","files-written","history-published"].includes(e.phase)||!iE(e.historyTransition)||!Array.isArray(e.files))throw new re(te.INVALID_SCHEMA,"transaction journal schema is invalid");for(let t of e.files)if(!vt(t)||typeof t.path!="string"||t.path.length===0||t.preDigest!==null&&!at(t.preDigest)||t.postDigest!==null&&!at(t.postDigest))throw new re(te.INVALID_SCHEMA,"transaction journal file digest is invalid")}function vE(e){return e.replace(/[\r\n]+/g," ").slice(0,512)}function Kr(e){return Le.join(e,"entries")}function Ur(e){return Le.join(e,"blobs")}function jr(e){return Le.join(e,"tmp")}function ja(e){return Le.join(jr(e),"stages")}function $a(e,t){return Le.join(ja(e),`${t}.json`)}function Va(e,t){return Le.join(Kr(e),`${tf(t)}.json`)}function Ka(e,t){return Le.join(Ur(e),tf(t))}function Ua(e,t){return Le.join(Kr(e),`${t}.json`)}function Ja(e,t){return Le.join(Ur(e),t)}async function kE(e,t){return ef(Va(e,t),Ua(e,t))}async function qd(e,t){return ef(Ka(e,t),Ja(e,t))}async function ef(e,t){return await nt(e)?e:await nt(t)?t:e}function tf(e){return e.slice(7)}function Ld(e){let t=e.startsWith("sha256:")?e:`sha256:${e}`;return at(t)?t:null}function vt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Jr(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function IE(e){return{maxEntries:e?.maxEntries??Ii.maxEntries,maxSessionBytes:e?.maxSessionBytes??Ii.maxSessionBytes,maxEntryBytes:e?.maxEntryBytes??Ii.maxEntryBytes}}async function CE(e){let t=Ba(e);await nt(t)||await Xd(e,[],-1)}var wE={affectedCompositions:[]};function af(e){let t=null,n=new WeakMap;async function r(){return t??=NE(e),t}async function o(i){if(!i)return null;let s=Xa(i);return s?PE(e,s):i}return{async prepareAppend(i){let s=await rr(e),a=await e.stageAppend(of(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 rr(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),f={kind:"undo",entry:s,historyTransition:u};return n.set(f,{expectedDigest:a.digest,cursor:l}),f},async prepareRedo(){let i=await r(),s=await o(i.redo.at(-1));if(!s?.historyId)return null;let a=await rr(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),f={kind:"redo",entry:s,historyTransition:u};return n.set(f,{expectedDigest:a.digest,cursor:l}),f},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);nf(c,i.historyTransition),i.entry.historyId=s.entryId,Object.assign(a,or(c))}else{if(s.cursor===void 0)throw new Error("prepared cursor is missing");let c=i.kind==="undo"?a.undo:a.redo;if(Xa(c.at(-1))!==Xa(i.entry))throw new Error("history state changed before publish");let l=await e.setCursor(s.cursor,s.expectedDigest);nf(l,i.historyTransition),Object.assign(a,or(l))}n.delete(i)},async discardPrepared(i){let s=n.get(i);if(!s)return;let a=i.historyTransition;if(a){let c=await rr(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 f=await e.setCursor(u);Object.assign(s,or(f));return}catch(f){throw s.redo.push(i),f}}let c=await e.append(of(i)),l=c.currentId;if(!l)throw new Error("history store did not publish an entry");i.historyId=l,Object.assign(s,or(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,or(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 nf(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 Xa(e){return typeof e=="string"?e:e?.historyId}async function NE(e){let t=await rr(e);return or(t)}function or(e){return{undo:[...e.undoIds].reverse(),redo:[...e.redoIds].reverse(),entryIds:[...e.entryIds],cursor:e.cursor}}async function PE(e,t){let n=await e.readEntry(t),r=AE(n),o=r.provenance??wE;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 rf(e,n,r.preSnapshots),postSnapshots:await rf(e,n,r.postSnapshots)}}async function rf(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(_E(r,o.blobName))).toString("utf8"):"";return{file:o.file,content:i,version:o.version,exists:o.exists,...o.sha256?{sha256:o.sha256}:{}}}))}function of(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=TE(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 AE(e){if(!lf(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:cf(t.provenance)}:{},preSnapshots:sf(t.preSnapshots,"preSnapshots"),postSnapshots:sf(t.postSnapshots,"postSnapshots")}}function TE(e){if(e.provenance!==void 0)return cf(e.provenance);if(e.composition)return{initiatingComposition:e.composition,affectedCompositions:[]}}function cf(e){let t=RE.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 sf(e,t){return e.map((n,r)=>{if(!lf(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&&!FE(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 FE(e){return/^sha256:[0-9a-f]{64}$/.test(e)}function _E(e,t){let n=e.get(t);if(!n)throw new Error(`durable history blob is missing: ${t}`);return n}function lf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{randomBytes as HE}from"node:crypto";import Mi from"node:path";import{parse as bf}from"@babel/parser";import GE from"@babel/traverse";import*as Sf from"@babel/types";import{COMPONENT_I18N_FILE_SUFFIX as Wa,PageResourceArtifactSchema as YE,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as ZE,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as QE,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as qE,parseComponentI18nResourcesJson as ev}from"@vcp-dev/contracts";var df=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\(/i,ff=/\b(?:bg-black|bg-white|text-white|text-black)(?:\b|\/)/g,ME=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke)-\[#(?:[0-9a-fA-F]{3,8})\](?:\/\d+)?/g,OE=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*#[0-9a-fA-F]{3,8}[^'"]*['"]/g,LE=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*rgba?\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,DE=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,BE=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,jE=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*(?:oklch|lab|lch|hsla?)\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,$E=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*(?:oklch|lab|lch|hsla?)\([^)]+\)[^'"]*['"]/gi,VE=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*color-mix\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,KE=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*color-mix\([^'"]*['"]/gi,UE=/\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,JE=/var\(\s*--(?:_|private-|vcp-)[^)]+\)/gi,XE=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\([^)]*\)/gi;function Xr(e,t){let n=_i([...ht(e,ME),...ht(e,OE),...ht(e,LE),...ht(e,t.includeRgbBackgroundImage?DE:BE),...t.includeExtendedColorFunctions?[...ht(e,jE),...ht(e,$E)]:[]]),r=_i([...ht(e,VE),...ht(e,KE)]).filter(o=>t.colorMixPolicy==="always"||df.test(o));return n.push(...r.filter(o=>!n.includes(o))),t.rejectTailwindPalette&&n.push(...ht(e,UE).filter(o=>!n.includes(o))),t.rejectAnyRawColorLiteral&&n.push(...ht(e,XE).filter(o=>!n.includes(o))),{hardCodedSurfaceHits:_i(ht(e,ff)),hardCodedSurfaceOccurrences:WE(e),rawColorHits:n,privateTokenHits:t.rejectPrivateTokens?_i(ht(e,JE)):[]}}function ht(e,t){return e.match(new RegExp(t.source,t.flags))??[]}var uf=160,zE=/((?:[a-z][a-z0-9-]*(?:\[[^\]]*\])?:)+)$/;function WE(e){let t=new RegExp(ff.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=zE.exec(l),f=r(i.index),m=e.indexOf(`
|
|
6
|
+
`,i.index),d=e.slice(n[f]??0,m===-1?void 0:m).trim();o.push({token:a,variant:u?.[1]??"",alpha:c?Number(c[1]):null,line:f+1,snippet:d.length>uf?`${d.slice(0,uf-1)}\u2026`:d})}return o}function _i(e){return[...new Set(e)]}var Ha="{{$INSTANCE}}",tv=/\{\{\$PAGE_ROUTE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,nv=/\{\{\$PAGE_TITLE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,Ga="components/site/generated",rv=/\.(?:tsx?|json)$/,ov=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,iv=["react","react/","next","next/","lucide-react","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],sv=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),za=GE,av=typeof za=="function"?za:za.default;async function Ya(e){let t=YE.safeParse(e.artifact);if(!t.success)return Te("Page resource artifact failed contract validation.");let n=t.data,r=e.randomHex??(()=>HE(4).toString("hex")),o=Math.max(1,Math.min(e.maxAttempts??5,5)),i=hv(r());if(!i)return Te("Random instance suffix must be 8 lowercase hex chars.");let s=`${yv(n.resource_id)}-${i}`,a=new Map,c=new Map,l=[];for(let v of n.pages){let C=v.final_route.slice(1);a.set(v.template_page_id,v.final_route),c.set(v.template_page_id,v.title),l.push({template_page_id:v.template_page_id,title:v.title,final_route:v.final_route,route_file_path:`app/${C}/page.tsx`})}let u=[],f=new Set,m=new Set,d=new Map,g=new Map,h=[],S=new Set(n.pages.flatMap(v=>v.components.map(C=>C.component_id)));for(let v of n.components){if(!S.has(v.component_id))continue;let C=pf({materialization:v.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c});if(!C.ok)return C;for(let N of C.files){let A=gf(N,f,u);if(A)return A}m.add(C.entry),g.set(C.entry,C.entryExport),d.set(v.component_id,C.entry)}for(let[v,C]of n.pages.entries()){let N=l[v],A=pf({materialization:C.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c,pageEntryTarget:N.route_file_path,pageTitle:N.title});if(!A.ok)return A;for(let R of A.files){let F=gf(R,f,u);if(F)return F}m.add(A.entry),g.set(A.entry,A.entryExport),h.push({entry:A.entry,declaredComponentIds:new Set(C.components.map(R=>R.component_id))})}let E=lv(u,m,s,d,h,g);if(!E.ok)return E;for(let v of u)if(await e.exists(v.file))return!v.file.startsWith("app/")&&o>1?Ya({...e,randomHex:r,maxAttempts:o-1}):{ok:!1,code:"MATERIALIZATION_CONFLICT",message:`Page resource create-only target already exists: ${v.file}`,path:v.file};let y=uv(u);return y||(u.sort((v,C)=>v.file.localeCompare(C.file)),{ok:!0,packageInstanceId:s,pages:l,files:u})}function pf(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:mf(o.pathTemplate,e.packageInstanceId);if(!s)return Te("Materialization path cannot be mapped into the package namespace.",o.pathTemplate);let a=cv(o.content,e.packageInstanceId,e.routeByPage,e.titleByPage);if(!a.ok)return a;let c=i&&e.pageTitle!==void 0?fv(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??mf(t,e.packageInstanceId);return!r||!n.some(o=>o.file===r)?Te("Materialization entry must match one controlled source file.",t):{ok:!0,files:n,entry:r,entryExport:e.materialization.entry.export}}function cv(e,t,n,r){let o,i=e.replace(tv,(c,l)=>{let u=n.get(l);return u||(o=l,c)});if(o)return Te(`Page route placeholder references unknown template page: ${o}`);let s=i.replace(nv,(c,l)=>{let u=r.get(l);return u?JSON.stringify(u):(o=l,c)});if(o)return Te(`Page title placeholder references unknown template page: ${o}`);let a=s.replaceAll(Ha,t);return a.includes("{{$PAGE_ROUTE:")||a.includes("{{$PAGE_TITLE:")||a.includes("{{$INSTANCE}}")?Te("Materialization contains an unresolved placeholder."):{ok:!0,data:a}}function mf(e,t){let n=`${Ga}/${t}`;if(e.split(Ha).length>2)return null;let o=e.replace(Ha,t),i=`${Ga}/${t}/`,s=o.startsWith(i)?o:`${n}/${o}`,a=Mi.posix.normalize(s);return a!==s||!a.startsWith(`${n}/`)||!rv.test(a)||ov.test(a)?null:a}function gf(e,t,n){return t.has(e.file)?Te(`Page resource materializations resolve duplicate target: ${e.file}`,e.file):(t.add(e.file),n.push(e),null)}function lv(e,t,n,r,o,i){let s=new Set(e.map(d=>d.file)),a=`${Ga}/${n}`,c=new Map(e.map(d=>[d.file,new Set])),l=new Map;for(let d of e){if(d.file.endsWith(".json")){try{JSON.parse(d.content)}catch{return Te("Materialization JSON file must contain valid JSON.",d.file)}if(d.file.endsWith(Wa)&&!ev(d.content).success)return Te("Materialization component i18n resources are invalid.",d.file);continue}try{let h=bf(d.content,{sourceType:"module",plugins:["jsx","typescript"]});l.set(d.file,h);for(let E of h.program.body)if((E.type==="ImportDeclaration"||E.type==="ExportAllDeclaration"||E.type==="ExportNamedDeclaration"&&E.source)&&E.source){let y=E.source.value,v=mv(d.file,y,s,a);if(!v.allowed)return Te(`Materialization import is outside the controlled package: ${y}`,d.file);v.internalPath&&c.get(d.file).add(v.internalPath)}let S;if(av(h,{Identifier(E){E.isReferencedIdentifier()&&sv.has(E.node.name)&&(S??=E.node.name,E.stop())},JSXAttribute(E){E.node.name.type==="JSXIdentifier"&&E.node.name.name==="style"&&(S??="inline style",E.stop())},JSXOpeningElement(E){E.node.name.type==="JSXIdentifier"&&E.node.name.name.toLowerCase()==="style"&&(S??="style element",E.stop())}}),S)return Te(`Materialization source uses forbidden capability: ${S}`,d.file)}catch{return Te("Materialization source must parse as TS/TSX.",d.file)}let g=Xr(d.content,{colorMixPolicy:"always",includeExtendedColorFunctions:!0,includeRgbBackgroundImage:!0,rejectAnyRawColorLiteral:!0,rejectPrivateTokens:!0,rejectTailwindPalette:!0});if(g.hardCodedSurfaceHits.length>0||g.rawColorHits.length>0||g.privateTokenHits.length>0)return Te("Materialization source violates the public theme token policy.",d.file)}if([...t].some(d=>!s.has(d)))return Te("Materialization entry is outside the controlled package.");for(let d of t)if(d.endsWith(".json"))return Te("Materialization JSON files cannot be package entries.");for(let[d,g]of i){let h=l.get(d);if(!h||!dv(h,g))return Te("Materialization entry does not declare its contracted export.",d)}let u=new Map([...r].map(([d,g])=>[g,d]));for(let d of o){let g=xf(d.entry,c);for(let h of d.declaredComponentIds){let S=r.get(h);if(!S||!g.has(S))return Te(`Page entry does not reach declared component: ${h}`,d.entry)}for(let h of g){let S=u.get(h);if(S&&!d.declaredComponentIds.has(S))return Te(`Page entry imports undeclared component: ${S}`,d.entry)}}let f=new Set;for(let d of t)for(let g of xf(d,c))f.add(g);if(f.size!==e.length)return Te("Every materialization file must be reachable from a package entry.");let m=gv(e,l,c);return m||{ok:!0}}function uv(e){if(e.length>ZE)return Te("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>QE)return Te("Page resource file exceeds the content byte limit.",n.file);t+=r}return t>qE?Te("Page resource exceeds the aggregate content byte limit."):null}function dv(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 fv(e,t,n){let r;try{r=bf(e,{sourceType:"module",sourceFilename:n,plugins:["jsx","typescript"]})}catch{return Te("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=hf(s.init);if(a?.type!=="ObjectExpression")return{ok:!0,data:e};let c=a.properties.find(u=>u.type==="ObjectProperty"&&!u.computed&&pv(u.key));if(!c||c.type!=="ObjectProperty")return{ok:!0,data:e};let l=hf(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 hf(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression"||t?.type==="TSNonNullExpression";)t=t.expression;return t&&Sf.isExpression(t)?t:null}function pv(e){return e.type==="Identifier"&&e.name==="title"||e.type==="StringLiteral"&&e.value==="title"}function mv(e,t,n,r){if(t.startsWith(`@/${r}/`)){let s=t.slice(2),a=yf(s,n);return a?{allowed:!0,internalPath:a}:{allowed:!1}}if(!t.startsWith("."))return{allowed:iv.some(s=>s.endsWith("/")?t.startsWith(s):t===s)};if(t.includes("\\")||t.includes("\0"))return{allowed:!1};let o=Mi.posix.normalize(Mi.posix.join(Mi.posix.dirname(e),t)),i=yf(o,n);return i&&(i.startsWith(`${r}/`)||i.startsWith("app/"))?{allowed:!0,internalPath:i}:{allowed:!1}}function yf(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 gv(e,t,n){let r=new Set(e.map(o=>o.file));for(let o of e){if(!o.file.endsWith(Wa))continue;let i=o.file.slice(0,-Wa.length),s=[`${i}.tsx`,`${i}.ts`].find(u=>r.has(u));if(!s)return Te("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 Te("Component i18n resources must have exactly one same-name Client Component static importer.",s)}return null}function xf(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 hv(e){return/^[a-f0-9]{8}$/.test(e)?e:null}function yv(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"page-resource"}function Te(e,t){return{ok:!1,code:"MATERIALIZATION_REJECTED",message:e,...t?{path:t}:{}}}import{randomBytes as xv}from"node:crypto";import Zt from"node:path";import{parse as bv}from"@babel/parser";import Sv from"@babel/traverse";import{COMPONENT_I18N_FILE_SUFFIX as Oi,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as Ef,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as Ev,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as vv,SiteEditMaterializationSchema as kv,parseComponentI18nResourcesJson as Iv}from"@vcp-dev/contracts";var qa="components/site/generated",vf="{{$INSTANCE}}",Li=5,Cv=/^[a-z][a-z0-9-]{0,48}$/,Rv=/^[a-f0-9]{8}$/,kf=/\.tsx?$/,wv=/\.json$/,Nv=/\.(?:tsx?|json)$/,Pv=/^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/,Av=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,Tv=["react","react/","next","next/","lucide-react","react-i18next","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],Za=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),Qa=Sv,Fv=typeof Qa=="function"?Qa:Qa.default;function _v(e){let t=Array.isArray(e.manifest.files)?e.manifest.files:[];if(t.length>Ef)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file count exceeds the reusable limit."}};let n=Jv(t);if(n)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Static prefab resolves duplicate target path: ${n}`,path:n}};let r=kv.safeParse(e.manifest);if(!r.success)return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab manifest failed schema validation."}};let o=Vv(e.generatedRoot);if(!o)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Generated root must be ${qa}.`,path:e.generatedRoot}};if(!Pf(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=Rf(r.data.files),s=Rf(e.controlledFiles);if(!Xv(i,s))return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Controlled file list must exactly match the manifest file templates."}};if(i.size>Ef)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>Ev)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>vv?{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 Mv(e){let t=_v(e);if(!t.ok)return t;let n=Object.keys(e.manifest.projectDependencies??{}),r=new Set(e.availableHostDependencies??[]),o=n.find(u=>!Pv.test(u)||!r.has(u));if(o)return{ok:!1,error:{code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:`Declared project dependency is not available in the target site host: ${o}.`,path:o}};let i=n.flatMap(u=>[u,`${u}/`]),s=[...e.allowedExternalImports??Tv,...i],a=t.data.generatedRoot,c=Pf(e.manifest.instanceBaseName),l=Math.max(1,Math.min(Li,e.maxAttempts??Li));for(let u=0;u<l;u+=1){let f=Kv(e.instanceNameGenerator?.()??xv(4).toString("hex"));if(!f)return{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_INVALID",message:"Static prefab instance suffix must be 8 lowercase hex chars."}};let m=`${c}-${f}`,d=Tf(a,m),g=Ov({manifest:e.manifest,generatedRoot:a,instanceName:m,instanceRoot:d,allowedExternalImports:s});if(!g.ok)return g;if(!await Lv(e.exists,d,g.data.files))return{ok:!0,data:g.data}}return{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:"Unable to allocate a create-only static prefab instance after repeated conflicts."}}}async function Nf(e){let t=Math.max(1,Math.min(Li,e.maxAttempts??Li));for(let n=0;n<t;n+=1){let r=await Mv({...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 Ov(e){let t=[],n=new Set;for(let i of e.manifest.files){let s=If({pathTemplate:i.pathTemplate,generatedRoot:e.generatedRoot,instanceName:e.instanceName,instanceRoot:e.instanceRoot});if(!s.ok)return s;if(n.has(s.data))return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Static prefab resolves duplicate target path: ${s.data}`,path:s.data}};n.add(s.data),t.push({kind:"create-only",path:s.data,content:i.content,...i.role?{role:i.role}:{},sourcePathTemplate:i.pathTemplate})}t.sort((i,s)=>i.path.localeCompare(s.path));let r=If({pathTemplate:e.manifest.entry.pathTemplate,generatedRoot:e.generatedRoot,instanceName:e.instanceName,instanceRoot:e.instanceRoot});if(!r.ok)return r;if(!t.some(i=>i.path===r.data))return{ok:!1,error:{code:"MATERIALIZATION_ENTRY_INVALID",message:"Entry path must match one of the static prefab files.",path:r.data}};let o=Dv(t,e.instanceRoot,r.data,e.manifest.entry.export,e.allowedExternalImports);return o.ok?{ok:!0,data:{kind:"static-prefab-materialization",instanceName:e.instanceName,generatedRoot:e.generatedRoot,instanceRoot:e.instanceRoot,entry:{path:r.data,export:e.manifest.entry.export},files:t}}:o}async function Lv(e,t,n){if(await e(t))return!0;for(let r of n)if(await e(r.path))return!0;return!1}function If(e){if(e.pathTemplate.split(vf).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(vf,e.instanceName),n=Uv(t);return n?Tf(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||!Nv.test(n)||Av.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 Dv(e,t,n,r,o){let i=new Set(e.map(f=>f.path)),s=new Map,a=new Map(e.map(f=>[f.path,new Set])),c=new Map;for(let f of e){if(wv.test(f.path)){if(f.path.endsWith(Oi)){let g=Iv(f.content);if(!g.success)return Pn("MATERIALIZATION_DATA_UNSUPPORTED",g.error.message,f.path);c.set(f.path,new Set)}else try{JSON.parse(f.content)}catch{return Pn("MATERIALIZATION_DATA_UNSUPPORTED","Static prefab JSON file must contain valid JSON.",f.path)}continue}let m;try{m=bv(f.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:f.path}}}let d=Xr(f.content,{colorMixPolicy:"always",includeExtendedColorFunctions:!0,includeRgbBackgroundImage:!0,rejectAnyRawColorLiteral:!0,rejectPrivateTokens:!0,rejectTailwindPalette:!0});if(d.hardCodedSurfaceHits.length>0||d.rawColorHits.length>0||d.privateTokenHits.length>0)return{ok:!1,error:{code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source must use public semantic design tokens instead of raw colors or private tokens.",file:f.path}};s.set(f.path,m)}for(let f of e){if(!kf.test(f.path))continue;let m=s.get(f.path),d=null;if(Fv(m,{ImportDeclaration(g){let h=Cf({importer:f.path,source:g.node.source.value,instanceRoot:t,filePaths:i,allowedExternalImports:o});if(!h.allowed)d??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab imports must resolve within the controlled instance or match the starter allowlist.",file:f.path},g.stop();else if(h.internalPath&&(a.get(f.path).add(h.internalPath),h.internalPath.endsWith(Oi))){let S=Bv({importer:f.path,imported:h.internalPath,source:g.node.source.value,ast:m});S.ok?c.get(h.internalPath).add(f.path):(d??=S.error,g.stop())}},ExportAllDeclaration(g){d??={code:"MATERIALIZATION_ENTRY_INVALID",message:"Static prefab files cannot use export-star declarations.",file:f.path},g.stop()},ExportNamedDeclaration(g){if(g.node.source){let h=Cf({importer:f.path,source:g.node.source.value,instanceRoot:t,filePaths:i,allowedExternalImports:o});!h.allowed||!h.internalPath?(d??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab re-exports must resolve within the controlled instance.",file:f.path},g.stop()):a.get(f.path).add(h.internalPath)}},CallExpression(g){if(g.node.callee.type==="Import"){d??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab files cannot use dynamic import().",file:f.path},g.stop();return}g.node.callee.type==="Identifier"&&g.node.callee.name==="require"&&(d??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab files cannot use require().",file:f.path},g.stop())},NewExpression(g){g.node.callee.type==="Identifier"&&g.node.callee.name==="Function"&&(d??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot construct functions dynamically.",file:f.path},g.stop())},MetaProperty(g){g.node.meta.type==="Identifier"&&g.node.meta.name==="import"&&(d??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot use import.meta.",file:f.path},g.stop())},MemberExpression(g){let h=wf(g.node);h&&Za.has(h)&&(d??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${h}.`,file:f.path},g.stop())},OptionalMemberExpression(g){let h=wf(g.node);h&&Za.has(h)&&(d??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${h}.`,file:f.path},g.stop())},Identifier(g){g.isReferencedIdentifier()&&Za.has(g.node.name)&&(d??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${g.node.name}.`,file:f.path},g.stop())},JSXAttribute(g){g.node.name.type==="JSXIdentifier"&&g.node.name.name==="style"&&(d??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot use inline style attributes.",file:f.path},g.stop())},JSXOpeningElement(g){g.node.name.type==="JSXIdentifier"&&g.node.name.name.toLowerCase()==="style"&&(d??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot declare style elements.",file:f.path},g.stop())}}),d)return{ok:!1,error:d}}if(!kf.test(n))return Pn("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must be a .ts/.tsx source module.",n);let l=s.get(n);if(!l)return Pn("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must resolve to a controlled source file.",n);if(!jv(l,r))return Pn("MATERIALIZATION_EXPORT_MISSING","Static prefab entry does not declare the manifest export.",n);for(let[f,m]of c)if(m.size!==1)return Pn("MATERIALIZATION_IMPORT_FORBIDDEN","Each component .i18n.json file must have exactly one same-name Client Component static importer.",f);return $v(n,a).size!==e.length?Pn("MATERIALIZATION_ENTRY_INVALID","Every controlled source file must be reachable from the entry module.",n):{ok:!0,data:{kind:"static-prefab-materialization",instanceName:"",generatedRoot:qa,instanceRoot:"",entry:{path:"",export:{kind:"default"}},files:[]}}}function Cf(e){if(!e.source.startsWith("./")&&!e.source.startsWith("../"))return e.source.startsWith("@/components/site/generated/")?{allowed:!1}:{allowed:e.allowedExternalImports.some(o=>o.endsWith("/")?e.source.startsWith(o):e.source===o)};if(e.source.includes("\\")||e.source.includes("\0"))return{allowed:!1};let t=Zt.posix.normalize(Zt.posix.join(Zt.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 Bv(e){let t=Zt.posix.dirname(e.importer),n=Zt.posix.dirname(e.imported),r=Zt.posix.basename(e.importer).replace(/\.tsx?$/,""),o=Zt.posix.basename(e.imported).slice(0,-Oi.length),i=`./${r}${Oi}`;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 jv(e,t){for(let n of e.program.body){if(t.kind==="default"&&n.type==="ExportDefaultDeclaration")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 $v(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 Pn(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{file:n}:{}}}}function Vv(e){let t=Af(e);return t===qa?t:null}function Kv(e){let t=e.trim().toLowerCase();return Rv.test(t)?t:null}function Pf(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 Cv.test(t)?t:null}function Af(e){if(!e||e.startsWith("/")||e.includes("\\"))return null;let t=Zt.posix.normalize(e);return t==="."||t.startsWith("../")||t.includes("/../")||t.includes("//")?null:t}function Uv(e){let t=Af(e);return!t||t!==e?null:t}function Tf(...e){return Zt.posix.join(...e)}function Rf(e){return new Set(e.map(t=>t.pathTemplate))}function Jv(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 Xv(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function wf(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 mc}from"node:crypto";import ac from"@babel/traverse";function ec(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}}import{createHash as zv}from"node:crypto";import Ff from"node:path";import*as Df from"@babel/parser";import tc from"@babel/generator";import*as Ue from"@babel/types";var _f=typeof tc=="function"?tc:tc.default;function rc(e){let t=jf(e);if(t)return{ok:!1,error:t};let n=e.projection,r=sc(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=Gv(n,o),s={jsx:`<${e.component.localName} />`},a=Wv(e);if(i){let d=nc(e);return d.ok?{ok:!0,plan:{kind:"route-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:e.placementKey,placementUnitKey:o.placementUnitKey,importStep:a,rewriteStep:{kind:"insert-root-expression",locator:d.locator,sourceHash:d.sourceHash,node:s,placement:o.relation,replaceOriginal:n.container.kind==="starter-placeholder"}}}:d.result}let c=o.containerSourceRange??n.container.sourceRange,l=o.containerSourceHash??(ic(c,n.container.sourceRange)?n.container.sourceHash:null);if(!c||!l)return zr("Route page composition does not expose a verifiable container boundary.");let u=Hr(c),f=Of(e.source,u,l,"Route page composition container");if(!f.ok)return f.result;let m=o.anchorSourceRange?Hr(o.anchorSourceRange):void 0;if(m){if(!o.anchorSourceHash)return zr("Route page composition placement does not expose a verifiable anchor boundary.");let d=Of(e.source,m,o.anchorSourceHash,"Route page composition anchor");if(!d.ok)return d.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:a,rewriteStep:{kind:"insert-child",parentLocator:u,node:s,placement:o.relation,...m?{anchorLocator:m}:{}}}}}function Wv(e){let t=qv(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 Di(e){if(e.locator.root.kind!=="expression"||e.locator.path?.length)return An(e.source,"Root expression rewrite requires an exact expression locator.");let t=kr(e.source,"value");if(!t.ok)return An(e.source,t.diagnostic.message);let n=se(t.ast,e.locator);if(!n.ok)return An(e.source,n.diagnostic.message);let r=n.match.path;if(!r.isExpression())return An(e.source,"Resolved value locator does not point to an expression.");let o=ir(e.source,r.node.start??null,r.node.end??null);if(!o||o!==e.expectedSourceHash)return An(e.source,"Root expression hash no longer matches the current source.");if(e.action.kind==="remove")return r.replaceWith(Ue.nullLiteral()),{ok:!0,source:_f(t.ast,{}).code};let i;try{i=Df.parseExpression(e.action.jsx,{plugins:["jsx","typescript"]})}catch(s){return An(e.source,s instanceof Error?s.message:String(s))}return!Ue.isJSXElement(i)&&!Ue.isJSXFragment(i)?An(e.source,"Root expression rewrite requires a JSX insertion expression."):(e.action.kind==="replace"?r.replaceWith(i):r.replaceWith(Hv(r.node,i,e.action.placement,e.action.replaceOriginal)),{ok:!0,source:_f(t.ast,{}).code})}function Hv(e,t,n,r){if(Ue.isNullLiteral(e)||r)return t;let o=Ue.isJSXFragment(e)?[...e.children]:[Ue.isJSXElement(e)?e:Ue.jsxExpressionContainer(e)],s=n==="before"||n==="prepend"?[t,...o]:[...o,t];return Ue.jsxFragment(Ue.jsxOpeningFragment(),Ue.jsxClosingFragment(),s)}function An(e,t){return{ok:!1,source:e,diagnostic:{message:t}}}function oc(e){let t=jf(e);if(t)return{ok:!1,error:t};let n=e.projection,r=$f(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(Yv(n,o)){let h=nc(e);return h.ok?e.operation==="remove-node"&&!Mf(n,o.placementUnitKey)?zr("The last editable page unit cannot be deleted."):e.operation==="move-node"?zr("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=Hr(o.sourceRange),a=Tt(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?[]:[Wr(a.diagnostic)]}};if(ir(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=nc(e);return h.ok?Mf(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}}}:zr("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||!Qv(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=sc(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 f=u.containerSourceRange;if(!f||!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 m=Hr(f),d=Tt(e.source,m);if(!d.ok||!d.match.node)return{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:d.ok===!1?d.diagnostic.message:"Route page composition target container could not be resolved.",diagnostics:d.ok?[]:[Wr(d.diagnostic)]}};if(ir(e.source,d.match.node.start??null,d.match.node.end??null)!==u.containerSourceHash)return Lf("Route page composition target container hash no longer matches the current source.");if(u.relation==="before"||u.relation==="after"){let h=u.anchorSourceRange,S=u.anchorSourceHash;if(!h||!S)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Route page composition target placement does not expose a verifiable anchor boundary.",diagnostics:[]}};let E=Hr(h),y=Tt(e.source,E);return!y.ok||!y.match.node?{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:y.ok===!1?y.diagnostic.message:"Route page composition target anchor could not be resolved.",diagnostics:y.ok?[]:[Wr(y.diagnostic)]}}:ir(e.source,y.match.node.start??null,y.match.node.end??null)!==S?Lf("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:m,anchorLocator:E,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:m,placement:u.relation}}}}function Mf(e,t){for(let n of e.placementUnitByKey.values())if(n.placementUnitKey!==t&&n.members.length>0)return!0;return!1}function Gv(e,t){let n=e.placementUnitByKey.get(t.placementUnitKey);return n&&e.container.kind!=="jsx-container"&&ic(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 Yv(e,t){return e.container.kind!=="jsx-container"&&ic(t.sourceRange,e.mutationTarget.sourceRange)&&t.sourceHash===e.mutationTarget.sourceHash}function nc(e){let t=e.projection.mutationTarget,n={kind:"value",root:{kind:"expression",sourceRange:t.sourceRange}},r=Tt(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?[]:[Wr(r.diagnostic)]}}}:ir(e.source,r.match.node.start??null,r.match.node.end??null)!==t.sourceHash?{ok:!1,result:Bf("Route mutation target hash no longer matches the current source.")}:{ok:!0,locator:n,sourceHash:t.sourceHash}}function Of(e,t,n,r){let o=Tt(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?[]:[Wr(o.diagnostic)]}}}:ir(e,o.match.node.start??null,o.match.node.end??null)!==n?{ok:!1,result:Bf(`${r} hash no longer matches the current source.`)}:{ok:!0}}function Bf(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function zr(e){return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:e,diagnostics:[]}}}function Lf(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function Wr(e){return{code:"UNSUPPORTED_PAGE_SHAPE",message:e.message,details:{astCode:e.code}}}function jf(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&&!Zv(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 Zv(e,t){return e.routeId===t.routeId&&e.effectiveTemplateId===t.effectiveTemplateId}function Qv(e,t){return e.routeId===t.routeId&&e.templateId===t.effectiveTemplateId}function qv(e,t){let n=Ff.posix.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=Ff.posix.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function Hr(e){return{kind:"jsx-node",strategy:"source-range",sourceRange:e}}function ir(e,t,n){return t==null||n==null?null:`sha256:${zv("sha256").update(e.slice(t,n)).digest("hex")}`}function ic(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}var ek=typeof ac=="function"?ac:ac.default;function Jf(e){if(!e.ast)return kt(e,[Ve("UNSUPPORTED_PAGE_SHAPE","SourceGraph entry AST is required",{reason:"parsed-ast-required"})]);let t=ck(e.ast);if(!t)return kt(e,[Ve("UNSUPPORTED_PAGE_SHAPE","Route default export must resolve to a local function component",{reason:"default-export-unresolved"})]);let n=uk(t);if(!n.ok)return kt(e,[n.diagnostic]);let r=n.expression;if(r.isIdentifier()){let o=fk(r,t);if(o.status==="resolved")r=o.expression;else if(o.status==="invalid")return kt(e,[Ve("UNSUPPORTED_PAGE_SHAPE","Route default export local binding is not a supported JSX root")])}if(mk(r,t))return kt(e,[Ve("INDIRECT_RETURN_ONLY","Route default export only returns through an indirect function boundary")]);if(r.isNullLiteral())return lc(e,t,"virtual-route-root",r);if(pk(r)){let o=xk({input:e,source:e.source,expression:r});return cc(e,t,o,{kind:"virtual-route-root",sourceKind:"atomic-expression"},r)}if(r.isConditionalExpression())return kt(e,[Ve("UNSUPPORTED_PAGE_SHAPE","Route conditional root contains an unsupported branch shape",{reason:"ambiguous-placement"})]);if(r.isJSXElement()&&!Me(r)&&!un(r)){let o=fc(r),i=Uf({input:e,containerKind:"virtual-route-root",sourceKind:"jsx-element",source:e.source,containerPath:r,members:[o]});return cc(e,t,i,{kind:"virtual-route-root",sourceKind:"jsx-element"},r)}if(r.isJSXElement()||r.isJSXFragment()){let o=hk(r);if(!o.ok)return kt(e,[o.diagnostic]);let i=sr(o.path);if(i.unsupported)return kt(e,[Ve("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);if(gk(e.source,r,i.members))return lc(e,t,"starter-placeholder",r);let s=r.isJSXFragment()||Me(r);if(i.members.length===0&&s)return lc(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=Uf({input:e,containerKind:a,sourceKind:c,source:e.source,containerPath:o.path,members:i.members});return cc(e,t,l,{kind:a,sourceKind:c},r)}return kt(e,[Ve("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")])}function sc(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:Ve("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:Ve("PLACEMENT_KEY_NOT_FOUND","Placement key was not found in the projected page composition",{placementKey:t})}}function $f(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:Ve("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:Ve("PLACEMENT_KEY_NOT_FOUND","Placement unit key was not found in the projected page composition",{placementUnitKey:t})}}function Xf(e){return e.ok?tk(e.projection):nk(e.projection)}function tk(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 f=u.members.flatMap((h,S)=>zf(e,u,h,S,e.container.placementKey)),m=f.filter(({member:h})=>h.isBusinessMember).map(({sourceMember:h})=>ok(l,h,u.independent)),d=f.length>0?f:[{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,d.map(({sourceMember:h})=>h)),o.set(l,m);let g=d[0]?.sourceMember.key??l;n.push({key:l,containerKey:g,businessMemberKeys:m.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:rk(e,a),sourceMembers:i,businessMembers:s,placementUnits:n,placements:c}}function nk(e){let t=e.diagnostics.map(ik);return{status:"unsupported",version:e.version,composition:e.composition,reason:sk(e.diagnostics),diagnostics:t}}function rk(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 zf(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)=>zf(e,t,a,c,i))]}function ok(e,t,n){return{key:`business:${e}:${t.key}`,sourceMemberKey:t.key,containerKey:e,label:t.label,isIndependent:n}}function ik(e){return{code:ak(e),message:e.message}}function sk(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 ak(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 ck(e){let t=null;return ek(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=lk(o.path);i&&(t=i,n.stop())}}),t}function lk(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 uk(e){let t=e.get("body");if(!t.isBlockStatement()){let s=Yr(t);return s?{ok:!0,expression:s}:{ok:!1,diagnostic:Ve("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:Ve("ROUTE_RETURN_NOT_FOUND","Route default export does not contain a proven return boundary")};if(!r.isReturnStatement())return{ok:!1,diagnostic:Ve("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(!dk(s))return{ok:!1,diagnostic:Ve("UNSUPPORTED_PAGE_SHAPE","Route guard return shape is not statically safe",{reason:"guard-shape"})};continue}if(Wf(s)||Hf(s))return{ok:!1,diagnostic:Ve("UNSUPPORTED_PAGE_SHAPE","Route default export contains unsupported control flow before the terminal return",{reason:"control-flow-return"})}}let o=r.get("argument"),i=Yr(o);return i?{ok:!0,expression:i}:{ok:!1,diagnostic:Ve("ROUTE_RETURN_NOT_FOUND","Route default export returns without a boundary expression",{reason:"bare-return"})}}function dk(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(Wf(o)||Hf(o))return null;return r}function Wf(e){return e.isForStatement()||e.isForInStatement()||e.isForOfStatement()||e.isWhileStatement()||e.isDoWhileStatement()||e.isSwitchStatement()||e.isTryStatement()||e.isWithStatement()}function Hf(e){let t=!1;return e.traverse({Function(n){n.skip()},ReturnStatement(){t=!0}}),t}function fk(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=Yr(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 pk(e){return e.isConditionalExpression()?Vf(Yr(e.get("consequent")))&&Vf(Yr(e.get("alternate"))):!1}function Vf(e){return!!(e&&(e.isJSXElement()||e.isJSXFragment()||e.isNullLiteral()))}function Yr(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 mk(e,t){if(e.isIdentifier())return Kf(e.node.name,t);if(e.isCallExpression()){let n=e.get("callee");if(n.isIdentifier())return Kf(n.node.name,t)}return!1}function Kf(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 gk(e,t,n){return e.includes("DESIGN_PLAN_REPLACE_ME")&&t.isJSXElement()&&n.length>0&&dc(t)}function dc(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(!dc(t))return!1;continue}if(t.isJSXElement()&&!dc(t))return!1}return!0}function hk(e){let t=e;if(e.isJSXFragment()||Me(e)){let r=Gr(e),o=r[0];if(r.length===1&&o?.isJSXElement()&&un(o))t=o;else return{ok:!0,path:t}}for(;t.isJSXElement()&&un(t);){let r=Gr(t);if(r.length!==1)return{ok:!0,path:t};let o=r[0];if(!o?.isJSXElement()||!un(o))return{ok:!0,path:t};if(Gr(o).length<=1)return{ok:!0,path:t};t=o}return{ok:!0,path:t}}function Gr(e){let t=[];for(let n of e.get("children"))if(!Array.isArray(n)){if(n.isJSXText()){n.node.value.trim()&&t.push(n);continue}if(n.isJSXExpressionContainer()){let r=n.get("expression");!r.isJSXEmptyExpression()&&!r.isNullLiteral()&&t.push(n);continue}if(n.isJSXFragment()){t.push(...Gr(n));continue}n.isJSXElement()&&(Me(n)?t.push(...Gr(n)):t.push(n))}return t}function sr(e){let t=[],n=!1;for(let r of e.get("children")){if(r.isJSXText()){if(!r.node.value.trim())continue;t.push({memberKey:pc(r.node.type,r.node.start,r.node.end),kind:"text",nodeType:r.node.type,sourceRange:yt(r.node.loc),businessMemberCount:0,parentSourceRange:yt(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=sr(o);n||=i.unsupported,t.push(...i.members);continue}if(o.isJSXElement()){let i=un(o)?sr(o):null;n||=i?.unsupported??!1,t.push({...fc(o,i?.members),sourceRange:yt(r.node.loc),parentSourceRange:yt(e.node.loc)});continue}if(o.isJSXSpreadChild()){n=!0;continue}t.push({memberKey:pc(o.node.type,o.node.start,o.node.end),kind:"atomic-expression",nodeType:o.node.type,sourceRange:yt(r.node.loc),businessMemberCount:1,parentSourceRange:yt(e.node.loc),children:[],isBusinessMember:!0,label:"atomic-expression"});continue}if(r.isJSXFragment()||r.isJSXElement()&&Me(r)){let o=sr(r);n||=o.unsupported,t.push(...o.members);continue}if(r.isJSXElement()){let o=un(r)?sr(r):null;n||=o?.unsupported??!1,t.push({...fc(r,o?.members),parentSourceRange:yt(e.node.loc)})}}return{members:t,unsupported:n}}function fc(e,t){let n=e.isJSXElement()&&un(e)?t??sr(e).members:[],r=e.isJSXElement()&&!un(e)&&!Me(e);return{memberKey:pc(e.node.type,e.node.start,e.node.end),kind:"jsx-element",nodeType:e.node.type,sourceRange:yt(e.node.loc),businessMemberCount:r?1:Gf(n),parentSourceRange:yt(e.parentPath?.node.loc),children:n,isBusinessMember:r,label:yk(e)}}function un(e){let t=e.node.openingElement.name;return t.type==="JSXIdentifier"&&t.name[0]===t.name[0]?.toLowerCase()}function yk(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 Gf(e){return e.reduce((t,n)=>t+n.businessMemberCount,0)}function Bi(e){return e.length===0?0:Math.max(1,Gf(e))}function Uf(e){let t=yt(e.containerPath.node.loc),n=gc(e.source,e.containerPath.node.start,e.containerPath.node.end),r=xt(e.input,e.containerKind,e.sourceKind,t),o=xt(e.input,e.containerKind,"placement-unit",t);return{placementKey:r,placementUnitKey:o,version:e.input.version,containerKey:r,independent:Bi(e.members)<=1,memberCount:Bi(e.members),sourceRange:t,sourceHash:n,relation:"append",containerSourceRange:t,containerSourceHash:n,anchorSourceRange:null,anchorSourceHash:null,members:e.members}}function xk(e){let t=yt(e.expression.node.loc),n=gc(e.source,e.expression.node.start,e.expression.node.end),r=xt(e.input,"virtual-route-root","atomic-expression",t),o=xt(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:xt(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 Yf(e,t){let n=yt(t.node.loc),r=gc(e.source,t.node.start,t.node.end);return!n||!r?null:{kind:"expression",documentVersion:e.version,sourceRange:n,sourceHash:r}}function cc(e,t,n,r,o){let i=Yf(e,o);if(!i)return kt(e,[Ve("UNSUPPORTED_PAGE_SHAPE","Route default export does not provide an exact mutation target",{reason:"mutation-target-unavailable"})]);let s=n.containerSourceRange??n.sourceRange,a=bk(e,n,s),c=ec(a),l={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:Qf(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 bk(e,t,n){if(t.members.length===0)return[t];let r=[],o=(l,u,f,m,d,g,h=n)=>({...t,placementKey:u,placementUnitKey:f,containerKey:t.placementKey,independent:Bi(g)<=1,memberCount:Bi(g),sourceRange:m,sourceHash:m?uc(e.source,m):null,relation:l,containerSourceRange:h,containerSourceHash:h?uc(e.source,h):null,anchorSourceRange:d,anchorSourceHash:d?uc(e.source,d):null,members:g}),i=t.placementKey,s=t.members.map(l=>xt(e,i,"placement-unit",l.sourceRange)),a=s[0]??t.placementUnitKey,c=s.at(-1)??t.placementUnitKey;r.push(o("prepend",xt(e,i,"prepend",n),a,n,null,[]));for(let l of t.members){let u=l.parentSourceRange??n,f=xt(e,i,"placement-unit",l.sourceRange);r.push(o("before",xt(e,f,"before",l.sourceRange),f,l.sourceRange,l.sourceRange,[l],u)),r.push(o("after",xt(e,f,"after",l.sourceRange),f,l.sourceRange,l.sourceRange,[l],u))}return r.push(o("append",i,c,n,null,[])),r}function lc(e,t,n,r){let o=Yf(e,r);if(!o)return kt(e,[Ve("UNSUPPORTED_PAGE_SHAPE","Route default export does not provide an exact mutation target",{reason:"mutation-target-unavailable"})]);let i=xt(e,n,"empty-container",void 0),s=xt(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=ec([a]),l={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:Qf(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 kt(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 Ve(e,t,n){return n===void 0?{code:e,message:t}:{code:e,message:t,details:n}}function xt(e,t,n,r){return Zf([e.route,e.entryFile,String(e.version),t,n,r?`${r.startLine}:${r.startColumn}-${r.endLine}:${r.endColumn}`:"no-range"])}function pc(e,t,n){return Zf(["member",e,String(t??-1),String(n??-1)])}function Zf(e){return`pc_${mc("sha256").update(e.join("\0")).digest("hex").slice(0,24)}`}function gc(e,t,n){return t==null||n==null?null:`sha256:${mc("sha256").update(e.slice(t,n)).digest("hex")}`}function uc(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:${mc("sha256").update(e.slice(r+t.startColumn,o+t.endColumn)).digest("hex")}`}function yt(e){return e?{startLine:e.start.line,startColumn:e.start.column,endLine:e.end.line,endColumn:e.end.column}:null}function Qf(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{PageTemplateIdSchema as Tk}from"@vcp-dev/contracts";import a_ from"node:fs";import l_ from"node:path";var Ek=/^page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function Zr(e){let t=e.map(r=>Ak(r.path)),n=vk(t);return n?t.filter(r=>Ik(n,r)).map(r=>({routeId:Ck(n,r),entryFile:r})).sort((r,o)=>r.routeId.localeCompare(o.routeId)):[]}function hc(e,t=""){let r=((e??"/").trim()||"/").split(/[?#]/,1)[0]||"/",o=r.startsWith("/")?r:`/${r}`,i=Pk(t),s=i&&(o===i||o.startsWith(`${i}/`))?o.slice(i.length)||"/":o,a=s.startsWith("/")?s:`/${s}`;return a==="/"?"/":a.replace(/\/+$/,"")}function vk(e){return e.some(r=>r.startsWith("app/")&&!kk(r))?"app":e.some(r=>r.startsWith("src/app/"))?"src/app":null}function kk(e){return/^(?:src\/)?app\/(?:_vcp|\.vcp)/.test(e)}function Ik(e,t){if(!t.startsWith(`${e}/`))return!1;let n=t.slice(t.lastIndexOf("/")+1);return Ek.test(n)?t.slice(e.length+1,-n.length-1).split("/").filter(Boolean).every(r=>!r.startsWith("_")&&!r.startsWith(".")):!1}function Ck(e,t){let n=t.slice(e.length+1).split("/").slice(0,-1).map(wk).filter(r=>!!r);return n.length===0?"/":`/${n.join("/")}`}function Rk(e){return e.startsWith("(")&&e.endsWith(")")}function wk(e){return!e||e.startsWith("@")||e.startsWith("_")||Rk(e)?null:Nk(e)}function Nk(e){return e.replace(/^\((?:\.|\.\.|\.\.\.)\)/,"")}function Pk(e){let t=e.trim();return!t||t==="/"?"":(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"")}function Ak(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}var Qr=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="PageTemplateManagedSourceError"}};function ot(e,t={}){throw new Qr("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Invalid page-template source (${e}): ${t.path??t.routeId??t.templateId??""}`,{reason:e,...t})}function yc(e){return Tk.safeParse(e).success||ot("invalid-template-id",{templateId:e}),Buffer.from(e,"utf8").toString("base64url")}function qf(e){/^[A-Za-z0-9_-]{1,255}$/.test(e)||ot("invalid-template-key",{path:e});let t;try{t=new TextDecoder("utf-8",{fatal:!0}).decode(Buffer.from(e,"base64url"))}catch{return ot("invalid-template-key",{path:e})}return yc(t)!==e&&ot("noncanonical-template-key",{path:e}),t}function Fk(e){let t=hc(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("(")||_k(r)&&!ep(r)))&&ot("invalid-public-route",{routeId:e}),t}function _k(e){return e.includes("[")||e.includes("]")}function ep(e){return/^\[\[\.\.\.[^\[\]]+\]\]$|^\[[^\[\]]+\]$/.test(e)}function tp(e){return e.some(ep)}function np(e,t,n="app"){n!=="app"&&n!=="src/app"&&ot("invalid-app-root");let r=Fk(e),o=yc(t),i=tp(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))&&ot("path-too-long",{path:a}),{appRoot:n,routeRoot:s,templateKey:o,templateEntryFile:a}}function rp(e){return/^(?:src\/)?app\/\.vcp\/page-templates\//.test(e)}function op(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===".")&&ot("invalid-file-path",{path:i}),n.has(i)&&ot("duplicate-file-path",{path:i}),n.set(i,o)}return n}function $i(e){let t=op(e.files),n=Zr([...t.keys()].map(i=>({path:i}))),r=new Map;for(let i of n){if(r.has(i.routeId))throw new Qr("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(!rp(i))continue;let s=/^(app|src\/app)\/\.vcp\/page-templates\/(.+)\/page\.tsx$/.exec(i);s||ot("candidate-must-be-single-page",{path:i});let a=s[1],c=s[2].split("/"),l=tp(c),u=l?c[0]:c.pop(),f=l?c.slice(1):c,m=qf(u),d=f.length?`/${f.join("/")}`:"/";np(d,m,a).templateEntryFile!==i&&ot("candidate-path-mismatch",{path:i,routeId:d});let h=r.get(d);(!h||!h.startsWith(`${a}/`))&&ot("canonical-entry-missing",{path:i,routeId:d}),o.push({routeId:d,templateId:m,entryFile:i,canonicalEntryFile:h,appRoot:a})}return o.sort((i,s)=>ji(i.routeId,s.routeId)||ji(i.templateId,s.templateId))}function ip(e){let t=op(e.files),n=$i({files:t}),r=Zr([...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)=>ji(o.context.routeId,i.context.routeId)||(o.context.effectiveTemplateId===void 0?-1:i.context.effectiveTemplateId===void 0?1:ji(o.context.effectiveTemplateId,i.context.effectiveTemplateId)))}function Mk(e){let t=hc(e.selector.routeId),n=ip({files:e.files}),r=n.find(i=>i.context.routeId===t&&i.context.effectiveTemplateId===void 0);(!r||r.entryFile!==e.canonicalEntryFile)&&ot("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||ot("template-selection-not-found",{routeId:t,templateId:e.selector.templateId}),{...o,mode:e.selector.templateId===void 0?"direct":"candidate",effectiveEntryFile:o.entryFile}}function ji(e,t){return e<t?-1:e>t?1:0}import{HOME_PAGE_URL_PATH as Wk}from"@vcp-dev/contracts";import{parse as uM}from"@babel/parser";import{parse as x_}from"@babel/parser";import{FormBlockIdSchema as S_,FormSpecV1Schema as E_}from"@vcp-dev/contracts";var qr="components/site/generated/forms",v_=`${qr}/vcp-form-runtime.tsx`,Vi="[A-Za-z0-9][A-Za-z0-9_-]{0,127}",k_=new RegExp(`^${qr}/form-(${Vi})\\.spec\\.ts$`),I_=new RegExp(`^${qr}/form-(${Vi})\\.tsx$`),C_=new RegExp(`^@/${qr}/form-(${Vi})$`),R_=new RegExp(`(?:^|/)${qr}/form-(${Vi})(?:\\.tsx?)?$`);var w_=Symbol("invalid-literal");import{createHash as A_}from"node:crypto";import{posix as F_}from"node:path";import{parse as M_}from"@babel/parser";import{FormSpecV1Schema as L_}from"@vcp-dev/contracts";var D_=Symbol("dynamic");import{parse as Ok}from"@babel/parser";function Ki(e){return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&typeof t.type=="string"):[]}var Lk=/^(?:src\/)?app\/(.*)page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function sp(e){let t=Lk.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 Dk(e){let t=e;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function ap(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function Bk(e){let t=e;for(;t&&(t.type==="TSAsExpression"||t.type==="TSSatisfiesExpression"||t.type==="ParenthesizedExpression");)t=t.expression??null;return t}function xc(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(xc);if(t?.type==="ObjectExpression"){let n={};for(let r of Ki(t.properties)){if(r.type!=="ObjectProperty"||r.computed)throw new Error("dynamic object property");let o=ap(r.key);if(!o)throw new Error("unsupported object key");n[o]=xc(r.value)}return n}throw new Error(`unsupported static value: ${t?.type??"unknown"}`)}function bc(e,t){let n=[],r=sp(t);if(r===null)return{found:!1,seo:null,diagnostics:n};let o;try{o=Ok(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 Ki(o.program.body)){let u=l.type==="ExportNamedDeclaration"?l.declaration:l;if(u?.type==="VariableDeclaration")for(let f of Ki(u.declarations)){let m=f.id;m?.type==="Identifier"&&m.name==="PAGE_SEO"&&(i=f.init)}}if(i==null)return{found:!1,seo:null,diagnostics:n};let s=Bk(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 Ki(s.properties)){if(l.type!=="ObjectProperty"||l.computed)continue;let u=ap(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 f=Dk(l.value);if(f===void 0){n.push({code:"page-seo.dynamic-field",message:`PAGE_SEO.${u} is not a static string; skipped`});continue}a[u]=f;continue}try{let f=xc(l.value);u==="meta_tags_json"&&f!==null&&typeof f=="object"&&!Array.isArray(f)?a.meta_tags_json=f:u==="schema_json"&&f!==null&&typeof f=="object"?a.schema_json=f:u==="breadcrumbs_json"&&Array.isArray(f)?a.breadcrumbs_json=f:n.push({code:"page-seo.dynamic-field",message:`PAGE_SEO.${u} has unsupported static shape; skipped`})}catch(f){n.push({code:"page-seo.dynamic-field",message:`PAGE_SEO.${u} is not a static JSON-like value; skipped: ${f instanceof Error?f.message:String(f)}`})}}}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 jk}from"@babel/parser";var cp=["page","anchor","external","email","phone","group","file"],$k=["link","cta"],up=["description","badge","iconKey"],Sc=["label","targetType","href","role","openInNewTab","nofollow","children",...up],Vk=new Set(Sc);function to(e){return Array.isArray(e)?e:[]}function eo(e){let t=e;return t?.type==="StringLiteral"&&typeof t.value=="string"?t.value:void 0}function Kk(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function lp(e){let t=e;return t?.type==="BooleanLiteral"&&typeof t.value=="boolean"?t.value:void 0}function Ec(e){let t=[],n;try{n=jk(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 to(n.program.body)){let s=i.type==="ExportNamedDeclaration"?i.declaration:i;if(s?.type==="VariableDeclaration")for(let a of to(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 to(r.elements).forEach((i,s)=>{let a=dp(i,`NAV_ITEMS[${s}]`,t);a&&o.push(a)}),{items:o,diagnostics:t}}function dp(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 to(e.properties)){if(l.type!=="ObjectProperty"||l.computed)continue;let u=Kk(l.key);u&&(r[u]=l.value)}let o=eo(r.label),i=eo(r.targetType);if(!o)return n.push({severity:"fatal",path:`${t}.label`,message:"label must be a static string"}),null;if(!i||!cp.includes(i))return n.push({severity:"fatal",path:`${t}.targetType`,message:`targetType must be one of ${cp.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 up){if(r[l]===void 0)continue;let u=eo(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))Vk.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 ${Sc.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=[];to(r.children.elements).forEach((u,f)=>{let m=dp(u,`${t}.children[${f}]`,n);m&&l.push(m)}),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=eo(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=eo(r.role);if(c!==void 0&&($k.includes(c)?s.role=c:n.push({severity:"warning",path:`${t}.role`,message:"role ignored: not link/cta"})),r.openInNewTab!==void 0){let l=lp(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=lp(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 Uk}from"@babel/parser";function no(e){return Array.isArray(e)?e:[]}function fp(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression";)t=t.expression;return t?.type==="ArrayExpression"?t:void 0}function Jk(e){let t;try{t=Uk(e,{sourceType:"module",plugins:["typescript","jsx"],tokens:!0})}catch{return{status:"unsupported"}}let n=[];for(let o of no(t.program.body)){let i=o.type==="ExportNamedDeclaration"?o.declaration:o;if(i?.type==="VariableDeclaration")for(let s of no(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=fp(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 vc(e,t){let n=pp(t);if(!n)return{status:"unsupported",source:e};let r=Jk(e);if(r.status!=="ok")return{status:r.status,source:e};let o=r.array;if(Ec(e).diagnostics.some(({severity:l})=>l==="fatal"))return{status:"unsupported",source:e};let s=[],a=l=>{let u=no(l.elements);for(let[f,m]of u.entries()){if(zk(m,n)){let g=u[f+1],h=u[f-1],S=m.start,E=m.end;if(typeof S!="number"||typeof E!="number")continue;if(g&&typeof g.start=="number")s.push({start:S,end:g.start});else if(h&&typeof h.end=="number")s.push({start:h.end,end:E});else{let y=/^\s*,/.exec(e.slice(E));s.push({start:S,end:y?E+y[0].length:E})}continue}let d=Xk(m);d&&a(d)}};if(a(o),s.length===0)return{status:"not_found",source:e};let c=e;for(let l of s.sort((u,f)=>f.start-u.start))c=c.slice(0,l.start)+c.slice(l.end);return{status:"removed",source:c,removedCount:s.length}}function Xk(e){if(e.type==="ObjectExpression")for(let t of no(e.properties)){if(t.type!=="ObjectProperty")continue;let n=t.key;if((n?.name??n?.value)==="children")return fp(t.value)}}function pp(e){let t=e.trim();return t.startsWith("/")?t==="/"?t:t.replace(/\/+$/,""):null}function zk(e,t){if(e.type!=="ObjectExpression")return!1;let n,r;for(let o of no(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"&&pp(n??"")===t}import{estimateNavLabelWidth as W_}from"@vcp-dev/contracts";import{parse as Y_}from"@babel/parser";var Hk="components/site/generated/",ro=[".tsx",".ts",".jsx",".js"];function mp(e){if(e.expectedUrlPath===Wk)return{ok:!1,code:"HOME_PAGE_LOCKED",message:"The homepage source is protected from deletion."};let t=new Set(Zr(Object.keys(e.files).map(h=>({path:h}))).map(h=>h.entryFile)),n=Object.entries(e.files).filter(([h,S])=>{let E=h.replace(/\\/g,"/");if(!t.has(E))return!1;let y=bc(S,E);return y.found&&y.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=$i({files:new Map(Object.entries(e.files))});for(let S of h)S.canonicalEntryFile===r&&o.add(S.entryFile)}catch(h){return{ok:!1,code:"SOURCE_DEPENDENCY_UNSAFE",message:h instanceof Error?h.message:"Invalid page template source."}}let i=Gk(e.files);if(!i.ok)return i.error;let s=i.graph,a=qk(o,s),c=eI(o,a,s),l=[...a].filter(h=>!c.has(h)).sort((h,S)=>h.localeCompare(S)),u=[...o,...[...c].sort((h,S)=>h.localeCompare(S))],f=new Set(u),m=u.map(h=>({operation:"delete",file:h})),d=[],g=[];for(let[h,S]of Object.entries(e.files))if(!f.has(h)){if(S.includes("NAV_ITEMS")){let E=vc(S,e.expectedUrlPath);E.status==="removed"?(m.push({operation:"upsert",file:h,content:E.source}),d.push(h)):E.status==="unsupported"&&g.push(`unsupported_navigation:${h}`)}S.includes(e.expectedUrlPath)&&!S.includes("NAV_ITEMS")&&g.push(`preserved_link:${h}`)}return{ok:!0,edits:m,deletedFiles:u,updatedFiles:d,preservedSharedFiles:l,warnings:g}}function Gk(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")||!Yk(r))continue;let s=Ut(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(Zk(c))continue;let l=bn(r,c),u=Qk(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 Yk(e){let t=e.toLowerCase();return ro.some(n=>t.endsWith(n))}function Zk(e){return!!(/\.([a-z0-9]+)$/i.exec(e)&&!ro.some(n=>e.endsWith(n)))}function Qk(e,t){let n=e.replace(/\\/g,"/");return(ro.some(o=>n.endsWith(o))?[n]:[...ro.map(o=>`${n}${o}`),...ro.map(o=>`${n}/index${o}`)]).find(o=>t.has(o))??null}function qk(e,t){let n=new Set,r=[...e].flatMap(o=>[...t.get(o)??[]]);for(;r.length>0;){let o=r.pop();!o.startsWith(Hk)||n.has(o)||(n.add(o),r.push(...t.get(o)??[]))}return n}function eI(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 mm from"@babel/parser";import*as pe from"@babel/types";import*as is from"node:path";import*as Ee from"@babel/types";function gp(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 Mt(e){if(e.path.isObjectPattern()||e.path.isArrayPattern())return Tn(e.path.node,e.identifier.name);if(e.path.isVariableDeclarator()){let n=e.path.node.id;if(Ee.isObjectPattern(n)||Ee.isArrayPattern(n))return Tn(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(nI(e.path,n))return!0}if(t.isFunction()||t.isVariableDeclarator())return!1;t=t.parentPath}return!1}function Tn(e,t,n=!1){return Ee.isIdentifier(e)?e.name===t&&n:Ee.isObjectPattern(e)?e.properties.some(r=>Ee.isObjectProperty(r)?Tn(r.value,t,n):Tn(r.argument,t,n)):Ee.isArrayPattern(e)?e.elements.some(r=>{if(!r)return!1;let o=Ee.isRestElement(r)?r.argument:r;return Tn(o,t,n)}):Ee.isAssignmentPattern(e)?Tn(e.left,t,!0):Ee.isRestElement(e)?Tn(e.argument,t,n):!1}function ar(e,t){if(e.path.isObjectPattern()){if(t){let r=It(e.path.node,t.base),[o,...i]=r??[];if(o?.kind==="property")return{propName:o.name,remainingPath:[...i,...t.path],hasDefault:Mt(e)}}return t?{propName:t.base,remainingPath:t.path,hasDefault:Mt(e)}:null}if(e.path.isVariableDeclarator()){let r=e.path.get("init");if(r?.isExpression()){let o=hp(r),i=!1,s=o?o.initBinding&&kc(o.initBinding)?(i=Mt(o.initBinding),[...o.initPathPrefix]):o.initBinding?(()=>{let c=ar(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=It(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||Mt(e)}}}}let n=iI(e);if(n){let r=tI(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||Mt(e)}}if(n.findParent(s=>s.isVariableDeclarator()))return null;let o=rI(e);if(o){let[s,...a]=o;return!s||s.kind!=="property"?null:{propName:s.name,remainingPath:[...a,...t?.path??[]],hasDefault:Mt(e)}}let i=oo(n.node);return i?{propName:i,remainingPath:t?.path??[],hasDefault:Mt(e)}:null}if(kc(e)){let[r,...o]=t?.path??[];return!r||r.kind!=="property"?null:{propName:r.name,remainingPath:o,hasDefault:Mt(e)}}return null}function tI(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=hp(r);if(!o)return null;let{initBinding:i,initPathPrefix:s}=o;if(!i)return null;let a=!1,c=kc(i)?(a=Mt(i),[...s]):(()=>{let u=ar(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=It(n.node.id,t.identifier.name);return l?{path:[...c,...l],hasDefault:a||Mt(t)}:null}function hp(e){if(e.isIdentifier())return{initBinding:e.scope.getBinding(e.node.name),initPathPrefix:[]};if(!e.isMemberExpression())return null;let t=sI(e.node);return t?{initBinding:e.scope.getBinding(t.base),initPathPrefix:t.path}:null}function kc(e){return e.path.isIdentifier()&&e.path.key===0&&Array.isArray(e.path.container)&&e.path.parentPath?.isFunction()===!0}function nI(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function rI(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=It(i.node,t);if(a)return a}return null}function yp(e,t,n){if(e.path.isVariableDeclarator()){let a=e.path.get("id");if(!Array.isArray(a)&&(a.isObjectPattern()||a.isArrayPattern())){let c=Ui(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=oo(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=oI(e);if(!r)return null;let o=r.parentPath;if(!o?.isObjectProperty())return null;let i=oo(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 Ui(e,t){if(e.isObjectPattern()){for(let n of e.get("properties"))if(n.isObjectProperty()){let r=oo(n.node),o=n.get("value");if(o.isAssignmentPattern()){let i=o.get("left"),s=o.get("right");if(r&&!Array.isArray(i)&&It(i.node,t)&&!Array.isArray(s)&&s.isExpression())return{propName:r,expressionPath:s}}if(!Array.isArray(o)&&(o.isObjectPattern()||o.isArrayPattern())){let i=Ui(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=Ui(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=Ui(r,t);if(o)return o}}return null}function It(e,t,n=[]){if(Ee.isIdentifier(e))return e.name===t?n:null;if(Ee.isObjectPattern(e)){for(let r of e.properties)if(Ee.isObjectProperty(r)){let o=oo(r);if(!o)continue;let i=It(r.value,t,[...n,{kind:"property",name:o}]);if(i)return i}else if(Ee.isRestElement(r)){let o=It(r.argument,t,n);if(o)return o}}if(Ee.isArrayPattern(e))for(let r=0;r<e.elements.length;r+=1){let o=e.elements[r];if(!o)continue;let i=Ee.isRestElement(o)?o.argument:o,s=It(i,t,[...n,{kind:"index",index:r}]);if(s)return s}return Ee.isAssignmentPattern(e)?It(e.left,t,n):null}function oI(e){if(!e.path.isIdentifier())return null;let t=e.path.parentPath;return t?.isAssignmentPattern()&&t.node.left===e.path.node?t:null}function iI(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 oo(e){return e.computed?null:Ee.isIdentifier(e.key)?e.key.name:Ee.isStringLiteral(e.key)?e.key.value:null}function sI(e){let t=[],n=e;for(;Ee.isMemberExpression(n);){if(n.computed)if(Ee.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(Ee.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(Ee.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return Ee.isIdentifier(n)?{base:n.name,path:t}:null}import*as vp from"@babel/parser";import Rc from"@babel/traverse";import*as cr from"@babel/types";import*as ae from"@babel/types";function zi(e,t=[]){if(e.isIdentifier()){let n=e.scope.getBinding(e.node.name);return n?Ji(n,t):null}if(e.isMemberExpression()){let n=fI(e.node),r=aI(e.node);if(!n||r===null)return null;let o=e.scope.getBinding(n);return o?Ji(o,[...r,...t]):null}return e.isAwaitExpression()||Cc(e.node)?dn(mI(e.node),t,"awaited or fetched expression"):null}function aI(e){let t=[],n=e;for(;ae.isMemberExpression(n);){if(n.computed)if(ae.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(ae.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(ae.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return ae.isIdentifier(n)?t:null}function Ji(e,t=[],n){let r=cI(e,t);if(r)return r;let o=lI(e,t);if(o)return o;let i=uI(e,t,n);return i||null}function so(e){return e?.kind==="api-source"}function cI(e,t){if(e.path.isVariableDeclarator()&&ae.isIdentifier(e.path.node.id)){let s=e.path.get("init");if(s?.isCallExpression()&&Ic(s.node)&&t[0]?.kind==="property"&&t[0].name==="data")return dn(e.identifier.name,t,"query hook result.data binding")}if(e.path.isVariableDeclarator()&&ae.isObjectPattern(e.path.node.id)){let s=e.path.node.id.properties.find(c=>ae.isObjectProperty(c)&&Sp(c)==="data"&&io(c.value,e.identifier.name)),a=e.path.get("init");if(s&&a?.isCallExpression()&&Ic(a.node))return dn(e.identifier.name,t,"query hook data binding")}let n=dI(e);if(!n||Sp(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()||!Ic(i.node)?null:dn(e.identifier.name,t,"query hook data binding")}function lI(e,t){if(e.path.isVariableDeclarator()&&ae.isArrayPattern(e.path.node.id)){let a=e.path.get("init");if(!a?.isCallExpression()||!bp(a.node))return null;let[c,l]=e.path.node.id.elements;return!ae.isIdentifier(c)||c.name!==e.identifier.name||!ae.isIdentifier(l)?null:xp(e,l.name)?dn(e.identifier.name,t,"state setter is updated by API data"):null}if(!e.path.isIdentifier())return null;let n=e.path.parentPath;if(!n?.isArrayPattern())return null;let r=n.parentPath;if(!r?.isVariableDeclarator())return null;let o=r.get("init");if(!o?.isCallExpression()||!bp(o.node)||n.node.elements.findIndex(a=>a===e.path.node)!==0)return null;let s=n.node.elements[1];return ae.isIdentifier(s)&&xp(e,s.name)?dn(e.identifier.name,t,"state setter is updated by API data"):null}function uI(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()?dn(e.identifier.name,t,"awaited binding result"):Cc(o.node,n)?dn(e.identifier.name,t,"fetch-backed binding result"):null:null}function dI(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 io(e,t){return ae.isIdentifier(e)?e.name===t:ae.isAssignmentPattern(e)?io(e.left,t):ae.isObjectPattern(e)?e.properties.some(n=>ae.isObjectProperty(n)?io(n.value,t):io(n.argument,t)):ae.isArrayPattern(e)?e.elements.some(n=>!!n&&io(ae.isRestElement(n)?n.argument:n,t)):!1}function xp(e,t){let n=!1,r=!1;return e.scope.path.traverse({CallExpression(i){Cc(i.node)&&(n=!0),(pI(i.node.callee,t)||i.node.arguments.some(s=>ae.isIdentifier(s)&&s.name===t))&&(r=!0)}}),n&&r}function Ic(e){let t=Wi(e.callee);return t==="useQuery"||t==="useSWR"||t==="useSuspenseQuery"}function bp(e){return Wi(e.callee)==="useState"}function Cc(e,t){let n=t?.get(e);if(n!==void 0)return n;let r=Xi(e,o=>ae.isCallExpression(o)&&Wi(o.callee)==="fetch");return t?.set(e,r),r}function fI(e){let t=e;for(;ae.isMemberExpression(t);)t=t.object;return ae.isIdentifier(t)?t.name:null}function Sp(e){return e.computed?null:ae.isIdentifier(e.key)?e.key.name:ae.isStringLiteral(e.key)?e.key.value:null}function Wi(e){return ae.isIdentifier(e)?e.name:ae.isMemberExpression(e)&&ae.isIdentifier(e.property)?e.property.name:null}function pI(e,t){return Xi(e,n=>ae.isIdentifier(n)&&n.name===t)}function Xi(e,t){if(t(e))return!0;let n=ae.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(ae.isNode(i)&&Xi(i,t))return!0;continue}if(ae.isNode(o)&&Xi(o,t))return!0}return!1}function mI(e){return ae.isIdentifier(e)?e.name:ae.isCallExpression(e)?Wi(e.callee)??"api":ae.isAwaitExpression(e)?"awaited-api":"api"}function dn(e,t,n){return{kind:"api-source",readonly:!0,sourceId:e,displayPath:gI(e,t),reason:n}}function gI(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}var kp=typeof Rc=="function"?Rc:Rc.default;function Ip(e,t){let n=Rp(e);if(!n)return{allowed:!0};let r=!1;return kp(n,{CallExpression(o){if(!wp(o.node,t.sourceRange)||!hI(o.node))return;let i=o.get("callee");if(!i.isMemberExpression())return;let s=i.get("object");Array.isArray(s)||!s.isExpression()||so(zi(s))&&(r=!0,o.stop())}}),r?{allowed:!1,reason:"Cannot add data-backed items to a dynamic API list"}:{allowed:!0}}function Cp(e,t){let n=Rp(e);if(!n)return{allowed:!0};let r=!1;return kp(n,{JSXExpressionContainer(o){wp(o.node,t.sourceRange)&&(cr.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 Rp(e){try{return vp.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function hI(e){let t=e.callee;return cr.isMemberExpression(t)&&cr.isIdentifier(t.property)&&t.property.name==="map"}function wp(e,t){let n=e.loc;return n?Ep({line:n.start.line,column:n.start.column},{line:t.startLine,column:t.startColumn})>=0&&Ep({line:n.end.line,column:n.end.column},{line:t.endLine,column:t.endColumn})<=0:!1}function Ep(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 X from"@babel/types";import*as Np from"@babel/parser";import wc from"@babel/traverse";import*as Fe from"@babel/types";import*as lr from"node:path";var Ct=typeof wc=="function"?wc:wc.default;function Je(e){try{return Np.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function Nc(e){return e.computed?Fe.isStringLiteral(e.key)||Fe.isNumericLiteral(e.key)?String(e.key.value):null:yI(e.key)}function yI(e){return Fe.isIdentifier(e)?e.name:Fe.isStringLiteral(e)||Fe.isNumericLiteral(e)?String(e.value):null}function Fn(e){return Fe.isParenthesizedExpression(e)||Fe.isTSAsExpression(e)||Fe.isTSSatisfiesExpression(e)||Fe.isTSNonNullExpression(e)||Fe.isTSTypeAssertion(e)?Fn(e.expression):Fe.isExpression(e)?e:null}function Pc(e){if(Fe.isIdentifier(e))return[e.name];if((Fe.isMemberExpression(e)||Fe.isOptionalMemberExpression(e))&&!e.computed&&Fe.isIdentifier(e.property)){let t=Fn(e.object),n=t?Pc(t):null;return n?[...n,e.property.name]:null}return null}function _n(e,t){return t.startsWith("@/")?t.slice(2).replace(/\\/g,"/"):t.startsWith(".")?lr.normalize(lr.join(lr.dirname(e),t)).replace(/\\/g,"/"):t}function ct(e,t){return Hi(e)===Hi(t)}function Hi(e){let t=ur(e);return t.endsWith("/index")?t.slice(0,-6):t}function ur(e){return e.replace(/\.(tsx|ts|jsx|js)$/,"")}function Tp(e,t,n){let r=Op(e,t);if(Lp(e,r),Dp(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 Ct(e,{JSXElement(s){Vp(s,r)&&o.push(s)}}),o.length!==1?{ok:!1,reason:"Cannot move prop-backed repeat child without a single unambiguous component call site"}:Gi(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 Fp(e,t){let n=new Map,r=i=>{let s=dr(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 xI(i,n))o=r(s)||o}return[...n.values()]}function xI(e,t){let n=[],r=bI(e,t);for(let o of e.ast.program.body){if(X.isExportDefaultDeclaration(o)&&X.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=ao(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(X.isExportNamedDeclaration(o)&&o.source&&typeof o.source.value=="string"){let i=_n(e.file,o.source.value);for(let s of o.specifiers){if(X.isExportNamespaceSpecifier(s)){let l=fn(s.exported);for(let u of t.values())ct(u.file,i)&&n.push({file:e.file,namespace:Ac(l,u.namespace),exportName:u.exportName});continue}if(!X.isExportSpecifier(s))continue;let a=fn(s.local),c=[...t.values()].filter(l=>ct(l.file,i)&&Mn(l.namespace,a));if(c.length>0){let l=fn(s.exported);for(let u of c){let f=ao(u.namespace,a,l);f&&n.push({file:e.file,namespace:f,exportName:u.exportName})}continue}t.has(dr({file:i,exportName:a}))&&n.push({file:e.file,exportName:fn(s.exported)})}continue}if(X.isExportNamedDeclaration(o)&&!o.source){for(let i of o.specifiers){if(!X.isExportSpecifier(i))continue;let s=fn(i.local),a=r.get(s)??[];if(a.length>0){let c=fn(i.exported);n.push({file:e.file,exportName:c});for(let l of a){let u=ao(l.namespace,s,c);u&&n.push({file:e.file,namespace:u,exportName:l.exportName})}}}continue}if(X.isExportAllDeclaration(o)&&typeof o.source.value=="string"){let i=_n(e.file,o.source.value),s=o.exported;if(s){let a=fn(s);for(let c of t.values())ct(c.file,i)&&n.push({file:e.file,namespace:Ac(a,c.namespace),exportName:c.exportName});continue}for(let a of t.values())ct(a.file,i)&&(a.namespace||a.exportName!=="default")&&n.push({file:e.file,namespace:a.namespace,exportName:a.exportName})}}return n}function Ac(e,t){return t?`${e}.${t}`:e}function Mn(e,t){return e===t||e?.startsWith(`${t}.`)===!0}function ao(e,t,n){return!Mn(e,t)||!e?null:e===t?n:`${n}${e.slice(t.length)}`}function bI(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(!X.isImportDeclaration(i)||typeof i.source.value!="string")continue;let s=_n(e.file,i.source.value);for(let a of i.specifiers){if(X.isImportDefaultSpecifier(a)){let c=t.get(dr({file:s,exportName:"default"}));c&&r(a.local.name,c);let l=[...t.values()].filter(u=>ct(u.file,s)&&Mn(u.namespace,"default"));for(let u of l){let f=ao(u.namespace,"default",a.local.name);f&&r(a.local.name,{...u,namespace:f})}continue}if(X.isImportSpecifier(a)){let c=fn(a.imported),l=[...t.values()].filter(f=>ct(f.file,s)&&Mn(f.namespace,c));for(let f of l)r(a.local.name,f);let u=t.get(dr({file:s,exportName:c}));u&&r(a.local.name,u);continue}if(X.isImportNamespaceSpecifier(a))for(let c of t.values())ct(c.file,s)&&r(a.local.name,{...c,namespace:Ac(a.local.name,c.namespace)})}}let o=!0;for(;o;){o=!1;for(let i of e.ast.program.body)if(X.isVariableDeclaration(i))for(let s of i.declarations){if(!X.isIdentifier(s.id)||!s.init)continue;let a=Fn(s.init);if(!a||!X.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(dr));for(let f of c){let m=ao(f.namespace,a.name,s.id.name),d=m?{...f,namespace:m}:f,g=dr(d);u.has(g)||(r(s.id.name,d),u.add(g),o=!0)}}}return n}function dr(e){let t=e.namespace?`${e.namespace}.${e.exportName}`:e.exportName;return`${Hi(e.file)}#${t}`}function fn(e){return X.isIdentifier(e)?e.name:e.value}function _p(e,t){for(let n of e.program.body){if(X.isExportDefaultDeclaration(n)){let o=n.declaration;if((X.isFunctionDeclaration(o)||X.isClassDeclaration(o))&&o.id?.name===t)return{exportName:"default"};if(X.isIdentifier(o)&&o.name===t)return{exportName:"default"}}if(!X.isExportNamedDeclaration(n))continue;let r=n.declaration;if((X.isFunctionDeclaration(r)||X.isClassDeclaration(r))&&r.id?.name===t)return{exportName:t};if(X.isVariableDeclaration(r)){for(let o of r.declarations)if(X.isIdentifier(o.id,{name:t}))return{exportName:t}}for(let o of n.specifiers){if(!X.isExportSpecifier(o)||o.local.name!==t)continue;return{exportName:X.isIdentifier(o.exported)?o.exported.name:o.exported.value}}}return null}function Fc(e){let t=SI(e),n=[],r=Dp(e.ast,t);return Ct(e.ast,{JSXElement(o){ct(e.file,e.sourceFile)&&Gi(o)===e.sourceComponent||Vp(o,t)&&n.push({file:e.file,path:o})}}),{callSites:n,hasUnsafeReference:r}}function Mp(){return{localBindings:new Set,namespaceMembers:new Map,hasUnsupportedAlias:!1}}function Op(e,t){let n=Mp();return Ct(e,{Program(r){let o=r.scope.getBinding(t);o&&n.localBindings.add(o),r.stop()}}),n}function SI(e){let t=Mp();return ct(e.file,e.sourceFile)&&EI(t,Op(e.ast,e.sourceComponent)),Ct(e.ast,{ImportDeclaration(n){let r=n.node,o=r.source.value;if(typeof o!="string")return;let i=_n(e.file,o),s=e.componentIdentities.filter(a=>ct(a.file,i));if(s.length!==0)for(let a of r.specifiers){let c=n.scope.getBinding(a.local.name);if(c){if(X.isImportDefaultSpecifier(a)&&s.some(l=>l.exportName==="default")&&t.localBindings.add(c),X.isImportDefaultSpecifier(a)){let l=s.filter(u=>Mn(u.namespace,"default"));if(l.length>0){let u=t.namespaceMembers.get(c)??new Set;for(let f of l){let m=Ap(f,"default");m&&u.add(m)}t.namespaceMembers.set(c,u)}continue}if(X.isImportSpecifier(a)){let l=X.isIdentifier(a.imported)?a.imported.name:a.imported.value,u=s.filter(f=>Mn(f.namespace,l));if(u.length>0){let f=t.namespaceMembers.get(c)??new Set;for(let m of u){let d=Ap(m,l);d&&f.add(d)}t.namespaceMembers.set(c,f);continue}s.some(f=>!f.namespace&&f.exportName===l)&&t.localBindings.add(c);continue}if(X.isImportNamespaceSpecifier(a))for(let l of s){let u=l.namespace?`${l.namespace}.${l.exportName}`:l.exportName,f=t.namespaceMembers.get(c)??new Set;f.add(u),t.namespaceMembers.set(c,f)}}}}}),Lp(e.ast,t),t}function EI(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 Lp(e,t){Ct(e,{VariableDeclarator(n){if(!n.node.init)return;let r=Fn(n.node.init);if(r){if(X.isIdentifier(n.node.id)){let o=On(r,t,n),i=n.scope.getBinding(n.node.id.name);o&&i&&Tc(t,i,o);return}if(X.isObjectPattern(n.node.id)){let o=On(r,t,n);o?.unsupported||o?.local?t.hasUnsupportedAlias=!0:o&&o.namespaceMembers.size>0&&$p(n.node.id,o.namespaceMembers,t,n)}}}})}function Dp(e,t){if(t.hasUnsupportedAlias)return!0;let n=!1;return Ct(e,{ReferencedIdentifier(r){if(n){r.stop();return}vI(r)||!r.isIdentifier()||!Bp(r,t)||kI(r,t)||II(r)||(n=!0,r.stop())}}),n}function vI(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 Bp(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)&&On(r.node,t,r)?r:null}function kI(e,t){let n=e.findParent(c=>c.isVariableDeclarator());if(!n?.isVariableDeclarator())return!1;let r=n.get("init");if(!r?.isExpression()||!Pp(e,r))return!1;let o=Bp(e,t);if(!o)return!1;if(Fn(r.node)===o.node)return!!On(r.node,t,r);let s=e.findParent(c=>c.isObjectProperty());if(!s?.isObjectProperty())return!1;let a=s.get("value");return a.isExpression()&&Pp(e,a)&&!!On(a.node,t,a)}function II(e){let t=e.parentPath;return t?.isExportDefaultDeclaration()&&t.node.declaration===e.node?!0:!!(t?.isExportSpecifier()&&t.node.local===e.node)}function Pp(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function On(e,t,n){let r=Fn(e);if(!r)return null;if(X.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(X.isObjectExpression(r))return CI(r,t,n);let o=Pc(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?jp(s,o.slice(1).join(".")):null}function CI(e,t,n){let r=new Set,o=!1;for(let i of e.properties){if(!X.isObjectProperty(i))continue;let s=Nc(i);if(!s||!X.isExpression(i.value)){X.isExpression(i.value)&&(o||=On(i.value,t,n)!==null);continue}let a=On(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 jp(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 Tc(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 $p(e,t,n,r){for(let o of e.properties){if(X.isRestElement(o)){if(X.isIdentifier(o.argument)){let c=r.scope.getBinding(o.argument.name);c&&Tc(n,c,{local:!1,namespaceMembers:new Set(t),unsupported:!1})}else n.hasUnsupportedAlias=!0;continue}if(!X.isObjectProperty(o))continue;let i=Nc(o);if(!i){n.hasUnsupportedAlias=!0;continue}let s=jp(t,i);if(!s)continue;n.hasUnsupportedAlias||=s.unsupported;let a=X.isAssignmentPattern(o.value)?o.value.left:o.value;if(X.isIdentifier(a)){let c=r.scope.getBinding(a.name);c&&Tc(n,c,s);continue}if(X.isObjectPattern(a)&&s.namespaceMembers.size>0){$p(a,s.namespaceMembers,n,r);continue}n.hasUnsupportedAlias=!0}}function Ap(e,t){if(!Mn(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 Vp(e,t){let n=e.node.openingElement.name;if(X.isJSXIdentifier(n)){let o=e.scope.getBinding(n.name);return!!(o&&t.localBindings.has(o))}let r=Kp(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 Kp(e){if(X.isJSXIdentifier(e))return[e.name];if(X.isJSXMemberExpression(e)){let t=Kp(e.object);return t?[...t,e.property.name]:null}return null}function Gi(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()&&X.isIdentifier(n.node.id))return n.node.id.name}return null}function Up(e,t){let n=Je(e);if(!n||!t.tag||!t.importedFrom||!t.exportName)return Number.POSITIVE_INFINITY;let r=Fc({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 xe(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 ye(e){return typeof e.start=="number"&&typeof e.end=="number"?{start:e.start,end:e.end}:null}function Ot(e,t){let n=ye(e);return!!(n&<(t,n))}function lt(e,t){return t.start>=e.start&&t.end<=e.end}function bt(e,t){let n=se(e,xe(t));return n.ok&&n.match.path.isJSXElement()?n.match.path:Yi(e,t)}function fr(e,t){let n=ye(t);return n?e.slice(n.start,n.end):""}function Jp(e,t){return e.start===t.start&&e.end===t.end}function Yi(e,t){let n=null;return Ct(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 Zi(e,t){return _c(e,t).length>0}function Qi(e,t){let n=ye(e.node),r=ye(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()&&!RI(o,n,r)))return!0;o=o.parentPath}return!1}function RI(e,t,n){let r=ye(e.node.consequent);if(r&<(r,t)&&!lt(r,n))return!1;let o=e.node.alternate?ye(e.node.alternate):null;return!(o&<(o,t)&&!lt(o,n))}function _c(e,t){let n=ye(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=ye(o.node.consequent),a=ye(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()&&Mc(o.node.operator)){let s=ye(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 Mc(e){return e==="&&"||e==="||"||e==="??"}function Xp(e,t){let n=ye(e.consequent);if(n&<(n,t))return n;let r=ye(e.alternate);return r&<(r,t)?r:null}function zp(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=>ur(a.file)));if(!t.has(ur(e.sourceFile))||!t.has(ur(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(ur(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=_p(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=Je(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=Fp(r,{file:e.sourceFile,exportName:n.exportName}),i=[];for(let a of r){let c=Fc({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!ct(s.file,e.targetFile)||Gi(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 FI}from"@vcp-dev/contracts";function qi(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 co();let a=s.target,c=a.locator;if(a.sourceKind==="repeat-template"){let l=o?.instanceIndex;if(l===void 0)return co();let u=wI(a,l,o?.instanceCount);if(!u)return co();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"?co():{ok:!0,target:{kind:"jsx-attribute"}}}function co(){return{ok:!1,code:"unsupported-binding",reason:"Property does not have a safe typed binding write target for this scope and operation"}}function wI(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 Lt from"@babel/types";import{SiteEditSetPropsParamsSchema as NI}from"@vcp-dev/contracts";function Wp(e){let t=e.changes??(e.change?[e.change]:[]);if(!NI.safeParse({kind:"set-props",scope:"selection",changes:t}).success)return lo("invalid-change","Repeat property changes are invalid");if(t.length!==1||t[0].name!==e.target.propertyName)return lo("target-mismatch","A repeat property plan must contain exactly one change for its target property");let r=t[0];if(r.operation==="remove"&&e.target.propertyState==="missing")return{ok:!0,steps:[]};let o=we(e.source,"value");if(!o.ok)return lo("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=se(o.ast,a);if(!c.ok||!c.match.path.isObjectExpression())return lo("unsupported-object",`Repeat item ${s} is not a writable object expression`);let l=s===e.target.sourceItemIndex?PI(r):AI(c.match.path.node,r.name);if(!l)return lo("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 PI(e){return e.operation==="set"?{kind:"value",value:e.value}:{kind:"undefined"}}function AI(e,t){let n=e.properties.filter(i=>Lt.isObjectProperty(i)&&TI(i.key)===t);if(n.length>1)return null;let r=n[0];if(!r)return{kind:"undefined"};if(!Lt.isExpression(r.value))return null;let o=_t(r.value);return o.status==="undefined"?{kind:"undefined"}:o.status!=="resolved"?null:{kind:"value",value:o.value}}function TI(e){return Lt.isIdentifier(e)?e.name:Lt.isStringLiteral(e)?e.value:Lt.isNumericLiteral(e)?String(e.value):null}function lo(e,t){return{ok:!1,errorCode:e,reason:t}}function Hp(e){if(e.change.name!=="className"&&e.change.name!=="class")return uo("unsupported-owner",`No specialized property owner is available for '${e.change.name}'`);let t=e.classNameSource;if(!t||t.filePath!==e.node.file)return uo("owner-source-unavailable","className source details are unavailable for the selected node");if(e.change.name==="class"&&t.sourceKind==="missing")return uo("owner-source-unavailable","The class alias requires an existing className source");if(t.sourceKind==="expression")return uo("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 uo("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 uo(e,t){return{ok:!1,errorCode:e,reason:t}}async function Yp(e){let t=FI.safeParse({kind:"set-props",scope:e.scope,changes:e.changes});if(!t.success)return pn("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 pn("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 _I(e,r);if(o){if(!o.ok)return pn("owner-plan-failed",o.reason);Gp(n,o.steps);continue}let i=await e.getPropertyState(e.node.key,r.name,e.selectionRef);if(!i)return pn("missing-property-state",`No authoritative property state is available for '${r.name}'`);if(i.status==="blocked")return pn("readonly-property",i.diagnostic?.message??`Property '${r.name}' is not writable`);if(LI(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=qi({state:i,scope:e.scope,operation:r.operation,selectionRef:e.selectionRef,repeatTarget:s});if(!a.ok)return pn(a.code,a.reason);let c=a.target;if(c.kind==="value-binding"&&r.operation==="set"){Oc(n,{type:"update-value",order:n.length,file:c.file,locator:c.locator,value:r.value});continue}if(c.kind==="repeat-property"){let l=Wp({source:e.getFileContent(c.target.sourceFile),target:c.target,changes:[r]});if(!l.ok)return pn("repeat-target-failed",l.reason);Gp(n,l.steps);continue}Oc(n,{type:"set-property-changes",order:n.length,file:e.node.file,locator:MI(e.node),scope:e.scope,changes:[r]})}return n.forEach((r,o)=>{r.order=o}),OI(n)?pn("step-conflict","Property changes resolve to conflicting write steps"):{ok:!0,steps:n}}async function _I(e,t){return t.name!=="className"&&t.name!=="class"?null:Hp({node:e.node,change:t,classNameSource:e.classNameSource})}function MI(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 OI(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 Gp(e,t){for(let n of t)Oc(e,{...n,order:e.length})}function Oc(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 LI(e,t){if(t.operation!=="set"||e.status!=="direct")return!1;let n=e.attribute?.resolution;return n?.status==="resolved"?Lc(n.value,t.value):e.attribute?.source===null&&e.attribute.value===t.value}function Lc(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)=>Lc(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=>Lc(n[i],r[i]))}return!1}function pn(e,t){return{ok:!1,errorCode:e,reason:t}}import*as mr from"@babel/types";import*as G from"@babel/types";function Dc(e,t,n){let r=bt(t,n);return r?Dt(e,r):null}function Dt(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(!G.isIdentifier(l)||l.name!=="map"||c.computed)return null;let u=a.get("object"),f=fr(e,u.node),m=r.node.params.map(h=>fr(e,h)),d=ye(i.node),g=ye(r.node);return!f||m.some(h=>h.length===0)||!d||!g?null:{callStart:d.start,callEnd:d.end,callbackStart:g.start,callbackEnd:g.end,collectionExpression:f,callbackParams:m,mapOperator:G.isOptionalMemberExpression(c)&&c.optional?"?.map":".map",collectionNeedsParens:es(u.node),callbackPath:r,collectionPath:u}}function fo(e,t){return!!(e&&t&&e.callStart===t.callStart&&e.callEnd===t.callEnd&&e.callbackStart===t.callbackStart&&e.callbackEnd===t.callbackEnd)}function DI(e,t){let n=ye(e.node);return n?BI(t).some(r=>{let o=ye(r);return r===e.node||!!(o&&o.start===n.start&&o.end===n.end)}):!1}function BI(e){let t=e.callbackPath.node.body;return G.isBlockStatement(t)?mn(t.body):gn(t)}function mn(e){let t=[];for(let n of e){if(G.isReturnStatement(n)){n.argument&&t.push(...gn(n.argument));continue}if(G.isBlockStatement(n)){t.push(...mn(n.body));continue}if(G.isIfStatement(n)){let r=G.isBlockStatement(n.consequent)?n.consequent.body:[n.consequent];if(t.push(...mn(r)),n.alternate){let o=G.isBlockStatement(n.alternate)?n.alternate.body:[n.alternate];t.push(...mn(o))}continue}if(G.isSwitchStatement(n)){for(let r of n.cases)t.push(...mn(r.consequent));continue}G.isTryStatement(n)&&(t.push(...mn(n.block.body)),n.handler&&t.push(...mn(n.handler.body.body)),n.finalizer&&t.push(...mn(n.finalizer.body)))}return t}function gn(e){return G.isJSXElement(e)?jI(e)?Zp(e.children):[e]:G.isJSXFragment(e)?Zp(e.children):G.isParenthesizedExpression(e)||G.isTSAsExpression(e)||G.isTSSatisfiesExpression(e)||G.isTSNonNullExpression(e)||G.isTSTypeAssertion(e)?gn(e.expression):G.isConditionalExpression(e)?[...gn(e.consequent),...gn(e.alternate)]:G.isLogicalExpression(e)&&Mc(e.operator)?gn(e.right):[]}function Zp(e){return e.flatMap(t=>G.isJSXElement(t)||G.isJSXFragment(t)?gn(t):G.isJSXExpressionContainer(t)&&(G.isJSXElement(t.expression)||G.isJSXFragment(t.expression)||G.isConditionalExpression(t.expression)||G.isLogicalExpression(t.expression))?gn(t.expression):[])}function jI(e){let t=e.openingElement.name;return G.isJSXIdentifier(t)?t.name==="Fragment":G.isJSXMemberExpression(t)&&t.property.name==="Fragment"}function Qp(e,t){return!!(e&&t&&e.callbackStart<t.callbackStart&&e.callbackEnd>t.callbackEnd)}function es(e){return!(G.isIdentifier(e)||G.isThisExpression(e)||G.isMemberExpression(e)||G.isOptionalMemberExpression(e)||G.isCallExpression(e)||G.isOptionalCallExpression(e))}function qp(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(G.isMemberExpression(n)||G.isOptionalMemberExpression(n))&&G.isIdentifier(n.property)&&n.property.name==="map"&&!n.computed}function pr(e,t){let n=Je(e);if(!n)return t.isRepeatItemRoot===!0;let r=se(n,xe(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:Yi(n,t);if(!o)return t.isRepeatItemRoot===!0;let i=Dt(e,o);return i?DI(o,i):t.isRepeatItemRoot===!0}function em(e,t){let n=Je(e);if(!n)return!1;let r=se(n,xe(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:Yi(n,t);return o?!!o.findParent(i=>{if(!i.isCallExpression()&&!i.isOptionalCallExpression())return!1;let s=i.node.callee;return(G.isMemberExpression(s)||G.isOptionalMemberExpression(s))&&G.isIdentifier(s.property)&&s.property.name==="map"}):!1}import*as Ie from"@babel/types";function Bc(e){if(Ie.isJSXIdentifier(e))return/^[A-Z]/.test(e.name)?e.name:null;if(Ie.isJSXMemberExpression(e)){let t=e;for(;Ie.isJSXMemberExpression(t);)t=t.object;return t.name}return null}function $I(e,t){let n=ye(e.node);if(!n)return[];let r=new Set,o=(i,s)=>{let a=s.scope.getBinding(i);!a||Ot(a.path.node,n)||hn(a,i,t)||r.add(i)};return e.traverse({ReferencedIdentifier(i){o(i.node.name,i)},JSXOpeningElement(i){let s=Bc(i.node.name);s&&o(s,i)}}),[...r].sort()}function jc(e,t,n){let r=Je(e);if(!r)return{ok:!0};let o=se(r,xe(t));if(!o.ok||!o.match.path.isJSXElement())return{ok:!0};let i=se(r,xe(n));if(!i.ok||!i.match.path.isJSXElement())return{ok:!0};let s=Tr(o.match.path,i.match.path);if(Zi(s,i.match.path))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let a=$I(s,i.match.path);return a.length>0?{ok:!1,bindingNames:a}:{ok:!0}}function nm(e){let t=e;for(;Ie.isTSQualifiedName(t);)t=t.left;return Ie.isIdentifier(t)?t.name:null}function po(e,t){e.isIdentifier()&&e.isReferencedIdentifier()&&t(e),e.traverse({ReferencedIdentifier(n){n.isIdentifier()&&t(n)}})}function ts(e){let t=[],n=r=>{if(r){if(Ie.isIdentifier(r)){t.push(r.name);return}if(Ie.isObjectPattern(r)){for(let o of r.properties){if(Ie.isRestElement(o)){n(o.argument);continue}Ie.isObjectProperty(o)&&n(o.value)}return}if(Ie.isArrayPattern(r)){for(let o of r.elements)n(o);return}if(Ie.isAssignmentPattern(r)){n(r.left);return}if(Ie.isRestElement(r)){n(r.argument);return}Ie.isTSParameterProperty(r)&&n(r.parameter)}};return n(e),t}function $c(e,t){let n=ye(e.node),r=ye(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=tm(e),i=tm(t);if(!o||!i||!Jp(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=Xp(s.node,n);if(a&&!lt(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=ye(s.node.right);if(a&<(a,n)&&!lt(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())&&qp(s)){let a=ye(s.node.body)??ye(s.node);if(a&&!lt(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 tm(e){let t=e;for(;t;){if(t.isReturnStatement())return t.node.argument?ye(t.node.argument):null;if(t.isArrowFunctionExpression()&&(Ie.isJSXElement(t.node.body)||Ie.isJSXFragment(t.node.body)||Ie.isConditionalExpression(t.node.body)||Ie.isLogicalExpression(t.node.body)))return ye(t.node.body);t=t.parentPath}return null}function hn(e,t,n){return n.scope.getBinding(t)===e}function Vc(e,t,n,r={}){if(!r.preserveConditionalBoundary&&Zi(e,t))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let o=ye(e.node);if(!o)return{ok:!0};let i=new Set(n.callbackPath.node.params.flatMap(c=>ts(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||Ot(u.path.node,o)||i.has(u.path.node)||hn(u,c,t)||s.add(c)};return e.traverse({ReferencedIdentifier(c){a(c.node.name,c)},JSXOpeningElement(c){let l=Bc(c.node.name);l&&a(l,c)}}),s.size>0?{ok:!1,bindingNames:[...s].sort()}:{ok:!0}}function Kc(e,t,n){let r=ye(e.node);if(!r)return{ok:!0};let o=new Set(n.callbackPath.node.params.flatMap(s=>ts(s)).map(s=>n.callbackPath.scope.getBinding(s)?.path.node).filter(Boolean)),i=new Set;return po(e,s=>{let a=s.scope.getBinding(s.node.name);!a||Ot(a.path.node,r)||o.has(a.path.node)||hn(a,s.node.name,t)||i.add(s.node.name)}),i.size>0?{ok:!1,bindingNames:[...i].sort()}:{ok:!0}}function rm(e,t){let n=new Set(e.callbackPath.node.params.flatMap(a=>ts(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)||hn(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(mr.isIdentifier(l))o(l.name,c);else{let u=nm(l);u&&o(u,c)}}});return r.size>0?{ok:!1,bindingNames:[...r].sort()}:{ok:!0}}function Uc(e,t){let n=ye(e.node),r=new Set;return po(e,o=>{let i=o.scope.getBinding(o.node.name);i&&(n&&Ot(i.path.node,n)||hn(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 om(e){let t=[];for(let n of e.callbackPath.node.params){if(mr.isIdentifier(n)){t.push(n.name);continue}if(mr.isRestElement(n)&&mr.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 im(e,t){return{...e,callbackParams:t}}function Jc(e,t){return`${e.collectionNeedsParens?`(${e.collectionExpression})`:e.collectionExpression}${e.mapOperator}((${e.callbackParams.join(", ")}) => ${t})`}function mo(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 sm(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 Ln(e){return{file:e.file,component:e.component}}function VI(e){return e.target.kind==="node"?e.target.key:null}function KI(e){return"kind"in e}function ns(e){return!KI(e)}function Gc(e,t){let n=is.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=is.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function Xc(e,t){let n=e.getFileContent(t.file);if(!n)return;let r=Tt(n,xe(t));if(r.ok)return n.slice(r.match.start,r.match.end)}function Zc(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 UI(e){if(e.isNumericLiteral())return!0;if(!e.isUnaryExpression({operator:"-"}))return!1;let t=e.get("argument");return!Array.isArray(t)&&t.isNumericLiteral()}function JI(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 zc(e){return e==="Cannot edit repeat-backed child node structure with a generic node operation"}function XI(e){let t=Tp(e.ast,e.sourceNode.component,e.targetParent.component);if(!t.ok)return{ok:!1,reason:t.reason};let n=$c(t.path,e.targetParentPath);if(!n.ok)return{ok:!1,reason:n.reason};let r=zI({source:e.source,sourceContext:e.sourceContext,callSitePath:t.path,targetParentPath:e.targetParentPath});if(!r.ok)return r;let o=gm(r.collectionExpression);return{ok:!0,context:{...e.sourceContext,collectionExpression:r.collectionExpression,collectionNeedsParens:o?es(o):!0}}}function zI(e){let t=ye(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||Ot(a.path.node,t))return;let c=GI(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=ZI(e.callSitePath,c.propName,e.source);if(!l.ok){o=l.reason;return}let u=WI(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 f=Uc(l.expressionPath,e.targetParentPath);if(!f.ok){o=f.reason??`Cannot move prop-backed repeat child because the mapped prop source is not visible at the target: ${f.bindingNames.join(", ")}`;return}n.set(`${c.range.start}:${c.range.end}`,{...c.range,text:u});return}hn(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:QI(e.source,t,[...n.values()])}}function WI(e,t){if(t.length===0)return e;let n=gm(e);if(!n)return null;let r=es(n)?`(${e})`:e;for(let o of t){if(o.kind==="property"){r=HI(o.name)?`${r}.${o.name}`:`${r}[${JSON.stringify(o.name)}]`;continue}r=`${r}[${o.index}]`}return r}function HI(e){return/^[$A-Z_a-z][$\w]*$/.test(e)}function GI(e,t,n){let r=YI(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=ar(t,o);if(!i)return null;let s=r?.range??ye(e.node);return s?{propName:i.propName,remainingPath:i.remainingPath,hasDefault:i.hasDefault,range:s}:null}function YI(e,t){let n=e.parentPath;if(!n||!n.isMemberExpression()&&!n.isOptionalMemberExpression()||n.node.object!==e.node||!Ot(n.node,t)||n.node.computed||!pe.isIdentifier(n.node.property))return null;let r=ye(n.node);return r?{propertyName:n.node.property.name,range:r}:null}function ZI(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()&&pe.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=fr(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 QI(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 gm(e){try{let n=mm.parse(`const __VD_EXPR__ = (${e});`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0],r=pe.isVariableDeclaration(n)?n.declarations[0]?.init:null;return r&&pe.isExpression(r)?r:null}catch{return null}}function qI(e){let t=ye(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||Ot(s.path.node,t))return;let a=am(s,e.sourceFile,e.targetFile);if(a){let c=e.targetParentPath.scope.getBinding(a.localName);if(c){let u=am(c,e.targetFile,e.targetFile);(!u||u.moduleFile!==a.moduleFile||!eC(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 po(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 eC(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 am(e,t,n){let r=tC(e),o=r?.parentPath;if(!r||!o?.isImportDeclaration())return null;let i=o.node.source.value;if(typeof i!="string")return null;let s=_n(t,i),a=i.startsWith(".")?Gc(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=pe.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 tC(e){let t=e.path;for(;t&&!t.isImportDeclaration();){if(t.isImportSpecifier()||t.isImportDefaultSpecifier()||t.isImportNamespaceSpecifier())return t;t=t.parentPath}return null}function cm(e,t,n,r){let o=_c(t,n);if(o.length===0)return{sourceJsx:r,conditionPaths:[]};let i=r,s=[];for(let a of o){let c=fr(e,a.conditionPath.node);if(!c)return{sourceJsx:r,conditionPaths:[]};let l=nC(a.conditionPath,c);if(s.push(a.conditionPath),a.kind==="logical"){i=`${l} ${a.operator} ${oC(i)}`;continue}i=a.branch==="consequent"?`${l} ? ${i} : null`:`${l} ? null : ${i}`}return{sourceJsx:i,conditionPaths:s}}function nC(e,t){return rC(e.node)?t:`(${t})`}function rC(e){return pe.isIdentifier(e)||pe.isThisExpression(e)||pe.isSuper(e)||pe.isMemberExpression(e)||pe.isOptionalMemberExpression(e)||pe.isCallExpression(e)||pe.isOptionalCallExpression(e)||pe.isBooleanLiteral(e)||pe.isNumericLiteral(e)||pe.isStringLiteral(e)||pe.isNullLiteral(e)||pe.isUnaryExpression(e)}function oC(e){return e.trim().startsWith("<")?e:`(${e})`}var iC={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 rs(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=iC[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 sC(e,t){for(let n of e.program.body){if(!pe.isImportDeclaration(n)||n.source.value!==t)continue;let r=n.specifiers.find(o=>pe.isImportDefaultSpecifier(o));if(r&&pe.isImportDefaultSpecifier(r))return r.local.name}return null}function aC(e,t,n){for(let r of e.program.body){if(!pe.isImportDeclaration(r)||r.source.value!==t)continue;let o=r.specifiers.find(i=>pe.isImportSpecifier(i)&&(pe.isIdentifier(i.imported)?i.imported.name:i.imported.value)===n);if(o&&pe.isImportSpecifier(o))return o.local.name}return null}function lm(e){let t=new Set;return Ct(e,{Program(n){for(let r of Object.keys(n.scope.bindings))t.add(r);n.stop()}}),t}function um(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n+=1;return`${e}${n}`}function cC(e,t){if(!e.component)return{localName:"Component"};let n=e.component,r=Zc(e),o=Je(t);if(n.exportName!=="default"){let a=o?aC(o,n.source,n.exportName):null;if(a)return{localName:a};let c=o?um(r,lm(o)):r;return{localName:c,importStep:Wc(e,c)}}if(!o)return{localName:r,importStep:Wc(e,r)};let i=sC(o,n.source);if(i)return{localName:i};let s=um(r,lm(o));return{localName:s,importStep:Wc(e,s)}}function lC(e,t){if(e.kind==="native-tag")return e.text?`<${e.tag}>${e.text}</${e.tag}>`:`<${e.tag} />`;let n=t??Zc(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 uC(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?dC(e.props):void 0;return{kind:e.kind,component:{source:e.component.source,exportName:e.component.exportName},...t?{props:t}:{}}}function dC(e){return Object.fromEntries(Object.entries(e).filter(t=>Yc(t[1])))}function Yc(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(Yc):typeof e=="object"?Object.values(e).every(Yc):!1}function Wc(e,t=Zc(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 dm(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 fC(e,t,n){let r=e;for(;r;){if(r===t)return!0;r=n.getNode(r)?.parentKey}return!1}function gr(e,t){return`Operation kind '${e}' does not match params.kind '${t}'`}function Qc(e,t=e.path){return{kind:"value",root:e.root,path:t&&t.length>0?t:void 0,expectedRange:e.expectedRange}}function go(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:Qc(e,t.slice(0,n)),index:r.index}}return null}function Hc(e,t){return e.locator?e.collectionPathMap?.[t]?Qc(e.locator,e.collectionPathMap[t]):go(e.locator)?mC(e.locator,gC(t,e.collectionIndexMap)):null:null}function pC(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:hm(o,t)}function hm(e,t){let[n,...r]=e;if(!n)return t;if(n.kind!=="property")return;let o=hm(r,t);return o===void 0?void 0:{[n.name]:o}}function mC(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},Qc(e,i)}return null}function gC(e,t){return t?.[e]??e}function fm(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 hC(e,t){return yC(e.root,t.root)&&bC(e.path??[],t.path??[])}function yC(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&&xC(e.sourceRange,t.sourceRange)}}function xC(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function bC(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 os=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:gr(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:gr(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:gr(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:gr(t.kind,t.params.kind)};let r=t;if(!ns(r.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};let o=dm(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:gr(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:gr(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=VI(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):pm(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 pm(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:xe(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?Yp({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),f=r.attributes?.find(d=>d.name===c);if((await this.graph.getPropertyState?.(r.key,c,i))?.status==="blocked"||!u&&f?.source)return{ok:!1,errorCode:"capability-denied",reason:`apply-style-draft cannot overwrite a derived or unresolved property '${c}'`};if(!(typeof f?.resolvedValue=="string"&&f.resolvedValue===l||f?.source===null&&f.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 d=u.locator;if(u.sourceKind==="repeat-template"&&typeof i?.instanceIndex=="number"){let g=Hc(u,i.instanceIndex);if(!g)return{ok:!1,errorCode:"invalid-params",reason:"apply-style-draft could not resolve the selected repeat item"};d=g}s.push({order:n+s.length,file:u.file,type:"update-value",locator:d,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:xe(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=Hc(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:xe(t),segmentIndex:n,newText:r}]}}coerceTextValueForValueTarget(t,n,r,o="update-text"){let i=this.graph.getFileContent(t),s=Je(i);if(!s)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not inspect the value source`};let a=se(s,n);if(!a.ok)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not resolve the value source`};if(!UI(a.match.path))return{ok:!0,value:r};let c=JI(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=Hc(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=Je(this.graph.getFileContent(t));if(!o)return!1;let i=se(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 f=i;if(f?.kind==="value-binding"&&f.locator){let m=go(f.locator);if(m)return this.buildPlan(t,n,[{order:0,file:f.file,type:"remove-bound-array-item",locator:m.locator,index:m.index}],o)}return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed node removal requires a writable array target"}}let s=mo(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:xe(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||Up(n,t)>1)return null;let r=Gc(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(!ns(n.params.position))return{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=mo(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 f=await this.planRepeatBackedInsertChild(t,n,r,o);if(f)return f;let m=this.getRepeatBackedTemplateStructureReason(r);if(m)return{ok:!1,errorCode:"unsupported-operation",reason:m};let d=Ip(this.graph.getFileContent(r.file),r);if(!d.allowed)return{ok:!1,errorCode:"unsupported-operation",reason:d.reason??"Cannot insert child into this node"};let g=rs(r,n.params.node);if(g)return{ok:!1,errorCode:"unsupported-operation",reason:g};let h=[],S=0,E=n.params.node.kind==="component-call"?cC(n.params.node,this.graph.getFileContent(r.file)):void 0,y=E?.importStep;return y&&h.push({order:S++,file:r.file,type:"add-import",moduleSpecifier:y.moduleSpecifier,imports:y.imports}),h.push({order:S++,file:r.file,type:"insert-child",parentLocator:xe(r),node:{jsx:lC(n.params.node,E?.localName)},placement:n.params.position.relation,anchorLocator:i?xe(i):void 0}),this.buildPlan(t,n,h,o)}async planExternalBackedInsertChild(t,n,r,o,i,s){if(!ns(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:uC(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(!ns(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(f=>f.isRepeatItemRoot&&f.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=go(a.locator);if(!c)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child requires an array-backed target"};let l=pC(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"?fm(0,a.collectionIndexMap):fm(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=mo(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 pr(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:")||em(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&&pr(this.graph.getFileContent(r.file),r)||r.file!==o.file)return null;let c=this.graph.getFileContent(r.file),l=Je(c);if(!l)return null;let u=bt(l,r),f=bt(l,o);if(!u||!f)return null;let m=Dt(c,u),d=Dt(c,f);if(!fo(m,d))return null;if(a&&(s==="before"||s==="after")){let h=bt(l,a),S=h?Dt(c,h):null;if(!fo(m,S))return null}if(Qi(u,f))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child across statement-level conditional branches"};let g=jc(c,r,o);return g.ok?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:xe(r),targetParentLocator:xe(o),placement:s,anchorLocator:a?xe(a):void 0,selectionContext:Ln(o)}],i):{ok:!1,errorCode:"unsupported-operation",reason:g.reason??`Cannot move node because it depends on bindings outside the target scope: ${g.bindingNames.join(", ")}`}}planRepeatTemplateHoistMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&pr(this.graph.getFileContent(r.file),r)||r.file!==o.file)return null;let c=this.graph.getFileContent(r.file),l=Je(c);if(!l)return null;let u=bt(l,r),f=bt(l,o);if(!u||!f)return null;let m=Dt(c,u);if(!m)return null;let d=Dt(c,f);if(fo(m,d))return null;if(d&&!Qp(d,m))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child into a different repeat template"};if(a&&(s==="before"||s==="after")){let v=Dc(c,l,a);if(d&&!fo(d,v)||!d&&v)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 v=rs(o,{kind:"native-tag",tag:r.tag});if(v)return{ok:!1,errorCode:"unsupported-operation",reason:v}}let g=Xc(this.graph,r);if(!g)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(Qi(u,f))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let h=cm(c,u,f,g);for(let v of h.conditionPaths){let C=Kc(v,f,m);if(!C.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its condition depends on bindings outside the target scope: ${C.bindingNames.join(", ")}`}}let S=Vc(u,f,m,{preserveConditionalBoundary:h.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 E=rm(m,f);if(!E.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its callback parameters depend on bindings outside the target scope: ${E.bindingNames.join(", ")}`};let y=m;if(r.component!==o.component){let v=XI({source:c,ast:l,sourceContext:m,sourceNode:r,targetParent:o,targetParentPath:f});if(!v.ok)return{ok:!1,errorCode:"unsupported-operation",reason:v.reason};y=v.context}else{let v=Uc(m.collectionPath,f);if(!v.ok)return{ok:!1,errorCode:"unsupported-operation",reason:v.reason??`Cannot move repeat-backed child because the repeat collection is not visible at the target: ${v.bindingNames.join(", ")}`}}return this.buildPlan(t,n,[{order:0,file:r.file,type:"move-repeat-template-child",locator:xe(r),targetParentLocator:xe(o),placement:s,anchorLocator:a?xe(a):void 0,repeatExpression:Jc(y,h.sourceJsx),selectionContext:Ln(o)}],i)}planCrossFileRepeatTemplateHoistMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&pr(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=Je(c),f=Je(l);if(!u||!f)return null;let m=zp({knownSourceFiles:this.graph.getKnownSourceFiles?.(),routeEntryFiles:this.graph.getRouteEntryFiles?.(),sourceAst:u,sourceFile:r.file,targetFile:o.file,sourceComponent:r.component,targetComponent:o.component});if(!m.ok)return{ok:!1,errorCode:"unsupported-operation",reason:m.reason};let d=bt(u,r),g=bt(f,o);if(!d||!g)return null;let h=$c(m.callSitePath,g);if(!h.ok)return{ok:!1,errorCode:"unsupported-operation",reason:h.reason};let S=Dt(c,d);if(!S)return null;if(Dt(l,g))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child into a different repeat template"};if(a&&(s==="before"||s==="after")&&Dc(l,f,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 _=rs(o,{kind:"native-tag",tag:r.tag});if(_)return{ok:!1,errorCode:"unsupported-operation",reason:_}}let y=Xc(this.graph,r);if(!y)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(Qi(d,g))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let v=cm(c,d,g,y);for(let _ of v.conditionPaths){let D=Kc(_,g,S);if(!D.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its condition depends on bindings outside the target scope: ${D.bindingNames.join(", ")}`}}let C=Vc(d,g,S,{preserveConditionalBoundary:v.conditionPaths.length>0});if(!C.ok)return{ok:!1,errorCode:"unsupported-operation",reason:C.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${C.bindingNames.join(", ")}`};let N=qI({sourceFile:r.file,targetFile:o.file,sourceContext:S,targetParentPath:g});if(!N.ok)return{ok:!1,errorCode:"unsupported-operation",reason:N.reason};let A=om(S);if(!A.ok)return{ok:!1,errorCode:"unsupported-operation",reason:A.reason};let R=im(S,A.callbackParams),F=[{order:0,file:r.file,type:"remove-node",locator:xe(r),removeWhitespace:!0}];for(let _ of N.imports)F.push({order:F.length,file:o.file,type:"add-import",moduleSpecifier:_.moduleSpecifier,imports:_.imports});return F.push({order:F.length,file:o.file,type:"insert-jsx-expression-child",parentLocator:xe(o),expression:Jc(R,v.sourceJsx),placement:s,anchorLocator:a?xe(a):void 0,selectionContext:Ln(o)}),this.buildPlan(t,n,F,i)}async planMoveNode(t,n,r,o){if(!o.canMove)return{ok:!1,errorCode:"capability-denied",reason:"Cannot move this node"};if("kind"in n.params.target&&n.params.target.kind==="source-sibling"){let v=n.params.target,C=this.graph.getNode(v.anchorKey);if(!C||r.file!==C.file||r.component!==C.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 A=this.graph.getFileContent(r.file),R=Je(A),F=R?bt(R,r):null,_=R?bt(R,C):null,D=F?.parentPath,L=_?.parentPath;if(!F||!_||!D||!L||D.node!==L.node||!D.isJSXFragment()&&!(D.isJSXElement()&&Me(D)))return{ok:!1,errorCode:"unsupported-operation",reason:"Source sibling move requires two direct children of the same transparent Fragment"};let oe=D.node.loc;return oe?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:xe(r),targetParentLocator:{kind:"jsx-node",strategy:"source-range",sourceRange:{startLine:oe.start.line,startColumn:oe.start.column,endLine:oe.end.line,endColumn:oe.end.column}},placement:v.relation,anchorLocator:xe(C),selectionContext:Ln(r)}],o):{ok:!1,errorCode:"locator-miss",reason:"Source Fragment has no stable source range"}}let i=dm(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(fC(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 v=n.params.target.relation,C=i.anchorNode&&(v==="before"||v==="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:v,anchorSourceId:C?.kind==="external-entry"?C.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,f=i.anchorNode,m=this.graph.getTextProvenance?.(r.key,0)??null,d=mo(r,c,m);if(d&&!zc(d)&&!sm(r,s,c,m))return{ok:!1,errorCode:"unsupported-operation",reason:d};if(r.isRepeatItemRoot&&f?.isRepeatItemRoot&&r.repeatOwnerKey&&r.repeatOwnerKey===f.repeatOwnerKey&&(u==="before"||u==="after")){let v=c,C=await this.graph.getTextWriteTarget(f.key,0);if(v?.kind==="value-binding"&&C?.kind==="value-binding"&&v.locator&&C.locator){let N=go(v.locator),A=go(C.locator);if(N&&A&&v.file===C.file&&hC(N.locator,A.locator)){let R=N.index,F=A.index,_=u==="before"?F-(R<F?1:0):F+(R<F?0:1);return this.buildPlan(t,n,[{order:0,file:v.file,type:"move-array-item",locator:N.locator,fromIndex:R,toIndex:_}],o)}}}if(r.isRepeatItemRoot&&pr(this.graph.getFileContent(r.file),r))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed item outside its collection"};let g=this.getRepeatBackedTemplateStructureReason(r),h=zc(d)?d:g;if(h&&zc(h)){let v=this.planRepeatTemplateInternalMove(t,n,r,s,o,u,f);if(v)return v;let C=this.planRepeatTemplateHoistMove(t,n,r,s,o,u,f);if(C)return C;let N=this.planCrossFileRepeatTemplateHoistMove(t,n,r,s,o,u,f);return N||{ok:!1,errorCode:"unsupported-operation",reason:h}}if(g)return{ok:!1,errorCode:"unsupported-operation",reason:g};let S=await this.getUpstreamBackedDescendantReason(r);if(S)return{ok:!1,errorCode:"unsupported-operation",reason:S};if(r.tag&&r.tag.toLowerCase()===r.tag){let v=rs(s,{kind:"native-tag",tag:r.tag});if(v)return{ok:!1,errorCode:"unsupported-operation",reason:v}}if(l)return this.planCrossFileMove(t,n,r,s,o,u,f);let E=jc(this.graph.getFileContent(r.file),r,s);if(!E.ok)return{ok:!1,errorCode:"unsupported-operation",reason:E.reason??`Cannot move node because it depends on bindings outside the target scope: ${E.bindingNames.join(", ")}`};let y=[{order:0,file:r.file,type:"move-node",locator:xe(r),targetParentLocator:xe(s),placement:u,anchorLocator:f?xe(f):void 0,selectionContext:Ln(s)}];return this.buildPlan(t,n,y,o)}planCrossFileMove(t,n,r,o,i,s,a){let c=[],l=0,u=this.graph.getFileContent(r.file),f=Xc(this.graph,r)??`<${r.component} />`,m=Cp(u,r);if(!m.allowed)return{ok:!1,errorCode:"unsupported-operation",reason:m.reason??"Cannot move subtree across files"};if(c.push({order:l++,file:r.file,type:"remove-node",locator:xe(r),removeWhitespace:!0}),r.importedFrom&&r.exportName){let g=r.tag??r.component,S={moduleSpecifier:Gc(o.file,r.importedFrom),imports:r.exportName==="default"?[{kind:"default",local:g}]:[{kind:"named",imported:r.exportName,local:g===r.exportName?void 0:g}]};c.push({order:l++,file:o.file,type:"add-import",moduleSpecifier:S.moduleSpecifier,imports:S.imports}),c.push({order:l++,file:o.file,type:"insert-child",parentLocator:xe(o),node:{jsx:f},placement:s,anchorLocator:a?xe(a):void 0,selectionContext:Ln(o)})}else c.push({order:l++,file:o.file,type:"insert-child",parentLocator:xe(o),node:{jsx:f},placement:s,anchorLocator:a?xe(a):void 0,selectionContext:Ln(o)});let d=this.buildRemoveComponentImportStep(r,u);return d&&c.push({...d,order:l++}),this.buildPlan(t,n,c,i)}buildPlan(t,n,r,o){let s=[...new Set(r.map(a=>a.file))].map(a=>({file:a,content:this.graph.getFileContent(a),version:this.graph.getFileVersion(a),exists:!0,sha256:ke(this.graph.getFileContent(a))}));return{ok:!0,plan:{operationId:t,kind:n.kind,target:n.target,documentVersion:n.documentVersion,steps:r,preSnapshots:s,validatedCapability:o}}}};function pm(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 rl from"@babel/generator";import{parse as MC}from"@babel/parser";import ol from"@babel/traverse";import*as w from"@babel/types";import*as jt from"@babel/types";import qc from"@babel/generator";import*as ve from"@babel/types";var SC=typeof qc=="function"?qc:qc.default,EC=/(?:token|secret|key|password|authorization|cookie|signature|credential)/i,vC=/^((?:https?:)?\/\/)[^/@\s]+@/i,kC=/(\/(?:token|secret|api[-_]?key|password|credential|signature)\/)[^/?#]+/gi;function xm(e,t){let n=Bt(e.callee);if(!n)return null;if(n==="fetch")return el(e.arguments[0],"GET",t,["fetch call"]);if(n.startsWith("axios.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(ym(r))return el(e.arguments[0],r,t,["axios client contract"])}if(n.startsWith("ky.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(ym(r))return el(e.arguments[0],r,t,["ky client contract"])}return null}function el(e,t,n,r){if(!e||ve.isSpreadElement(e)||ve.isJSXNamespacedName(e))return wC(t,n,r,"missing url argument");let o=ho(e);return{sourceKind:RC(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 ho(e){if(ve.isStringLiteral(e))return ss(e.value);if(ve.isTemplateLiteral(e))return ss(IC(e));if(ve.isBinaryExpression(e)&&e.operator==="+"){let t=ho(e.left),n=ho(e.right);return!t&&!n?void 0:ss(`${t??tl(e.left)}${n??tl(e.right)}`)}if(ve.isMemberExpression(e)){let t=bm(e);if(t)return`env:${t}`}if(!(ve.isCallExpression(e)&&Bt(e.callee)==="new URL")){if(ve.isNewExpression(e)&&ve.isIdentifier(e.callee,{name:"URL"})){let[t,n]=e.arguments,r=t&&!ve.isSpreadElement(t)?ho(t):void 0,o=n&&!ve.isSpreadElement(n)?ho(n):void 0;return o&&r?ss(`${o} + ${r}`):r??o}if(ve.isIdentifier(e))return`:${e.name}`}}function IC(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+=tl(r))}return t}function tl(e){if(ve.isIdentifier(e))return`:${e.name}`;if(ve.isMemberExpression(e)){let t=bm(e);if(t)return`env:${t}`}return`:${CC(e)}`}function CC(e){return SC(e,{comments:!1}).code.replace(/[^a-zA-Z0-9_$]+/g,"_").replace(/^_+|_+$/g,"")||"param"}function ss(e){let[t]=e.split("#"),[n,r]=t.split("?"),o=n.replace(vC,"$1<redacted>@").replace(kC,"$1<redacted>");if(!r)return o;let i=r.split("&").map(s=>{let[a]=s.split("=");return a?EC.test(a)?`${a}=<redacted>`:`${a}=:${a}`:""}).filter(Boolean).join("&");return i?`${o}?${i}`:o}function RC(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 wC(e,t,n,r){return{sourceKind:"unknown-api",method:e,confidence:"partial",evidence:[{file:t.file,reason:[...n,r].join("; ")}]}}function ym(e){return["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(e)}function bm(e){return!ve.isMemberExpression(e.object)||!ve.isIdentifier(e.object.object,{name:"process"})||!NC(e.object.property,"env")?null:ve.isIdentifier(e.property)?e.property.name:ve.isStringLiteral(e.property)?e.property.value:null}function NC(e,t){return ve.isIdentifier(e)&&e.name===t}function Bt(e){if(ve.isIdentifier(e))return e.name;if(ve.isMemberExpression(e)){let t=Bt(e.object),n=ve.isIdentifier(e.property)?e.property.name:ve.isStringLiteral(e.property)?e.property.value:null;if(t&&n)return`${t}.${n}`}return null}var PC=new Set(["list","listStrict","get","getStrict","getByUrl","getByUrlStrict","schema","categories"]),AC=new Set(["getConfig","submit"]);function Sm(e,t){let n=TC(Bt(e.callee),t);if(!n)return null;let r="cms.collections.";if(n.startsWith(r)){let i=n.slice(r.length);if(!PC.has(i))return null;let s=nl(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(!AC.has(i))return null;let s=nl(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=nl(e,0)??FC(e,0,"path")??"/cms/:path",s=_C(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 TC(e,t){let n=e?.indexOf(".")??-1;if(!e||n<1)return e;let r=t.imports?.get(e.slice(0,n));return r?.importedName==="collections"&&/(?:^|\/)lib\/cms\/collections(?:\.js)?$/.test(r.source)?`cms.collections${e.slice(n)}`:e}function Em(e,t){let n=Bt(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 vm(e){let t=Bt(e.callee);return typeof t=="string"&&t.startsWith("cms.field.")}function nl(e,t){let n=e.arguments[t];return jt.isStringLiteral(n)?n.value:null}function FC(e,t,n){let r=e.arguments[t];if(!jt.isObjectExpression(r))return null;for(let o of r.properties)if(jt.isObjectProperty(o)&&!o.computed&&(jt.isIdentifier(o.key)&&o.key.name===n||jt.isStringLiteral(o.key)&&o.key.value===n)&&jt.isStringLiteral(o.value))return o.value.value;return null}function _C(e){return/^\/collections\/([^/]+)(?:\/|$)/.exec(e)?.[1]??null}function km(e=4096){if(!Number.isSafeInteger(e)||e<1)throw new RangeError("Re-export relation capacity must be positive.");let t=new Map;return{resolve(n,r){let o=JSON.stringify([n.fromFile,n.exportName,n.targetFile,n.maxImportDepth]),i=t.get(o);if(i)return i;let s=r();return t.size>=e&&t.delete(t.keys().next().value),t.set(o,s),s.catch(()=>{t.get(o)===s&&t.delete(o)}),s}}}var Fm=typeof ol=="function"?ol:ol.default,YO=typeof rl=="function"?rl:rl.default,_m=new WeakMap;function Mm(e){let t=new Map;return _m.set(t,new Map([...e].map(n=>[n.file,n]))),t}var OC={maxFunctionDepth:8,maxImportDepth:6},LC=new Set(["src","href","alt","poster","content","title","aria-label"]),Im=new WeakMap;function DC(e,t,n){let r=Im.get(t.fileCache);r||(r=new WeakMap,Im.set(t.fileCache,r));let o=r.get(e);if(!o){o={imported:[],local:new Map};let u=0;for(let f of e.elements.values()){let m={element:f,order:u++};f.importedFrom&&f.exportName&&o.imported.push(m);let d=o.local.get(f.sourceFile);d||(d=new Map,o.local.set(f.sourceFile,d));let g=d.get(f.tag)??[];g.push(m),d.set(f.tag,g)}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],f=i[l];u&&(!f||u.order<f.order)?(a.push(u.element),c++):f&&(!u||f.order<u.order)?(a.push(f.element),l++):(a.push(u.element),c++,l++)}return a}async function Om(e){if(!e.element.textSegments.some(s=>s.source)&&!(e.element.attributes??[]).some(s=>s.source&&Rm(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=cl(e.file,e.source,t),r={file:e.file,analysis:n,readFile:e.readFile,exists:e.exists,fileCache:t,options:{...OC,...e.options},variableCache:new Map,functionDepth:0,importDepth:0,paramSources:new Map,resolvingVariables:new Set,resolvingComponentProps:new Set,scopeVariables:Ym(n,e.element.componentName)};await Lm(e.element.componentName,e.graph,r);let o=[];o.push(...await VC(e.element,e.graph,r),...await KC(e.element,e.graph,r));for(let s of e.element.textSegments){let a=await UC(s,e.element,e.graph,r);a&&o.push(ls(a,"text","children"))}for(let s of e.element.attributes??[]){let a=Rm(s,e.element);if(!a)continue;let c=await $m(s.source,e.element,e.graph,r);c&&o.push(ls(c,a,s.name))}let i=oR(o).sort(Hm);return{hasDynamicData:i.length>0,bindings:i}}async function Lm(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 DC(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 BC(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 f=await jm(l.sourceFile,n);if(!f)continue;let m=ds(f,n,{importDepth:n.importDepth+1});m.paramSources.clear(),m.scopeVariables=Ym(f,l.componentName),await Lm(l.componentName,t,m);let d=await jC(l,m);for(let[g,h]of d){if(!h)continue;let S=a.get(g)??[];S.push(h),a.set(g,S)}}finally{n.resolvingComponentProps.delete(u)}}}let c=new Map;for(let[l,u]of a){let f=zm(u);f.length===1&&c.set(l,f[0])}$C(o,c,n)}var Cm=new WeakMap;function BC(e,t,n,r){let o=Cm.get(r.fileCache);return o||(o=km(),Cm.set(r.fileCache,o)),o.resolve({fromFile:e,exportName:t,targetFile:n,maxImportDepth:r.options.maxImportDepth},()=>Dm(e,t,n,r))}async function Dm(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 jm(e,r))?.imports.get(t);if(!s||!Nt(s.source))return!1;let a=await qm(e,s.source,r.exists);return a?a===n?!0:Dm(a,s.importedName,n,r,o):!1}async function jC(e,t){let n=new Map,r=t.analysis.jsxElementsByRange.get(Bm(e.sourceRange));if(r)for(let i of r.openingElement.attributes)!w.isJSXAttribute(i)||!w.isJSXIdentifier(i.name)||!w.isJSXExpressionContainer(i.value)||!w.isExpression(i.value.expression)||n.set(i.name.name,i.value.expression);let o=new Map;for(let[i,s]of n){let a=await je(s,t);a&&o.set(i,a)}return o}function Bm(e){return`${e.startLine}:${e.startColumn}:${e.endLine}:${e.endColumn}`}async function jm(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 cl(e,r,t.fileCache)}function $C(e,t,n){if(w.isIdentifier(e)){t.size>0&&n.paramSources.set(e.name,al(Object.fromEntries(t),n.file));return}if(w.isObjectPattern(e))for(let r of e.properties){if(!w.isObjectProperty(r)||r.computed||!w.isIdentifier(r.key))continue;let o=t.get(r.key.name);if(!o)continue;let i=w.isAssignmentPattern(r.value)?r.value.left:r.value;w.isIdentifier(i)&&n.paramSources.set(i.name,ze(o))}}function Rm(e,t){return e.name==="dangerouslySetInnerHTML"?"richtext":LC.has(e.name)?"attribute":t.importedFrom||/^[A-Z]/.test(t.tag)?"component-prop":null}async function VC(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 us(i.collectionSource,n);s&&r.push(ls(Dn(s),"repeat-region",i.collectionExpression))}return r}async function KC(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 us(i.conditionSource,n);s&&r.push(ls(Dn(s),"conditional-region",i.conditionExpression))}return r}async function UC(e,t,n,r){return $m(e.source,t,n,r)}async function $m(e,t,n,r){let o=await JC(e,t,n,r);return o||us(e,r)}async function JC(e,t,n,r){if(!e)return null;let o=XC(e.base,t,n);if(!o)return null;let i=await us(o.collectionSource,r);return i?So(i,e.path,!0):null}function XC(e,t,n){let r=t.identity.key;for(;r;){for(let o of n.regions){if(o.kind!=="repeat-region"||!o.childKeys.includes(r))continue;let i=o.sourceCandidates?.find(s=>s.kind==="repeat-template"&&s.itemParamName===e);if(i)return i}r=n.elements.get(r)?.parentKey??null}return null}async function us(e,t){if(!e)return null;let n=await Vm(e.base,t);return n?So(n,e.path,!1):null}async function Vm(e,t){let n=t.paramSources.get(e);if(n)return ze(n);if(t.variableCache.has(e))return iR(t.variableCache.get(e)??null);if(t.resolvingVariables.has(e))return null;t.resolvingVariables.add(e);let r=await zC(e,t);if(r)return t.variableCache.set(e,ze(r)),t.resolvingVariables.delete(e),r;let o=t.scopeVariables?.get(e)??t.analysis.variables.get(e);if(o){let s=await je(o,t);return t.variableCache.set(e,s?ze(s):null),t.resolvingVariables.delete(e),s}let i=t.analysis.imports.get(e);if(i&&t.importDepth<t.options.maxImportDepth){let s=await Zm(i,t);if(s){let a=ds(s,t,{importDepth:t.importDepth+1}),c=Qm(i,s);if(c){let f=(await Bn(c,[],a)).returnSource;return t.variableCache.set(e,f?ze(f):null),t.resolvingVariables.delete(e),f}let l=s.variables.get(i.importedName);if(l){let u=await je(l,a);return t.variableCache.set(e,u?ze(u):null),t.resolvingVariables.delete(e),u}}}return t.variableCache.set(e,null),t.resolvingVariables.delete(e),null}async function zC(e,t){let n=t.analysis.stateSetters.get(e);if(!n)return null;let r=[];Fm(t.analysis.ast,{CallExpression(o){if(w.isIdentifier(o.node.callee,{name:n})){let i=o.node.arguments[0];w.isExpression(i)&&r.push(i);return}o.node.arguments.some(i=>w.isIdentifier(i)&&i.name===n)&&r.push(o.node)}});for(let o of r){let i=await je(o,t);if(i)return i}return null}async function je(e,t){if(w.isIdentifier(e))return Vm(e.name,t);if(w.isMemberExpression(e)||w.isOptionalMemberExpression(e)){let n=w.isMemberExpression(e)?Em(e,{file:t.file}):null;if(n)return Xm(n);let r=await WC(e,t);if(!r)return null;let o=nR(e);return So(r,o,!1)}if(w.isAwaitExpression(e))return w.isExpression(e.argument)?je(e.argument,t):null;if(w.isCallExpression(e))return Km(e,t);if(w.isObjectExpression(e)){let n=await Um(e,t);return Object.keys(n).length>0?al(n,t.file):null}if(w.isConditionalExpression(e)){let n=await je(e.consequent,t),r=await je(e.alternate,t);return bo(Nm(n,r))}if(w.isLogicalExpression(e)){let n=await je(e.left,t),r=await je(e.right,t);return bo(Nm(n,r))}return w.isTSAsExpression(e)||w.isTSSatisfiesExpression(e)||w.isTSNonNullExpression(e)||w.isTypeCastExpression(e)||w.isParenthesizedExpression(e)?je(e.expression,t):null}async function WC(e,t){let n=e;for(;w.isMemberExpression(n)||w.isOptionalMemberExpression(n);)n=n.object;return w.isExpression(n)?je(n,t):null}async function Km(e,t){let n=Sm(e,{file:t.file,imports:t.analysis.imports});if(n)return Xm(n);if(vm(e)){let f=e.arguments[0];if(f&&w.isExpression(f))return bo(await je(f,t))}let r=await HC(e,t);if(r)return r;let o=xm(e,{file:t.file});if(o)return{sourceKind:o.sourceKind,sourceType:"api-field",endpointPattern:o.endpointPattern,valuePath:o.valuePath,confidence:o.confidence,readonly:!0,evidence:o.evidence};let i=await ZC(e,t);if(i)return i;let s=await QC(e,t);if(s)return s;let a=await qC(e,t);if(a)return a;let c=await eR(e,t);if(c)return c;let l=[];for(let f of e.arguments)if(w.isExpression(f)){let m=await je(f,t);m&&l.push(m)}let u=zm(l);return u.length===1?bo(u[0]):null}async function HC(e,t){let n=Bt(e.callee);if(n!=="useQuery"&&n!=="useSuspenseQuery"&&n!=="useInfiniteQuery"&&n!=="useSWR")return null;if(n==="useSWR"){let i=YC(e.arguments[0],t.file,"SWR key"),s=e.arguments[1];if(w.isIdentifier(s)){let a=await xo(s.name,t);if(a)return(await Bn(a.node,i?[i]:[],a.context)).returnSource??i}return i}let r=e.arguments[0];if(!w.isObjectExpression(r))return as(t.file,`${n} without static options`);let o=GC(r,"queryFn");if(!o)return as(t.file,`${n} without queryFn`);if(w.isIdentifier(o)){let i=await xo(o.name,t);return i?(await Bn(i.node,[],i.context)).returnSource:as(t.file,`${n} queryFn unresolved`)}return w.isArrowFunctionExpression(o)||w.isFunctionExpression(o)?(await Bn(o,[],t)).returnSource:w.isCallExpression(o)?Km(o,t):null}function GC(e,t){for(let n of e.properties){if(!w.isObjectProperty(n)||!w.isExpression(n.value))continue;if(Jm(n)===t)return n.value}return null}function YC(e,t,n){return w.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 ZC(e,t){if(!w.isMemberExpression(e.callee)||!w.isIdentifier(e.callee.property))return null;let n=e.callee.property.name;if(!["map","filter","slice","sort","toSorted"].includes(n))return null;let r=w.isExpression(e.callee.object)?await je(e.callee.object,t):null;if(!r)return null;if(n!=="map")return Dn(r);let o=e.arguments[0];if(w.isIdentifier(o)){let i=await xo(o.name,t);if(!i)return Dn(r);let s=await Bn(i.node,[r],i.context);return{...Dn(r),...s.objectReturnMap??s.returnSource?.fieldMap?{fieldMap:s.objectReturnMap??s.returnSource.fieldMap}:{}}}if(w.isArrowFunctionExpression(o)||w.isFunctionExpression(o)){let i=await Bn(o,[r],t);return{...Dn(r),...i.objectReturnMap??i.returnSource?.fieldMap?{fieldMap:i.objectReturnMap??i.returnSource.fieldMap}:{}}}return Dn(r)}async function QC(e,t){return!w.isMemberExpression(e.callee)||!w.isIdentifier(e.callee.property,{name:"json"})||!w.isExpression(e.callee.object)?null:je(e.callee.object,t)}async function qC(e,t){return!w.isMemberExpression(e.callee)||!w.isIdentifier(e.callee.property,{name:"then"})||!w.isExpression(e.callee.object)?null:bo(await je(e.callee.object,t))}async function eR(e,t){if(!w.isIdentifier(e.callee))return null;let n=await xo(e.callee.name,t);if(!n)return null;let r=[];for(let i of e.arguments){if(!w.isExpression(i)){r.push(as(t.file,`unsupported argument for ${e.callee.name}`));continue}let s=await je(i,t);r.push(s)}return(await Bn(n.node,r,n.context)).returnSource}async function xo(e,t){let n=t.analysis.functions.get(e);if(n)return{node:n,context:t};let r=t.analysis.imports.get(e);if(!r||t.importDepth>=t.options.maxImportDepth)return null;let o=await Zm(r,t);if(!o)return null;let i=ds(o,t,{importDepth:t.importDepth+1}),s=Qm(r,o);return s?{node:s,context:i}:xo(r.importedName,i)}async function Bn(e,t,n){if(n.functionDepth>=n.options.maxFunctionDepth)return{returnSource:null};let r=ds(n.analysis,n,{functionDepth:n.functionDepth+1});r.scopeVariables=n.analysis.functionVariables.get(e),e.params.forEach((c,l)=>{let u=t[l];u&&il(c,rR(u),r)});let o=tR(e),i=null,s,a=!1;for(let c of o){if(w.isObjectExpression(c)){s={...s??{},...await Um(c,r)},i=i??al(s,n.file);continue}let l=await je(c,r);if(l){if(!i){i=l;continue}let u=sl(i,l);if(!u){a=!0,i=null;continue}i=u}}return{returnSource:a?null:i,...s?{objectReturnMap:s}:{}}}function il(e,t,n){if(w.isIdentifier(e)){n.paramSources.set(e.name,ze(t));return}if(w.isAssignmentPattern(e)){il(e.left,t,n);return}if(w.isObjectPattern(e))for(let r of e.properties){if(!w.isObjectProperty(r)||r.computed||!w.isIdentifier(r.key))continue;let o=So(t,[{kind:"property",name:r.key.name}],!0),i=w.isAssignmentPattern(r.value)?r.value.left:r.value;il(i,o,n)}}function tR(e){if(w.isArrowFunctionExpression(e)&&w.isExpression(e.body))return[e.body];let t=[],n=e.body;if(!w.isBlockStatement(n))return t;let r=o=>{if(w.isFunction(o)&&o!==e)return;if(w.isReturnStatement(o)){o.argument&&w.isExpression(o.argument)&&t.push(o.argument);return}let i=w.VISITOR_KEYS[o.type];for(let s of i??[]){let a=o[s];if(Array.isArray(a))for(let c of a)w.isNode(c)&&r(c);else w.isNode(a)&&r(a)}};return r(n),t}async function Um(e,t){let n={};for(let r of e.properties){if(!w.isObjectProperty(r))continue;let o=Jm(r);if(!o||!w.isExpression(r.value))continue;let i=await je(r.value,t);i&&(n[o]=i)}return n}function Jm(e){return w.isIdentifier(e.key)&&!e.computed?e.key.name:w.isStringLiteral(e.key)?e.key.value:null}function nR(e){let t=[],n=e;for(;w.isMemberExpression(n)||w.isOptionalMemberExpression(n);){let r=n.property;n.computed?w.isStringLiteral(r)?t.unshift({kind:"property",name:r.value}):w.isNumericLiteral(r)&&t.unshift({kind:"index",index:r.value}):w.isIdentifier(r)&&t.unshift({kind:"property",name:r.name}),n=n.object}return w.isIdentifier(n),t}function So(e,t,n){if(t.length===0)return ze(e);let r=t[0];if(r?.kind==="property"&&e.fieldMap?.[r.name])return So(e.fieldMap[r.name],t.slice(1),n);let o=ze(e);if(o.sourceType==="cms-field"){let i=t.filter(s=>s.kind==="property").map(s=>s.name);return i[0]==="data"&&i[1]==="items"?(o.valuePath=yo(o.valuePath,"data.items[]"),o.cmsFieldRoot=!1,o):i[0]==="fields"?(o.fieldPath=yo(o.fieldPath,i.slice(1).join(".")),o.cmsFieldRoot=!0,o):o.cmsFieldRoot||n||o.fieldMap?(o.fieldPath=yo(o.fieldPath,i.join(".")),o):(o.valuePath=yo(o.valuePath,wm(t)),o)}return o.valuePath=yo(o.valuePath,wm(t)),o}function wm(e){return e.map(t=>t.kind==="property"?t.name:`[${t.index}]`).join(".").replace(/\.\[/g,"[")}function yo(e,t){return t?e?t.startsWith("[")?`${e}${t}`:`${e}.${t}`:t:e}function Xm(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 Dn(e){let t=ze(e);return t.sourceType==="cms-field"&&!t.valuePath&&(t.valuePath="items[]"),t}function rR(e){let t=ze(e);return t.valuePath=void 0,t.sourceType==="cms-field"&&(t.cmsFieldRoot=!1),t}function bo(e){return e?{...ze(e),confidence:e.confidence==="unknown"?"unknown":"safe-derived",evidence:[...e.evidence,{file:e.evidence[0]?.file??"unknown",reason:"safe derived expression"}]}:null}function Nm(e,t){return e?t?sl(e,t):ze(e):t?ze(t):null}function sl(e,t){if(cs(e)!==cs(t))return null;let n=Gm(e.confidence,t.confidence)<=0?e.confidence:t.confidence;return{...e,confidence:n,evidence:[...e.evidence,...t.evidence]}}function zm(e){let t=new Map;for(let n of e){let r=cs(n),o=t.get(r);t.set(r,o?sl(o,n):ze(n))}return[...t.values()]}function cs(e){let t=e.fieldMap?Object.fromEntries(Object.entries(e.fieldMap).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>[n,cs(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 al(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 as(e,t){return{sourceKind:"unknown-api",sourceType:"api-field",confidence:"unknown",readonly:!0,evidence:[{file:e,reason:t}]}}function ls(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 Wm(e){let t=[...e].sort(Hm),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 oR(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 Hm(e,t){return Pm(e.targetKind)-Pm(t.targetKind)||Gm(e.confidence,t.confidence)||Am(e.sourceKind)-Am(t.sourceKind)||e.targetName.localeCompare(t.targetName)}function Pm(e){return{"repeat-region":0,"conditional-region":1,text:2,richtext:3,attribute:4,"component-prop":5}[e]}function Am(e){return e.startsWith("vcp-cms-")?0:e==="site-api-route"?1:e==="external-api"?2:3}function Gm(e,t){let n={exact:0,"safe-derived":1,partial:2,unknown:3};return n[e]-n[t]}function cl(e,t,n){let r=n.get(e);if(r?.source===t)return r;let o=_m.get(n)?.get(e),i=o?.source===t?o.ast:MC(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,jsxElementsByRange:new Map,functionVariables:new WeakMap};return Fm(i,{JSXElement(a){let c=a.node.loc;if(!c)return;let l=Bm({startLine:c.start.line,startColumn:c.start.column,endLine:c.end.line,endColumn:c.end.column});s.jsxElementsByRange.has(l)||s.jsxElementsByRange.set(l,a.node)},ImportDeclaration(a){let c=a.node.source.value;for(let l of a.node.specifiers)w.isImportSpecifier(l)&&w.isIdentifier(l.local)?s.imports.set(l.local.name,{source:c,importedName:w.isIdentifier(l.imported)?l.imported.name:l.imported.value,localName:l.local.name,isDefault:!1}):w.isImportDefaultSpecifier(l)&&s.imports.set(l.local.name,{source:c,importedName:"default",localName:l.local.name,isDefault:!0})},FunctionDeclaration(a){a.node.id?.name&&s.functions.set(a.node.id.name,a.node)},VariableDeclarator(a){let c=a.getFunctionParent(),l=c&&(w.isFunctionDeclaration(c.node)||w.isFunctionExpression(c.node)||w.isArrowFunctionExpression(c.node))?c.node:null,u=l?s.functionVariables.get(l)??new Map:s.variables;l&&!s.functionVariables.has(l)&&s.functionVariables.set(l,u);for(let f of hr(a.node.id))u.set(f,w.isExpression(a.node.init)?a.node.init:null);if(w.isArrayPattern(a.node.id)&&w.isCallExpression(a.node.init)&&Bt(a.node.init.callee)==="useState"){let[f,m]=a.node.id.elements;w.isIdentifier(f)&&w.isIdentifier(m)&&s.stateSetters.set(f.name,m.name)}w.isIdentifier(a.node.id)&&Tm(a.node.init)&&s.functions.set(a.node.id.name,a.node.init)},ExportNamedDeclaration(a){let c=a.node.declaration,l=a.node.source?.value;if(l)for(let u of a.node.specifiers){if(!w.isExportSpecifier(u))continue;let f=w.isIdentifier(u.exported)?u.exported.name:u.exported.value,m=u.local.name;s.imports.set(f,{source:l,importedName:m,localName:f,isDefault:m==="default"})}if(w.isFunctionDeclaration(c)&&c.id?.name&&s.functions.set(c.id.name,c),w.isVariableDeclaration(c))for(let u of c.declarations)w.isIdentifier(u.id)&&Tm(u.init)&&s.functions.set(u.id.name,u.init)},ExportDefaultDeclaration(a){let c=a.node.declaration;if((w.isFunctionDeclaration(c)||w.isFunctionExpression(c)||w.isArrowFunctionExpression(c))&&s.functions.set("default",c),w.isIdentifier(c)){let l=s.functions.get(c.name);l&&s.functions.set("default",l)}}}),n.set(e,s),s}function hr(e){return!e||w.isVoidPattern(e)?[]:w.isIdentifier(e)?[e.name]:w.isObjectPattern(e)?e.properties.flatMap(t=>w.isObjectProperty(t)?hr(t.value):hr(t.argument)):w.isArrayPattern(e)?e.elements.flatMap(t=>t?hr(w.isRestElement(t)?t.argument:t):[]):w.isAssignmentPattern(e)?hr(e.left):w.isRestElement(e)?hr(e.argument):[]}function Tm(e){return w.isFunctionExpression(e)||w.isArrowFunctionExpression(e)}function Ym(e,t){let n=e.functions.get(t)??e.functions.get("default");return n?e.functionVariables.get(n):void 0}async function Zm(e,t){let n=await qm(t.file,e.source,t.exists);if(!n)return null;let r=await t.readFile(n);return cl(n,r,t.fileCache)}function Qm(e,t){return e.isDefault?t.functions.get("default")??t.functions.get(e.localName)??null:t.functions.get(e.importedName)??null}async function qm(e,t,n){return Nt(t)?Sn(e,t,n):null}function ds(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),resolvingVariables:new Set,resolvingComponentProps:t.resolvingComponentProps,scopeVariables:e===t.analysis?t.scopeVariables:void 0}}function iR(e){return e?ze(e):null}function ze(e){return{...e,evidence:e.evidence.map(t=>({...t})),...e.fieldMap?{fieldMap:Object.fromEntries(Object.entries(e.fieldMap).map(([t,n])=>[t,ze(n)]))}:{}}}import*as ul from"@babel/parser";import ll from"@babel/traverse";import*as Y from"@babel/types";import{classifySiteEditPropertyName as sR}from"@vcp-dev/contracts";var dl=typeof ll=="function"?ll:ll.default;function fl(e){let t=sR(e.propertyName);if(t.owner!=="generic")return ut("invalid-property",t.diagnostic?.message??`Property '${e.propertyName}' is not a generic property`);let n=e.selectionRef;if(!n)return ut("missing-selection-ref","A repeat property target requires a complete selection reference");if(n.key!==e.element.identity.key)return ut("selection-mismatch","Selection reference does not identify the requested element");if(n.instanceIndex===void 0)return ut("missing-instance-index","A repeat property target requires an instance index");let r;try{r=ul.parse(e.source,{sourceType:"module",plugins:["typescript","jsx"]})}catch(S){return ut("repeat-not-found",`Unable to parse repeat source: ${S instanceof Error?S.message:String(S)}`)}let o=aR(r,e.element.sourceRange);if(!o)return ut("repeat-not-found","The selected element is not inside a supported map repeat");if(!Y.isIdentifier(o.callback.params[0]))return ut("unsupported-callback","Repeat property materialization requires an identifier callback item");let i=cR(r,o.collection,e.file,e.sources);if(!i)return ut("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[S,E]of s.elements.entries()){if(!E||!Y.isObjectExpression(E)||!ig(E))return ut("unsafe-collection","Repeat materialization requires an array of local static objects without spreads");let y=[{kind:"index",index:S}];l.push(y),u.push({kind:"value",root:a.root,path:y})}let f=u.length;if(n.instanceCount!==void 0&&n.instanceCount!==f)return ut("count-mismatch",`Selection reports ${n.instanceCount} instances but the source collection has ${f}`);let m=n.instanceIndex;if(m>=f)return ut("index-out-of-range",`Selected repeat instance ${m} is outside the source collection`);let d=s.elements[m];if(!d||!Y.isObjectExpression(d))return ut("unsafe-collection","Selected repeat item is not an object");let g=mR(e.element,e.propertyName),h=fR(d,e.propertyName);return h?{ok:!0,sourceFile:c,templateFile:e.file,collectionLocator:a,parentObjectLocators:u,selectedParentObjectLocator:u[m],sourceItemIndex:m,sourceItemPath:l[m],collectionIndexMap:Array.from({length:f},(S,E)=>E),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:pR(d,e.propertyName),...g?{property:g}:{},selectionRef:n}:ut("unsafe-property-source",`Property '${e.propertyName}' has a dynamic or unsupported source in the repeat item`)}function aR(e,t){let n=[];return dl(e,{CallExpression(r){let o=eg(r.node);o&&ng(o.callback,t)&&n.push({...o,span:tg(r.node)})},OptionalCallExpression(r){let o=eg(r.node);o&&ng(o.callback,t)&&n.push({...o,span:tg(r.node)})}}),n.sort((r,o)=>r.span-o.span),n[0]??null}function eg(e){let t=e.callee;if(!Y.isMemberExpression(t)&&!Y.isOptionalMemberExpression(t)||t.computed||!Y.isIdentifier(t.property)||t.property.name!=="map"||!Y.isExpression(t.object))return null;let n=e.arguments[0];return!n||!Y.isExpression(n)||!Y.isArrowFunctionExpression(n)&&!Y.isFunctionExpression(n)?null:{collection:t.object,callback:n}}function cR(e,t,n,r){let o=Eo(t);if(o&&Y.isArrayExpression(o))return{array:o,locator:{kind:"value",root:{kind:"expression",sourceRange:ag(o)}},sourceFile:n};if(!Y.isIdentifier(t))return null;let i=[];if(dl(e,{VariableDeclarator(s){Y.isIdentifier(s.node.id)&&s.node.id.name===t.name&&s.node.init&&i.push(s.node)}}),i.length===1){let s=Eo(i[0].init);return!s||!Y.isArrayExpression(s)?null:{array:s,locator:{kind:"value",root:{kind:"binding",name:t.name}},sourceFile:n}}return lR(e,t.name,n,r)}function lR(e,t,n,r){if(!r)return null;for(let o of e.program.body){if(!Y.isImportDeclaration(o))continue;let i=o.specifiers.find(m=>m.local.name===t);if(!i||!Y.isStringLiteral(o.source)||!Y.isImportSpecifier(i))continue;let s=dR(n,o.source.value,r);if(!s)return null;let a=Y.isIdentifier(i.imported)?i.imported.name:i.imported.value,c=r.get(s);if(c===void 0)return null;let l;try{l=ul.parse(c,{sourceType:"module",plugins:["typescript","jsx"]})}catch{return null}let u=uR(l,a),f=u?Eo(u):null;return!f||!Y.isArrayExpression(f)?null:{array:f,locator:{kind:"value",root:{kind:"binding",name:a}},sourceFile:s}}return null}function uR(e,t){let n=null;return dl(e,{VariableDeclarator(r){n||!Y.isIdentifier(r.node.id)||r.node.id.name!==t||!r.node.init||!Y.isExpression(r.node.init)||(n=r.node.init)}}),n}function dR(e,t,n){let r=bn(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 Eo(e){return Y.isParenthesizedExpression(e)?Eo(e.expression):Y.isTSAsExpression(e)?og(e.typeAnnotation)?Eo(e.expression):null:Y.isTSSatisfiesExpression(e)?null:e}function og(e){return Y.isTSTypeReference(e)&&Y.isIdentifier(e.typeName)&&e.typeName.name==="const"}function ig(e){return e.properties.every(t=>!Y.isObjectProperty(t)||t.computed||!Y.isExpression(t.value)?!1:fs(t.value))}function fs(e){if(Y.isTSAsExpression(e)&&og(e.typeAnnotation))return fs(e.expression);if(Y.isTSSatisfiesExpression(e))return!1;if(Y.isArrayExpression(e))return e.elements.every(n=>!n||Y.isSpreadElement(n)||!Y.isExpression(n)?!1:fs(n));if(Y.isObjectExpression(e))return ig(e);let t=_t(e);return t.status==="resolved"||t.status==="undefined"}function fR(e,t){let n=e.properties.filter(o=>Y.isObjectProperty(o)&&sg(o.key)===t);if(n.length>1)return null;let r=n[0];return r?Y.isExpression(r.value)?fs(r.value)?"static":Y.isIdentifier(r.value)||Y.isMemberExpression(r.value)?"binding":null:null:"missing"}function pR(e,t){let n=e.properties.filter(o=>Y.isObjectProperty(o)&&sg(o.key)===t);if(n.length>1)return{status:"unresolved"};let r=n[0];return!r||!Y.isExpression(r.value)?{status:"undefined"}:_t(r.value)}function mR(e,t){let n=e.attributes?.filter(r=>r.name===t)??[];return n.length===1?n[0]:void 0}function sg(e){return Y.isIdentifier(e)?e.name:Y.isStringLiteral(e)?e.value:Y.isNumericLiteral(e)?String(e.value):null}function ag(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 tg(e){return e.start==null||e.end==null?Number.MAX_SAFE_INTEGER:e.end-e.start}function ng(e,t){let n=ag(e);return rg(n.startLine,n.startColumn,t.startLine,t.startColumn)<=0&&rg(n.endLine,n.endColumn,t.endLine,t.endColumn)>=0}function rg(e,t,n,r){return e===n?t-r:e-n}function ut(e,t){return{ok:!1,errorCode:e,reason:t}}import{classifySiteEditPropertyName as ew}from"@vcp-dev/contracts";import*as Z from"@babel/types";import Ro from"node:path";import*as V from"@babel/types";import*as pg from"@babel/parser";import pl from"@babel/traverse";import*as ne from"@babel/types";function ms(e,t){let n=[],r=e;for(;ne.isMemberExpression(r);){if(r.computed)if(ne.isNumericLiteral(r.property))n.unshift({kind:"index",index:r.property.value});else if(ne.isStringLiteral(r.property))n.unshift({kind:"property",name:r.property.value});else return null;else{if(!ne.isIdentifier(r.property))return null;n.unshift({kind:"property",name:r.property.name})}r=r.object}return!ne.isIdentifier(r)||r.name!==t?null:n}function cg(e){if(ne.isIdentifier(e))return{base:e.name,path:[]};if(!ne.isMemberExpression(e))return null;let t=[],n=e;for(;ne.isMemberExpression(n);){if(n.computed)if(ne.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(ne.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else{if(!ne.isIdentifier(n.property))return null;t.unshift({kind:"property",name:n.property.name})}n=n.object}return ne.isIdentifier(n)?{base:n.name,path:t}:null}function qe(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 $t=Symbol("not-closed-literal");function ps(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:$t;case"TSAsExpression":case"TSSatisfiesExpression":case"TSNonNullExpression":return ps(e.expression);case"ArrayExpression":{let t=[];for(let n of e.elements){if(!n||ne.isSpreadElement(n))return $t;let r=ps(n);if(r===$t)return $t;t.push(r)}return t}case"ObjectExpression":{let t={};for(let n of e.properties){if(!ne.isObjectProperty(n)||n.computed||n.shorthand||!ne.isExpression(n.value))return $t;let r=ne.isIdentifier(n.key)?n.key.name:ne.isStringLiteral(n.key)?n.key.value:null;if(!r)return $t;let o=ps(n.value);if(o===$t)return $t;t[r]=o}return t}default:return $t}}function lg(e){let{resolveBindingTarget:t}=e;async function n(i,s,a,c,l,u,f){let m=ps(i);if(m!==$t)return m;if(!ne.isTemplateLiteral(i)){if(ne.isTSAsExpression(i)||ne.isTSSatisfiesExpression(i)||ne.isTSNonNullExpression(i))return await n(i.expression,s,a,c,l,u,f);if(ne.isIdentifier(i)){let d=s.getBinding(i.name);if(!d)return;let g=await t({currentFile:a,binding:d,readFile:c,exists:l,fileCache:u,visited:f});return g?.kind==="static"?g.value:void 0}if(ne.isArrayExpression(i)){let d=[];for(let g of i.elements){if(!g||ne.isSpreadElement(g))return;let h=await r(g,s,a,c,l,u,f);if(h===void 0)return;d.push(h)}return d}if(ne.isObjectExpression(i)){let d={};for(let g of i.properties){if(!ne.isObjectProperty(g)||g.computed)return;let h=null;if(ne.isIdentifier(g.key)?h=g.key.name:ne.isStringLiteral(g.key)&&(h=g.key.value),!h)return;if(g.shorthand){if(!ne.isIdentifier(g.value))return;let E=await r(g.value,s,a,c,l,u,f);if(E===void 0)return;d[h]=E;continue}if(!ne.isExpression(g.value))return;let S=await r(g.value,s,a,c,l,u,f);S!==void 0&&(d[h]=S)}return d}if(ne.isMemberExpression(i)){let d=await o(i,s,a,c,l,u,f);if(!d)return;let g=s.getBinding(d.base);if(!g)return;let h=await t({currentFile:a,binding:g,readFile:c,exists:l,fileCache:u,visited:f});return!h||h.kind!=="static"?void 0:qe(h.value,d.path)}}}async function r(i,s,a,c,l,u,f){if(!ne.isSpreadElement(i))return await n(i,s,a,c,l,u,f)}async function o(i,s,a,c,l,u,f){if(ne.isIdentifier(i))return{base:i.name,path:[]};if(!ne.isMemberExpression(i))return null;let m=[],d=i;for(;ne.isMemberExpression(d);){if(d.computed){let g=d.property;if(ne.isNumericLiteral(g))m.unshift({kind:"index",index:g.value});else if(ne.isStringLiteral(g))m.unshift({kind:"property",name:g.value});else{let h=ne.isExpression(g)?await n(g,s,a,c,l,u,f):void 0;if(typeof h=="string")m.unshift({kind:"property",name:h});else if(Number.isInteger(h))m.unshift({kind:"index",index:h});else return null}}else{if(!ne.isIdentifier(d.property))return null;m.unshift({kind:"property",name:d.property.name})}d=d.object}return ne.isIdentifier(d)?{base:d.name,path:m}:null}return{normalizeExpressionWithScope:o,evaluateStaticExpression:n}}var mg=typeof pl=="function"?pl:pl.default,ug=new WeakMap;function gg(e){try{return pg.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function gs(e,t,n){let r=e.get(t);if(r?.source===n)return r.ast;let o=gg(n);return e.set(t,{source:n,ast:o}),o}function hs(e,t){return gl(vo(e).expressionRanges,t,!1)}function hg(e,t){return vo(e).exactExpressions.get(yg(t))??null}function ml(e,t){return gl(vo(e).jsxRanges,t,!0)}function vo(e){let t=ug.get(e);if(t)return t;let n={expressions:[],expressionRanges:[],jsxRanges:[],exactExpressions:new Map};return mg(e,{Expression(r){let o=r;n.expressions.push(o);let i=dg(o,n.expressions.length-1);if(!i)return;n.expressionRanges.push(i);let s=yg(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=dg(r,n.jsxRanges.length);o&&n.jsxRanges.push(o)}}),n.expressionRanges.sort(fg),n.jsxRanges.sort(fg),ug.set(e,n),n}function dg(e,t){let n=ko(e.node);return n?{path:e,range:n,traversalIndex:t,span:(e.node.end??0)-(e.node.start??0)}:null}function yg(e){return`${e.startLine}:${e.startColumn}:${e.endLine}:${e.endColumn}`}function fg(e,t){return e.range.startLine-t.range.startLine||e.range.startColumn-t.range.startColumn||e.traversalIndex-t.traversalIndex}function gl(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 ko(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 yr(e,t){if(t)return hl(e,t);let n=cg(e);return n?n.path.reduce((r,o)=>o.kind==="property"?`${r}.${o.name}`:`${r}[${o.index}]`,n.base):""}function hl(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function Io(e,t,n){let r=null,o=Number.POSITIVE_INFINITY;for(let i of vo(e).expressions){if(hl(i.node,t)!==n)continue;let s=(i.node.end??0)-(i.node.start??0);s<=o&&(r=i,o=s)}return r}function xg(e,t,n,r){return gl(vo(e).expressionRanges,r,!0,o=>hl(o.node,t)===n)}function xr(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}function Co(e){let t=null;if(mg(e,{Program(n){t=n.scope,n.stop()}}),!t)throw new Error("Unable to determine program scope");return t}async function Vt(e,t,n){let r=n.get(e);if(r)return r;let o=await t(e),i=gg(o),s={source:o,ast:i};return n.set(e,s),s}function gR(e){return V.isIdentifier(e.callee)&&(e.callee.name==="useState"||e.callee.name==="useReducer")?e.callee.name:V.isMemberExpression(e.callee)&&V.isIdentifier(e.callee.property)&&(e.callee.property.name==="useState"||e.callee.property.name==="useReducer")?e.callee.property.name:null}function hR(e){if(!V.isNewExpression(e)||!V.isIdentifier(e.callee,{name:"Proxy"})||e.arguments.length!==2||!V.isIdentifier(e.arguments[0])||!V.isObjectExpression(e.arguments[1])||e.arguments[1].properties.length!==1)return null;let[t]=e.arguments[1].properties;if(!V.isObjectMethod(t)||t.kind!=="method"||t.computed||t.async||t.generator||!V.isIdentifier(t.key,{name:"get"})||t.params.length!==3||!t.params.every(V.isIdentifier)||t.body.body.length!==2)return null;let[n,r,o]=t.params,[i,s]=t.body.body;if(V.isIfStatement(i)&&V.isBlockStatement(i.consequent)&&i.consequent.body.length!==1)return null;let a=V.isIfStatement(i)?i.test:null,c=a&&V.isLogicalExpression(a,{operator:"&&"})?a.right:null,l=V.isIfStatement(i)?V.isBlockStatement(i.consequent)?i.consequent.body[0]:i.consequent:null,u=V.isReturnStatement(s)?s.argument:null;return!a||!V.isLogicalExpression(a,{operator:"&&"})||!V.isBinaryExpression(a.left,{operator:"==="})||!V.isUnaryExpression(a.left.left,{operator:"typeof"})||!V.isIdentifier(a.left.left.argument,{name:r.name})||!V.isStringLiteral(a.left.right,{value:"string"})||!V.isUnaryExpression(c,{operator:"!"})||!V.isBinaryExpression(c.argument,{operator:"in"})||!V.isIdentifier(c.argument.left,{name:r.name})||!V.isIdentifier(c.argument.right,{name:n.name})||!V.isReturnStatement(l)||!V.isIfStatement(i)||i.alternate||!V.isCallExpression(u)||!V.isMemberExpression(u.callee)||!V.isIdentifier(u.callee.object,{name:"Reflect"})||!V.isIdentifier(u.callee.property,{name:"get"})||u.arguments.length!==3||!V.isIdentifier(u.arguments[0],{name:n.name})||!V.isIdentifier(u.arguments[1],{name:r.name})||!V.isIdentifier(u.arguments[2],{name:o.name})?null:e.arguments[0].name}function yR(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()||!V.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 xR(e,t){let n=yR(e.path);if(!n)return null;let r=ar(e,t);return r?{...n,...r}:null}function bR(e,t,n,r){return e.importedFrom===t?r?e.exportName===r:!0:e.sourceFile===t&&e.tag===n}function yl(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 xl(e,t){for(let n of e.program.body){if(t==="default"&&V.isExportDefaultDeclaration(n))return V.isExpression(n.declaration)?{kind:"default-expression",expression:n.declaration}:(V.isFunctionDeclaration(n.declaration)||V.isClassDeclaration(n.declaration))&&n.declaration.id?{kind:"default-binding",name:n.declaration.id.name}:null;if(V.isExportNamedDeclaration(n)){if(n.declaration){if(V.isVariableDeclaration(n.declaration)){for(let r of n.declaration.declarations)if(V.isIdentifier(r.id)&&r.id.name===t)return{kind:"local-binding",name:r.id.name}}if((V.isFunctionDeclaration(n.declaration)||V.isClassDeclaration(n.declaration))&&n.declaration.id&&n.declaration.id.name===t)return{kind:"local-binding",name:t}}for(let r of n.specifiers)if((V.isIdentifier(r.exported)?r.exported.name:r.exported.value)===t&&V.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 bg(e){let{resolveExternalExpression:t,resolveCollectionCallTarget:n,evaluateStaticExpression:r,resolveSourceInfoProvenance:o,buildExpressionSourceInfo:i}=e;async function s(d){let{currentFile:g,binding:h,readFile:S,exists:E,fileCache:y,visited:v}=d,C=`${g}::${h.kind}::${h.identifier.name}`;if(v.has(C))return null;v.add(C);try{let N=await a({currentFile:g,binding:h,readFile:S,exists:E,fileCache:y,visited:v});if(N)return N;if(h.path.isImportSpecifier()||h.path.isImportDefaultSpecifier())return await f({currentFile:g,binding:h,readFile:S,exists:E,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,fileCache:y,visited:v});if(h.kind==="param")return null;if(h.path.isVariableDeclarator()){let A=h.path.node.init;if(!A||!V.isExpression(A))return null;let R=hR(A);if(R&&!h.path.scope.getBinding("Proxy")&&!h.path.scope.getBinding("Reflect")){let D=h.path.scope.getBinding(R),L=D?await s({...d,binding:D}):null;if(L?.kind==="static"&&L.value!==null&&!Array.isArray(L.value)&&typeof L.value=="object")return L}let F=h.path.get("init");if(F&&!Array.isArray(F)&&F.isExpression()){let D=await t({currentFile:g,expressionPath:F,readFile:S,exists:E,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:y,visited:v});if(D)return D;if(F.isCallExpression()){let L=await n({currentFile:g,callPath:F,readFile:S,exists:E,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:y,visited:v});if(L)return L}}let _=await r(A,h.path.scope,g,S,E,y,v);return _===void 0?null:{kind:"static",file:g,root:{kind:"binding",name:h.identifier.name},value:_,sourceKind:"binding"}}if(h.path.isIdentifier()&&h.path.parentPath?.isExportDefaultDeclaration()){let A=h.path.parentPath.node.declaration;if(!V.isExpression(A))return null;let R=await r(A,h.path.scope,g,S,E,y,v);return R===void 0?null:{kind:"static",file:g,root:{kind:"binding",name:h.identifier.name},value:R,sourceKind:"binding"}}return null}finally{v.delete(C)}}async function a(d){let{currentFile:g,binding:h,readFile:S,exists:E,fileCache:y,visited:v}=d;if(!h.path.isVariableDeclarator()||!h.path.get("id").isArrayPattern())return null;let C=h.path,N=C.node.init;if(!N||!V.isCallExpression(N))return null;let A=gR(N);if(!A||!V.isArrayPattern(C.node.id)||C.node.id.elements.findIndex(L=>V.isIdentifier(L)&&L.name===h.identifier.name)!==0)return null;let F=A==="useReducer"?1:0,_=N.arguments[F];if(!_||!V.isExpression(_))return null;let D=await r(_,C.scope,g,S,E,y,v);return D===void 0?null:{kind:"static",file:g,root:{kind:"hook-state",name:h.identifier.name,hook:A},value:D,sourceKind:"binding"}}async function c(d){let g=xR(d.binding,d.sourceInfo);if(!g||!d.graph)return null;let h=[...d.graph.elements.values()].filter(A=>bR(A,d.currentFile,g.componentName,g.exportName));if(h.length!==1)return null;let S=h[0],E=S.attributes?.find(A=>A.name===g.propName);if(E&&!E.source){let A=await l({caller:S,propName:g.propName,remainingPath:g.remainingPath,readFile:d.readFile,fileCache:d.fileCache});if(A)return yl(A,{componentName:g.componentName,propName:g.propName,file:S.sourceFile})}if(!E?.source){let A=await u({caller:S,propName:g.propName,remainingPath:g.remainingPath,readFile:d.readFile,exists:d.exists,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:d.fileCache,visited:d.visited});if(A)return yl(A,{componentName:g.componentName,propName:g.propName,file:S.sourceFile});let R=yp(d.binding,g.componentName,g.propName);if(!R||R.propName!==g.propName)return null;let F=await r(R.expressionPath.node,R.expressionPath.scope,d.currentFile,d.readFile,d.exists,d.fileCache,d.visited);if(F===void 0)return null;let _=g.remainingPath;return _.length>0&&qe(F,_)===void 0?null:{kind:"value",file:d.currentFile,root:{kind:"binding",name:g.propName},path:_,sourceKind:"binding",semanticKind:"component-prop",displayExpression:R.displayPath,chainPrefix:[{kind:"component-prop",file:d.currentFile,displayName:R.displayPath,canEditHere:!0}],editMode:"upstream",diagnostics:[]}}let y=await Vt(S.sourceFile,d.readFile,d.fileCache);if(!y.ast)return null;let v=xg(y.ast,y.source,E.source.expression,E.sourceRange)??Io(y.ast,y.source,E.source.expression);if(!v)return null;let C={...E.source,expression:xr(E.source.expression,g.remainingPath),path:[...E.source.path,...g.remainingPath]},N=await o({currentFile:S.sourceFile,expressionPath:v,sourceInfo:C,readFile:d.readFile,exists:d.exists,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:d.fileCache,visited:d.visited});return N?yl(N.kind==="external"?N:{...N,displayExpression:C.expression},{componentName:g.componentName,propName:g.propName,file:S.sourceFile}):null}async function l(d){let g=await Vt(d.caller.sourceFile,d.readFile,d.fileCache);if(!g.ast)return null;let h=ml(g.ast,d.caller.sourceRange);if(!h)return null;let S=h.get("openingElement").get("attributes").find(C=>C.isJSXAttribute()&&C.node.name.type==="JSXIdentifier"&&C.node.name.name===d.propName);if(!S?.isJSXAttribute())return null;let E=S.get("value"),y=E.isStringLiteral()?E:E.isJSXExpressionContainer()?E.get("expression"):null;if(!y?.isExpression())return null;let v=ko(y.node);return v?{kind:"value",file:d.caller.sourceFile,root:{kind:"expression",sourceRange:v},path:d.remainingPath,sourceKind:"binding",semanticKind:"component-prop",displayExpression:d.propName,editMode:"upstream",diagnostics:[]}:null}async function u(d){let g=await Vt(d.caller.sourceFile,d.readFile,d.fileCache);if(!g.ast)return null;let h=ml(g.ast,d.caller.sourceRange);if(!h)return null;let S=h.get("openingElement");for(let E of S.get("attributes")){if(!E.isJSXSpreadAttribute())continue;let y=E.get("argument");if(!y.isExpression())continue;let v=await i({expression:y.node,scope:y.scope,source:g.source,currentFile:d.caller.sourceFile,readFile:d.readFile,exists:d.exists,fileCache:d.fileCache,visited:d.visited});if(!v)continue;let C=[{kind:"property",name:d.propName},...d.remainingPath],N={...v,expression:xr(v.expression,C),path:[...v.path,...C]},A=await o({currentFile:d.caller.sourceFile,expressionPath:y,sourceInfo:N,readFile:d.readFile,exists:d.exists,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:d.fileCache,visited:d.visited});if(A)return A.kind==="external"?A:{...A,displayExpression:N.expression}}return null}async function f(d){let{currentFile:g,binding:h,readFile:S,exists:E,fileCache:y,visited:v}=d,C=h.path.parentPath;if(!C||!C.isImportDeclaration())return null;let N=C.node.source.value;if(typeof N!="string")return null;let A=await Sn(g,N,E);if(!A)return null;if(h.path.isImportDefaultSpecifier()){let oe=await Vt(A,S,y),me=oe.ast?xl(oe.ast,"default"):null,ee=await m({file:A,exportName:"default",readFile:S,exists:E,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:y,visited:v});return!ee||ee.kind!=="static"?null:{kind:"static",file:me?.kind==="default-expression"?ee.file:A,root:me?.kind==="default-expression"?ee.root:{kind:"default-export"},value:ee.value,sourceKind:"imported-binding"}}if(!h.path.isImportSpecifier())return null;let R=h.path.node.imported,F=V.isIdentifier(R)?R.name:R.value,_=await Vt(A,S,y),D=_.ast?xl(_.ast,F):null,L=await m({file:A,exportName:F,readFile:S,exists:E,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:y,visited:v});return L?L.kind==="external"?L:{kind:"static",file:D?.kind==="re-export"?L.file:A,root:D?.kind==="re-export"||L.root.kind==="binding"&&L.root.name!==D?.name?L.root:{kind:"named-export",name:F},value:L.value,sourceKind:"imported-binding"}:null}async function m(d){let{file:g,exportName:h,readFile:S,exists:E,fileCache:y,visited:v}=d,C=`export::${g}::${h}`;if(!v.has(C)){v.add(C);try{let N=await Vt(g,S,y);if(!N.ast)return;let A=xl(N.ast,h);if(!A)return;if(A.kind==="default-expression"){let D=A.expression;if(!D||!V.isIdentifier(D))return;let L=Co(N.ast).getBinding(D.name);return L?await s({currentFile:g,binding:L,readFile:S,exists:E,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:y,visited:v})??void 0:void 0}if(A.kind==="re-export"){if(!A.source||!A.name)return;let D=await Sn(g,A.source,E);return D?m({...d,file:D,exportName:A.name}):void 0}let R=A.name;if(!R)return;let F=Co(N.ast).getBinding(R);return F?await s({currentFile:g,binding:F,readFile:S,exists:E,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:y,visited:v})??void 0:void 0}finally{v.delete(C)}}}return{resolveExportValue:m,resolveComponentPropBinding:c,resolveBindingTarget:s}}import*as H from"@babel/types";function Sl(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=It(o,t);if(!i)return null;let s=r.parentPath;return!s||!s.isCallExpression()||!SR(s,r)?null:{callPath:s,basePath:i}}function SR(e,t){let n=e.node.callee;return!H.isMemberExpression(n)||!H.isIdentifier(n.property)||n.property.name!=="map"?!1:e.node.arguments.some(r=>r===t.node)}function vg(e,t){let n=e.get("callee");if(!n.isMemberExpression())return null;let r=n.get("object");return Array.isArray(r)||!r.isExpression()?null:zi(r,t)}function Sg(e,t){return e?H.isNumericLiteral(e)&&Number.isInteger(e.value)?e.value:null:t}function Eg(e,t,n,r,o){let i=H.isExpression(e.body)?e.body:e.body.body.find(a=>H.isReturnStatement(a))?.argument;if(!i||!H.isExpression(i))return;let s=bl(i,t,n,r,o);return typeof s=="number"?s:void 0}function bl(e,t,n,r,o){if(H.isNumericLiteral(e)||H.isStringLiteral(e)||H.isBooleanLiteral(e))return e.value;if(H.isIdentifier(e))return e.name===t?r:e.name===n?o:void 0;if(H.isMemberExpression(e)){let i=ms(e,t);if(i)return qe(r,i);let s=ms(e,n);return s?qe(o,s):void 0}if(H.isBinaryExpression(e)&&e.operator==="-"){let i=H.isExpression(e.left)?bl(e.left,t,n,r,o):void 0,s=H.isExpression(e.right)?bl(e.right,t,n,r,o):void 0;return typeof i=="number"&&typeof s=="number"?i-s:void 0}}function ER(e){if(H.isExpression(e.body))return e.body;for(let t of e.body.body)if(H.isReturnStatement(t)&&t.argument&&H.isExpression(t.argument))return t.argument;return null}function vR(e,t,n){let r=jn(e,t,n);return typeof r=="boolean"?r:void 0}function jn(e,t,n){if(H.isStringLiteral(e)||H.isNumericLiteral(e)||H.isBooleanLiteral(e))return e.value;if(H.isNullLiteral(e))return null;if(H.isIdentifier(e))return e.name===t?n:void 0;if(H.isMemberExpression(e)){let r=ms(e,t);return r?qe(n,r):void 0}if(H.isUnaryExpression(e)&&e.operator==="!"){let r=jn(e.argument,t,n);return r===void 0?void 0:!r}if(H.isLogicalExpression(e)){let r=jn(e.left,t,n);if(r===void 0)return;if(e.operator==="&&")return r&&jn(e.right,t,n);if(e.operator==="||")return r||jn(e.right,t,n)}if(H.isBinaryExpression(e)){let r=H.isExpression(e.left)?jn(e.left,t,n):void 0,o=H.isExpression(e.right)?jn(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 kg(e){let t=[],n=e;for(;H.isMemberExpression(n)||H.isOptionalMemberExpression(n);){let r=n.property;if(n.computed)if(H.isNumericLiteral(r))t.unshift({kind:"index",index:r.value});else if(H.isStringLiteral(r))t.unshift({kind:"property",name:r.value});else if(H.isExpression(r))t.unshift({kind:"dynamic",expression:r});else return null;else if(H.isIdentifier(r))t.unshift({kind:"property",name:r.name});else return null;n=n.object}return H.isIdentifier(n)?{base:n.name,segments:t}:null}function Ig(e){return e.some(t=>t.kind==="dynamic")}function kR(e){return typeof e=="string"?{kind:"property",name:e}:Number.isInteger(e)?{kind:"index",index:e}:null}function Cg(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 IR(e,t){let n=[],r=[];for(let o of t){let i=qe(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 Rg(e){let{resolveBindingTarget:t,evaluateStaticExpression:n,buildExpressionSourceInfo:r,resolveSourceInfoProvenance:o}=e;async function i(d){let{currentFile:g,callPath:h,readFile:S,exists:E,fileCache:y,visited:v}=d,C=h.node.callee;if(!H.isMemberExpression(C)||!H.isIdentifier(C.property)||C.property.name!=="map")return null;let N=h.get("callee");if(!N.isMemberExpression())return null;let A=N.get("object");if(Array.isArray(A)||!A.isExpression())return null;let R=await s({currentFile:g,expressionPath:A,readFile:S,exists:E,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:y,visited:v});return!R||!Array.isArray(R.value)||R.value.length===0?null:R}async function s(d){let{currentFile:g,expressionPath:h,readFile:S,exists:E,fileCache:y,visited:v}=d;if(h.isIdentifier()){let C=h.scope.getBinding(h.node.name);if(!C)return null;let N=await t({currentFile:g,binding:C,readFile:S,exists:E,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:y,visited:v});return N?.kind==="static"?N:null}if(h.isCallExpression())return c({currentFile:g,callPath:h,readFile:S,exists:E,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:y,visited:v});if(h.isTSAsExpression()||h.isTSSatisfiesExpression()||h.isTSNonNullExpression()){let C=h.get("expression");if(!Array.isArray(C)&&C.isExpression())return s({...d,expressionPath:C})}if(h.isArrayExpression()){let C=ko(h.node);if(!C)return null;let N=await n(h.node,h.scope,g,S,E,y,v);return Array.isArray(N)?{kind:"static",file:g,root:{kind:"expression",sourceRange:C},value:N,sourceKind:"binding"}:null}if(h.isMemberExpression()){let C=await r({expression:h.node,scope:h.scope,currentFile:g,readFile:S,exists:E,fileCache:y,visited:v});if(!C)return null;let N=await o({currentFile:g,expressionPath:h,sourceInfo:C,readFile:S,exists:E,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:y,visited:v});if(!N||N.kind==="external")return null;let A=await a({currentFile:g,expressionPath:h,provenance:N,readFile:S,exists:E,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:y,visited:v});if(!A||A.kind!=="static")return null;if(N.collectionPathMap?.length){let F=IR(A.value,N.collectionPathMap);if(F)return{kind:"static",file:N.file,root:N.root,value:F.value,sourceKind:N.sourceKind,collectionPathMap:F.collectionPathMap}}let R=qe(A.value,N.path);return Array.isArray(R)?{kind:"static",file:N.file,root:N.root,value:R,sourceKind:N.sourceKind,pathPrefix:N.path,collectionIndexMap:N.collectionIndexMap,collectionPathMap:N.collectionPathMap}:null}return null}async function a(d){let{provenance:g}=d;if(g.root.kind==="binding"){let y=d.expressionPath.scope.getBinding(g.root.name);if(!y&&g.file!==d.currentFile){let v=await Vt(g.file,d.readFile,d.fileCache);y=v.ast?Co(v.ast).getBinding(g.root.name):void 0}return y?await t({currentFile:g.file,binding:y,readFile:d.readFile,exists:d.exists,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:d.fileCache,visited:d.visited}):null}if(g.root.kind!=="expression")return null;let h=await Vt(g.file,d.readFile,d.fileCache);if(!h.ast)return null;let S=hg(h.ast,g.root.sourceRange);if(!S)return null;let E=await n(S.node,S.scope,g.file,d.readFile,d.exists,d.fileCache,d.visited);return E===void 0?null:{kind:"static",file:g.file,root:g.root,value:E,sourceKind:g.sourceKind}}async function c(d){return await l(d)??await u(d)??await f(d)}async function l(d){let{callPath:g}=d,h=g.node.callee;if(!H.isMemberExpression(h)||!H.isIdentifier(h.property)||h.property.name!=="filter")return null;let S=g.get("callee");if(!S.isMemberExpression())return null;let E=S.get("object");if(Array.isArray(E)||!E.isExpression())return null;let y=await s({currentFile:d.currentFile,expressionPath:E,readFile:d.readFile,exists:d.exists,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:d.fileCache,visited:d.visited});if(!y||!Array.isArray(y.value))return null;let[v]=g.node.arguments;if(!H.isArrowFunctionExpression(v)&&!H.isFunctionExpression(v))return null;let C=v.params[0];if(!H.isIdentifier(C))return null;let N=ER(v);if(!N)return null;let A=[],R=[],F=[];for(let[_,D]of y.value.entries()){let L=vR(N,C.name,D);if(typeof L!="boolean")return null;if(L){A.push(D),R.push(y.collectionIndexMap?.[_]??_);let oe=y.collectionPathMap?.[_];oe&&F.push(oe)}}return{...y,value:A,pathPrefix:y.pathPrefix,collectionIndexMap:R,...F.length>0?{collectionPathMap:F}:{}}}async function u(d){let{callPath:g}=d,h=g.node.callee;if(!H.isMemberExpression(h)||!H.isIdentifier(h.property)||h.property.name!=="slice")return null;let S=g.get("callee");if(!S.isMemberExpression())return null;let E=S.get("object");if(Array.isArray(E)||!E.isExpression())return null;let y=await s({currentFile:d.currentFile,expressionPath:E,readFile:d.readFile,exists:d.exists,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:d.fileCache,visited:d.visited});if(!y||!Array.isArray(y.value))return null;let[v,C]=g.node.arguments,N=Sg(v,0),A=Sg(C,y.value.length);if(N===null||A===null)return null;let R=Math.max(0,N<0?y.value.length+N:N),F=Math.max(0,A<0?y.value.length+A:A),_=y.value.map((L,oe)=>y.collectionIndexMap?.[oe]??oe).slice(R,F),D=y.collectionPathMap?.slice(R,F);return{...y,value:y.value.slice(R,F),pathPrefix:y.pathPrefix,collectionIndexMap:_,...D?{collectionPathMap:D}:{}}}async function f(d){let{callPath:g}=d,h=g.node.callee;if(!H.isMemberExpression(h)||!H.isIdentifier(h.property)||h.property.name!=="sort"&&h.property.name!=="toSorted")return null;let S=g.get("callee");if(!S.isMemberExpression())return null;let E=S.get("object");if(Array.isArray(E)||!E.isExpression())return null;let y=await s({currentFile:d.currentFile,expressionPath:E,readFile:d.readFile,exists:d.exists,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:d.fileCache,visited:d.visited});if(!y||!Array.isArray(y.value))return null;let[v]=g.node.arguments;if(!H.isArrowFunctionExpression(v)&&!H.isFunctionExpression(v))return null;let[C,N]=v.params;if(!H.isIdentifier(C)||!H.isIdentifier(N))return null;let A=y.value.map((F,_)=>({value:F,sourceIndex:y.collectionIndexMap?.[_]??_,originalIndex:_})),R=[...A];for(let F of A)for(let _ of A)if(Eg(v,C.name,N.name,F.value,_.value)===void 0)return null;return R.sort((F,_)=>{let D=Eg(v,C.name,N.name,F.value,_.value)??0;return D===0?F.originalIndex-_.originalIndex:D}),{...y,value:R.map(F=>F.value),pathPrefix:y.pathPrefix,collectionIndexMap:R.map(F=>F.sourceIndex),...y.collectionPathMap?{collectionPathMap:R.map(F=>y.collectionPathMap?.[F.originalIndex]).filter(F=>!!F)}:{}}}async function m(d){let g=null,h,S=[];for(let y of d.segments){if(y.kind!=="dynamic")continue;let v=await r({expression:y.expression,scope:d.expressionPath.scope,source:d.fileCache.get(d.currentFile)?.source,currentFile:d.currentFile,readFile:d.readFile,exists:d.exists,fileCache:d.fileCache,visited:d.visited});if(!v)return null;let C=Sl(d.expressionPath,v.base);if(!C)return null;let N=await i({currentFile:d.currentFile,callPath:C.callPath,readFile:d.readFile,exists:d.exists,graph:d.graph,externalSourceResolvers:d.externalSourceResolvers,externalAdapters:d.externalAdapters,functionCallContracts:d.functionCallContracts,fileCache:d.fileCache,visited:d.visited});if(!N||!Array.isArray(N.value))return null;let A=N.value.map((R,F)=>{let _=qe(N.value,[{kind:"index",index:F},...C.basePath,...v.path]);return kR(_)});if(A.some(R=>R===null)||g!==null&&g!==A.length)return null;g=A.length,h??=N.collectionIndexMap,S.push(A)}if(g===null||g===0)return null;let E=[];for(let y=0;y<g;y+=1){let v=[...d.rootPath],C=0;for(let N of d.segments){if(N.kind==="dynamic"){let A=S[C]?.[y];if(!A)return null;v.push(A),C+=1;continue}v.push({...N})}E.push(v)}return{...h?{collectionIndexMap:h}:{},collectionPathMap:E}}return{resolveRepeatCollectionTarget:i,resolveCollectionCallTarget:c,resolveDynamicMemberPathMap:m}}var{normalizeExpressionWithScope:CR,evaluateStaticExpression:ys}=lg({resolveBindingTarget:e=>xs(e)}),{resolveRepeatCollectionTarget:RR,resolveCollectionCallTarget:wR,resolveDynamicMemberPathMap:NR}=Rg({resolveBindingTarget:e=>xs(e),evaluateStaticExpression:ys,buildExpressionSourceInfo:Kt,resolveSourceInfoProvenance:St}),{resolveExportValue:PR,resolveComponentPropBinding:AR,resolveBindingTarget:xs}=bg({resolveExternalExpression:wl,resolveCollectionCallTarget:wR,evaluateStaticExpression:ys,resolveSourceInfoProvenance:St,buildExpressionSourceInfo:Kt});function Og(e){return new Map([...e].map(t=>[t.file,{source:t.source,ast:t.ast}]))}var wg=new WeakMap;function TR(e){let t=wg.get(e);return t||(t=new WeakMap,wg.set(e,t)),t}function Ng(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 Lg(e){let{file:t,source:n,segment:r,readFile:o,exists:i}=e,s=e.fileCache??new Map,a=gs(s,t,n);if(!a)return null;let c=hs(a,r.sourceRange);if(!c)return null;let l=await Kt({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:o,exists:i,fileCache:s,visited:new Set});if(!l){let m=await Tl({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 m?kl(m,yr(c.node,n)):null}let u=new Set,f=await qR({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 f?kl(f,l.expression):null}async function br(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=gs(i,t,n);if(!s)return null;let a=e.sourceRange?hs(s,e.sourceRange):e.expression!==void 0?Io(s,n,e.expression):null;if(!a)return null;let c=bs(a);if(!c.isIdentifier()&&!c.isMemberExpression())return null;let l=new Set,u=await Kt({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:r,exists:o,fileCache:i,visited:l}),f=u?await St({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 Jg({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 kl(f,e.expression??yr(c.node,n))}async function Rl(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=gs(i,t,n);if(!s)return dt("unsupported-expression","Unable to parse source for provenance resolution");let a=new Set;return e.target.kind==="text-segment"?FR({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}):_R({file:t,source:n,ast:s,candidate:e.target.candidate,readFile:r,exists:o,graph:e.graph,fileCache:i,visited:a})}async function Kt(e){if(Z.isIdentifier(e.expression))return{kind:"identifier",expression:e.expression.name,base:e.expression.name,path:[]};if(!Z.isMemberExpression(e.expression))return null;let t=await CR(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:yr(e.expression,e.source),base:t.base,path:t.path}:null}function kl(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 FR(e){let{file:t,source:n,ast:r,segment:o,readFile:i,exists:s,fileCache:a,visited:c}=e,l=hs(r,o.sourceRange),u=l?await Kt({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 Pg(t,o.value);let m=await Tl({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 m?m.kind==="external"?Mg(t,m):Cl(t,yr(l.node,n),m):MR({expression:l.node,scope:l.scope,currentFile:t,source:n,readFile:i,exists:s,fileCache:a,visited:c,functionCallContracts:e.functionCallContracts})}if(!l)return dt("unsupported-expression","Unable to locate text expression for provenance resolution");let f=await St({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(!f){let m=Il(l.node);if(m)return dt(m.code,m.message);let d=l.scope.getBinding(u.base);if(d?.path.isVariableDeclarator()){let g=Il(d.path.node.init);if(g)return dt(g.code,g.message)}return d?.path.isVariableDeclarator()&&Z.isCallExpression(d.path.node.init)?OR("unsupported-expression",Vg(d.path.node.init,e.functionCallContracts)):dt("unsupported-expression",`Unable to resolve provenance for expression "${u.expression}"`)}return f.kind==="external"?Mg(t,f):Cl(t,u.expression,f)}async function _R(e){let{file:t,source:n,ast:r,candidate:o,readFile:i,exists:s,fileCache:a,visited:c}=e;if(!o.conditionSource)return dt("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let l=Io(r,n,o.conditionExpression);if(!l)return dt("conditional-branch-unresolved",`Unable to locate conditional expression "${o.conditionExpression}"`);let u=await St({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 dt("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);if(u.kind==="external")return dt("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let f=Cl(t,o.conditionExpression,u);return f.finalSource?{...f,finalSource:{...f.finalSource,kind:"conditional-branch",displayPath:o.conditionExpression},chain:[...f.chain,{kind:"conditional-branch",file:u.file,displayName:o.conditionExpression,canEditHere:!0}]}:f}function Pg(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 MR(e){let t=await Bg(e);if(t.length===0)return dt("unsupported-expression",`Unsupported expression type: ${e.expression.type}`);if(LR(e.expression))return Dg(t);if($g(e.expression))return dt("unsupported-expression","i18n helpers require a static message id string");if(Z.isMemberExpression(e.expression)&&e.expression.computed&&!Z.isNumericLiteral(e.expression.property)&&!Z.isStringLiteral(e.expression.property))return dt("dynamic-key","Computed member expressions are not supported for provenance resolution");let[n]=t;return dt(n.code,n.message)}function dt(e,t){return{finalSource:null,chain:[],confidence:"unknown",editMode:"unsupported",diagnostics:[{code:e,message:t}]}}function OR(e,t){return Dg([{code:e,message:t}])}function Dg(e){return{finalSource:null,chain:[],confidence:"partial",editMode:"readonly",diagnostics:e}}function LR(e){return Z.isCallExpression(e)||Z.isConditionalExpression(e)||Z.isLogicalExpression(e)||Z.isBinaryExpression(e)}function wo(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 Bg(e){let{expression:t,scope:n,currentFile:r,readFile:o,exists:i,fileCache:s,visited:a,functionCallContracts:c}=e,l=Il(t);if(l)return[l];if(Z.isCallExpression(t))return[{code:"unsupported-expression",message:Vg(t,c)}];if(Z.isMemberExpression(t)&&t.computed){let u=t.property;if(!Z.isNumericLiteral(u)&&!Z.isStringLiteral(u)){if(!Z.isExpression(u))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}];let m=await ys(u,n,r,o,i,s,a);if(typeof m!="string"&&!Number.isInteger(m))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}]}}return Z.isBinaryExpression(t)?wo([...await El(t.left,t.right,e),{code:"unsupported-expression",message:"Mixed expressions are recognized but remain readonly until a safer composition editing strategy is available"}]):Z.isLogicalExpression(t)?wo([...await El(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"}]):Z.isConditionalExpression(t)?wo([...await El(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 Il(e){return $g(e)?Ag("i18n helpers require a static message id string"):VR(e)?Ag("CMS helpers require static entry id and field path string arguments"):null}async function El(...e){let t=e[e.length-1],n=e.slice(0,-1),r=[];for(let o of n)r.push(...await Bg({...t,expression:o}));return r}function DR(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:[BR(e.sourceType)]}}async function wl(e){for(let n of XR){if(!Tg(e.expressionPath,n.helperNames))continue;let r=await n.resolve(e);if(r)return _g(Fg(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(!Tg(e.expressionPath,n.helperNames))continue;let r=await n.resolve(t);if(r)return _g(Fg(r),e.externalAdapters)}return null}function BR(e){return{code:"missing-adapter",message:`No external adapter is registered for ${e}`}}function jR(e){return{code:"external-source-readonly",message:e}}function Ag(e){return{code:"unsupported-expression",message:e}}function Nl(e){return!e||!Z.isCallExpression(e)?null:Z.isIdentifier(e.callee)?e.callee.name:Z.isMemberExpression(e.callee)&&!e.callee.computed&&Z.isIdentifier(e.callee.object)&&Z.isIdentifier(e.callee.property)?`${e.callee.object.name}.${e.callee.property.name}`:null}function Tg(e,t){if(!t||t.length===0)return!0;let n=Nl(e.node);return n?t.includes(n):!1}function Fg(e){return"match"in e?{match:e.match,editMode:e.editMode,diagnostics:wo(e.diagnostics??[])}:{match:e,diagnostics:[]}}function _g(e,t){let n=DR(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:wo([...e.diagnostics,...e.editMode==="readonly"||n.editMode==="readonly"?n.diagnostics:[]])}}function $R(e){if(!e.isCallExpression())return null;let t=e.node.callee;if(!Z.isIdentifier(t)||t.name!=="getCmsField")return null;let[n,r]=e.node.arguments;if(!n||!r||!Z.isStringLiteral(n)||!Z.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 VR(e){return!!e&&Z.isCallExpression(e)&&Z.isIdentifier(e.callee)&&e.callee.name==="getCmsField"&&(e.arguments.length<2||!Z.isStringLiteral(e.arguments[0])||!Z.isStringLiteral(e.arguments[1]))}function jg(e){if(!(!e||!Z.isCallExpression(e))){if(Z.isIdentifier(e.callee)&&e.callee.name==="t"){let[t]=e.arguments;return t&&Z.isStringLiteral(t)?t.value:null}if(Z.isMemberExpression(e.callee)&&!e.callee.computed&&Z.isIdentifier(e.callee.object)&&e.callee.object.name==="intl"&&Z.isIdentifier(e.callee.property)&&e.callee.property.name==="formatMessage"){let[t]=e.arguments;if(!t||!Z.isObjectExpression(t))return null;for(let n of t.properties)if(Z.isObjectProperty(n)&&!n.computed&&(Z.isIdentifier(n.key)&&n.key.name==="id"||Z.isStringLiteral(n.key)&&n.key.value==="id")&&Z.isStringLiteral(n.value))return n.value.value;return null}}}function $g(e){return jg(e)===null}async function KR(e,t,n){let r=new Set,o=Ro.posix.dirname(e);for(;r.add(o),!(o==="."||o==="/");){let i=Ro.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"]:[Ro.posix.join(i,"locales"),Ro.posix.join(i,"messages")];for(let a of s){let c=Ro.posix.join(a,`${t}.json`);if(await n(c))return c}}return null}async function UR(e){let t=jg(e.expressionPath.node);if(typeof t!="string"||t.length===0)return null;let n="en",r=await KR(e.currentFile,n,e.exists);return r?{sourceType:"i18n-message",sourceId:`${n}:${t}`,file:r,displayPath:t}:null}async function JR(e){if(!e.expressionPath.isCallExpression())return null;let t=e.expressionPath.node.callee;if(!Z.isIdentifier(t)||t.name!=="apiField")return null;let[n,r]=e.expressionPath.node.arguments;if(!n||!Z.isExpression(n))return null;let o=await ys(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:[jR("API mapping transforms must stay readonly until a reversible mapping strategy is registered")]}:i}var XR=[{helperNames:["getCmsField"],resolve:({expressionPath:e})=>$R(e)},{helperNames:["apiField"],resolve:e=>JR(e)},{helperNames:["t","intl.formatMessage"],resolve:({currentFile:e,expressionPath:t,exists:n})=>UR({currentFile:e,expressionPath:t,exists:n})}];function Pl(e){return{...e,editMode:"readonly",diagnostics:[{code:"unsupported-expression",message:"Derived display values are readonly because no identity-preserving write target exists"}]}}function Mg(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 Cl(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=QR(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 zR=[{helperName:"formatPrice",purity:"pure",sourceArgIndex:0},{helperName:"formatDate",purity:"pure",sourceArgIndex:0},{helperName:"pickLabel",purity:"pure",sourceArgIndex:0}];function Al(e,t){let n=[...zR,...t??[]];for(let r=n.length-1;r>=0;r-=1){let o=n[r];if(o?.helperName===e)return o}return null}function Vg(e,t){let n=e.callee;return Z.isIdentifier(n)&&Al(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 Tl(e){let t=await wl(e);if(t)return t;let n=await Kg({...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 Kt({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 St({...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 YR(e)}async function Kg(e){let t=await Rt({...e,allowComposed:!1});if(t?.kind!=="source")return null;let n=bs(e.expressionPath);return n.isIdentifier()||n.isMemberExpression()?t.provenance:Pl(t.provenance)}async function Rt(e){let t=bs(e.expressionPath),n=GR(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 Kt({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 St({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 Kt({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 St({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 Rt({...e,expressionPath:r,allowComposed:!0}),a=await Rt({...e,expressionPath:o,allowComposed:!1}),c=await Rt({...e,expressionPath:i,allowComposed:!1});return vl(s,a,c)}if(t.isCallExpression())return WR({...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 Rt({...e,expressionPath:r,allowComposed:!0}),s=await Rt({...e,expressionPath:o,allowComposed:!0});return vl(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 Rt({...e,expressionPath:r,allowComposed:!0}),s=await Rt({...e,expressionPath:o,allowComposed:!0});return vl(i,s)}if(t.isUnaryExpression()){let r=t.get("argument");return Array.isArray(r)||!r.isExpression()?null:Rt({...e,expressionPath:r,allowComposed:!0})}return null}finally{n&&e.visited.delete(n)}}function bs(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 WR(e){let t=Nl(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:Rt({...e,expressionPath:r,allowComposed:!1})}let n=e.expressionPath.get("callee");if(n.isMemberExpression()&&!n.node.computed){let r=n.node.property;if(Z.isIdentifier(r)&&(r.name==="toFixed"||r.name==="toString")){let o=n.get("object");return Array.isArray(o)||!o.isExpression()?null:Rt({...e,expressionPath:o,allowComposed:!1})}}return null}function vl(...e){let t=null;for(let n of e){if(!n)return null;if(n.kind!=="none"){if(!t){t=n.provenance;continue}if(!HR(t,n.provenance))return null}}return t?{kind:"source",provenance:t}:{kind:"none"}}function HR(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 GR(e,t){return t.start==null||t.end==null?null:`safe-derived:${e}:${t.start}:${t.end}`}async function YR(e){if(!e.expressionPath.isCallExpression())return null;let t=Nl(e.expressionPath.node);if(!t)return null;let n=Al(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 Ug({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?Pl(i):null}async function Ug(e){let t=await wl({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 Kt({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 St({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 Tl({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 ZR(e){if(!e.binding.path.isVariableDeclarator())return null;let t=e.binding.path.node.init;if(!t||!Z.isCallExpression(t))return null;let n=t.callee;if(!Z.isIdentifier(n))return null;let r=Al(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 Ug({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?Pl(a):null}function QR(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=xr(t,e.path);return{sourceId:o,displayPath:o}}async function qR(e){let t=e.segment.source;return t?St({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 St(e){let t=e.sourceInfo,n=Sl(e.expressionPath,t.base);if(n){let l=await RR({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=vg(n.callPath,[...n.basePath,...t.path]);return so(h)?Ng(e.currentFile,h.sourceId,h.displayPath):null}let u=Cg(l,[...n.basePath,...t.path]),f=l.collectionIndexMap?.[0]??0,m=[...l.pathPrefix??[],{kind:"index",index:f},...n.basePath,...t.path],d=[{kind:"index",index:0},...n.basePath,...t.path];return qe(l.value,d)===void 0?null:{kind:"value",file:l.file,root:l.root,path:u?.[0]??m,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 f=await Sn(e.currentFile,u.node.source.value,e.exists);if(!f)return null;let m=await PR({file:f,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(!m||m.kind==="external")return null;let d=t.path.slice(1);return qe(m.value,d)===void 0?null:{kind:"value",file:m.file,root:m.root,path:d,sourceKind:"imported-binding",collectionIndexMap:m.collectionIndexMap}}let o=gp(r);if(o){let l=o.expressionPath,u=await Kt({expression:l.node,scope:l.scope,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(u){let f=await St({...e,expressionPath:l,sourceInfo:{...u,expression:xr(u.expression,t.path),path:[...u.path,...t.path]}});if(f)return f}else if(r.constant){let f=`dynamic-alias:${e.currentFile}:${l.node.start}`;if(e.visited.has(f))return null;e.visited.add(f);try{let m=await Jg({...e,expressionPath:bs(l),memberSuffix:t.path});if(m?.kind==="value")return m}finally{e.visited.delete(f)}}if(t.path.length===0){let f=await Kg({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(f)return f}}if(r.kind==="param")return AR({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 ZR({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=Ji(r,t.path,TR(e.fileCache));if(so(s))return Ng(e.currentFile,s.sourceId,s.displayPath);let a=await xs({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:qe(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 Jg(e){let t=kg(e.expressionPath.node);if(!t||!Ig(t.segments))return null;let n=await St({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 NR({...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 xs({...e,binding:i}):null;if(s?.kind!=="static"||o.some(a=>qe(s.value,a.slice(n.path.length))===void 0))return null}return{...n,path:o[0]??n.path,sourceKind:"repeat-template",displayExpression:yr(e.expressionPath.node,e.fileCache.get(e.currentFile)?.source),...r.collectionIndexMap?{collectionIndexMap:r.collectionIndexMap}:{},collectionPathMap:o}}async function Xg(e){let t=ew(e.propertyName);if(t.owner==="blocked")return yn(t.owner,t.diagnostic);if(t.owner==="class-name-source"||t.owner==="style")return yn(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 yn("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 nw(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 yn("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}:yn("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?yn("generic",{code:"remove-exposes-spread",message:`Removing '${e.propertyName}' would expose an earlier spread source`}):tw(e,s.attribute)}async function tw(e,t){if(t.resolution&&t.resolution.status!=="resolved"&&!t.source){let r=await br({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}}:yn("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 br({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"?yn("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 nw(e,t){let n=t.source?.expression;if(!n)return;let r=await br({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:rw(r,e.propertyName)}}function rw(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 yn(e,t){return{status:"blocked",owner:e,...t?{diagnostic:t}:{}}}function zg(e){let{key:t,element:n,graph:r,provenances:o}=e,i=iw(t,n,r),s=i?.tag??($n(n.tag)?n.tag:n.componentName),a=i?.identity.key??Wg(n,r)??t,c=cw(i),l=lw(t,n,r,o,i),u=ow(t,n,r,o,a);return{componentName:s,instanceKey:a,templateOwner:aw(i??n,s),...c.length>0?{variantKeys:c}:{},...l.length>0?{slotKeys:l}:{},editableStrategy:u,impactScope:uw(u),alternativeStrategies:dw(u)}}function ow(e,t,n,r,o){for(let i of r.values())if(i?.editMode==="upstream")return"upstream";return Fl(e,n)?"instance":!$n(t.tag)&&t.sourceFile!==n.routeId&&o!==e?"template":"instance"}function Wg(e,t){if($n(e.tag))return e.identity.key;let n=[...t.elements.values()].filter(r=>r.importedFrom===e.sourceFile&&sw(r,e.componentName));return n.length!==1?null:n[0].identity.key}function iw(e,t,n){if($n(t.tag))return t;let r=Fl(e,n);if(r)return r;let o=Wg(t,n);return o?n.elements.get(o)??null:null}function sw(e,t){return e.exportName===t||e.tag===t||e.exportName==="default"}function aw(e,t){return $n(e.tag)&&e.importedFrom?`${e.importedFrom}#${t}`:`${e.sourceFile}#${t}`}function cw(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 lw(e,t,n,r,o){let i=new Set,s=Fl(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&&$n(t.tag)&&t.childKeys.length>0&&i.add("children"),[...i]}function Fl(e,t){let n=t.elements.get(e)?.parentKey??null;for(;n;){let r=t.elements.get(n);if(!r)break;if($n(r.tag))return r;n=r.parentKey}return null}function $n(e){return/^[A-Z]/.test(e)}function uw(e){switch(e){case"template":return"component-template";case"upstream":return"upstream-source";default:return"current-instance"}}function dw(e){switch(e){case"template":return["instance"];case"upstream":return["template"];default:return["template"]}}function Yg(e){let t=e.isRepeat??(e.graph?Sw(e.element,e.graph):!1),n=e.propertyProvenance??new Map,r=e.repeatTargets??new Map,o=bw(e.element.attributes??[]),i=[...r.values()].some(u=>u.ok),s=o.map(u=>fw({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,f)=>u.order-f.order).map(u=>({raw:u.raw,sourceRange:Ew(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 fw(e){let{attribute:t,provenance:n,repeatTarget:r}=e,o=e.selectionRef?.instanceIndex!==void 0&&r?.ok===!0?r:null,i=pw(t,n,e.isRepeat),s=["selection","template"].map(S=>({scope:S,result:qi({state:n,scope:S,operation:"set",selectionRef:e.selectionRef,isRepeat:e.isRepeat,repeatTarget:r})})),a=s.find(({result:S})=>S.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=mw(t,n,l,e.isRepeat),f=c?yw(c,e.element,t.name):void 0,m=s.filter(({result:S})=>S.ok).map(({scope:S})=>S),d=m.length>0?hw(n,o,e.element):"unsupported",g=o?"repeat-item":e.isRepeat?"repeat-template":"node",h=xw(t,n,r);if(m.length===0&&h.length===0){let S=s.find(({result:E})=>!E.ok)?.result;S&&!S.ok&&h.push({code:S.code,message:S.reason})}return{name:t.name,source:i,resolution:u,editMode:d,sourceScope:g,allowedWriteScopes:m,...f?{effectiveWriteTarget:f}:{},diagnostics:h}}function pw(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 mw(e,t,n,r){return n?Hg(n.selectedResolution):t?.status==="blocked"?{status:"unresolved"}:r&&t?.status==="binding"?{status:"unresolved"}:Hg(gw(e))}function gw(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 Hg(e){return!e||e.status==="unresolved"?{status:"unresolved"}:e.status==="undefined"?{status:"undefined"}:{status:"resolved",value:e.value}}function hw(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 yw(e,t,n){return e.kind==="repeat-property"?{kind:"value-path",file:e.target.sourceFile,isProxy:e.target.sourceFile!==t.sourceFile,displayPath:Gg({...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:Gg(e.locator)}:{kind:"jsx-node",file:t.sourceFile,isProxy:!1,displayPath:t.componentName+" > "+n}}function xw(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 bw(e){let t=new Set;return e.filter(n=>t.has(n.name)?!1:(t.add(n.name),!0))}function Sw(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 Gg(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 Ew(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 vw(e){return e==="api-field"||e==="cms-field"||e==="i18n-message"||e==="config-entry"}var kw=160;function Zg(e,t,n,r={}){let o=er(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 Qg(e,t,n,r,o,i,s,a,c,l,u){let f=er(t),m=t.elements.get(e),d=n.nodes.get(e),g=r.get(e);if(!m||!d||!g)throw new Error(`Node not found: ${e}`);let h=rh(m.textSegments,s),S=oh(e,t,m,g,h),E=h?ww(h):void 0,y=Nw(i,h),v=m.textSegments.map(R=>({index:R.index,value:R.value,editable:ih(R,g,s?.get(R.index)??null),source:o.get(R.index)??null})),C=th(m,t),N=m.childKeys.map(R=>{let F=t.elements.get(R);return F?{key:R,tag:F.tag,label:F.tag}:null}).filter(R=>R!==null),A=[];if(m.parentKey){let R=t.elements.get(m.parentKey);if(R)for(let F of R.childKeys){if(F===e)continue;let _=t.elements.get(F);_&&A.push({key:F,tag:_.tag,label:_.tag})}}return{composition:f,key:e,tag:m.tag,componentName:m.componentName,sourceFile:m.sourceFile,sourceLocator:eh(m),label:m.tag,capabilities:S,writeTarget:i,effectiveWriteTarget:y,provenanceChain:E,componentSemantic:c,styleSource:l,conditional:a,...u?{dynamicData:u}:{},textSegments:v,boundaryKind:m.boundaryKind,isOpaque:m.isOpaque,ancestors:C,children:N,siblings:A}}function qg(e,t,n,r,o,i,s,a){let c=er(t),l=t.elements.get(e),u=n.nodes.get(e),f=r.get(e);if(!l||!u||!f)throw new Error(`Node not found: ${e}`);let m=rh(l.textSegments,i),d=Iw(l);return{composition:c,key:e,tag:l.tag,...d?{linkSourceKind:d}:{},componentName:l.componentName,sourceFile:l.sourceFile,sourceLocator:eh(l),label:l.tag,capabilities:oh(e,t,l,f,m),provenanceChain:m?{editMode:m.editMode,diagnostics:m.diagnostics.map(g=>({code:g.code,message:g.message}))}:void 0,...s?{dynamicData:s}:{},...a?{properties:a}:{},textSegments:l.textSegments.map(g=>{let h=o.get(g.index);return{index:g.index,editable:ih(g,f,i?.get(g.index)??null),source:h?{kind:h.kind}:null}}),boundaryKind:l.boundaryKind,isOpaque:l.isOpaque,ancestors:th(l,t)}}function Iw(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 eh(e){return{sourceFile:e.sourceFile,componentName:e.componentName,openingElementRange:Cw(e.sourceRange),structuralPath:e.identity.structuralPath,...Rw(e.textSegments)}}function th(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 Cw(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function Rw(e){let t=e.map(n=>n.value.trim()).filter(Boolean).join(" ").replace(/\s+/g," ").trim();return t?{textPreview:t.slice(0,kw)}:{}}function nh(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 rh(e,t){if(!t)return null;for(let n of e){let r=t.get(n.index);if(r)return r}return null}function oh(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&&sh(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 ih(e,t,n){return!e.editable||!t.canUpdateText?!1:n?sh(n.editMode):!0}function sh(e){return e==="direct"||e==="proxy"||e==="upstream"}function ww(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 Nw(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}:vw(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 _l=["set-class-name-source","apply-style-draft"];function ah(e){let t=e.attributes?.find(n=>n.name==="className");if(!t)return{kind:"class-name-source",className:"",sourceKind:"missing",editable:!0,operationBoundary:_l,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:_l,sourcePath:n}}return{kind:"class-name-source",className:t.value,sourceKind:t.resolvedValue===void 0?"static-attribute":"static-expression",editable:!0,operationBoundary:_l}}function ch(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}),lh(i,r,o,t,e)}}return{nodes:t,rootKeys:[...e.rootKeys]}}function lh(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}),lh(s,t,n,r,o))}}import uh from"node:path";function Ol(){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 fh(e,t,n){let r=[],o=new Set;for(let i of e.intents){let s=Fw(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 Ss(e){let t=()=>Pw(e);return e.mutex?e.mutex.runExclusive(t):t()}async function Pw(e){let t=await fh(e.plan,e.overlay,e.exists);if(!t.ok)return{ok:!1,stage:"precheck",reason:t.reason,error:t,recoveryRequired:!1};let n=Aw(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 Ml({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 Ml({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 Ml({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 dh("swap",l,"Live state swap failed after durable publish.")}try{await e.finalizeCandidate?.(c)}catch(l){return dh("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 Aw(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 Ml(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:Tw(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 dh(e,t,n){return{ok:!1,stage:e,reason:n,error:t,recoveryRequired:!0}}function Tw(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 Fw(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)||uh.isAbsolute(e))return{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`};let t=uh.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 _w=50,Mw=8*1024*1024;function hh(e,t={}){let n=[],r=[],o=t.externalAdapters??[],i=Math.max(0,t.maxUndoEntries??_w),s=Math.max(0,t.maxUndoBytes??Mw);return{prepareRewritePlan:a,execute:c,executeFilePlan:l,undo:u,redo:f};async function a(R){let F=[...R.steps].sort((ee,ce)=>ee.order-ce.order),_=F.filter(ee=>ee.type!=="invoke-external-adapter");if(_.length!==F.length)return{ok:!1,errorCode:"unsupported-operation",reason:"External adapter writes require a transactional prepare/commit/rollback contract."};let D=new Set(_.map(ee=>ee.file)),L=await y(D),oe=new Map(L.map(ee=>[ee.file,ee.exists===!1?"":ee.content])),me;for(let ee of _){let ce=gh(ee,oe.get(ee.file)??"");if(!ce.ok)return{ok:!1,errorCode:ce.errorCode,reason:ce.reason};oe.set(ee.file,ce.source),me=ce.selectionRef??me}return{ok:!0,filePlan:{operationId:R.operationId,kind:"source-edit",target:R.target,documentVersion:R.documentVersion,conflictPolicy:"compare-and-swap",edits:[...oe].map(([ee,ce])=>({operation:"upsert",file:ee,content:ce,baseContentHash:L.find(_e=>_e.file===ee)?.sha256??null}))},...me?{selectionRef:me}:{}}}async function c(R){let F=[...R.steps].sort((_e,Qt)=>_e.order-Qt.order),_=F.filter(_e=>_e.type!=="invoke-external-adapter"),D=F.filter(_e=>_e.type==="invoke-external-adapter"),L=new Set(_.map(_e=>_e.file));if(_.length>0&&D.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(_.length===0)return S(R,D);let oe=await y(L),me=new Map;for(let _e of oe)me.set(_e.file,_e.exists===!1?"":_e.content);let ee;for(let _e of _){let Qt=me.get(_e.file)??"",qt=gh(_e,Qt);if(!qt.ok)return{ok:!1,operationId:R.operationId,errorCode:qt.errorCode,reason:qt.reason,rolledBack:!1};me.set(_e.file,qt.source),qt.selectionRef&&(ee=qt.selectionRef)}let ce=await C([...me].map(([_e,Qt])=>({file:_e,content:Qt,exists:!0,version:0,sha256:ke(Qt)})),oe);return ce.ok===!1?{ok:!1,operationId:R.operationId,errorCode:ce.rolledBack?"writeback-failed":"rollback-failed",reason:ce.reason,rolledBack:ce.rolledBack}:(n.push({operationId:R.operationId,preSnapshots:oe,postSnapshots:ce.snapshots,plan:R}),m(),r.length=0,{ok:!0,operationId:R.operationId,kind:R.kind,target:R.target,resultVersion:Math.max(...ce.snapshots.map(_e=>_e.version)),affectedFiles:[...L],...ee?{selectionRef:ee}:{}})}async function l(R){let F=new Set(R.edits.map(ce=>ce.file)),_=await y(F),D=E(R,_);if(D)return{ok:!1,operationId:R.operationId,errorCode:"stale-version",reason:D.reason,affectedFiles:[D.file],rolledBack:!1};let L=new Map(_.map(ce=>[ce.file,ce])),oe=R.edits.find(ce=>ce.operation==="create-only"&&L.get(ce.file)?.exists!==!1);if(oe)return{ok:!1,operationId:R.operationId,errorCode:"stale-version",reason:`MATERIALIZATION_INSTANCE_CONFLICT: create-only target already exists: ${oe.file}`,affectedFiles:[oe.file],rolledBack:!1};let me=R.edits.map(ce=>ce.operation==="delete"?{file:ce.file,content:"",exists:!1,version:0}:{file:ce.file,content:ce.content,exists:!0,version:0,sha256:ke(ce.content)}),ee=await C(me,_,new Set(R.edits.filter(ce=>ce.operation==="create-only").map(ce=>ce.file)));return ee.ok===!1?{ok:!1,operationId:R.operationId,errorCode:ee.rolledBack?"writeback-failed":"rollback-failed",reason:ee.reason,rolledBack:ee.rolledBack}:(n.push({operationId:R.operationId,preSnapshots:_,postSnapshots:ee.snapshots,plan:{operationId:R.operationId,kind:R.kind,target:R.target,documentVersion:R.documentVersion,steps:[],preSnapshots:_}}),m(),r.length=0,{ok:!0,operationId:R.operationId,kind:R.kind,target:R.target,resultVersion:Math.max(...ee.snapshots.map(ce=>ce.version)),affectedFiles:[...F]})}async function u(){let R=n.at(-1);if(!R)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to undo"};let F=await C(R.preSnapshots,R.postSnapshots);return F.ok===!1?{ok:!1,operationId:R.operationId,errorCode:F.rolledBack?"writeback-failed":"rollback-failed",reason:F.reason,rolledBack:F.rolledBack}:(n.pop(),r.push(R),{ok:!0,operationId:R.operationId,kind:R.plan.kind,target:R.plan.target,resultVersion:Math.max(...F.snapshots.map(_=>_.version)),affectedFiles:R.preSnapshots.map(_=>_.file)})}async function f(){let R=r.at(-1);if(!R)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to redo"};let F=await C(R.postSnapshots,R.preSnapshots);return F.ok===!1?{ok:!1,operationId:R.operationId,errorCode:F.rolledBack?"writeback-failed":"rollback-failed",reason:F.reason,rolledBack:F.rolledBack}:(r.pop(),n.push(R),m(),{ok:!0,operationId:R.operationId,kind:R.plan.kind,target:R.plan.target,resultVersion:Math.max(...F.snapshots.map(_=>_.version)),affectedFiles:R.postSnapshots.map(_=>_.file)})}function m(){for(;n.length>i;)n.shift();for(;n.length>0&&d()>s;)n.shift()}function d(){return n.reduce((R,F)=>R+g(F),0)}function g(R){return h(R.preSnapshots)+h(R.postSnapshots)}function h(R){return R.reduce((F,_)=>F+_.file.length+_.content.length,0)}async function S(R,F){let _=[];for(let D of F){let L=D.capability??"write-text",oe=o.find(ee=>ee.sourceType===D.sourceType&&(D.adapterId===void 0||ee.adapterId===D.adapterId)&&(ee.capabilities===void 0||ee.capabilities.includes(L)));if(!oe)return{ok:!1,operationId:R.operationId,errorCode:"unsupported-operation",reason:`No external adapter registered for ${D.sourceType}`,rolledBack:!1};let me=await oe.execute(D);if(!me.ok)return{ok:!1,operationId:R.operationId,errorCode:"writeback-failed",reason:me.reason??`External adapter failed for ${D.sourceType}`,rolledBack:!1};_.push(D.file)}return{ok:!0,operationId:R.operationId,kind:R.kind,target:R.target,resultVersion:0,affectedFiles:_}}function E(R,F){if(R.conflictPolicy!=="compare-and-swap")return null;let _=new Map(F.map(D=>[D.file,D]));for(let D of R.edits){if(D.operation==="create-only")continue;if(D.baseContentHash===void 0)return{file:D.file,reason:`Source file ${D.file} is missing baseContentHash. Reopen the file before saving.`};let L=_.get(D.file),oe=D.baseContentHash;if(oe===null){if(L?.exists!==!1)return{file:D.file,reason:`Source file ${D.file} was created or changed before save.`};continue}if(!oe)return{file:D.file,reason:`Source file ${D.file} is missing baseContentHash. Reopen the file before saving.`};if(L?.exists===!1||L?.sha256!==oe)return{file:D.file,reason:`Source file ${D.file} changed before save. Reload or explicitly overwrite the newer version.`}}return null}async function y(R){let F=[];for(let _ of R)F.push(await v(_));return F}async function v(R){if(!await e.exists(R))return{file:R,content:"",version:0,exists:!1};let _=Math.max(1,e.getVersion(R)),D=await e.readFile(R);return{file:R,content:D,version:_,exists:!0,sha256:ke(D)}}async function C(R,F,_=new Set){let D=[];try{for(let L of R){if(_.has(L.file)){if(!e.createExclusive)throw new Error("Create-only write requires atomic exclusive-create support.");await e.createExclusive(L.file,L.content)}else await N(L);let oe=e.bumpVersion(L.file);D.push(L.file),L.version=oe}}catch(L){let oe=await A(F.filter(ee=>D.includes(ee.file)));if(oe.ok===!1)return{ok:!1,reason:`Writeback failed, then rollback failed for ${oe.failedFiles.join(", ")}: ${mh(L)}`,rolledBack:!1,instanceConflict:ph(L)};let me=ph(L);return{ok:!1,reason:`${me?"MATERIALIZATION_INSTANCE_CONFLICT: ":""}Writeback failed and committed files were restored: ${mh(L)}`,rolledBack:!0,instanceConflict:me}}return{ok:!0,snapshots:R.map(Ow)}}async function N(R){if(R.exists===!1){await e.deleteFile(R.file);return}await e.writeFile(R.file,R.content)}async function A(R){let F=[];for(let _ of R)try{await N(_),e.bumpVersion(_.file)}catch{F.push(_.file)}return F.length===0?{ok:!0}:{ok:!1,failedFiles:F}}}function ph(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="EEXIST"}function Ow(e){let t=e.exists!==!1;return{file:e.file,content:t?e.content:"",version:e.version,exists:t,...t?{sha256:ke(e.content)}:{}}}function mh(e){return e instanceof Error?e.message:String(e)}function gh(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 We(Qn({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-import":return We(qn({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-node":return We(Hn({source:t,locator:e.locator,removeWhitespace:e.removeWhitespace}));case"insert-child":return We(Gn({source:t,locator:e.parentLocator,node:e.node,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"update-text":return We(ei({source:t,locator:e.locator,segmentIndex:e.segmentIndex,newText:e.newText}));case"update-value":return We(_r({source:t,locator:e.locator,next:e.value}));case"update-array-item":return We(_r({source:t,locator:e.locator,next:e.value}));case"insert-bound-array-item":return We(ai({source:t,locator:e.locator,index:e.index,value:e.value}));case"insert-jsx-expression-child":return We(ni({source:t,locator:e.parentLocator,expression:e.expression,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"remove-bound-array-item":return We(ci({source:t,locator:e.locator,index:e.index}));case"move-array-item":return We(li({source:t,locator:e.locator,fromIndex:e.fromIndex,toIndex:e.toIndex}));case"move-node":return We(Yn({source:t,locator:e.locator,targetParentLocator:e.targetParentLocator,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"move-repeat-template-child":return We(ri({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 Lw(e,t);case"set-property-changes":return We(oi({source:t,locator:e.locator,changes:e.changes}));case"set-link-target":return We(ii({source:t,locator:e.locator,link:e.link,changes:e.changes}));case"set-property-binding":return We(si({source:t,locator:e.locator,name:e.name,object:e.object,property:e.property}));case"upsert-object-property":return We(di({source:t,objectLocator:e.locator,name:e.name,value:e.value}));default:return{ok:!1,reason:`Unknown step type: ${e.type}`,errorCode:"unknown"}}}function Lw(e,t){let{request:n}=e;if(n.newAttrRaw!==null&&!hd(n.newAttrRaw))return{ok:!1,reason:"newAttrRaw must be a valid JSX className attribute.",errorCode:"invalid-params"};let r=n.oldAttrRange!==null&&n.oldAttrRaw!==null,o=n.openingElementRange.start,i=n.openingElementRange.end,s=t.slice(o,i);if(!(Number.isInteger(o)&&Number.isInteger(i)&&o>=0&&i>o&&i<=t.length&&s.startsWith("<")&&s.endsWith(">")&&!s.startsWith("</")&&(n.oldAttrRange===null||n.oldAttrRange.start>=o&&n.oldAttrRange.end<=i)))return{ok:!1,reason:"The opening element range changed before className save.",errorCode:"stale-version"};if(!r&&n.expectedVersion.contentHash!==ke(t))return{ok:!1,reason:"The source file changed before className save.",errorCode:"stale-version"};if(n.oldAttrRange){if(t.slice(n.oldAttrRange.start,n.oldAttrRange.end)!==n.oldAttrRaw)return{ok:!1,reason:"The className attribute changed before save.",errorCode:"stale-version"}}else if(n.oldAttrRaw!==null)return{ok:!1,reason:"The className attribute range no longer matches.",errorCode:"stale-version"};return{ok:!0,source:gd({source:t,oldAttrRange:n.oldAttrRange,openingElementRange:n.openingElementRange,newAttrRaw:n.newAttrRaw})}}function We(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 Es,SiteEditCompositionContextSchema as Dw,SiteEditCompositionSelectorSchema as Bw}from"@vcp-dev/contracts";var Ze=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="SiteEditCompositionError"}};function yh(e,t){throw new Ze("INVALID_COMPOSITION",e,{value:t})}function vs(e){let t=Dw.safeParse(e);return t.success?t.data:yh("Invalid SiteEditCompositionContext.",e)}function xh(e){let t=[],n=new Map,r=new Map;for(let l of e.compositions){let u=vs(l?.context);if(typeof l.entryFile!="string"||!l.entryFile)throw new Ze("INVALID_COMPOSITION","A registered composition must have a non-empty entryFile.");let f=Es(u);if(n.has(f))throw new Ze("DUPLICATE_COMPOSITION",`Composition key ${f} is registered more than once.`,{key:f,context:u});let m=r.get(l.entryFile);if(m)throw new Ze("DUPLICATE_COMPOSITION",`Entry file ${l.entryFile} is registered more than once.`,{entryFile:l.entryFile,context:m});let d={context:u,entryFile:l.entryFile,key:f};t.push(d),n.set(f,d),r.set(l.entryFile,f)}if(t.length===0)throw new Ze("INVALID_COMPOSITION","At least one composition must be registered.");let o=new Map;for(let l of e.initialDocumentVersions??[]){let u=vs(l?.composition);if(!Number.isInteger(l?.version)||(l?.version??-1)<0)throw new Ze("INVALID_INITIAL_DOCUMENT_VERSION","Initial document version must be a non-negative integer.",{context:u,version:l?.version});let f=Es(u);if(!n.has(f))throw new Ze("UNKNOWN_COMPOSITION","Initial document version references an unregistered composition.",{context:u,key:f});if(o.has(f))throw new Ze("DUPLICATE_COMPOSITION","Initial document versions must contain each composition at most once.",{context:u,key:f});o.set(f,l.version)}function i(l){let u=Bw.safeParse(l);if(!u.success)return yh("Invalid SiteEditCompositionSelector.",l);let f=t.filter(({context:m})=>m.routeId===u.data.routeId&&(u.data.templateId===void 0?m.effectiveTemplateId===void 0:m.effectiveTemplateId===u.data.templateId));if(f.length===1)return f[0];throw f.length>1?new Ze("AMBIGUOUS_COMPOSITION","The composition selector matches multiple registered contexts.",{selector:u.data}):new Ze("UNKNOWN_COMPOSITION","The composition selector is not registered.",{selector:u.data})}function s(l){let u=vs(l),f=Es(u),m=n.get(f);if(!m)throw new Ze("UNKNOWN_COMPOSITION","The composition context is not registered.",{context:u,key:f});return m}function a(l){let u=vs(l?.context);if(typeof l.entryFile!="string"||!l.entryFile)throw new Ze("INVALID_COMPOSITION","A registered composition must have a non-empty entryFile.");let f=Es(u),m=n.get(f);if(m){if(m.entryFile===l.entryFile)return m;throw new Ze("DUPLICATE_COMPOSITION",`Composition key ${f} is registered more than once.`,{key:f,context:u})}let d=[...n.values()].find(h=>h.entryFile===l.entryFile);if(d)throw new Ze("DUPLICATE_COMPOSITION",`Entry file ${l.entryFile} is registered more than once.`,{entryFile:l.entryFile,context:d.context});let g={context:u,entryFile:l.entryFile,key:f};return t.push(g),n.set(f,g),g}function c(l){let u=n.get(l);if(!u)return;n.delete(l);let f=t.findIndex(m=>m.key===l);return f>=0&&t.splice(f,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 Ll(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}}}import{composeSiteEditRepeatInstanceKey as jw,stripSiteEditRepeatInstanceKeys as bh}from"@vcp-dev/contracts";function Sh(e){let t=new Map,n=new Map,r=new Map;for(let o of e.entries){t.set(o.key,o);let i=bh(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 $w(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 ks(e){return e?.map(t=>({...t}))}function Dl(e,t){if(t===null||e?.kind!=="value-binding"||e.sourceKind!=="repeat-template")return e;let n=e.collectionIndexMap?.[t]??t,r=ks(e.collectionPathMap?.[t])??ks(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:ks(e.path),locator:e.locator?{...e.locator,path:r}:e.locator,collectionIndexMap:e.collectionIndexMap?[...e.collectionIndexMap]:void 0,collectionPathMap:e.collectionPathMap?.map(o=>ks(o)??[])}}function Eh(e,t,n){let r=new Set;for(let d of t.regions)if(d.kind==="repeat-region")for(let g of d.childKeys)r.add(g);if(r.size===0)return e;let o=new Map(e.entries.map(d=>[d.key,d])),i=[],s=new Map,a=(d,g)=>jw(d,g),c=(d,g,h)=>{let S=o.get(d);if(!S)return a(d,h);let E=a(d,h),y={...S,key:E,parentKey:g,childKeys:[]};return i.push(y),y.childKeys=S.childKeys.flatMap(v=>l(v,h,E)),E},l=(d,g,h)=>{if(!r.has(d))return[c(d,h,g)];let S=f(d,g),E=[];for(let y=0;y<S;y+=1)E.push(c(d,h,[...g,y]));return E},u=Array.from(new Set([...e.rootKeys,...e.entries.filter(d=>d.parentKey===null).map(d=>d.key)]));for(let d of u){if(!r.has(d)){c(d,null,[]);continue}let g=f(d,[]);for(let h=0;h<g;h+=1)c(d,null,[h])}return{...e,rootKeys:[...e.rootKeys],entries:i};function f(d,g){let h=new Set;for(let S of m(d)){let E=n.get(S);if(E){for(let y of[...E.textTargets.values(),...E.elementPropertyTargets.values()])if(!(y?.kind!=="value-binding"||y.sourceKind!=="repeat-template"))for(let v of Vw(y))v.length<=g.length||Kw(v,g)&&h.add(v[g.length])}}return h.size>0?h.size:$w(n.get(d))}function m(d){let g=s.get(d);if(g)return g;let h=[d],S=o.get(d);for(let E of S?.childKeys??[])h.push(...m(E));return s.set(d,h),h}}function vh(e){let t=e.parts.at(-1);return typeof t?.repeatIndex=="number"?t.repeatIndex:null}function kh(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((bh(s.key)??s.key)===n){if(s.key===t)return i;i+=1}return null}function Vw(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 Kw(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 Ih(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 Ch(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 Rh(e){return{path:e.path,code:e.code,message:e.message,...e.details?{details:JSON.parse(JSON.stringify(e.details))}:{}}}function Uw(e){return e.map(t=>`${t.code} (${t.path}): ${t.message}`).join("; ")}var No=class extends Error{constructor(t){let n=t.map(Rh);super(Uw(n)),this.name="RouteBuildDiagnosticsError",this.diagnostics=n}};function wh(e,t){let n=t instanceof Error&&t.message?t.message:String(t);return t instanceof No?{routeId:e,message:n,diagnostics:t.diagnostics.map(Rh)}:{routeId:e,message:n}}function Bl(e){return e.map(({routeId:t,message:n})=>`${t}: ${n}`).join("; ")}function jl(e,t){let n=new Map(e);for(let r of t)n.delete(r);return n}function Sr(e,t){e.clear();for(let[n,r]of t)e.set(n,r)}function Nh(e,t){for(let n of t){if(n.exists===!1){e.delete(n.file);continue}e.set(n.file,n.content)}}function $l(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 Ph(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 Zw=/^(?:src\/)?app\/.*\/?page\.[cm]?[jt]sx?$/,Qw=["layout.tsx","layout.ts","layout.jsx","layout.js","layout.mjs","layout.cjs"],Ah=32,Th=256;function qw(e){return{expectedIndexDigest:e.digest,publishedIndexDigest:e.digest,publishedCursor:e.cursor,publishedCurrentId:e.currentId}}var Fh={maxEntries:50,maxBytes:8*1024*1024};function eN(){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 pi(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 tN(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 nN(){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>Fh.maxEntries||rN(e)>Fh.maxBytes;)e.shift()}}function rN(e){return e.reduce((t,n)=>t+oN(n),0)}function oN(e){return _h(e.preSnapshots)+_h(e.postSnapshots)+iN(e.provenance)}function iN(e){return e?new TextEncoder().encode(JSON.stringify(e)).byteLength:0}function _h(e){return e.reduce((t,n)=>t+n.file.length+n.content.length,0)}function Mh(e,t){return{key:Xw(e),composition:e,routeId:e.routeId,entryFile:t,graph:null,topology:null,capabilities:null,document: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 Cs=class extends Error{constructor(t){super(t.reason),this.result=t}},Vn=class extends Error{constructor(t){super(Bl(t)),this.failedRoutes=t}};function Oh(e,t){if(!e)return;let n=[...t];if(n.some(o=>o?.entries.some(i=>i.key===e.key)))return e;let r=it(e.key)??e.key;for(let o of n){let i=o?.entries.find(s=>(it(s.key)??s.key)===r);if(i)return{...e,key:i.key}}return e}function sN(e,t,n){if(!n)return;let r=it(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 aN=/\.(?:[cm]?[jt]sx?)$/i,cN=/\.json$/i,lN=/\.(?:css|scss|sass)$/i,uN=/\.mdx$/i,dN=/\.ya?ml$/i;function fN(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 pN(e){return{kind:e.isProxy?"component-proxy":"jsx-node",file:e.file,componentName:e.componentName,isProxy:e.isProxy}}function mN(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=Vh(await e.listFiles(i)),a=new Map(s.files.map(l=>[l.path,l]));for(let[l,u]of n)if(gN(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 gN(e,t){return t.length===0?!0:t.some(n=>e===n||e.startsWith(`${n}/`))}function Vh(e){return Array.isArray(e)?{files:e}:e}function hN(e){if(!Ww(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!==Gw||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=zw(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(aN.test(e.path)){let t=Pt({source:e.content,profile:vn({filePath:e.path,source:e.content})});if(!t.ok)return{ok:!1,errorCode:"ast-error",message:t.diagnostic.message,details:{path:e.path}}}if(cN.test(e.path))try{JSON.parse(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`JSON parse failed: ${et(t)}`,details:{path:e.path}}}if(lN.test(e.path)){let t=Lh({content:e.content,path:e.path,profile:"css"});if(!t.ok)return t}if(uN.test(e.path)){let t=Lh({content:e.content,path:e.path,profile:"mdx"});if(!t.ok)return t}if(dN.test(e.path))try{Yw(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`YAML parse failed: ${et(t)}`,details:{path:e.path}}}return{ok:!0}}function Lh({content:e,path:t,profile:n}){let r=[],o=null,i=!1,s=!1,a=!1,c=!1,l=!0;for(let f=0;f<e.length;f+=1){let m=e[f]??"",d=e[f+1]??"";if(n==="mdx"&&l&&e.startsWith("```",f)){c=!c;let g=e.indexOf(`
|
|
8
8
|
`,f);if(g===-1){l=!0;break}f=g,l=!0;continue}if(c){l=m===`
|
|
9
9
|
`||m==="\r";continue}if(s){m==="*"&&d==="/"&&(s=!1,f+=1),l=m===`
|
|
10
10
|
`||m==="\r";continue}if(a){m===`
|
|
11
11
|
`||m==="\r"?(a=!1,l=!0):l=!1;continue}if(o){if(i)i=!1;else if(m==="\\")i=!0;else if(m===o)o=null;else if(n==="css"&&(m===`
|
|
12
12
|
`||m==="\r"))return Er(t,`Unterminated string literal in ${t}.`);l=m===`
|
|
13
13
|
`||m==="\r";continue}if(m==="/"&&d==="*"){s=!0,f+=1,l=!1;continue}if(n==="mdx"&&m==="/"&&d==="/"){a=!0,f+=1,l=!1;continue}if(m==="'"||m==='"'||n==="mdx"&&m==="`"){o=m,l=!1;continue}if(m==="{"||m==="("||m==="["){r.push({char:m,offset:f}),l=!1;continue}if(m==="}"||m===")"||m==="]"){let g=m==="}"?"{":m===")"?"(":"[",h=r.pop();if(!h||h.char!==g)return Er(t,`Unexpected closing token "${m}" in ${t}.`);l=!1;continue}l=m===`
|
|
14
|
-
`||m==="\r"}if(s)return Er(t,`Unterminated block comment in ${t}.`);if(o)return Er(t,`Unterminated string literal in ${t}.`);if(c)return Er(t,`Unterminated MDX code fence in ${t}.`);let u=r.at(-1);return u?Er(t,`Unclosed token "${u.char}" in ${t}.`):{ok:!0}}function Er(e,t){return{ok:!1,errorCode:"ast-error",message:t,details:{path:e}}}function Rs(e){let t="idle",n=e.fileSystem??eN(),r=yd(),o=yh({compositions:e.compositions,initialDocumentVersions:e.initialDocumentVersions}),i=new Map,s=new Map,a=new Set,c=null,l=e.history??(e.historyStore?af(e.historyStore):nN()),u=gh(n,{externalAdapters:e.externalAdapters}),f=new Map,m=new Set,d=0,g=e.historyStore?.recoveryRequired??!1,h=Ol(),S=C();function E(p){return(Is.isAbsolute(p)?Is.relative(e.projectRoot,p):p).replace(/\\/g,"/").replace(/^\.\//,"")}function y(p,b){let x=Is.posix.dirname(p),I=b.replace(/\.(?:tsx?|jsx?)$/i,""),P=Is.posix.relative(x,I);return P.startsWith(".")?P:`./${P}`}function v(p,b){return p.startLine===b.startLine&&p.startColumn===b.startColumn&&p.endLine===b.endLine&&p.endColumn===b.endColumn}async function C(){let p=e.historyStore;if(p)try{let b=await p.readTransactionJournal();if(!b)return;let x=await p.readIndex(),I=await Promise.all(b.files.map(async T=>await n.exists(T.path)?ke(await n.readFile(T.path)):null));if(Nh({journal:b,index:x,observedFileDigests:I})!=="ambiguous"){await p.clearTransactionJournal(b.transactionId);let T=await p.readStatus();T.recoveryRequired||(await p.cleanupTmp(),T=await p.readStatus()),g=T.recoveryRequired;return}await p.markRecoveryRequired(`Ambiguous transaction journal ${b.transactionId} at phase ${b.phase}`),g=!0}catch(b){g=!0,await p.markRecoveryRequired(`Transaction journal recovery failed: ${et(b)}`).catch(()=>{})}}function N(){return t==="disposed"}e.onEvent&&r.subscribe(e.onEvent);for(let p of o.entries){let b=_h(p.context,p.entryFile);i.set(p.key,b),A(b,b.dependencyFiles)}function A(p,b){let x=new Set(b);R(p),p.dependencyFiles=x;for(let I of p.dependencyFiles){let P=s.get(I);P||(P=new Set,s.set(I,P)),P.add(p.key)}}function R(p){for(let b of p.dependencyFiles){let x=s.get(b);x&&(x.delete(p.key),x.size===0&&s.delete(b))}p.dependencyFiles.clear()}function F(p){let b=new Set;for(let x of p)for(let I of s.get(x)??[])b.add(I);return b}function _(p){for(let b of p)if(!s.has(b))return!1;return!0}async function D(p,b,x,I,P,T){let O=new Map,j=Mg(P.values()),q=_m(P.values()),$=typeof T.exists=="function"?B=>T.exists(B):async()=>!1;for(let[B,W]of p.elements){let de=b.nodes.get(B);if(!de)continue;let ue=x.get(W.sourceFile)??I.get(W.sourceFile),be=new Map,Ce=new Map,Pe=new Map,M=[];for(let Ne of W.textSegments){if(!ue){be.set(Ne.index,null);continue}let vr=await Og({file:W.sourceFile,source:ue,segment:Ne,readFile:st=>T.readFile(st),exists:$,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:st,adapterId:xn,capabilities:Ds})=>({sourceType:st,adapterId:xn,capabilities:Ds})),functionCallContracts:e.functionCallContracts,fileCache:j}),Qe=await Rl({file:W.sourceFile,source:ue,target:{kind:"text-segment",segment:Ne},readFile:st=>T.readFile(st),exists:$,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:st,adapterId:xn,capabilities:Ds})=>({sourceType:st,adapterId:xn,capabilities:Ds})),functionCallContracts:e.functionCallContracts,fileCache:j}),ft=fN(vr);be.set(Ne.index,ft),Ce.set(Ne.index,vr),Pe.set(Ne.index,Qe),M.push({editable:Ne.editable,source:ft})}let U=new Map,ie=new Map;if(ue)for(let Ne of W.attributes??[]){let vr=await br({file:W.sourceFile,source:ue,sourceRange:Ne.sourceRange,expression:Ne.source?.expression??Ne.value,sourceInfo:Ne.source,readFile:ft=>T.readFile(ft),exists:$,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:ft,adapterId:st,capabilities:xn})=>({sourceType:ft,adapterId:st,capabilities:xn})),functionCallContracts:e.functionCallContracts,fileCache:j}),Qe=await Jg({element:W,file:W.sourceFile,source:ue,propertyName:Ne.name,readFile:ft=>T.readFile(ft),exists:$,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:ft,adapterId:st,capabilities:xn})=>({sourceType:ft,adapterId:st,capabilities:xn})),functionCallContracts:e.functionCallContracts,fileCache:j});ie.set(Ne.name,Qe),U.set(Ne.name,vr)}let ge=th(pN(de.writeTarget),M),Se=Xg({key:B,element:W,graph:p,provenances:Pe}),Ae=sh(W),en=ue?await Mm({element:W,graph:p,file:W.sourceFile,source:ue,readFile:Ne=>T.readFile(Ne),exists:$,fileCache:q}):void 0,He=p.regions.find(Ne=>Ne.kind==="conditional-region"&&Ne.childKeys.includes(B)),Mo,Ls=He?.sourceCandidates?.[0];if(ue&&He&&Ls?.kind==="conditional-branch"){let Ne=await Rl({file:W.sourceFile,source:ue,target:{kind:"conditional-branch",candidate:Ls},readFile:Qe=>T.readFile(Qe),exists:$,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Qe,adapterId:ft,capabilities:st})=>({sourceType:Qe,adapterId:ft,capabilities:st})),functionCallContracts:e.functionCallContracts,fileCache:j});Mo={currentBranch:He.childKeys.indexOf(B)<=0?"then":"else",availableBranches:He.childKeys.length>1?["then","else"]:["then"],conditionExpression:Ls.conditionExpression,provenance:{finalSource:Ne.finalSource?{kind:Ne.finalSource.kind,file:Ne.finalSource.file,displayPath:Ne.finalSource.displayPath}:null,chain:Ne.chain.map(Qe=>({kind:Qe.kind,file:Qe.file,displayName:Qe.displayName,canEditHere:Qe.canEditHere})),confidence:Ne.confidence,editMode:Ne.editMode,diagnostics:Ne.diagnostics.map(Qe=>({code:Qe.code,message:Qe.message}))}}}O.set(B,{textSources:be,textTargets:Ce,elementPropertyTargets:U,propertyProvenances:ie,isRepeat:FN(B,p),provenances:Pe,writeTarget:ge,componentSemantic:Se,styleSource:Ae,conditional:Mo,dynamicData:en})}return O}function L(p){return typeof n.getVersion=="function"?n.getVersion(p):0}function oe(p,b){let x=o.initialVersions.get(p.key)??0;for(let I of b.values())x=Math.max(x,I);return Math.max(x,p.graph?.version??0)}function me(p){return i.get(p)?.graph?.version??o.initialVersions.get(p)??0}function ee(p){try{return me(o.resolveSelector(p.composition).key)}catch{return 0}}async function ce(p,b,x=n,I={}){let P=await wd(p,b,T=>x.readFile(T),T=>x.exists(T),{additionalEntries:await Qt(p,x),...I});if(P.diagnostics.length>0)throw new No(P.diagnostics);return P}async function _e(p,b,x={}){let I=i.get(p);if(!I)return null;let P=x.sourceCache??jl(f,[]),T=x.fileSystem??Ll(n),{graph:O,allSources:j,parsedModules:q,entryModule:$}=await ce(I.entryFile,b,T,{version:I.graph?.version??1}),B=new Map;for(let He of j.keys())B.set(He,L(He));let W=Math.max(oe(I,B),x.minimumVersion??0);x.changed&&W<=(I.graph?.version??0)&&(W=(I.graph?.version??0)+1),O.version=W;for(let[He,Mo]of j)$l(P,He,Mo,Ah);let de=await qt(I.composition,I.entryFile,j,P,T);O.routeId=I.routeId,O.composition=I.composition;let ue=ah(O),be=fd(ue,O),Ce=await D(O,ue,j,P,q,T),Pe=Xh(O,be,Ce),M=Jh(Ce),U=Sh(Yg(O,ue,be,{canUpdateTextByKey:Pe,dynamicDataSummaryByKey:M}),O,Ce),ie=Jf({route:I.routeId,composition:I.composition,entryFile:I.entryFile,version:W,source:b,ast:$?.ast}),ge=Xf(ie);ie.ok&&xN(U,O,ie.projection,q);let Se={...U,composition:I.composition,...de?{styleContext:de}:{},pageComposition:ge},Ae=new Set([I.entryFile,...j.keys()]);if(de){Ae.add(de.entryCss.path);for(let He of de.stylesheets)Ae.add(He.path)}let en={...I,dependencyFiles:Ae,graph:O,topology:ue,capabilities:be,document:Se,pageComposition:ge,pageCompositionProjection:ie.projection,pagePlacementByKey:ie.ok?ie.projection.placementByKey:null,pagePlacementUnitByKey:ie.ok?ie.projection.placementUnitByKey:null,pageUnitByKey:ie.ok?ie.projection.unitByKey:null,pagePlacementsByUnitKey:ie.ok?ie.projection.placementsByUnitKey:null,documentIndex:bh(Se),detailProjections:Ce,fileVersions:B,styleContext:de};if(x.publish===!1)return en;Sr(f,P);for(let He of P.keys())m.delete(He);return A(I,Ae),Object.assign(I,en),I}async function Qt(p,b=n){let x=[];for(let I of RN(p))typeof b.exists=="function"&&await b.exists(I)&&x.push({file:I,source:await b.readFile(I)});return x}async function qt(p,b,x,I,P){let T=[];for(let[B,W]of x){if(Vl(B)){T.push(B);continue}for(let de of NN(W)){let ue=jh(B,de);ue&&T.push(ue)}}if(!T.length){for(let B of wN(b))if(await P.exists(B)){T.push(B);break}}let O=new Map,j=TN(T).slice(0,Ph);for(;j.length>0&&O.size<Ph;){let B=j.shift();if(O.has(B)||!Vl(B))continue;let W=await Uh(B,I,P);if(W!==null){O.set(B,{path:B,content:W});for(let de of PN(W)){let ue=jh(B,de);ue&&!O.has(ue)&&!j.includes(ue)&&j.push(ue)}}}let q=[...O.values()].map(B=>({...B,hash:ke(B.content)})),$=q[0];return $?{composition:p,revision:ke(JSON.stringify(q.map(({path:B,hash:W})=>({path:B,hash:W})))),entryCss:$,stylesheets:q.slice(1)}:null}async function Uh(p,b,x){let I=b.get(p);if(I!==void 0)return I;if(!await x.exists(p))return null;let P=await x.readFile(p);return $l(b,p,P,Ah),P}function Jh(p){let b=new Map;for(let[x,I]of p)I.dynamicData?.bindings.length&&b.set(x,zm(I.dynamicData.bindings));return b}function Xh(p,b,x){let I=new Map;for(let[P,T]of p.elements){if(!b.get(P)?.canUpdateText){I.set(P,!1);continue}let j=x.get(P),q=T.textSegments.some($=>{if(!$.editable)return!1;let B=j?.provenances.get($.index)??null;return!B||zh(B)});I.set(P,q)}return I}function zh(p){return p.editMode==="direct"||p.editMode==="proxy"||p.editMode==="upstream"}async function To(p,b={}){let x=[...new Set(p)],I=b.affectedCompositionKeys!==void 0,P=I?new Set(b.affectedCompositionKeys):F(x);if(!I&&(P.size===0||!_(x)))for(let $ of i.values())Ul($,x)&&P.add($.key);let T=!I&&P.size===0&&x.some(Bh),O=b.publish===!1?jl(f,x):void 0,j={rebuiltRoutes:[],failedRoutes:[],...b.publish===!1?{candidateRouteStates:[],candidateSourceCache:O}:{}},q=Ll(n);for(let $ of i.values())if(!(b.excludedCompositionKeys?.has($.key)||!(P.has($.key)||T)))try{let W=!!$.graph,de=await q.readFile($.entryFile),ue=await _e($.key,de,{...b,fileSystem:q,...O?{sourceCache:O}:{}});ue?.graph&&(j.rebuiltRoutes.push({documentChanged:W,composition:$.composition,routeId:$.routeId,version:ue.graph.version}),j.candidateRouteStates?.push({composition:$.composition,key:$.key,routeId:$.routeId,state:ue}))}catch(W){j.failedRoutes.push({...Rh($.routeId,W),composition:$.composition})}return j}function Un(p){let b=[...new Set(p)],x=F(b);if(x.size>0&&_(b))return[...x];for(let I of i.values())Ul(I,b)&&x.add(I.key);return[...x]}function Wh(p){let b=new Set(Un(p));return o.entries.filter(x=>b.has(x.key)).map(x=>x.context)}function Hh(p){return[...new Set(Un(p))].sort((x,I)=>x<I?-1:x>I?1:0).map(x=>o.getByKey(x)?.context).filter(x=>x!==void 0)}function Gh(p,b){let x=new Set(Un(b)),I=p.provenance?.affectedCompositions??[];if(I.length===0)return x;if([...new Set(I.map(T=>o.resolveContext(T).key))].some(T=>!x.has(T)))throw new Error("History provenance does not match the affected composition index.");return x}function Yh(p,b){let x=p.composition??p.provenance?.initiatingComposition;if(x){let T=o.resolveContext(x);return{context:T.context,key:T.key}}let I=[...new Set(Un(b))];if(I.length!==1)throw new Error(`Legacy history entry cannot be attributed to a unique composition (affected composition count: ${I.length}).`);let P=o.getByKey(I[0]);if(!P)throw new Error("Legacy history entry references an unknown affected composition.");return{context:P.context,key:P.key}}function As(p,b){r.emit({type:"operation-completed",composition:p.composition,result:p});for(let{composition:x,version:I}of b.rebuiltRoutes)r.emit({type:"document-changed",composition:x,version:I});for(let{composition:x,message:I}of b.failedRoutes)r.emit({type:"graph-error",composition:x,message:I})}function Ul(p,b){return b.some(x=>p.dependencyFiles.has(x)||p.entryFile===x||p.graph?.fileIndex.has(x))}function Jl(p){for(let b of p)a.add(b);c||N()||(c=(async()=>{t="building";let b=!1;try{for(;a.size>0;){if(N())return;await Zh(),await h.runExclusive(async()=>{if(d>0||N())return;let x=[...a];a.clear();let I=await Xl(x);if(I.length===0)return;let P=Un(I);for(let j of P){let q=i.get(j)?.composition;q&&r.emit({type:"graph-invalidated",composition:q})}let{rebuiltRoutes:T,failedRoutes:O}=await To(I,{changed:!0});for(let{documentChanged:j,composition:q,version:$}of T)r.emit({type:"graph-ready",composition:q,version:$}),j&&r.emit({type:"document-changed",composition:q,version:$});for(let{composition:j,message:q}of O)b=!0,r.emit({type:"graph-error",composition:j,message:q})})}}finally{c=null,t!=="disposed"&&(t=!b&&[...i.values()].some(x=>x.graph)?"ready":"idle"),a.size>0&&Jl([])}})())}async function Zh(){for(;d>0;)await new Promise(p=>setTimeout(p,0))}async function Xl(p){let b=[];for(let x of new Set(p)){let I=f.get(x);if(I===void 0){if(m.has(x)&&!await n.exists(x))continue;m.delete(x),b.push(x);continue}try{await n.readFile(x)!==I&&(m.delete(x),b.push(x))}catch(P){if(!yN(P))try{if(await n.exists(x))continue}catch{continue}m.add(x),b.push(x)}}return b}function zl(p){wh(f,p);for(let b of p)b.exists===!1?m.add(b.file):m.delete(b.file)}function Wl(p){m.clear();for(let b of p)m.add(b)}async function Hl(p){let b=await Xl(p);if(b.length===0)return;let x=Un(b);for(let T of x){let O=i.get(T)?.composition;O&&r.emit({type:"graph-invalidated",composition:O})}let{rebuiltRoutes:I,failedRoutes:P}=await To(b,{changed:!0});for(let{documentChanged:T,composition:O,version:j}of I)r.emit({type:"graph-ready",composition:O,version:j}),T&&r.emit({type:"document-changed",composition:O,version:j});for(let{composition:T,message:O}of P)r.emit({type:"graph-error",composition:T,message:O})}async function Qh(p,b){let x=zn(p,b);if(!x?.graph)return;let I=it(p)??p,P=x.graph.elements.get(I);P&&await Hl([P.sourceFile])}async function Gl(p){let b=new Set;if(p.target.kind==="node"){let x=zn(p.target.key,p.composition),I=it(p.target.key)??p.target.key,P=x?.graph?.elements.get(I);P&&b.add(P.sourceFile)}else if(p.target.kind==="route"){let x=i.get(o.resolveSelector(p.target.composition).key);x&&b.add(x.entryFile)}else if(p.target.kind==="page-unit"){let x=i.get(o.resolveSelector(p.target.composition).key);x&&b.add(x.entryFile)}else if(p.target.kind==="source-file")b.add(p.target.path);else if(p.target.kind==="source-batch")for(let x of p.target.paths)b.add(x);if(p.params.kind==="move-node"&&!("kind"in p.params.target)){let x=[p.params.target.parentKey,...p.params.target.relation==="before"||p.params.target.relation==="after"?[p.params.target.anchorKey]:[]];for(let I of x){let P=zn(I,p.composition),T=it(I)??I,O=P?.graph?.elements.get(T);O&&b.add(O.sourceFile)}}await Hl(b)}async function qh(p){if(p.params.kind!=="source-edit")return Ts(p,"invalid-params","source-edit requires source-edit params");for(let b of p.params.edits){let x=hN(b);if(!x.ok)return Ts(p,x.errorCode,x.message,x.details)}d+=1;try{let b=await oy(p.params.edits);if(!b.ok)return Ts(p,b.errorCode,b.message,b.details);await Gl(p);let x={operationId:p.id,kind:"source-edit",target:p.target,documentVersion:p.documentVersion,conflictPolicy:p.params.conflictPolicy,edits:p.params.edits.map(I=>I.operation==="delete"?{operation:"delete",file:I.path,baseContentHash:I.baseContentHash??null}:{operation:"upsert",file:I.path,baseContentHash:I.baseContentHash??null,content:I.content})};return await Xn({request:p,filePlan:x})}catch(b){return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:ee(p),error:{code:K.INTERNAL_ERROR,message:et(b)}}}finally{d-=1}}async function ey(p){if(p.target.kind!=="project"||p.params.kind!=="insert-page-resource")return le(p,K.INVALID_PARAMS,"insert-page-resource requires project target and matching params.");d+=1;try{let b=await Lo({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:[...p.params.artifact.components.flatMap(I=>I.materialization.files.map(P=>({path:P.pathTemplate,content:P.content}))),...p.params.artifact.pages.flatMap(I=>I.materialization.files.map(P=>({path:P.pathTemplate,content:P.content})))],exists:I=>n.exists(I),readFile:I=>n.readFile(I)});if(!b.ok)return le(p,K.MATERIALIZATION_REJECTED,b.message);let x=await Ya({artifact:p.params.artifact,exists:I=>n.exists(I)});return x.ok?await Xn({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:p.target,documentVersion:p.documentVersion,conflictPolicy:"overwrite",edits:x.files},output:{kind:"insert-page-resource",package_instance_id:x.packageInstanceId,pages:x.pages},historyPolicy:"none"}):le(p,x.code==="MATERIALIZATION_CONFLICT"?K.MATERIALIZATION_CONFLICT:K.MATERIALIZATION_REJECTED,x.message,x.path?{path:x.path}:void 0)}catch(b){return le(p,K.INTERNAL_ERROR,et(b))}finally{d-=1}}async function ty(p){if(p.target.kind!=="project"||p.params.kind!=="delete-page-source")return le(p,K.INVALID_PARAMS,"delete-page-source requires project target and matching params.");if(!n.listFiles)return le(p,K.PLAN_FAILED,"Complete project file listing is required for page deletion.");d+=1;try{let b=$h(await n.listFiles({maxFiles:5e4,maxDepth:64}));if(b.truncated)return le(p,K.PLAN_FAILED,"Project file listing is incomplete; page deletion was refused.",{truncationReasons:b.truncated.reasons});let x=b.files.filter(({path:O})=>/\.(?:tsx?|jsx?)$/.test(O)),I=Object.fromEntries(await Promise.all(x.map(async({path:O})=>[O,await n.readFile(O)]))),P=mp({expectedUrlPath:p.params.expectedUrlPath,files:I});if(!P.ok)return le(p,P.code==="HOME_PAGE_LOCKED"?K.HOME_PAGE_LOCKED:P.code==="ROUTE_NOT_FOUND"?K.ROUTE_NOT_FOUND:K.PLAN_FAILED,P.message);let T=await Promise.all(P.edits.map(async O=>({...O,baseContentHash:ke(await n.readFile(O.file))})));return Xn({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:p.target,documentVersion:p.documentVersion,conflictPolicy:"compare-and-swap",edits:T},output:{kind:"delete-page-source",deleted_files:P.deletedFiles,updated_files:P.updatedFiles,preserved_shared_files:P.preservedSharedFiles,warnings:P.warnings},historyPolicy:"none"})}catch(b){return le(p,K.INTERNAL_ERROR,et(b))}finally{d-=1}}async function ny(p,b){if(p.kind!=="insert-child"&&p.kind!=="replace-node")return le(p,K.UNSUPPORTED_OPERATION,"Only page-unit insert-child and replace-node materialization are supported by this transaction.");if(p.params.kind!=="insert-child"&&p.params.kind!=="replace-node"||p.kind!==p.params.kind)return le(p,K.INVALID_PARAMS,"Page-unit materialization operation kind must match its params.");if(p.params.kind==="insert-child"){if(!("kind"in p.params.position)||p.params.position.kind!=="page-composition")return le(p,K.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.");if(p.params.position.documentVersion!==p.documentVersion)return le(p,K.VERSION_STALE,"Page-unit insert-child placement belongs to a different document version.")}let x=b.document,I=b.pageCompositionProjection;if(!x||x.pageComposition?.status!=="supported"||!I||I.status!=="supported")return le(p,K.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(p.documentVersion!==x.version||I.documentVersion!==x.version)return le(p,K.VERSION_STALE,`Document version ${p.documentVersion} is stale (current: ${x.version}).`);let P=p.params.node.kind==="component-call"?p.params.node.materialization:void 0;if(!P)return le(p,K.UNSUPPORTED_OPERATION,"Page-unit insertion currently requires a static materialization manifest.");let T=p.params.kind==="insert-child"?p.params.position:null,O=await Lo({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:P.files.map($=>({path:$.pathTemplate,content:$.content})),exists:$=>n.exists($),readFile:$=>n.readFile($)});if(!O.ok)return le(p,K.MATERIALIZATION_REJECTED,O.message);let j=await tN(n,Object.keys(P.projectDependencies??{})),q=await Nf({manifest:P,generatedRoot:"components/site/generated",controlledFiles:P.files.map($=>({pathTemplate:$.pathTemplate})),exists:$=>n.exists($),availableHostDependencies:j,commit:async $=>{let B=await n.readFile(b.entryFile),W=b.document,de=b.pageCompositionProjection;if(!W||W.pageComposition?.status!=="supported"||W.version!==p.documentVersion||!de||de.status!=="supported"||de.documentVersion!==W.version)return{ok:!0,data:le(p,K.VERSION_STALE,"The route changed before the page-unit insertion could commit.")};let ue=$.entry.path,be=dy($.instanceName),Ce,Pe=[];if(p.params.kind==="insert-child"){if(!T||!("kind"in T)||T.kind!=="page-composition")return{ok:!0,data:le(p,K.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.")};let ge=rc({routeId:b.routeId,entryFile:b.entryFile,currentDocumentVersion:W.version,expectedDocumentVersion:p.documentVersion,source:B,projection:de,placementKey:T.placementKey,component:{source:ue,exportName:$.entry.export.kind==="default"?"default":$.entry.export.name,localName:be}});if(!ge.ok)return{ok:!0,data:le(p,Os(ge.error.code),ge.error.message,{diagnostics:ge.error.diagnostics})};let Se=ge.plan.rewriteStep,Ae;switch(Se.kind){case"insert-root-expression":Ae=Di({source:B,locator:Se.locator,expectedSourceHash:Se.sourceHash,action:{kind:"insert",jsx:Se.node.jsx,placement:Se.placement,replaceOriginal:Se.replaceOriginal}});break;case"insert-child":Ae=Gn({source:B,locator:Se.parentLocator,node:Se.node,placement:Se.placement,...Se.anchorLocator?{anchorLocator:Se.anchorLocator}:{}});break;default:Ae={ok:!1,source:B,diagnostic:{code:"unsupported-syntax",message:`Unsupported route composition rewrite: ${String(Se)}`}}}if(!Ae.ok)return{ok:!0,data:le(p,K.AST_PARSE_ERROR,Ae.diagnostic.message)};Ce=Ae.source}else{let ge=oc({routeId:b.routeId,composition:b.composition,entryFile:b.entryFile,currentDocumentVersion:W.version,expectedDocumentVersion:p.documentVersion,source:B,projection:de,placementUnitKey:p.target.placementUnitKey,operation:"replace-node"});if(!ge.ok)return{ok:!0,data:le(p,Os(ge.error.code),ge.error.message,{diagnostics:ge.error.diagnostics})};let Se=ge.plan.rewriteStep,Ae;switch(Se.kind){case"replace-root-expression":Ae=Di({source:B,locator:Se.locator,expectedSourceHash:Se.sourceHash,action:{kind:"replace",jsx:`<${be} />`}});break;case"replace-node":Ae=ti({source:B,locator:Se.locator,node:{jsx:`<${be} />`}});break;default:Ae={ok:!1,source:B,diagnostic:{message:`Unsupported page-unit replacement rewrite: ${Se.kind}`}}}if(!Ae.ok)return{ok:!0,data:le(p,K.AST_PARSE_ERROR,Ae.diagnostic.message)};let en=await Yl({routeState:b,placementUnitKey:p.target.placementUnitKey,source:B,mutatedSource:Ae.source});Ce=en.source,Pe=await Promise.all(en.files.map(async He=>({operation:"delete",file:He,baseContentHash:ke(await n.readFile(He))})))}let M=Qn({source:Ce,moduleSpecifier:y(b.entryFile,ue),imports:$.entry.export.kind==="default"?[{kind:"default",local:be}]:[{kind:"named",imported:$.entry.export.name,local:be}]});if(!M.ok)return{ok:!0,data:le(p,K.AST_PARSE_ERROR,M.diagnostic.message)};let U=$.files.map(ge=>({operation:"create-only",file:ge.path,content:ge.content})),ie=[{operation:"upsert",file:b.entryFile,content:M.source,baseContentHash:ke(B)},...U,...Pe];d+=1;try{let ge=await Xn({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:{kind:"source-file",path:b.entryFile},documentVersion:p.documentVersion,conflictPolicy:"compare-and-swap",edits:ie}});return!ge.ok&&ge.error?.message.includes("MATERIALIZATION_INSTANCE_CONFLICT")?{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:ge.error?.message??"Static prefab instance conflicted during commit."}}:{ok:!0,data:ge}}finally{d-=1}}});return q.ok?q.data:le(p,q.error.code==="MATERIALIZATION_INSTANCE_CONFLICT"?K.MATERIALIZATION_CONFLICT:K.MATERIALIZATION_REJECTED,q.error.message,{materializationCode:q.error.code})}async function ry(p,b){if(p.kind!=="move-node"&&p.kind!=="remove-node")return le(p,K.UNSUPPORTED_OPERATION,"Only page-unit move-node and remove-node are currently supported by the page composition transaction.");let x=b.document,I=b.pageCompositionProjection;if(!x||x.pageComposition?.status!=="supported"||!I||I.status!=="supported")return le(p,K.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(p.documentVersion!==x.version||I.documentVersion!==x.version)return le(p,K.VERSION_STALE,`Document version ${p.documentVersion} is stale (current: ${x.version}).`);let P=await n.readFile(b.entryFile),T=oc({routeId:b.routeId,composition:b.composition,entryFile:b.entryFile,currentDocumentVersion:x.version,expectedDocumentVersion:p.documentVersion,source:P,projection:I,placementUnitKey:p.target.placementUnitKey,operation:p.kind,targetPlacement:p.kind==="move-node"&&p.params.kind==="move-node"&&"kind"in p.params.target&&p.params.target.kind==="page-composition"?p.params.target:void 0});if(!T.ok)return le(p,Os(T.error.code),T.error.message,{diagnostics:T.error.diagnostics});let O=T.plan.rewriteStep,j;switch(O.kind){case"move-node":j=Yn({source:P,locator:O.locator,targetParentLocator:O.targetParentLocator,placement:O.placement,...O.anchorLocator?{anchorLocator:O.anchorLocator}:{}});break;case"remove-node":j=Hn({source:P,locator:O.locator});break;case"remove-root-expression":j=Di({source:P,locator:O.locator,expectedSourceHash:O.sourceHash,action:{kind:"remove"}});break;default:j={ok:!1,source:P,diagnostic:{message:`Unsupported page-unit mutation rewrite: ${O.kind}`}}}if(!j.ok)return le(p,K.AST_PARSE_ERROR,j.diagnostic.message);let q=j.source,$=[];if(p.kind==="remove-node"){let W=await Yl({routeState:b,placementUnitKey:p.target.placementUnitKey,source:P,mutatedSource:q});q=W.source,$=await Promise.all(W.files.map(async de=>({operation:"delete",file:de,baseContentHash:ke(await n.readFile(de))})))}let B=[{operation:"upsert",file:b.entryFile,content:q,baseContentHash:ke(P)},...$];d+=1;try{return await Xn({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:{kind:"source-file",path:b.entryFile},documentVersion:p.documentVersion,conflictPolicy:"compare-and-swap",edits:B}})}finally{d-=1}}async function Yl(p){let b={source:p.mutatedSource,files:[]},x=p.routeState.graph,I=p.routeState.pageCompositionProjection;if(!x||!I||I.status!=="supported"||!n.listFiles)return b;let T=I.placementUnitByKey.get(p.placementUnitKey)?.sourceRange;if(!T)return b;let O=[...x.elements.values()].find(M=>M.sourceFile===p.routeState.entryFile&&M.importedFrom&&v(M.sourceRange,T));if(!O?.importedFrom||!O.exportName)return b;let j=E(O.importedFrom),q="components/site/generated/";if(!j.startsWith(q))return b;let $=j.slice(q.length).split("/")[0];if(!$||!/-[0-9a-f]{8}$/i.test($))return b;let B=`${q}${$}`;if([...x.elements.values()].filter(M=>M.sourceFile===p.routeState.entryFile&&E(M.importedFrom??"")===j).length!==1)return b;let de=await n.listFiles({maxFiles:5e3,maxDepth:32}),ue=Array.isArray(de)?de:de.files;if(!Array.isArray(de)&&de.truncated)return b;let be=ue.map(({path:M})=>M).filter(M=>M===B||M.startsWith(`${B}/`));if(be.length===0||!be.includes(j))return b;for(let{path:M}of ue)if(!(M===p.routeState.entryFile||M===B||M.startsWith(`${B}/`)))try{if((await n.readFile(M)).includes($))return b}catch{return b}let Ce=y(p.routeState.entryFile,j),Pe=qn({source:p.mutatedSource,moduleSpecifier:Ce,imports:O.exportName==="default"?[{kind:"default"}]:[{kind:"named",imported:O.exportName}]});return Pe.ok?Pe.source.includes($)?{source:Pe.source,files:[]}:{source:Pe.source,files:be.sort((M,U)=>M.localeCompare(U))}:b}async function oy(p){if(n.getFileInfo){for(let T of p)if(await n.exists(T.path)&&await n.getFileInfo(T.path)===null)return{ok:!1,errorCode:"invalid-params",message:`Source edit path must resolve to a regular non-symbolic-link file: ${T.path}`,details:{path:T.path}}}for(let T of p){if(T.operation!=="upsert"||!/^(?:src\/)?app\/globals\.css$/i.test(T.path))continue;let O=await n.exists(T.path)?await Qs(n,T.path):null;if(O?.ok){let j=Jw(O.content,T.content);if(!j.ok)return{ok:!1,errorCode:"invalid-params",message:j.message,details:{path:T.path,code:j.code}}}}let b=iy(p);if(b.length===0)return{ok:!0};let x=mN(n,p),I=new Map,P=(T,O)=>{let j=I.get(T);if(j?.source===O)return j.result;let q=Ut(T,O);return I.set(T,{source:O,result:q}),q};try{for(let T of b){let O=i.get(T);O&&await ce(O.entryFile,await x.readFile(O.entryFile),x,{validationOnly:!0,parseModule:P})}}catch(T){return{ok:!1,errorCode:"ast-error",message:`Source edit preflight failed: ${et(T)}`,details:{compositionKeys:b}}}return{ok:!0}}function iy(p){return p.map(x=>x.path).some(Bh)?[...i.keys()]:[]}function Ts(p,b,x,I){let P=Po(b);return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:ee(p),error:{code:P,message:x,...I?{details:I}:{}}}}async function Fs(p){let b=[];for(let x of new Set(p))b.push(await sy(x));return b}async function sy(p){if(!(typeof n.exists=="function"?await n.exists(p):!0))return{file:p,content:"",version:Math.max(0,L(p)),exists:!1};let x=await n.readFile(p);return{file:p,content:x,version:Math.max(1,L(p)),exists:!0,sha256:ke(x)}}async function Zl(p,b,x,I){if(!e.historyStore)return null;let P=new Map(b.map(j=>[j.file,j])),T=new Map(x.map(j=>[j.file,j])),O=[...new Set([...P.keys(),...T.keys()])].sort().map(j=>{let q=P.get(j),$=T.get(j);return{path:j,preDigest:q?.exists===!1||!q?null:ke(q.content),postDigest:$?.exists===!1||!$?null:ke($.content)}});return{schemaVersion:2,transactionId:`${p}:${I.expectedIndexDigest}`,operationId:p,phase:"prepared",historyTransition:I,files:O}}async function Ql(p){return!p||!e.historyStore||await e.historyStore.writeTransactionJournal(p),p}async function Jn(p){p&&e.historyStore&&await e.historyStore.clearTransactionJournal(p.transactionId)}async function _s(p,b){let x=[];try{for(let I of p)await ql(I),typeof n.bumpVersion=="function"&&n.bumpVersion(I.file),x.push(I.file)}catch(I){let P=await ay(b.filter(T=>x.includes(T.file)));return P.ok?{ok:!1,reason:`Writeback failed and committed files were restored: ${et(I)}`,rolledBack:!0}:{ok:!1,reason:`Writeback failed, then rollback failed for ${P.failedFiles.join(", ")}: ${et(I)}`,rolledBack:!1}}return{ok:!0,snapshots:p.map(cy)}}async function ql(p){if(p.exists===!1){await n.deleteFile(p.file);return}await n.writeFile(p.file,p.content)}async function ay(p){let b=[];for(let x of p)try{await ql(x),typeof n.bumpVersion=="function"&&n.bumpVersion(x.file)}catch{b.push(x.file)}return b.length===0?{ok:!0}:{ok:!1,failedFiles:b}}function cy(p){let b=p.exists!==!1;return{file:p.file,content:b?p.content:"",version:p.version,exists:b,...b?{sha256:ke(p.content)}:{}}}async function Xn(p){return h.runExclusive(()=>ly(p))}async function ly(p){let b=p.filePlan.edits.map(M=>M.file),x=o.resolveSelector(p.request.composition),I=x.context,P=p.historyPolicy==="none"?void 0:{initiatingComposition:I,affectedCompositions:Hh(b)},T=await Fs(b),O=new Map(T.filter(M=>M.exists!==!1).map(M=>[M.file,M.content])),j=tu(),q=new Map(f),$=new Set(m),B=new Set([...i.values()].filter(M=>p.filePlan.edits.some(U=>U.operation==="delete"&&U.file===M.entryFile)).map(M=>M.key)),W=p.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:ke(M.content)}),de={operationId:p.filePlan.operationId,intents:p.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})},ue=null,be=!1,Ce=await Ss({overlay:O,exists:M=>n.exists(M),plan:de,buildCandidate:async({plan:M})=>({plan:M}),prepareHistory:async()=>{let M=p.historyPolicy==="none"?null:await l.prepareAppend({composition:o.resolveSelector(p.request.composition).context,operationId:p.request.id,kind:p.request.kind,target:p.request.target,preSnapshots:T,postSnapshots:W,...p.selectionRef?{selectionRef:p.selectionRef}:{},...p.output?{output:p.output}:{},...P?{provenance:P}:{}}),U=M?.historyTransition?M.historyTransition:e.historyStore?qw(await e.historyStore.readIndex()):null;if(e.historyStore&&!U)throw new Error("Durable history did not provide an exact index transition.");return ue=await Zl(p.request.id,T,W,U),ue=await Ql(ue),{history:M,historyTransition:U}},reverify:async()=>{},writeCandidate:async()=>{let M=await u.executeFilePlan(p.filePlan);if(!M.ok)throw new Cs(M);return{postSnapshots:await Fs(M.affectedFiles),affectedFiles:M.affectedFiles,internalResultVersion:M.resultVersion}},validateCandidate:async({candidate:M,receipt:U})=>{let ie=await To(U.affectedFiles,{changed:!0,minimumVersion:U.internalResultVersion,publish:!1,excludedCompositionKeys:B});if(ie.failedRoutes.length>0)throw new Vn(ie.failedRoutes);let ge=ru(j,ie.candidateRouteStates??[]),Se=nu(ge,x.key);return{...M,rebuild:ie,routeSnapshots:ge,resultVersion:Se,...Mh(p.selectionRef,ge.map(Ae=>Ae.state.document))?{selectionRef:Mh(p.selectionRef,ge.map(Ae=>Ae.state.document))}:{}}},publishCandidate:async({candidate:M,history:U,receipt:ie})=>{U?.history&&(await l.publishPrepared(U.history),be=!0);let ge=M.resultVersion??ie.internalResultVersion;return{composition:I,requestId:p.request.id,kind:p.request.kind,target:p.request.target,ok:!0,resultVersion:ge,affectedFiles:ie.affectedFiles,fileChanges:ie.postSnapshots.map(Se=>({path:Se.file,operation:Se.exists===!1?"delete":"upsert"})),...p.output?{output:p.output}:{},...M.selectionRef?{selectionRef:M.selectionRef}:{}}},swapCandidate:({candidate:M,receipt:U})=>{M.routeSnapshots&&Fo(M.routeSnapshots),M.rebuild?.candidateSourceCache&&Sr(f,M.rebuild.candidateSourceCache),zl(U.postSnapshots)},finalizeCandidate:async()=>{await Jn(ue);for(let M of B)i.delete(M)},emitCommitted:({candidate:M,published:U})=>{As(U,M.rebuild??{rebuiltRoutes:[],failedRoutes:[]})},rollbackCandidate:async({history:M,receipt:U})=>{if(be)throw new Error("history was published before transaction finalization failed");if(U){let ie=await _s(T,U.postSnapshots);if(!ie.ok)throw new Error(ie.reason)}Fo(j),Sr(f,q),Wl($),M?.history&&await l.discardPrepared?.(M.history),await Jn(ue)}});if(Ce.ok)return Ce.published;if(Ce.stage==="precheck"||Ce.stage==="build")try{await Jn(ue)}catch(M){let U=await _o(et(M));return le(p.request,U,"Unable to clear an uncommitted transaction journal.")}if(Ce.recoveryRequired){let M=await _o(Ce.reason);return le(p.request,M===K.RECOVERY_PERSIST_FAILED?M:K.ROLLBACK_FAILED,Ce.reason)}let Pe=Ce.error;return Pe instanceof Cs?{...le(p.request,Po(Pe.result.errorCode),Pe.result.reason),...Pe.result.affectedFiles?{affectedFiles:Pe.result.affectedFiles}:{}}:Pe instanceof Vn?le(p.request,K.ROUTE_REBUILD_FAILED,`Route rebuild failed and source was rolled back: ${Bl(Pe.failedRoutes)}`,{failedRoutes:Pe.failedRoutes}):le(p.request,iu(Ce.stage),et(Pe))}async function eu(p){return h.runExclusive(async()=>{let b=p==="undo"?await l.prepareUndo():await l.prepareRedo();return b?uy(p,b):{composition:o.entries[0].context,requestId:p,kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:o.initialVersions.get(o.entries[0].key)??0,error:{code:K.INTERNAL_ERROR,message:p==="undo"?"Nothing to undo":"Nothing to redo"}}})}async function uy(p,b){let x=b.entry,I=p==="undo"?x.preSnapshots:x.postSnapshots,P=p==="undo"?x.postSnapshots:x.preSnapshots,T=I.map(U=>U.file),{context:O,key:j}=Yh(x,T),q=await Fs(T),$=new Map(q.filter(U=>U.exists!==!1).map(U=>[U.file,U.content])),B=me(j),W=tu(),de=new Map(f),ue=new Set(m),be=null,Ce=!1,Pe,M=await Ss({overlay:$,plan:{operationId:`${p}:${x.operationId}`,intents:I.map(U=>U.exists===!1?{kind:"delete",path:U.file}:{kind:"upsert",path:U.file,content:U.content})},buildCandidate:async()=>({}),prepareHistory:async()=>(be=await Zl(`${p}:${x.operationId}`,q,I,b.historyTransition),be=await Ql(be),b),reverify:async()=>{},writeCandidate:async()=>{let U=await _s(I,P);if(!U.ok)throw new Error(U.reason);return{snapshots:U.snapshots}},validateCandidate:async({candidate:U})=>{Pe=Gh(x,T);let ie=await To(T,{changed:!0,minimumVersion:B+1,publish:!1,affectedCompositionKeys:Pe});if(ie.failedRoutes.length>0)throw new Vn(ie.failedRoutes);let ge=ru(W,ie.candidateRouteStates??[]),Se=nu(ge,j);return{...U,rebuild:ie,routeSnapshots:ge,resultVersion:Se}},publishCandidate:async({candidate:U,history:ie,receipt:ge})=>{if(!ie)throw new Error("history cursor intent is missing");await l.publishPrepared(ie),Ce=!0;let Se=U.resultVersion??B+1;return{composition:O,requestId:p,kind:x.kind,target:x.target,ok:!0,resultVersion:Se,affectedFiles:T,fileChanges:ge.snapshots.map(Ae=>({path:Ae.file,operation:Ae.exists===!1?"delete":"upsert"})),...x.output?{output:x.output}:{}}},swapCandidate:({candidate:U,receipt:ie})=>{U.routeSnapshots&&Fo(U.routeSnapshots),U.rebuild?.candidateSourceCache&&Sr(f,U.rebuild.candidateSourceCache),zl(ie.snapshots)},finalizeCandidate:async()=>{await Jn(be)},emitCommitted:({candidate:U,published:ie})=>As(ie,U.rebuild??{rebuiltRoutes:[],failedRoutes:[]}),rollbackCandidate:async({history:U,receipt:ie})=>{if(Ce)throw new Error("history cursor was published before transaction finalization failed");if(ie){let ge=await _s(P,ie.snapshots);if(!ge.ok)throw new Error(ge.reason)}Fo(W),Sr(f,de),Wl(ue),U&&await l.discardPrepared?.(U),await Jn(be)}});if(M.ok)return M.published;if(M.stage==="precheck"||M.stage==="build")try{await Jn(be)}catch(U){let ie=await _o(et(U));return{composition:O,requestId:p,kind:x.kind,target:x.target,ok:!1,resultVersion:B,error:{code:ie,message:"Unable to clear an uncommitted transaction journal."}}}if(M.recoveryRequired){let U=await _o(M.reason);return{composition:O,requestId:p,kind:x.kind,target:x.target,ok:!1,resultVersion:B,affectedFiles:T,error:{code:U===K.RECOVERY_PERSIST_FAILED?U:K.ROLLBACK_FAILED,message:M.reason}}}return{composition:O,requestId:p,kind:x.kind,target:x.target,ok:!1,resultVersion:B,affectedFiles:T,error:{code:M.error instanceof Vn?K.ROUTE_REBUILD_FAILED:iu(M.stage),message:et(M.error),...M.error instanceof Vn?{details:{failedRoutes:M.error.failedRoutes}}:{}}}}function tu(){return[...i.values()].map(p=>({composition:p.composition,key:p.key,routeId:p.routeId,state:{...p,dependencyFiles:new Set(p.dependencyFiles),fileVersions:new Map(p.fileVersions)}}))}function nu(p,b){return p.find(I=>I.key===b)?.state.graph?.version??o.initialVersions.get(b)??0}function ru(p,b){let x=new Map(p.map(I=>[I.key,I]));for(let I of b)x.set(I.key,I);return[...x.values()]}function Fo(p){for(let b of i.values())R(b);for(let b of p){let x={...b.state,dependencyFiles:new Set(b.state.dependencyFiles),fileVersions:new Map(b.state.fileVersions)};i.set(b.key,x),A(x,x.dependencyFiles)}}async function Ms(p){let b=i.get(p);if(!b)throw new Error(`Composition not found: ${p}`);if(b.graph)return;let x=await n.readFile(b.entryFile);await _e(p,x)}function zn(p,b){let x=i.get(o.resolveSelector(b).key)??null;return!x||!ou(x,p)?null:x}function ou(p,b){if(p.documentIndex?.entriesByKey.has(b)||p.graph?.elements.has(b))return!0;let x=it(b);return x&&x!==b?p.graph?.elements.has(x)===!0:!1}function le(p,b,x,I){return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:ee(p),error:{code:b,message:x,...I?{details:I}:{}}}}function iu(p){return p==="validate"?K.ROUTE_REBUILD_FAILED:p==="publish"?K.HISTORY_COMMIT_FAILED:K.WRITE_IO_ERROR}async function _o(p){if(g=!0,!l.markRecoveryRequired)return K.RECOVERY_REQUIRED;try{return await l.markRecoveryRequired(p),K.RECOVERY_REQUIRED}catch{return K.RECOVERY_PERSIST_FAILED}}function dy(p){let x=p.split(/[^a-zA-Z0-9]+/).filter(Boolean).map(I=>I.charAt(0).toUpperCase()+I.slice(1)).join("").replace(/^[^a-zA-Z_$]+/,"");return x?`Prefab${x}`:"GeneratedPrefab"}function Os(p){return p==="VERSION_STALE"?K.VERSION_STALE:p==="CROSS_PAGE_MOVE_UNSUPPORTED"?K.CROSS_PAGE_MOVE_UNSUPPORTED:K.UNSUPPORTED_OPERATION}async function su(p){if(p.target.kind==="route"){let x=i.get(o.resolveSelector(p.target.composition).key)??null;return x?(x.graph||await Ms(x.key),x):le(p,K.ROUTE_NOT_FOUND,"Composition not found for route target.")}if(p.target.kind==="page-unit"){let x=i.get(o.resolveSelector(p.target.composition).key)??null;return x?(x.graph||await Ms(x.key),x):le(p,K.ROUTE_NOT_FOUND,"Composition not found for page-unit target.")}if(p.target.kind!=="node")return le(p,K.UNSUPPORTED_OPERATION,`${p.kind} source target execution is not implemented yet.`);let b=i.get(o.resolveSelector(p.composition).key)??null;return b?(b.graph||await Ms(b.key),ou(b,p.target.key)?b:le(p,K.NODE_NOT_FOUND,`Target key not found: ${p.target.key}`)):le(p,K.ROUTE_NOT_FOUND,"Composition not found for node target.")}return{get status(){return t},dispose(){t="disposed",a.clear(),i.clear(),s.clear(),f.clear(),m.clear()},registerComposition(p,b){let x=o.register({context:p,entryFile:b}),I=i.get(x.key);if(I?.entryFile===b)return;I&&R(I);let P=_h(x.context,b);i.set(x.key,P),A(P,P.dependencyFiles),r.emit({type:"graph-invalidated",composition:x.context})},unregisterComposition(p){let b=o.resolveSelector(p),x=i.get(b.key);x&&(R(x),i.delete(b.key),o.unregister(b.key),i.size===0&&(t="idle"),r.emit({type:"graph-invalidated",composition:b.context}))},getCompositionEntryFiles(){return[...i.values()].map(p=>p.entryFile)},getCompositionContext(p){return o.resolveSelector(p).context},async initializeComposition(p){let b=o.resolveSelector(p),x=i.get(b.key);if(!x)throw new Error(`Composition not registered: ${b.key}`);if(x.graph)t="ready";else{t="building";try{let I=await n.readFile(x.entryFile);await _e(b.key,I),t="ready",r.emit({type:"graph-ready",composition:b.context,version:i.get(b.key)?.graph?.version??0})}catch(I){throw t="idle",r.emit({type:"graph-error",composition:b.context,message:et(I)}),I}}},getDocument(p){let b=o.resolveSelector(p),x=i.get(b.key);if(!x)throw new Error(`Composition not registered: ${b.key}`);if(!x.document)throw new Error(`Composition not built: ${b.key}`);return x.document},async getHistoryStatus(){await S;let p=await l.getStatus?.();return p?{...p,recoveryRequired:g}:{canUndo:!1,canRedo:!1,undoDepth:0,redoDepth:0,recoveryRequired:g}},getObjectEditContext(p,b,x){let I=zn(p,b),P=it(p)??p;if(I?.graph&&I.topology&&I.capabilities&&I.detailProjections){let T=I.detailProjections.get(P);if(T){let O=I.graph.elements.get(P);if(!O)throw new Error(`Key not found: ${p}`);let j=sN(p,P,x),q=new Map;if(T.isRepeat&&j?.instanceIndex!==void 0)for(let W of O.attributes??[])q.set(W.name,fl({file:O.sourceFile,source:f.get(O.sourceFile)??"",element:O,propertyName:W.name,selectionRef:j,graph:I.graph,sources:f}));let $=Gg({element:O,graph:I.graph,source:f.get(O.sourceFile),documentVersion:I.graph.version,selectionRef:x,isRepeat:T.isRepeat,propertyProvenance:T.propertyProvenances,repeatTargets:q}),B=Qg(P,I.graph,I.topology,I.capabilities,T.textSources,T.provenances,T.dynamicData,$);return p===P?B:Ih(B,p,I.document??null,I.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${p}`)},getRenderDetail(p,b){let x=zn(p,b),I=it(p)??p;if(x?.graph&&x.topology&&x.capabilities&&x.detailProjections){let P=x.detailProjections.get(I);if(P){let T=Zg(I,x.graph,x.topology,x.capabilities,P.textSources,P.writeTarget,P.provenances,P.conditional,P.componentSemantic,P.styleSource,P.dynamicData);return p===I?T:kh(T,p,x.document??null,x.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${p}`)},getClassNameSource(p,b){let x=zn(p,b),I=it(p)??p;if(!x?.graph)throw new Error(`Key not found: ${p}`);let P=x.graph.elements.get(I);if(!P)throw new Error(`Key not found: ${p}`);let T=f.get(P.sourceFile);if(T===void 0)throw new Error(`Source not loaded: ${P.sourceFile}`);return ya({key:I,route:{composition:x.composition,routeId:x.routeId,graph:x.graph,source:T}})},refreshSourceForKey:Qh,async execute(p){if(await S,g)return le(p,K.RECOVERY_REQUIRED,"The edit engine requires explicit recovery before accepting mutations.");if(p.kind==="source-edit")return qh(p);if(p.kind==="insert-page-resource")return ey(p);if(p.kind==="delete-page-source")return ty(p);let b=await su(p);if("ok"in b)return b;await Gl(p);let x=await su(p);if("ok"in x)return x;let I=x;if(p.target.kind==="page-unit"){let B=p;return p.kind==="insert-child"||p.kind==="replace-node"?ny(B,I):p.kind==="move-node"||p.kind==="remove-node"?ry(B,I):le(p,K.UNSUPPORTED_OPERATION,"Only page-unit insert-child, replace-node, move-node, and remove-node are currently supported by the page composition transaction.")}let T=p.params,O=p.target.kind==="node"?p.target.key:null;if(T.kind==="move-node"&&"kind"in T.target&&T.target.kind==="source-sibling"){let B=T.target,W=O?I.document?.entries.find(U=>U.key===O):null,de=I.document?.entries.find(U=>U.key===B.anchorKey),ue=W?.pageCompositionActionScope,be=ue?.kind==="source-siblings"?ue.siblingKeys:null,Ce=be?.indexOf(W?.key??"")??-1,Pe=be?.indexOf(B.anchorKey)??-1,M=B.relation==="before"?Ce-1:Ce+1;if(!W||!de||!be||Ce<0||Pe!==M||de.pageCompositionActionScope?.kind!=="source-siblings"||de.pageCompositionActionScope.siblingKeys.length!==be.length||de.pageCompositionActionScope.siblingKeys.some((U,ie)=>U!==be[ie])||!W.operationSummary.canMove)return le(p,K.INVALID_TARGET,"Source sibling move is unavailable because the current source sibling scope or adjacent anchor no longer matches.")}if(!I.graph||!I.topology||!I.capabilities)return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:ee(p),error:{code:p.target.kind==="route"?K.ROUTE_NOT_FOUND:K.NODE_NOT_FOUND,message:p.target.kind==="route"?"Composition not ready for route target.":p.target.kind==="node"?`Target key not found: ${p.target.key}`:`${p.kind} source target execution is not implemented yet.`}};let j=IN(I,I.graph,I.capabilities,f,i),q=await new os(j).plan(p);if(!q.ok)return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:ee(p),error:{code:Po(q.errorCode),message:q.reason}};let $=q.plan;if($.steps.length===0)return p.kind==="set-props"?{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!0,resultVersion:ee(p),affectedFiles:[]}:{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:ee(p),error:{code:K.PLAN_FAILED,message:"Planner could not generate a valid execution plan"}};d+=1;try{if($.steps.some(W=>W.type==="invoke-external-adapter")){let W=await u.execute($);if(!W.ok)return le(p,Po(W.errorCode),W.reason);let de={composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!0,resultVersion:Math.max(ee(p),W.resultVersion),affectedFiles:W.affectedFiles,...W.selectionRef?{selectionRef:W.selectionRef}:{}};return As(de,{rebuiltRoutes:[],failedRoutes:[]}),de}let B=await u.prepareRewritePlan($);return B.ok?await Xn({request:p,filePlan:B.filePlan,...B.selectionRef?{selectionRef:B.selectionRef}:{}}):le(p,Po(B.errorCode),B.reason)}catch(B){return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:ee(p),error:{code:K.INTERNAL_ERROR,message:et(B)}}}finally{d-=1}},async undo(p){if(await S,g)return{composition:o.entries[0].context,requestId:"undo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:me(o.entries[0].key),error:{code:K.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting undo."}};d+=1;try{return await eu("undo")}finally{d-=1}},async redo(p){if(await S,g)return{composition:o.entries[0].context,requestId:"redo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:me(o.entries[0].key),error:{code:K.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting redo."}};d+=1;try{return await eu("redo")}finally{d-=1}},notifyFileChanged(p){Jl([p])},getAffectedCompositions(p){return Wh(p)},subscribe(p){return r.subscribe(p)}}}function yN(e){return e instanceof Error&&"code"in e&&(e.code==="ENOENT"||e.code==="ENOTDIR")}function xN(e,t,n,r){let o=new Map,i=new Map,s=(f,m,d)=>{let g=f.get(m)??new Set,h=g.size;return g.add(d),f.set(m,g),g.size!==h},a=(f,m)=>{if(!f.importedFrom)return!1;if(f.exportName==="default")return s(i,f.importedFrom,m);let d=s(o,`${f.importedFrom}#${f.tag}`,m);return f.exportName&&f.exportName!==f.tag&&(d=s(o,`${f.importedFrom}#${f.exportName}`,m)||d),d},c=f=>o.get(`${f.sourceFile}#${f.componentName}`)??i.get(f.sourceFile);for(let f of t.elements.values()){if(f.sourceFile!==n.entryFile||!f.importedFrom||!/^[A-Z]/.test(f.tag))continue;let m=n.placements.find(g=>g.members.some(h=>h.sourceRange!==null&&Ao(f.sourceRange,h.sourceRange)));if(!m)continue;let d=m.placementUnitKey;a(f,d)}let l=!0;for(;l;){l=!1;for(let f of t.elements.values()){if(f.sourceFile===n.entryFile||!f.importedFrom||!/^[A-Z]/.test(f.tag))continue;let m=c(f);if(m)for(let d of m)l=a(f,d)||l}}let u=n.placements.find(f=>f.placementKey===n.container.placementKey&&f.relation==="append");for(let f of e.entries){let m=it(f.key)??f.key,d=t.elements.get(f.key)??t.elements.get(m);if(!d)continue;if(d.sourceFile===n.entryFile){if(n.container.sourceRange&&Ao(d.sourceRange,n.container.sourceRange)&&u){f.pageCompositionUnitKey=u.placementUnitKey;continue}let S=n.placements.find(E=>E.members.some(y=>y.sourceRange!==null&&(Ao(d.sourceRange,y.sourceRange)||kN(y.sourceRange,d.sourceRange))));if(S){f.pageCompositionUnitKey=S.placementUnitKey;continue}}let g=o.get(`${d.sourceFile}#${d.componentName}`);if(g){g.size===1&&(f.pageCompositionUnitKey=g.values().next().value);continue}let h=i.get(d.sourceFile);h?.size===1&&(f.pageCompositionUnitKey=h.values().next().value)}bN(e,t,n,r)}function bN(e,t,n,r){let o=new Map(e.entries.map(m=>[m.key,m])),i=e.entries.filter(m=>{let d=m.pageCompositionUnitKey;return d?m.parentKey?o.get(m.parentKey)?.pageCompositionUnitKey!==d:!0:!1}),s=new Map,a=(m,d)=>{s.set(m,Math.min(2,(s.get(m)??0)+d))},c=m=>n.placements.some(d=>d.members.some(g=>g.sourceRange!==null&&Ao(m.sourceRange,g.sourceRange)));for(let m of t.elements.values())m.sourceFile!==n.entryFile||!m.importedFrom||!/^[A-Z]/.test(m.tag)||!c(m)||a(`${m.importedFrom}#${m.exportName??m.tag}`,1);let l=[...t.elements.values()].flatMap(m=>m.sourceFile!==n.entryFile&&m.importedFrom&&/^[A-Z]/.test(m.tag)?[{owner:`${m.sourceFile}#${m.componentName}`,ownerDefault:`${m.sourceFile}#default`,target:`${m.importedFrom}#${m.exportName??m.tag}`}]:[]);for(let m=0;m<=l.length;m+=1){let d=!1;for(let g of l){let h=s.get(g.owner)??s.get(g.ownerDefault)??0;if(!h)continue;let S=s.get(g.target)??0,E=Math.min(2,S+h);E!==S&&(s.set(g.target,E),d=!0)}if(!d)break}let u=m=>s.get(`${m.sourceFile}#${m.componentName}`)??s.get(`${m.sourceFile}#default`)??0;for(let m of i){m.pageCompositionActionScope={kind:"unavailable"};let d=t.elements.get(m.key);m.pageCompositionUnitKey&&d?.sourceFile===n.entryFile&&(m.pageCompositionActionScope={kind:"route-unit"})}let f=new Map;for(let m of i){let d=t.elements.get(m.key);if(!d||d.sourceFile===n.entryFile||m.key!==(it(m.key)??m.key))continue;let g=r.get(d.sourceFile);if(!g)continue;let h=se(g.ast,{kind:"jsx-node",strategy:"source-range",sourceRange:d.sourceRange});if(!h.ok||!h.match.path.isJSXElement())continue;let S=h.match.path,E=S.parentPath;if(!E||!E.isJSXFragment()&&!(E.isJSXElement()&&Me(E))){u(d)===1&&Lh(S)&&(m.pageCompositionActionScope={kind:"route-unit"});continue}if(!Lh(E))continue;let y=f.get(E.node)??[];y.push({entry:m,element:d,parentPath:E}),f.set(E.node,y)}for(let m of f.values()){let d=m[0];if(!d)continue;let g=d.entry.pageCompositionUnitKey,h=[],S=!!(g&&u(d.element)===1);for(let y of d.parentPath.node.children){if(SN(y))continue;if(!EN(y)){S=!1;break}let v=[...t.elements.values()].find(N=>N.sourceFile===d.element.sourceFile&&N.componentName===d.element.componentName&&Ao(N.sourceRange,vN(y))),C=v?o.get(v.identity.key):null;if(!v||!C||C.parentKey||C.pageCompositionUnitKey!==g||u(v)!==1){S=!1;break}h.push(C)}if(!S||h.length!==m.length||m.some(({entry:y})=>!h.some(v=>v.key===y.key)))continue;if(h.length===1){h[0].pageCompositionActionScope={kind:"route-unit"};continue}if(h.length<2)continue;let E=h.map(y=>y.key);for(let y of h)y.pageCompositionActionScope={kind:"source-siblings",siblingKeys:E}}}function Lh(e){let t=e.parentPath;return!!(t?.isReturnStatement?.()||t?.isArrowFunctionExpression?.()&&t.node.body===e.node)}function SN(e){return!!(e&&typeof e=="object"&&e.type==="JSXText"&&!(e.value??"").trim())}function EN(e){return!!(e&&typeof e=="object"&&e.type==="JSXElement")}function vN(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 Ao(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function kN(e,t){return Dh(e.startLine,e.startColumn,t.startLine,t.startColumn)<=0&&Dh(e.endLine,e.endColumn,t.endLine,t.endColumn)>=0}function Dh(e,t,n,r){return e!==n?e-n:t-r}function IN(e,t,n,r,o){let i=new Map,s=new Map,a=(u,f)=>{if(s.has(u))return;s.set(u,f);let m=t.elements.get(u);for(let d of m?.childKeys??[])a(d,f)};for(let u of t.regions)if(u.kind==="repeat-region")for(let f of u.childKeys)i.set(f,u.ownerKey),a(f,u.ownerKey);return{getNode(u){let f=c(u),m=t.elements.get(f.baseKey);return m?l(u,m):null},getChildNodes(u){let f=c(u),d=e.documentIndex?.entriesByKey.get(u)?.childKeys;if(d)return d.map(h=>{let S=it(h)??h,E=t.elements.get(S);return E?l(h,E):null}).filter(h=>h!==null);let g=t.elements.get(f.baseKey);return g?g.childKeys.map(h=>{let S=t.elements.get(h);return S?l(h,S):null}).filter(h=>h!==null):[]},getKnownSourceFiles(){return[...r.entries()].map(([u,f])=>({file:u,content:f}))},getRouteEntryFiles(){return[...o.values()].map(u=>u.entryFile)},getCapability(u){let f=c(u),m=n.get(f.baseKey);return m?{...m,key:u,constraints:m.constraints.map(d=>({...d})),...m.editModes?{editModes:{...m.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 f=c(u);return e.detailProjections?.get(f.baseKey)?.componentSemantic??null},getClassNameSource(u){let f=c(u),m=t.elements.get(f.baseKey),d=m?r.get(m.sourceFile):void 0;return!m||d===void 0?null:ya({key:f.baseKey,route:{composition:e.composition,routeId:e.routeId,graph:t,source:d}})},getEditableTextSegmentIndex(u){let f=c(u),d=e.detailProjections?.get(f.baseKey)?.textTargets.keys()?.next();return d&&!d.done?d.value:null},async getTextWriteTarget(u,f){let m=c(u);return Dl(e.detailProjections?.get(m.baseKey)?.textTargets.get(f)??null,m.repeatIndex)},async getElementPropertyWriteTarget(u,f){let m=c(u);return Dl(e.detailProjections?.get(m.baseKey)?.elementPropertyTargets.get(f)??null,m.repeatIndex)},getPropertyState(u,f,m){let d=c(u),g=t.elements.get(d.baseKey);if(!g)return null;let S=e.detailProjections?.get(d.baseKey)?.propertyProvenances.get(f);if(S)return S;let E=g.attributes?.find(y=>y.name===f);return E?E.source?{status:"blocked",owner:"generic",diagnostic:{code:"unsupported-property-source",message:`Property '${f}' has an unresolved value source`}}:{status:"direct",owner:"generic",attribute:E,target:{kind:"jsx-attribute",file:g.sourceFile,sourceRange:E.sourceRange}}:(g.attributeSpreads?.length??0)>0?{status:"blocked",owner:"generic",diagnostic:{code:"ambiguous-property-source",message:`A spread may provide or override property '${f}'`}}:{status:"missing",owner:"generic"}},getRepeatPropertyTarget(u,f,m){let d=c(u),g=t.elements.get(d.baseKey);if(!g)return{ok:!1,errorCode:"repeat-not-found",reason:`Node not found: ${u}`};let h=m?{...m,key:d.baseKey}:d.repeatIndex!==null?{key:d.baseKey,instanceIndex:d.repeatIndex}:void 0;return fl({file:g.sourceFile,source:r.get(g.sourceFile)??"",element:g,propertyName:f,selectionRef:h,graph:t,sources:r})},getTextProvenance(u,f){let m=c(u);return e.detailProjections?.get(m.baseKey)?.provenances.get(f)??null}};function c(u){let f=Hw(u);return f?{baseKey:f.baseKey,repeatIndex:vh(e.document??null,u,f.baseKey,e.documentIndex)??Eh(f)}:{baseKey:u,repeatIndex:null}}function l(u,f){let m=it(u)??u,d=e.documentIndex?.entriesByKey.get(u);return{key:u,file:f.sourceFile,component:f.componentName,tag:f.tag,structuralPath:f.identity.structuralPath,sourceRange:f.sourceRange,parentKey:d?.parentKey??f.parentKey??void 0,isRepeatRegion:f.boundaryKind==="repeat-region"||s.has(m),isBoundary:!1,importedFrom:f.importedFrom,exportName:f.exportName,isRepeatItemRoot:i.has(m),repeatOwnerKey:i.get(m)??s.get(m),attributes:f.attributes?.map(g=>({name:g.name,value:g.value,source:g.source?{expression:g.source.expression,base:g.source.base,path:g.source.path.map(h=>({...h}))}:null,resolvedValue:g.resolvedValue}))}}}var CN={"stale-version":K.VERSION_STALE,"capability-denied":K.CAPABILITY_REJECTED,"invalid-params":K.INVALID_PARAMS,"locator-miss":K.LOCATOR_FAILED,"route-not-found":K.ROUTE_NOT_FOUND,"unsupported-operation":K.UNSUPPORTED_OPERATION,"invalid-target":K.INVALID_TARGET,"ast-error":K.AST_PARSE_ERROR,"writeback-failed":K.WRITE_IO_ERROR,"rollback-failed":K.RECOVERY_REQUIRED,unknown:K.INTERNAL_ERROR};function Po(e){return CN[e]}function et(e){return e instanceof Error&&e.message?e.message:String(e)}function Bh(e){return/\.(?:[cm]?[jt]sx?|css|scss|sass|mdx|json)$/i.test(e)}function RN(e){let t=Kn(e);if(!Zw.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=>Qw.map(a=>`${s}/${a}`))}function wN(e){let n=Kn(e).startsWith("src/app/")?"src/app":"app";return[`${n}/globals.css`,`${n}/global.css`]}function NN(e){return Vh(e,/\bimport\s+(?:[^'";]+?\s+from\s+)?["']([^"']+\.css(?:\?[^"']*)?)["']/g)}function PN(e){return Vh(e,/@import\s+(?:url\(\s*)?["']([^"']+)["']/g)}function Vh(e,t){let n=[];for(let r of e.matchAll(t)){let o=Kh(r[1]??"");o&&n.push(o)}return n}function jh(e,t){let n=Kh(t);return!n||n.startsWith("tailwindcss")||n.startsWith("http:")||n.startsWith("https:")?null:n.startsWith("@/")?Kn(`src/${n.slice(2)}`):n.startsWith("./")||n.startsWith("../")?Kn(`${AN(e)}/${n}`):n.startsWith("/")?Kn(n.slice(1)):Vl(n)?Kn(n):null}function Kh(e){return e.split(/[?#]/,1)[0]?.trim()??""}function Vl(e){return/\.css$/i.test(e)}function AN(e){let t=Kn(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function TN(e){return Array.from(new Set(e))}function Kn(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 FN(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 ws=class{constructor(t){this.options=t,this.fileSystem=new Ir(t.files),this.engine=this.createEngine(this.fileSystem)}get status(){return this.engine.status}initializeComposition(t){return this.engine.initializeComposition(t)}getDocument(t){return Ko(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 Uo(r?this.engine.getObjectEditContext(t,n,r):this.engine.getObjectEditContext(t,n))}getClassNameSource(t,n){return this.engine.getClassNameSource(t,n)}getSourceTree(t){return zo(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}getSourceFile(t){return Wo(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}resolveSourceLocation(t){return Ho(t,this.engine.getRenderDetail(t.key,t.composition))}async planOperation(t){let n=MN.safeParse(t);if(!n.success)return{result:Vo(t,n.error.issues.map(i=>i.message))};let r=new Ir(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:Cn(i)},a=r.getChangedFiles();if(a.length===0)return{result:s};let c=ON.parse({siteId:t.siteId,baseSnapshotId:t.baseSnapshotId,operationId:t.id,reason:`site-edit:${t.kind}`,patches:a.map(l=>LN(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 Rs({projectRoot:"/snapshot",fileSystem:t,compositions:this.options.compositions,onEvent:r&&this.options.onEvent?o=>{let i=Jo(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 LN(e,t){return e.after===void 0?{path:e.path,operation:"delete",...t||e.before===void 0?{}:{expectedHash:ke(e.before)}}:{path:e.path,operation:e.before===void 0?"create":"update",...t||e.before===void 0?{}:{expectedHash:ke(e.before)},fullContent:e.after}}function DN(e){return new ws(e)}import{SiteEditOperationRequestSchema as $N}from"@vcp-dev/contracts";import wt from"node:fs/promises";import tt from"node:path";import{SITE_EDIT_SOURCE_ALLOWED_DIRS as BN,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as jN}from"@vcp-dev/contracts";var Ns=class{constructor(t){this.options=t,this.fileSystem=this.createFileSystem(),this.engine=Rs({...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 zo(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.engine.getCompositionEntryFiles()})}getSourceFile(t){return Wo(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.engine.getCompositionEntryFiles()})}resolveSourceLocation(t){return Ho(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 wt.readFile(tt.join(n,r),"utf8")},async readFileBytes(r){return wt.readFile(tt.join(n,r))},async getFileInfo(r){let o=tt.join(n,...r.split("/"));try{let i=await wt.lstat(o);return!i.isFile()||i.isSymbolicLink()?null:{path:r,sizeBytes:i.size}}catch{return null}},async writeFile(r,o){await pi(tt.join(n,r),o)},async createExclusive(r,o){let i=tt.join(n,r);await wt.mkdir(tt.dirname(i),{recursive:!0});let s=await wt.open(i,"wx");try{await s.writeFile(o,"utf8")}catch(a){throw await s.close(),await wt.rm(i,{force:!0}),a}await s.close()},async deleteFile(r){await wt.rm(tt.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=tt.join(n,i),a=tt.dirname(tt.join(n,o));for(;a!==s&&a.startsWith(`${s}${tt.sep}`);){try{await wt.rmdir(a)}catch(c){if(c instanceof Error&&"code"in c&&c.code==="ENOENT"){a=tt.dirname(a);continue}break}a=tt.dirname(a)}},async exists(r){try{return await wt.access(tt.join(n,r)),!0}catch{return!1}},async listFiles(r={}){let o=r.roots??[...jN,...BN],i=[],s=new Set,a=new Set,c=0;for(let f of o)await u(f,i,1);let l=i.sort((f,m)=>f.path.localeCompare(m.path));return a.size>0?{files:l,truncated:{reasons:[...a]}}:{files:l};async function u(f,m,d){if(r.maxDepth!==void 0&&d>r.maxDepth){a.add("max-depth");return}let g=tt.join(n,...f.split("/")),h;try{h=await wt.lstat(g)}catch{return}if(h.isSymbolicLink())return;if(h.isFile()){let E=h.ino>0?`${String(h.dev)}:${String(h.ino)}`:null;if(E&&s.has(E))return;if(r.maxFiles!==void 0&&m.length>=r.maxFiles){a.add("max-files");return}if(r.maxTotalBytes!==void 0&&c+h.size>r.maxTotalBytes){a.add("max-total-bytes");return}E&&s.add(E),m.push({path:f,sizeBytes:h.size}),c+=h.size;return}if(!h.isDirectory())return;if(r.maxFiles!==void 0&&m.length>=r.maxFiles){a.add("max-files");return}let S=await wt.readdir(g,{withFileTypes:!0});for(let E of S)E.isSymbolicLink()||await u(`${f}/${E.name}`,m,d+1)}},getVersion(r){return t.get(r)??1},bumpVersion(r){let o=(t.get(r)??1)+1;return t.set(r,o),o}}}};function Kl(e){return new Ns(e)}var Ps=class{constructor(t){this.options=t,this.listeners=new Set,this.engine=Kl({projectRoot:t.projectRoot,fileSystem:t.fileSystem,compositions:t.compositions,onEvent:n=>{let r=Jo(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:Ko(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:Uo(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=$N.safeParse(r);if(!o.success)return Vo(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:Cn(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:Cn(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:Cn(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 VN(e){return new Ps(e)}export{re as FileHistoryStoreError,Qr as PageTemplateManagedSourceError,Ps as PreviewFileSystemSiteEditEngineRuntime,df as SITE_EDIT_RAW_COLOR_LITERAL_RE,ws as SnapshotSiteEditEngineRuntime,Lo as checkComponentI18nHostCompatibility,np as computeManagedPageTemplatePaths,VN as createPreviewSiteEditEngineRuntime,DN as createSiteEditEngineRuntime,qf as decodePageTemplateKey,yc as encodePageTemplateId,Oy as instrumentSiteEditRuntimeAttributes,rp as isManagedPageTemplateSourcePath,$d as openFileHistoryStore,by as parseSourceModule,Sy as resolveImportBase,_k as resolveManagedPageTemplateComposition,$i as scanManagedPageTemplateCandidates,ip as scanSiteEditCompositionsFromFiles,Xr as scanSiteEditThemeStyleViolations};
|
|
14
|
+
`||m==="\r"}if(s)return Er(t,`Unterminated block comment in ${t}.`);if(o)return Er(t,`Unterminated string literal in ${t}.`);if(c)return Er(t,`Unterminated MDX code fence in ${t}.`);let u=r.at(-1);return u?Er(t,`Unclosed token "${u.char}" in ${t}.`):{ok:!0}}function Er(e,t){return{ok:!1,errorCode:"ast-error",message:t,details:{path:e}}}function Rs(e){let t="idle",n=e.fileSystem??eN(),r=yd(),o=xh({compositions:e.compositions,initialDocumentVersions:e.initialDocumentVersions}),i=new Map,s=new Map,a=new Set,c=null,l=e.history??(e.historyStore?af(e.historyStore):nN()),u=hh(n,{externalAdapters:e.externalAdapters}),f=new Map,m=new Set,d=0,g=e.historyStore?.recoveryRequired??!1,h=Ol(),S=C();function E(p){return(Is.isAbsolute(p)?Is.relative(e.projectRoot,p):p).replace(/\\/g,"/").replace(/^\.\//,"")}function y(p,b){let x=Is.posix.dirname(p),I=b.replace(/\.(?:tsx?|jsx?)$/i,""),P=Is.posix.relative(x,I);return P.startsWith(".")?P:`./${P}`}function v(p,b){return p.startLine===b.startLine&&p.startColumn===b.startColumn&&p.endLine===b.endLine&&p.endColumn===b.endColumn}async function C(){let p=e.historyStore;if(p)try{let b=await p.readTransactionJournal();if(!b)return;let x=await p.readIndex(),I=await Promise.all(b.files.map(async T=>await n.exists(T.path)?ke(await n.readFile(T.path)):null));if(Ph({journal:b,index:x,observedFileDigests:I})!=="ambiguous"){await p.clearTransactionJournal(b.transactionId);let T=await p.readStatus();T.recoveryRequired||(await p.cleanupTmp(),T=await p.readStatus()),g=T.recoveryRequired;return}await p.markRecoveryRequired(`Ambiguous transaction journal ${b.transactionId} at phase ${b.phase}`),g=!0}catch(b){g=!0,await p.markRecoveryRequired(`Transaction journal recovery failed: ${et(b)}`).catch(()=>{})}}function N(){return t==="disposed"}e.onEvent&&r.subscribe(e.onEvent);for(let p of o.entries){let b=Mh(p.context,p.entryFile);i.set(p.key,b),A(b,b.dependencyFiles)}function A(p,b){let x=new Set(b);R(p),p.dependencyFiles=x;for(let I of p.dependencyFiles){let P=s.get(I);P||(P=new Set,s.set(I,P)),P.add(p.key)}}function R(p){for(let b of p.dependencyFiles){let x=s.get(b);x&&(x.delete(p.key),x.size===0&&s.delete(b))}p.dependencyFiles.clear()}function F(p){let b=new Set;for(let x of p)for(let I of s.get(x)??[])b.add(I);return b}function _(p){for(let b of p)if(!s.has(b))return!1;return!0}async function D(p,b,x,I,P,T){let O=new Map,j=Og(P.values()),q=Mm(P.values()),$=typeof T.exists=="function"?B=>T.exists(B):async()=>!1;for(let[B,W]of p.elements){let de=b.nodes.get(B);if(!de)continue;let ue=x.get(W.sourceFile)??I.get(W.sourceFile),be=new Map,Ce=new Map,Pe=new Map,M=[];for(let Ne of W.textSegments){if(!ue){be.set(Ne.index,null);continue}let vr=await Lg({file:W.sourceFile,source:ue,segment:Ne,readFile:st=>T.readFile(st),exists:$,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:st,adapterId:xn,capabilities:Ds})=>({sourceType:st,adapterId:xn,capabilities:Ds})),functionCallContracts:e.functionCallContracts,fileCache:j}),Qe=await Rl({file:W.sourceFile,source:ue,target:{kind:"text-segment",segment:Ne},readFile:st=>T.readFile(st),exists:$,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:st,adapterId:xn,capabilities:Ds})=>({sourceType:st,adapterId:xn,capabilities:Ds})),functionCallContracts:e.functionCallContracts,fileCache:j}),ft=fN(vr);be.set(Ne.index,ft),Ce.set(Ne.index,vr),Pe.set(Ne.index,Qe),M.push({editable:Ne.editable,source:ft})}let U=new Map,ie=new Map;if(ue)for(let Ne of W.attributes??[]){let vr=await br({file:W.sourceFile,source:ue,sourceRange:Ne.sourceRange,expression:Ne.source?.expression??Ne.value,sourceInfo:Ne.source,readFile:ft=>T.readFile(ft),exists:$,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:ft,adapterId:st,capabilities:xn})=>({sourceType:ft,adapterId:st,capabilities:xn})),functionCallContracts:e.functionCallContracts,fileCache:j}),Qe=await Xg({element:W,file:W.sourceFile,source:ue,propertyName:Ne.name,readFile:ft=>T.readFile(ft),exists:$,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:ft,adapterId:st,capabilities:xn})=>({sourceType:ft,adapterId:st,capabilities:xn})),functionCallContracts:e.functionCallContracts,fileCache:j});ie.set(Ne.name,Qe),U.set(Ne.name,vr)}let ge=nh(pN(de.writeTarget),M),Se=zg({key:B,element:W,graph:p,provenances:Pe}),Ae=ah(W),en=ue?await Om({element:W,graph:p,file:W.sourceFile,source:ue,readFile:Ne=>T.readFile(Ne),exists:$,fileCache:q}):void 0,He=p.regions.find(Ne=>Ne.kind==="conditional-region"&&Ne.childKeys.includes(B)),Mo,Ls=He?.sourceCandidates?.[0];if(ue&&He&&Ls?.kind==="conditional-branch"){let Ne=await Rl({file:W.sourceFile,source:ue,target:{kind:"conditional-branch",candidate:Ls},readFile:Qe=>T.readFile(Qe),exists:$,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Qe,adapterId:ft,capabilities:st})=>({sourceType:Qe,adapterId:ft,capabilities:st})),functionCallContracts:e.functionCallContracts,fileCache:j});Mo={currentBranch:He.childKeys.indexOf(B)<=0?"then":"else",availableBranches:He.childKeys.length>1?["then","else"]:["then"],conditionExpression:Ls.conditionExpression,provenance:{finalSource:Ne.finalSource?{kind:Ne.finalSource.kind,file:Ne.finalSource.file,displayPath:Ne.finalSource.displayPath}:null,chain:Ne.chain.map(Qe=>({kind:Qe.kind,file:Qe.file,displayName:Qe.displayName,canEditHere:Qe.canEditHere})),confidence:Ne.confidence,editMode:Ne.editMode,diagnostics:Ne.diagnostics.map(Qe=>({code:Qe.code,message:Qe.message}))}}}O.set(B,{textSources:be,textTargets:Ce,elementPropertyTargets:U,propertyProvenances:ie,isRepeat:FN(B,p),provenances:Pe,writeTarget:ge,componentSemantic:Se,styleSource:Ae,conditional:Mo,dynamicData:en})}return O}function L(p){return typeof n.getVersion=="function"?n.getVersion(p):0}function oe(p,b){let x=o.initialVersions.get(p.key)??0;for(let I of b.values())x=Math.max(x,I);return Math.max(x,p.graph?.version??0)}function me(p){return i.get(p)?.graph?.version??o.initialVersions.get(p)??0}function ee(p){try{return me(o.resolveSelector(p.composition).key)}catch{return 0}}async function ce(p,b,x=n,I={}){let P=await wd(p,b,T=>x.readFile(T),T=>x.exists(T),{additionalEntries:await Qt(p,x),...I});if(P.diagnostics.length>0)throw new No(P.diagnostics);return P}async function _e(p,b,x={}){let I=i.get(p);if(!I)return null;let P=x.sourceCache??jl(f,[]),T=x.fileSystem??Ll(n),{graph:O,allSources:j,parsedModules:q,entryModule:$}=await ce(I.entryFile,b,T,{version:I.graph?.version??1}),B=new Map;for(let He of j.keys())B.set(He,L(He));let W=Math.max(oe(I,B),x.minimumVersion??0);x.changed&&W<=(I.graph?.version??0)&&(W=(I.graph?.version??0)+1),O.version=W;for(let[He,Mo]of j)$l(P,He,Mo,Th);let de=await qt(I.composition,I.entryFile,j,P,T);O.routeId=I.routeId,O.composition=I.composition;let ue=ch(O),be=fd(ue,O),Ce=await D(O,ue,j,P,q,T),Pe=zh(O,be,Ce),M=Xh(Ce),U=Eh(Zg(O,ue,be,{canUpdateTextByKey:Pe,dynamicDataSummaryByKey:M}),O,Ce),ie=Jf({route:I.routeId,composition:I.composition,entryFile:I.entryFile,version:W,source:b,ast:$?.ast}),ge=Xf(ie);ie.ok&&xN(U,O,ie.projection,q);let Se={...U,composition:I.composition,...de?{styleContext:de}:{},pageComposition:ge},Ae=new Set([I.entryFile,...j.keys()]);if(de){Ae.add(de.entryCss.path);for(let He of de.stylesheets)Ae.add(He.path)}let en={...I,dependencyFiles:Ae,graph:O,topology:ue,capabilities:be,document:Se,pageComposition:ge,pageCompositionProjection:ie.projection,pagePlacementByKey:ie.ok?ie.projection.placementByKey:null,pagePlacementUnitByKey:ie.ok?ie.projection.placementUnitByKey:null,pageUnitByKey:ie.ok?ie.projection.unitByKey:null,pagePlacementsByUnitKey:ie.ok?ie.projection.placementsByUnitKey:null,documentIndex:Sh(Se),detailProjections:Ce,fileVersions:B,styleContext:de};if(x.publish===!1)return en;Sr(f,P);for(let He of P.keys())m.delete(He);return A(I,Ae),Object.assign(I,en),I}async function Qt(p,b=n){let x=[];for(let I of RN(p))typeof b.exists=="function"&&await b.exists(I)&&x.push({file:I,source:await b.readFile(I)});return x}async function qt(p,b,x,I,P){let T=[];for(let[B,W]of x){if(Vl(B)){T.push(B);continue}for(let de of NN(W)){let ue=$h(B,de);ue&&T.push(ue)}}if(!T.length){for(let B of wN(b))if(await P.exists(B)){T.push(B);break}}let O=new Map,j=TN(T).slice(0,Ah);for(;j.length>0&&O.size<Ah;){let B=j.shift();if(O.has(B)||!Vl(B))continue;let W=await Jh(B,I,P);if(W!==null){O.set(B,{path:B,content:W});for(let de of PN(W)){let ue=$h(B,de);ue&&!O.has(ue)&&!j.includes(ue)&&j.push(ue)}}}let q=[...O.values()].map(B=>({...B,hash:ke(B.content)})),$=q[0];return $?{composition:p,revision:ke(JSON.stringify(q.map(({path:B,hash:W})=>({path:B,hash:W})))),entryCss:$,stylesheets:q.slice(1)}:null}async function Jh(p,b,x){let I=b.get(p);if(I!==void 0)return I;if(!await x.exists(p))return null;let P=await x.readFile(p);return $l(b,p,P,Th),P}function Xh(p){let b=new Map;for(let[x,I]of p)I.dynamicData?.bindings.length&&b.set(x,Wm(I.dynamicData.bindings));return b}function zh(p,b,x){let I=new Map;for(let[P,T]of p.elements){if(!b.get(P)?.canUpdateText){I.set(P,!1);continue}let j=x.get(P),q=T.textSegments.some($=>{if(!$.editable)return!1;let B=j?.provenances.get($.index)??null;return!B||Wh(B)});I.set(P,q)}return I}function Wh(p){return p.editMode==="direct"||p.editMode==="proxy"||p.editMode==="upstream"}async function To(p,b={}){let x=[...new Set(p)],I=b.affectedCompositionKeys!==void 0,P=I?new Set(b.affectedCompositionKeys):F(x);if(!I&&(P.size===0||!_(x)))for(let $ of i.values())Ul($,x)&&P.add($.key);let T=!I&&P.size===0&&x.some(jh),O=b.publish===!1?jl(f,x):void 0,j={rebuiltRoutes:[],failedRoutes:[],...b.publish===!1?{candidateRouteStates:[],candidateSourceCache:O}:{}},q=Ll(n);for(let $ of i.values())if(!(b.excludedCompositionKeys?.has($.key)||!(P.has($.key)||T)))try{let W=!!$.graph,de=await q.readFile($.entryFile),ue=await _e($.key,de,{...b,fileSystem:q,...O?{sourceCache:O}:{}});ue?.graph&&(j.rebuiltRoutes.push({documentChanged:W,composition:$.composition,routeId:$.routeId,version:ue.graph.version}),j.candidateRouteStates?.push({composition:$.composition,key:$.key,routeId:$.routeId,state:ue}))}catch(W){j.failedRoutes.push({...wh($.routeId,W),composition:$.composition})}return j}function Un(p){let b=[...new Set(p)],x=F(b);if(x.size>0&&_(b))return[...x];for(let I of i.values())Ul(I,b)&&x.add(I.key);return[...x]}function Hh(p){let b=new Set(Un(p));return o.entries.filter(x=>b.has(x.key)).map(x=>x.context)}function Gh(p){return[...new Set(Un(p))].sort((x,I)=>x<I?-1:x>I?1:0).map(x=>o.getByKey(x)?.context).filter(x=>x!==void 0)}function Yh(p,b){let x=new Set(Un(b)),I=p.provenance?.affectedCompositions??[];if(I.length===0)return x;if([...new Set(I.map(T=>o.resolveContext(T).key))].some(T=>!x.has(T)))throw new Error("History provenance does not match the affected composition index.");return x}function Zh(p,b){let x=p.composition??p.provenance?.initiatingComposition;if(x){let T=o.resolveContext(x);return{context:T.context,key:T.key}}let I=[...new Set(Un(b))];if(I.length!==1)throw new Error(`Legacy history entry cannot be attributed to a unique composition (affected composition count: ${I.length}).`);let P=o.getByKey(I[0]);if(!P)throw new Error("Legacy history entry references an unknown affected composition.");return{context:P.context,key:P.key}}function As(p,b){r.emit({type:"operation-completed",composition:p.composition,result:p});for(let{composition:x,version:I}of b.rebuiltRoutes)r.emit({type:"document-changed",composition:x,version:I});for(let{composition:x,message:I}of b.failedRoutes)r.emit({type:"graph-error",composition:x,message:I})}function Ul(p,b){return b.some(x=>p.dependencyFiles.has(x)||p.entryFile===x||p.graph?.fileIndex.has(x))}function Jl(p){for(let b of p)a.add(b);c||N()||(c=(async()=>{t="building";let b=!1;try{for(;a.size>0;){if(N())return;await Qh(),await h.runExclusive(async()=>{if(d>0||N())return;let x=[...a];a.clear();let I=await Xl(x);if(I.length===0)return;let P=Un(I);for(let j of P){let q=i.get(j)?.composition;q&&r.emit({type:"graph-invalidated",composition:q})}let{rebuiltRoutes:T,failedRoutes:O}=await To(I,{changed:!0});for(let{documentChanged:j,composition:q,version:$}of T)r.emit({type:"graph-ready",composition:q,version:$}),j&&r.emit({type:"document-changed",composition:q,version:$});for(let{composition:j,message:q}of O)b=!0,r.emit({type:"graph-error",composition:j,message:q})})}}finally{c=null,t!=="disposed"&&(t=!b&&[...i.values()].some(x=>x.graph)?"ready":"idle"),a.size>0&&Jl([])}})())}async function Qh(){for(;d>0;)await new Promise(p=>setTimeout(p,0))}async function Xl(p){let b=[];for(let x of new Set(p)){let I=f.get(x);if(I===void 0){if(m.has(x)&&!await n.exists(x))continue;m.delete(x),b.push(x);continue}try{await n.readFile(x)!==I&&(m.delete(x),b.push(x))}catch(P){if(!yN(P))try{if(await n.exists(x))continue}catch{continue}m.add(x),b.push(x)}}return b}function zl(p){Nh(f,p);for(let b of p)b.exists===!1?m.add(b.file):m.delete(b.file)}function Wl(p){m.clear();for(let b of p)m.add(b)}async function Hl(p){let b=await Xl(p);if(b.length===0)return;let x=Un(b);for(let T of x){let O=i.get(T)?.composition;O&&r.emit({type:"graph-invalidated",composition:O})}let{rebuiltRoutes:I,failedRoutes:P}=await To(b,{changed:!0});for(let{documentChanged:T,composition:O,version:j}of I)r.emit({type:"graph-ready",composition:O,version:j}),T&&r.emit({type:"document-changed",composition:O,version:j});for(let{composition:T,message:O}of P)r.emit({type:"graph-error",composition:T,message:O})}async function qh(p,b){let x=zn(p,b);if(!x?.graph)return;let I=it(p)??p,P=x.graph.elements.get(I);P&&await Hl([P.sourceFile])}async function Gl(p){let b=new Set;if(p.target.kind==="node"){let x=zn(p.target.key,p.composition),I=it(p.target.key)??p.target.key,P=x?.graph?.elements.get(I);P&&b.add(P.sourceFile)}else if(p.target.kind==="route"){let x=i.get(o.resolveSelector(p.target.composition).key);x&&b.add(x.entryFile)}else if(p.target.kind==="page-unit"){let x=i.get(o.resolveSelector(p.target.composition).key);x&&b.add(x.entryFile)}else if(p.target.kind==="source-file")b.add(p.target.path);else if(p.target.kind==="source-batch")for(let x of p.target.paths)b.add(x);if(p.params.kind==="move-node"&&!("kind"in p.params.target)){let x=[p.params.target.parentKey,...p.params.target.relation==="before"||p.params.target.relation==="after"?[p.params.target.anchorKey]:[]];for(let I of x){let P=zn(I,p.composition),T=it(I)??I,O=P?.graph?.elements.get(T);O&&b.add(O.sourceFile)}}await Hl(b)}async function ey(p){if(p.params.kind!=="source-edit")return Ts(p,"invalid-params","source-edit requires source-edit params");for(let b of p.params.edits){let x=hN(b);if(!x.ok)return Ts(p,x.errorCode,x.message,x.details)}d+=1;try{let b=await iy(p.params.edits);if(!b.ok)return Ts(p,b.errorCode,b.message,b.details);await Gl(p);let x={operationId:p.id,kind:"source-edit",target:p.target,documentVersion:p.documentVersion,conflictPolicy:p.params.conflictPolicy,edits:p.params.edits.map(I=>I.operation==="delete"?{operation:"delete",file:I.path,baseContentHash:I.baseContentHash??null}:{operation:"upsert",file:I.path,baseContentHash:I.baseContentHash??null,content:I.content})};return await Xn({request:p,filePlan:x})}catch(b){return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:ee(p),error:{code:K.INTERNAL_ERROR,message:et(b)}}}finally{d-=1}}async function ty(p){if(p.target.kind!=="project"||p.params.kind!=="insert-page-resource")return le(p,K.INVALID_PARAMS,"insert-page-resource requires project target and matching params.");d+=1;try{let b=await Lo({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:[...p.params.artifact.components.flatMap(I=>I.materialization.files.map(P=>({path:P.pathTemplate,content:P.content}))),...p.params.artifact.pages.flatMap(I=>I.materialization.files.map(P=>({path:P.pathTemplate,content:P.content})))],exists:I=>n.exists(I),readFile:I=>n.readFile(I)});if(!b.ok)return le(p,K.MATERIALIZATION_REJECTED,b.message);let x=await Ya({artifact:p.params.artifact,exists:I=>n.exists(I)});return x.ok?await Xn({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:p.target,documentVersion:p.documentVersion,conflictPolicy:"overwrite",edits:x.files},output:{kind:"insert-page-resource",package_instance_id:x.packageInstanceId,pages:x.pages},historyPolicy:"none"}):le(p,x.code==="MATERIALIZATION_CONFLICT"?K.MATERIALIZATION_CONFLICT:K.MATERIALIZATION_REJECTED,x.message,x.path?{path:x.path}:void 0)}catch(b){return le(p,K.INTERNAL_ERROR,et(b))}finally{d-=1}}async function ny(p){if(p.target.kind!=="project"||p.params.kind!=="delete-page-source")return le(p,K.INVALID_PARAMS,"delete-page-source requires project target and matching params.");if(!n.listFiles)return le(p,K.PLAN_FAILED,"Complete project file listing is required for page deletion.");d+=1;try{let b=Vh(await n.listFiles({maxFiles:5e4,maxDepth:64}));if(b.truncated)return le(p,K.PLAN_FAILED,"Project file listing is incomplete; page deletion was refused.",{truncationReasons:b.truncated.reasons});let x=b.files.filter(({path:O})=>/\.(?:tsx?|jsx?)$/.test(O)),I=Object.fromEntries(await Promise.all(x.map(async({path:O})=>[O,await n.readFile(O)]))),P=mp({expectedUrlPath:p.params.expectedUrlPath,files:I});if(!P.ok)return le(p,P.code==="HOME_PAGE_LOCKED"?K.HOME_PAGE_LOCKED:P.code==="ROUTE_NOT_FOUND"?K.ROUTE_NOT_FOUND:K.PLAN_FAILED,P.message);let T=await Promise.all(P.edits.map(async O=>({...O,baseContentHash:ke(await n.readFile(O.file))})));return Xn({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:p.target,documentVersion:p.documentVersion,conflictPolicy:"compare-and-swap",edits:T},output:{kind:"delete-page-source",deleted_files:P.deletedFiles,updated_files:P.updatedFiles,preserved_shared_files:P.preservedSharedFiles,warnings:P.warnings},historyPolicy:"none"})}catch(b){return le(p,K.INTERNAL_ERROR,et(b))}finally{d-=1}}async function ry(p,b){if(p.kind!=="insert-child"&&p.kind!=="replace-node")return le(p,K.UNSUPPORTED_OPERATION,"Only page-unit insert-child and replace-node materialization are supported by this transaction.");if(p.params.kind!=="insert-child"&&p.params.kind!=="replace-node"||p.kind!==p.params.kind)return le(p,K.INVALID_PARAMS,"Page-unit materialization operation kind must match its params.");if(p.params.kind==="insert-child"){if(!("kind"in p.params.position)||p.params.position.kind!=="page-composition")return le(p,K.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.");if(p.params.position.documentVersion!==p.documentVersion)return le(p,K.VERSION_STALE,"Page-unit insert-child placement belongs to a different document version.")}let x=b.document,I=b.pageCompositionProjection;if(!x||x.pageComposition?.status!=="supported"||!I||I.status!=="supported")return le(p,K.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(p.documentVersion!==x.version||I.documentVersion!==x.version)return le(p,K.VERSION_STALE,`Document version ${p.documentVersion} is stale (current: ${x.version}).`);let P=p.params.node.kind==="component-call"?p.params.node.materialization:void 0;if(!P)return le(p,K.UNSUPPORTED_OPERATION,"Page-unit insertion currently requires a static materialization manifest.");let T=p.params.kind==="insert-child"?p.params.position:null,O=await Lo({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:P.files.map($=>({path:$.pathTemplate,content:$.content})),exists:$=>n.exists($),readFile:$=>n.readFile($)});if(!O.ok)return le(p,K.MATERIALIZATION_REJECTED,O.message);let j=await tN(n,Object.keys(P.projectDependencies??{})),q=await Nf({manifest:P,generatedRoot:"components/site/generated",controlledFiles:P.files.map($=>({pathTemplate:$.pathTemplate})),exists:$=>n.exists($),availableHostDependencies:j,commit:async $=>{let B=await n.readFile(b.entryFile),W=b.document,de=b.pageCompositionProjection;if(!W||W.pageComposition?.status!=="supported"||W.version!==p.documentVersion||!de||de.status!=="supported"||de.documentVersion!==W.version)return{ok:!0,data:le(p,K.VERSION_STALE,"The route changed before the page-unit insertion could commit.")};let ue=$.entry.path,be=fy($.instanceName),Ce,Pe=[];if(p.params.kind==="insert-child"){if(!T||!("kind"in T)||T.kind!=="page-composition")return{ok:!0,data:le(p,K.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.")};let ge=rc({routeId:b.routeId,entryFile:b.entryFile,currentDocumentVersion:W.version,expectedDocumentVersion:p.documentVersion,source:B,projection:de,placementKey:T.placementKey,component:{source:ue,exportName:$.entry.export.kind==="default"?"default":$.entry.export.name,localName:be}});if(!ge.ok)return{ok:!0,data:le(p,Os(ge.error.code),ge.error.message,{diagnostics:ge.error.diagnostics})};let Se=ge.plan.rewriteStep,Ae;switch(Se.kind){case"insert-root-expression":Ae=Di({source:B,locator:Se.locator,expectedSourceHash:Se.sourceHash,action:{kind:"insert",jsx:Se.node.jsx,placement:Se.placement,replaceOriginal:Se.replaceOriginal}});break;case"insert-child":Ae=Gn({source:B,locator:Se.parentLocator,node:Se.node,placement:Se.placement,...Se.anchorLocator?{anchorLocator:Se.anchorLocator}:{}});break;default:Ae={ok:!1,source:B,diagnostic:{code:"unsupported-syntax",message:`Unsupported route composition rewrite: ${String(Se)}`}}}if(!Ae.ok)return{ok:!0,data:le(p,K.AST_PARSE_ERROR,Ae.diagnostic.message)};Ce=Ae.source}else{let ge=oc({routeId:b.routeId,composition:b.composition,entryFile:b.entryFile,currentDocumentVersion:W.version,expectedDocumentVersion:p.documentVersion,source:B,projection:de,placementUnitKey:p.target.placementUnitKey,operation:"replace-node"});if(!ge.ok)return{ok:!0,data:le(p,Os(ge.error.code),ge.error.message,{diagnostics:ge.error.diagnostics})};let Se=ge.plan.rewriteStep,Ae;switch(Se.kind){case"replace-root-expression":Ae=Di({source:B,locator:Se.locator,expectedSourceHash:Se.sourceHash,action:{kind:"replace",jsx:`<${be} />`}});break;case"replace-node":Ae=ti({source:B,locator:Se.locator,node:{jsx:`<${be} />`}});break;default:Ae={ok:!1,source:B,diagnostic:{message:`Unsupported page-unit replacement rewrite: ${Se.kind}`}}}if(!Ae.ok)return{ok:!0,data:le(p,K.AST_PARSE_ERROR,Ae.diagnostic.message)};let en=await Yl({routeState:b,placementUnitKey:p.target.placementUnitKey,source:B,mutatedSource:Ae.source});Ce=en.source,Pe=await Promise.all(en.files.map(async He=>({operation:"delete",file:He,baseContentHash:ke(await n.readFile(He))})))}let M=Qn({source:Ce,moduleSpecifier:y(b.entryFile,ue),imports:$.entry.export.kind==="default"?[{kind:"default",local:be}]:[{kind:"named",imported:$.entry.export.name,local:be}]});if(!M.ok)return{ok:!0,data:le(p,K.AST_PARSE_ERROR,M.diagnostic.message)};let U=$.files.map(ge=>({operation:"create-only",file:ge.path,content:ge.content})),ie=[{operation:"upsert",file:b.entryFile,content:M.source,baseContentHash:ke(B)},...U,...Pe];d+=1;try{let ge=await Xn({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:{kind:"source-file",path:b.entryFile},documentVersion:p.documentVersion,conflictPolicy:"compare-and-swap",edits:ie}});return!ge.ok&&ge.error?.message.includes("MATERIALIZATION_INSTANCE_CONFLICT")?{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:ge.error?.message??"Static prefab instance conflicted during commit."}}:{ok:!0,data:ge}}finally{d-=1}}});return q.ok?q.data:le(p,q.error.code==="MATERIALIZATION_INSTANCE_CONFLICT"?K.MATERIALIZATION_CONFLICT:K.MATERIALIZATION_REJECTED,q.error.message,{materializationCode:q.error.code})}async function oy(p,b){if(p.kind!=="move-node"&&p.kind!=="remove-node")return le(p,K.UNSUPPORTED_OPERATION,"Only page-unit move-node and remove-node are currently supported by the page composition transaction.");let x=b.document,I=b.pageCompositionProjection;if(!x||x.pageComposition?.status!=="supported"||!I||I.status!=="supported")return le(p,K.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(p.documentVersion!==x.version||I.documentVersion!==x.version)return le(p,K.VERSION_STALE,`Document version ${p.documentVersion} is stale (current: ${x.version}).`);let P=await n.readFile(b.entryFile),T=oc({routeId:b.routeId,composition:b.composition,entryFile:b.entryFile,currentDocumentVersion:x.version,expectedDocumentVersion:p.documentVersion,source:P,projection:I,placementUnitKey:p.target.placementUnitKey,operation:p.kind,targetPlacement:p.kind==="move-node"&&p.params.kind==="move-node"&&"kind"in p.params.target&&p.params.target.kind==="page-composition"?p.params.target:void 0});if(!T.ok)return le(p,Os(T.error.code),T.error.message,{diagnostics:T.error.diagnostics});let O=T.plan.rewriteStep,j;switch(O.kind){case"move-node":j=Yn({source:P,locator:O.locator,targetParentLocator:O.targetParentLocator,placement:O.placement,...O.anchorLocator?{anchorLocator:O.anchorLocator}:{}});break;case"remove-node":j=Hn({source:P,locator:O.locator});break;case"remove-root-expression":j=Di({source:P,locator:O.locator,expectedSourceHash:O.sourceHash,action:{kind:"remove"}});break;default:j={ok:!1,source:P,diagnostic:{message:`Unsupported page-unit mutation rewrite: ${O.kind}`}}}if(!j.ok)return le(p,K.AST_PARSE_ERROR,j.diagnostic.message);let q=j.source,$=[];if(p.kind==="remove-node"){let W=await Yl({routeState:b,placementUnitKey:p.target.placementUnitKey,source:P,mutatedSource:q});q=W.source,$=await Promise.all(W.files.map(async de=>({operation:"delete",file:de,baseContentHash:ke(await n.readFile(de))})))}let B=[{operation:"upsert",file:b.entryFile,content:q,baseContentHash:ke(P)},...$];d+=1;try{return await Xn({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:{kind:"source-file",path:b.entryFile},documentVersion:p.documentVersion,conflictPolicy:"compare-and-swap",edits:B}})}finally{d-=1}}async function Yl(p){let b={source:p.mutatedSource,files:[]},x=p.routeState.graph,I=p.routeState.pageCompositionProjection;if(!x||!I||I.status!=="supported"||!n.listFiles)return b;let T=I.placementUnitByKey.get(p.placementUnitKey)?.sourceRange;if(!T)return b;let O=[...x.elements.values()].find(M=>M.sourceFile===p.routeState.entryFile&&M.importedFrom&&v(M.sourceRange,T));if(!O?.importedFrom||!O.exportName)return b;let j=E(O.importedFrom),q="components/site/generated/";if(!j.startsWith(q))return b;let $=j.slice(q.length).split("/")[0];if(!$||!/-[0-9a-f]{8}$/i.test($))return b;let B=`${q}${$}`;if([...x.elements.values()].filter(M=>M.sourceFile===p.routeState.entryFile&&E(M.importedFrom??"")===j).length!==1)return b;let de=await n.listFiles({maxFiles:5e3,maxDepth:32}),ue=Array.isArray(de)?de:de.files;if(!Array.isArray(de)&&de.truncated)return b;let be=ue.map(({path:M})=>M).filter(M=>M===B||M.startsWith(`${B}/`));if(be.length===0||!be.includes(j))return b;for(let{path:M}of ue)if(!(M===p.routeState.entryFile||M===B||M.startsWith(`${B}/`)))try{if((await n.readFile(M)).includes($))return b}catch{return b}let Ce=y(p.routeState.entryFile,j),Pe=qn({source:p.mutatedSource,moduleSpecifier:Ce,imports:O.exportName==="default"?[{kind:"default"}]:[{kind:"named",imported:O.exportName}]});return Pe.ok?Pe.source.includes($)?{source:Pe.source,files:[]}:{source:Pe.source,files:be.sort((M,U)=>M.localeCompare(U))}:b}async function iy(p){if(n.getFileInfo){for(let T of p)if(await n.exists(T.path)&&await n.getFileInfo(T.path)===null)return{ok:!1,errorCode:"invalid-params",message:`Source edit path must resolve to a regular non-symbolic-link file: ${T.path}`,details:{path:T.path}}}for(let T of p){if(T.operation!=="upsert"||!/^(?:src\/)?app\/globals\.css$/i.test(T.path))continue;let O=await n.exists(T.path)?await Qs(n,T.path):null;if(O?.ok){let j=Jw(O.content,T.content);if(!j.ok)return{ok:!1,errorCode:"invalid-params",message:j.message,details:{path:T.path,code:j.code}}}}let b=sy(p);if(b.length===0)return{ok:!0};let x=mN(n,p),I=new Map,P=(T,O)=>{let j=I.get(T);if(j?.source===O)return j.result;let q=Ut(T,O);return I.set(T,{source:O,result:q}),q};try{for(let T of b){let O=i.get(T);O&&await ce(O.entryFile,await x.readFile(O.entryFile),x,{validationOnly:!0,parseModule:P})}}catch(T){return{ok:!1,errorCode:"ast-error",message:`Source edit preflight failed: ${et(T)}`,details:{compositionKeys:b}}}return{ok:!0}}function sy(p){return p.map(x=>x.path).some(jh)?[...i.keys()]:[]}function Ts(p,b,x,I){let P=Po(b);return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:ee(p),error:{code:P,message:x,...I?{details:I}:{}}}}async function Fs(p){let b=[];for(let x of new Set(p))b.push(await ay(x));return b}async function ay(p){if(!(typeof n.exists=="function"?await n.exists(p):!0))return{file:p,content:"",version:Math.max(0,L(p)),exists:!1};let x=await n.readFile(p);return{file:p,content:x,version:Math.max(1,L(p)),exists:!0,sha256:ke(x)}}async function Zl(p,b,x,I){if(!e.historyStore)return null;let P=new Map(b.map(j=>[j.file,j])),T=new Map(x.map(j=>[j.file,j])),O=[...new Set([...P.keys(),...T.keys()])].sort().map(j=>{let q=P.get(j),$=T.get(j);return{path:j,preDigest:q?.exists===!1||!q?null:ke(q.content),postDigest:$?.exists===!1||!$?null:ke($.content)}});return{schemaVersion:2,transactionId:`${p}:${I.expectedIndexDigest}`,operationId:p,phase:"prepared",historyTransition:I,files:O}}async function Ql(p){return!p||!e.historyStore||await e.historyStore.writeTransactionJournal(p),p}async function Jn(p){p&&e.historyStore&&await e.historyStore.clearTransactionJournal(p.transactionId)}async function _s(p,b){let x=[];try{for(let I of p)await ql(I),typeof n.bumpVersion=="function"&&n.bumpVersion(I.file),x.push(I.file)}catch(I){let P=await cy(b.filter(T=>x.includes(T.file)));return P.ok?{ok:!1,reason:`Writeback failed and committed files were restored: ${et(I)}`,rolledBack:!0}:{ok:!1,reason:`Writeback failed, then rollback failed for ${P.failedFiles.join(", ")}: ${et(I)}`,rolledBack:!1}}return{ok:!0,snapshots:p.map(ly)}}async function ql(p){if(p.exists===!1){await n.deleteFile(p.file);return}await n.writeFile(p.file,p.content)}async function cy(p){let b=[];for(let x of p)try{await ql(x),typeof n.bumpVersion=="function"&&n.bumpVersion(x.file)}catch{b.push(x.file)}return b.length===0?{ok:!0}:{ok:!1,failedFiles:b}}function ly(p){let b=p.exists!==!1;return{file:p.file,content:b?p.content:"",version:p.version,exists:b,...b?{sha256:ke(p.content)}:{}}}async function Xn(p){return h.runExclusive(()=>uy(p))}async function uy(p){let b=p.filePlan.edits.map(M=>M.file),x=o.resolveSelector(p.request.composition),I=x.context,P=p.historyPolicy==="none"?void 0:{initiatingComposition:I,affectedCompositions:Gh(b)},T=await Fs(b),O=new Map(T.filter(M=>M.exists!==!1).map(M=>[M.file,M.content])),j=tu(),q=new Map(f),$=new Set(m),B=new Set([...i.values()].filter(M=>p.filePlan.edits.some(U=>U.operation==="delete"&&U.file===M.entryFile)).map(M=>M.key)),W=p.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:ke(M.content)}),de={operationId:p.filePlan.operationId,intents:p.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})},ue=null,be=!1,Ce=await Ss({overlay:O,exists:M=>n.exists(M),plan:de,buildCandidate:async({plan:M})=>({plan:M}),prepareHistory:async()=>{let M=p.historyPolicy==="none"?null:await l.prepareAppend({composition:o.resolveSelector(p.request.composition).context,operationId:p.request.id,kind:p.request.kind,target:p.request.target,preSnapshots:T,postSnapshots:W,...p.selectionRef?{selectionRef:p.selectionRef}:{},...p.output?{output:p.output}:{},...P?{provenance:P}:{}}),U=M?.historyTransition?M.historyTransition:e.historyStore?qw(await e.historyStore.readIndex()):null;if(e.historyStore&&!U)throw new Error("Durable history did not provide an exact index transition.");return ue=await Zl(p.request.id,T,W,U),ue=await Ql(ue),{history:M,historyTransition:U}},reverify:async()=>{},writeCandidate:async()=>{let M=await u.executeFilePlan(p.filePlan);if(!M.ok)throw new Cs(M);return{postSnapshots:await Fs(M.affectedFiles),affectedFiles:M.affectedFiles,internalResultVersion:M.resultVersion}},validateCandidate:async({candidate:M,receipt:U})=>{let ie=await To(U.affectedFiles,{changed:!0,minimumVersion:U.internalResultVersion,publish:!1,excludedCompositionKeys:B});if(ie.failedRoutes.length>0)throw new Vn(ie.failedRoutes);let ge=ru(j,ie.candidateRouteStates??[]),Se=nu(ge,x.key);return{...M,rebuild:ie,routeSnapshots:ge,resultVersion:Se,...Oh(p.selectionRef,ge.map(Ae=>Ae.state.document))?{selectionRef:Oh(p.selectionRef,ge.map(Ae=>Ae.state.document))}:{}}},publishCandidate:async({candidate:M,history:U,receipt:ie})=>{U?.history&&(await l.publishPrepared(U.history),be=!0);let ge=M.resultVersion??ie.internalResultVersion;return{composition:I,requestId:p.request.id,kind:p.request.kind,target:p.request.target,ok:!0,resultVersion:ge,affectedFiles:ie.affectedFiles,fileChanges:ie.postSnapshots.map(Se=>({path:Se.file,operation:Se.exists===!1?"delete":"upsert"})),...p.output?{output:p.output}:{},...M.selectionRef?{selectionRef:M.selectionRef}:{}}},swapCandidate:({candidate:M,receipt:U})=>{M.routeSnapshots&&Fo(M.routeSnapshots),M.rebuild?.candidateSourceCache&&Sr(f,M.rebuild.candidateSourceCache),zl(U.postSnapshots)},finalizeCandidate:async()=>{await Jn(ue);for(let M of B)i.delete(M)},emitCommitted:({candidate:M,published:U})=>{As(U,M.rebuild??{rebuiltRoutes:[],failedRoutes:[]})},rollbackCandidate:async({history:M,receipt:U})=>{if(be)throw new Error("history was published before transaction finalization failed");if(U){let ie=await _s(T,U.postSnapshots);if(!ie.ok)throw new Error(ie.reason)}Fo(j),Sr(f,q),Wl($),M?.history&&await l.discardPrepared?.(M.history),await Jn(ue)}});if(Ce.ok)return Ce.published;if(Ce.stage==="precheck"||Ce.stage==="build")try{await Jn(ue)}catch(M){let U=await _o(et(M));return le(p.request,U,"Unable to clear an uncommitted transaction journal.")}if(Ce.recoveryRequired){let M=await _o(Ce.reason);return le(p.request,M===K.RECOVERY_PERSIST_FAILED?M:K.ROLLBACK_FAILED,Ce.reason)}let Pe=Ce.error;return Pe instanceof Cs?{...le(p.request,Po(Pe.result.errorCode),Pe.result.reason),...Pe.result.affectedFiles?{affectedFiles:Pe.result.affectedFiles}:{}}:Pe instanceof Vn?le(p.request,K.ROUTE_REBUILD_FAILED,`Route rebuild failed and source was rolled back: ${Bl(Pe.failedRoutes)}`,{failedRoutes:Pe.failedRoutes}):le(p.request,iu(Ce.stage),et(Pe))}async function eu(p){return h.runExclusive(async()=>{let b=p==="undo"?await l.prepareUndo():await l.prepareRedo();return b?dy(p,b):{composition:o.entries[0].context,requestId:p,kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:o.initialVersions.get(o.entries[0].key)??0,error:{code:K.INTERNAL_ERROR,message:p==="undo"?"Nothing to undo":"Nothing to redo"}}})}async function dy(p,b){let x=b.entry,I=p==="undo"?x.preSnapshots:x.postSnapshots,P=p==="undo"?x.postSnapshots:x.preSnapshots,T=I.map(U=>U.file),{context:O,key:j}=Zh(x,T),q=await Fs(T),$=new Map(q.filter(U=>U.exists!==!1).map(U=>[U.file,U.content])),B=me(j),W=tu(),de=new Map(f),ue=new Set(m),be=null,Ce=!1,Pe,M=await Ss({overlay:$,plan:{operationId:`${p}:${x.operationId}`,intents:I.map(U=>U.exists===!1?{kind:"delete",path:U.file}:{kind:"upsert",path:U.file,content:U.content})},buildCandidate:async()=>({}),prepareHistory:async()=>(be=await Zl(`${p}:${x.operationId}`,q,I,b.historyTransition),be=await Ql(be),b),reverify:async()=>{},writeCandidate:async()=>{let U=await _s(I,P);if(!U.ok)throw new Error(U.reason);return{snapshots:U.snapshots}},validateCandidate:async({candidate:U})=>{Pe=Yh(x,T);let ie=await To(T,{changed:!0,minimumVersion:B+1,publish:!1,affectedCompositionKeys:Pe});if(ie.failedRoutes.length>0)throw new Vn(ie.failedRoutes);let ge=ru(W,ie.candidateRouteStates??[]),Se=nu(ge,j);return{...U,rebuild:ie,routeSnapshots:ge,resultVersion:Se}},publishCandidate:async({candidate:U,history:ie,receipt:ge})=>{if(!ie)throw new Error("history cursor intent is missing");await l.publishPrepared(ie),Ce=!0;let Se=U.resultVersion??B+1;return{composition:O,requestId:p,kind:x.kind,target:x.target,ok:!0,resultVersion:Se,affectedFiles:T,fileChanges:ge.snapshots.map(Ae=>({path:Ae.file,operation:Ae.exists===!1?"delete":"upsert"})),...x.output?{output:x.output}:{}}},swapCandidate:({candidate:U,receipt:ie})=>{U.routeSnapshots&&Fo(U.routeSnapshots),U.rebuild?.candidateSourceCache&&Sr(f,U.rebuild.candidateSourceCache),zl(ie.snapshots)},finalizeCandidate:async()=>{await Jn(be)},emitCommitted:({candidate:U,published:ie})=>As(ie,U.rebuild??{rebuiltRoutes:[],failedRoutes:[]}),rollbackCandidate:async({history:U,receipt:ie})=>{if(Ce)throw new Error("history cursor was published before transaction finalization failed");if(ie){let ge=await _s(P,ie.snapshots);if(!ge.ok)throw new Error(ge.reason)}Fo(W),Sr(f,de),Wl(ue),U&&await l.discardPrepared?.(U),await Jn(be)}});if(M.ok)return M.published;if(M.stage==="precheck"||M.stage==="build")try{await Jn(be)}catch(U){let ie=await _o(et(U));return{composition:O,requestId:p,kind:x.kind,target:x.target,ok:!1,resultVersion:B,error:{code:ie,message:"Unable to clear an uncommitted transaction journal."}}}if(M.recoveryRequired){let U=await _o(M.reason);return{composition:O,requestId:p,kind:x.kind,target:x.target,ok:!1,resultVersion:B,affectedFiles:T,error:{code:U===K.RECOVERY_PERSIST_FAILED?U:K.ROLLBACK_FAILED,message:M.reason}}}return{composition:O,requestId:p,kind:x.kind,target:x.target,ok:!1,resultVersion:B,affectedFiles:T,error:{code:M.error instanceof Vn?K.ROUTE_REBUILD_FAILED:iu(M.stage),message:et(M.error),...M.error instanceof Vn?{details:{failedRoutes:M.error.failedRoutes}}:{}}}}function tu(){return[...i.values()].map(p=>({composition:p.composition,key:p.key,routeId:p.routeId,state:{...p,dependencyFiles:new Set(p.dependencyFiles),fileVersions:new Map(p.fileVersions)}}))}function nu(p,b){return p.find(I=>I.key===b)?.state.graph?.version??o.initialVersions.get(b)??0}function ru(p,b){let x=new Map(p.map(I=>[I.key,I]));for(let I of b)x.set(I.key,I);return[...x.values()]}function Fo(p){for(let b of i.values())R(b);for(let b of p){let x={...b.state,dependencyFiles:new Set(b.state.dependencyFiles),fileVersions:new Map(b.state.fileVersions)};i.set(b.key,x),A(x,x.dependencyFiles)}}async function Ms(p){let b=i.get(p);if(!b)throw new Error(`Composition not found: ${p}`);if(b.graph)return;let x=await n.readFile(b.entryFile);await _e(p,x)}function zn(p,b){let x=i.get(o.resolveSelector(b).key)??null;return!x||!ou(x,p)?null:x}function ou(p,b){if(p.documentIndex?.entriesByKey.has(b)||p.graph?.elements.has(b))return!0;let x=it(b);return x&&x!==b?p.graph?.elements.has(x)===!0:!1}function le(p,b,x,I){return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:ee(p),error:{code:b,message:x,...I?{details:I}:{}}}}function iu(p){return p==="validate"?K.ROUTE_REBUILD_FAILED:p==="publish"?K.HISTORY_COMMIT_FAILED:K.WRITE_IO_ERROR}async function _o(p){if(g=!0,!l.markRecoveryRequired)return K.RECOVERY_REQUIRED;try{return await l.markRecoveryRequired(p),K.RECOVERY_REQUIRED}catch{return K.RECOVERY_PERSIST_FAILED}}function fy(p){let x=p.split(/[^a-zA-Z0-9]+/).filter(Boolean).map(I=>I.charAt(0).toUpperCase()+I.slice(1)).join("").replace(/^[^a-zA-Z_$]+/,"");return x?`Prefab${x}`:"GeneratedPrefab"}function Os(p){return p==="VERSION_STALE"?K.VERSION_STALE:p==="CROSS_PAGE_MOVE_UNSUPPORTED"?K.CROSS_PAGE_MOVE_UNSUPPORTED:K.UNSUPPORTED_OPERATION}async function su(p){if(p.target.kind==="route"){let x=i.get(o.resolveSelector(p.target.composition).key)??null;return x?(x.graph||await Ms(x.key),x):le(p,K.ROUTE_NOT_FOUND,"Composition not found for route target.")}if(p.target.kind==="page-unit"){let x=i.get(o.resolveSelector(p.target.composition).key)??null;return x?(x.graph||await Ms(x.key),x):le(p,K.ROUTE_NOT_FOUND,"Composition not found for page-unit target.")}if(p.target.kind!=="node")return le(p,K.UNSUPPORTED_OPERATION,`${p.kind} source target execution is not implemented yet.`);let b=i.get(o.resolveSelector(p.composition).key)??null;return b?(b.graph||await Ms(b.key),ou(b,p.target.key)?b:le(p,K.NODE_NOT_FOUND,`Target key not found: ${p.target.key}`)):le(p,K.ROUTE_NOT_FOUND,"Composition not found for node target.")}return{get status(){return t},dispose(){t="disposed",a.clear(),i.clear(),s.clear(),f.clear(),m.clear()},registerComposition(p,b){let x=o.register({context:p,entryFile:b}),I=i.get(x.key);if(I?.entryFile===b)return;I&&R(I);let P=Mh(x.context,b);i.set(x.key,P),A(P,P.dependencyFiles),r.emit({type:"graph-invalidated",composition:x.context})},unregisterComposition(p){let b=o.resolveSelector(p),x=i.get(b.key);x&&(R(x),i.delete(b.key),o.unregister(b.key),i.size===0&&(t="idle"),r.emit({type:"graph-invalidated",composition:b.context}))},getCompositionEntryFiles(){return[...i.values()].map(p=>p.entryFile)},getCompositionContext(p){return o.resolveSelector(p).context},async initializeComposition(p){let b=o.resolveSelector(p),x=i.get(b.key);if(!x)throw new Error(`Composition not registered: ${b.key}`);if(x.graph)t="ready";else{t="building";try{let I=await n.readFile(x.entryFile);await _e(b.key,I),t="ready",r.emit({type:"graph-ready",composition:b.context,version:i.get(b.key)?.graph?.version??0})}catch(I){throw t="idle",r.emit({type:"graph-error",composition:b.context,message:et(I)}),I}}},getDocument(p){let b=o.resolveSelector(p),x=i.get(b.key);if(!x)throw new Error(`Composition not registered: ${b.key}`);if(!x.document)throw new Error(`Composition not built: ${b.key}`);return x.document},async getHistoryStatus(){await S;let p=await l.getStatus?.();return p?{...p,recoveryRequired:g}:{canUndo:!1,canRedo:!1,undoDepth:0,redoDepth:0,recoveryRequired:g}},getObjectEditContext(p,b,x){let I=zn(p,b),P=it(p)??p;if(I?.graph&&I.topology&&I.capabilities&&I.detailProjections){let T=I.detailProjections.get(P);if(T){let O=I.graph.elements.get(P);if(!O)throw new Error(`Key not found: ${p}`);let j=sN(p,P,x),q=new Map;if(T.isRepeat&&j?.instanceIndex!==void 0)for(let W of O.attributes??[])q.set(W.name,fl({file:O.sourceFile,source:f.get(O.sourceFile)??"",element:O,propertyName:W.name,selectionRef:j,graph:I.graph,sources:f}));let $=Yg({element:O,graph:I.graph,source:f.get(O.sourceFile),documentVersion:I.graph.version,selectionRef:x,isRepeat:T.isRepeat,propertyProvenance:T.propertyProvenances,repeatTargets:q}),B=qg(P,I.graph,I.topology,I.capabilities,T.textSources,T.provenances,T.dynamicData,$);return p===P?B:Ch(B,p,I.document??null,I.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${p}`)},getRenderDetail(p,b){let x=zn(p,b),I=it(p)??p;if(x?.graph&&x.topology&&x.capabilities&&x.detailProjections){let P=x.detailProjections.get(I);if(P){let T=Qg(I,x.graph,x.topology,x.capabilities,P.textSources,P.writeTarget,P.provenances,P.conditional,P.componentSemantic,P.styleSource,P.dynamicData);return p===I?T:Ih(T,p,x.document??null,x.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${p}`)},getClassNameSource(p,b){let x=zn(p,b),I=it(p)??p;if(!x?.graph)throw new Error(`Key not found: ${p}`);let P=x.graph.elements.get(I);if(!P)throw new Error(`Key not found: ${p}`);let T=f.get(P.sourceFile);if(T===void 0)throw new Error(`Source not loaded: ${P.sourceFile}`);return ya({key:I,route:{composition:x.composition,routeId:x.routeId,graph:x.graph,source:T}})},refreshSourceForKey:qh,async execute(p){if(await S,g)return le(p,K.RECOVERY_REQUIRED,"The edit engine requires explicit recovery before accepting mutations.");if(p.kind==="source-edit")return ey(p);if(p.kind==="insert-page-resource")return ty(p);if(p.kind==="delete-page-source")return ny(p);let b=await su(p);if("ok"in b)return b;await Gl(p);let x=await su(p);if("ok"in x)return x;let I=x;if(p.target.kind==="page-unit"){let B=p;return p.kind==="insert-child"||p.kind==="replace-node"?ry(B,I):p.kind==="move-node"||p.kind==="remove-node"?oy(B,I):le(p,K.UNSUPPORTED_OPERATION,"Only page-unit insert-child, replace-node, move-node, and remove-node are currently supported by the page composition transaction.")}let T=p.params,O=p.target.kind==="node"?p.target.key:null;if(T.kind==="move-node"&&"kind"in T.target&&T.target.kind==="source-sibling"){let B=T.target,W=O?I.document?.entries.find(U=>U.key===O):null,de=I.document?.entries.find(U=>U.key===B.anchorKey),ue=W?.pageCompositionActionScope,be=ue?.kind==="source-siblings"?ue.siblingKeys:null,Ce=be?.indexOf(W?.key??"")??-1,Pe=be?.indexOf(B.anchorKey)??-1,M=B.relation==="before"?Ce-1:Ce+1;if(!W||!de||!be||Ce<0||Pe!==M||de.pageCompositionActionScope?.kind!=="source-siblings"||de.pageCompositionActionScope.siblingKeys.length!==be.length||de.pageCompositionActionScope.siblingKeys.some((U,ie)=>U!==be[ie])||!W.operationSummary.canMove)return le(p,K.INVALID_TARGET,"Source sibling move is unavailable because the current source sibling scope or adjacent anchor no longer matches.")}if(!I.graph||!I.topology||!I.capabilities)return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:ee(p),error:{code:p.target.kind==="route"?K.ROUTE_NOT_FOUND:K.NODE_NOT_FOUND,message:p.target.kind==="route"?"Composition not ready for route target.":p.target.kind==="node"?`Target key not found: ${p.target.key}`:`${p.kind} source target execution is not implemented yet.`}};let j=IN(I,I.graph,I.capabilities,f,i),q=await new os(j).plan(p);if(!q.ok)return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:ee(p),error:{code:Po(q.errorCode),message:q.reason}};let $=q.plan;if($.steps.length===0)return p.kind==="set-props"?{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!0,resultVersion:ee(p),affectedFiles:[]}:{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:ee(p),error:{code:K.PLAN_FAILED,message:"Planner could not generate a valid execution plan"}};d+=1;try{if($.steps.some(W=>W.type==="invoke-external-adapter")){let W=await u.execute($);if(!W.ok)return le(p,Po(W.errorCode),W.reason);let de={composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!0,resultVersion:Math.max(ee(p),W.resultVersion),affectedFiles:W.affectedFiles,...W.selectionRef?{selectionRef:W.selectionRef}:{}};return As(de,{rebuiltRoutes:[],failedRoutes:[]}),de}let B=await u.prepareRewritePlan($);return B.ok?await Xn({request:p,filePlan:B.filePlan,...B.selectionRef?{selectionRef:B.selectionRef}:{}}):le(p,Po(B.errorCode),B.reason)}catch(B){return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:ee(p),error:{code:K.INTERNAL_ERROR,message:et(B)}}}finally{d-=1}},async undo(p){if(await S,g)return{composition:o.entries[0].context,requestId:"undo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:me(o.entries[0].key),error:{code:K.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting undo."}};d+=1;try{return await eu("undo")}finally{d-=1}},async redo(p){if(await S,g)return{composition:o.entries[0].context,requestId:"redo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:me(o.entries[0].key),error:{code:K.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting redo."}};d+=1;try{return await eu("redo")}finally{d-=1}},notifyFileChanged(p){Jl([p])},getAffectedCompositions(p){return Hh(p)},subscribe(p){return r.subscribe(p)}}}function yN(e){return e instanceof Error&&"code"in e&&(e.code==="ENOENT"||e.code==="ENOTDIR")}function xN(e,t,n,r){let o=new Map,i=new Map,s=(f,m,d)=>{let g=f.get(m)??new Set,h=g.size;return g.add(d),f.set(m,g),g.size!==h},a=(f,m)=>{if(!f.importedFrom)return!1;if(f.exportName==="default")return s(i,f.importedFrom,m);let d=s(o,`${f.importedFrom}#${f.tag}`,m);return f.exportName&&f.exportName!==f.tag&&(d=s(o,`${f.importedFrom}#${f.exportName}`,m)||d),d},c=f=>o.get(`${f.sourceFile}#${f.componentName}`)??i.get(f.sourceFile);for(let f of t.elements.values()){if(f.sourceFile!==n.entryFile||!f.importedFrom||!/^[A-Z]/.test(f.tag))continue;let m=n.placements.find(g=>g.members.some(h=>h.sourceRange!==null&&Ao(f.sourceRange,h.sourceRange)));if(!m)continue;let d=m.placementUnitKey;a(f,d)}let l=!0;for(;l;){l=!1;for(let f of t.elements.values()){if(f.sourceFile===n.entryFile||!f.importedFrom||!/^[A-Z]/.test(f.tag))continue;let m=c(f);if(m)for(let d of m)l=a(f,d)||l}}let u=n.placements.find(f=>f.placementKey===n.container.placementKey&&f.relation==="append");for(let f of e.entries){let m=it(f.key)??f.key,d=t.elements.get(f.key)??t.elements.get(m);if(!d)continue;if(d.sourceFile===n.entryFile){if(n.container.sourceRange&&Ao(d.sourceRange,n.container.sourceRange)&&u){f.pageCompositionUnitKey=u.placementUnitKey;continue}let S=n.placements.find(E=>E.members.some(y=>y.sourceRange!==null&&(Ao(d.sourceRange,y.sourceRange)||kN(y.sourceRange,d.sourceRange))));if(S){f.pageCompositionUnitKey=S.placementUnitKey;continue}}let g=o.get(`${d.sourceFile}#${d.componentName}`);if(g){g.size===1&&(f.pageCompositionUnitKey=g.values().next().value);continue}let h=i.get(d.sourceFile);h?.size===1&&(f.pageCompositionUnitKey=h.values().next().value)}bN(e,t,n,r)}function bN(e,t,n,r){let o=new Map(e.entries.map(m=>[m.key,m])),i=e.entries.filter(m=>{let d=m.pageCompositionUnitKey;return d?m.parentKey?o.get(m.parentKey)?.pageCompositionUnitKey!==d:!0:!1}),s=new Map,a=(m,d)=>{s.set(m,Math.min(2,(s.get(m)??0)+d))},c=m=>n.placements.some(d=>d.members.some(g=>g.sourceRange!==null&&Ao(m.sourceRange,g.sourceRange)));for(let m of t.elements.values())m.sourceFile!==n.entryFile||!m.importedFrom||!/^[A-Z]/.test(m.tag)||!c(m)||a(`${m.importedFrom}#${m.exportName??m.tag}`,1);let l=[...t.elements.values()].flatMap(m=>m.sourceFile!==n.entryFile&&m.importedFrom&&/^[A-Z]/.test(m.tag)?[{owner:`${m.sourceFile}#${m.componentName}`,ownerDefault:`${m.sourceFile}#default`,target:`${m.importedFrom}#${m.exportName??m.tag}`}]:[]);for(let m=0;m<=l.length;m+=1){let d=!1;for(let g of l){let h=s.get(g.owner)??s.get(g.ownerDefault)??0;if(!h)continue;let S=s.get(g.target)??0,E=Math.min(2,S+h);E!==S&&(s.set(g.target,E),d=!0)}if(!d)break}let u=m=>s.get(`${m.sourceFile}#${m.componentName}`)??s.get(`${m.sourceFile}#default`)??0;for(let m of i){m.pageCompositionActionScope={kind:"unavailable"};let d=t.elements.get(m.key);m.pageCompositionUnitKey&&d?.sourceFile===n.entryFile&&(m.pageCompositionActionScope={kind:"route-unit"})}let f=new Map;for(let m of i){let d=t.elements.get(m.key);if(!d||d.sourceFile===n.entryFile||m.key!==(it(m.key)??m.key))continue;let g=r.get(d.sourceFile);if(!g)continue;let h=se(g.ast,{kind:"jsx-node",strategy:"source-range",sourceRange:d.sourceRange});if(!h.ok||!h.match.path.isJSXElement())continue;let S=h.match.path,E=S.parentPath;if(!E||!E.isJSXFragment()&&!(E.isJSXElement()&&Me(E))){u(d)===1&&Dh(S)&&(m.pageCompositionActionScope={kind:"route-unit"});continue}if(!Dh(E))continue;let y=f.get(E.node)??[];y.push({entry:m,element:d,parentPath:E}),f.set(E.node,y)}for(let m of f.values()){let d=m[0];if(!d)continue;let g=d.entry.pageCompositionUnitKey,h=[],S=!!(g&&u(d.element)===1);for(let y of d.parentPath.node.children){if(SN(y))continue;if(!EN(y)){S=!1;break}let v=[...t.elements.values()].find(N=>N.sourceFile===d.element.sourceFile&&N.componentName===d.element.componentName&&Ao(N.sourceRange,vN(y))),C=v?o.get(v.identity.key):null;if(!v||!C||C.parentKey||C.pageCompositionUnitKey!==g||u(v)!==1){S=!1;break}h.push(C)}if(!S||h.length!==m.length||m.some(({entry:y})=>!h.some(v=>v.key===y.key)))continue;if(h.length===1){h[0].pageCompositionActionScope={kind:"route-unit"};continue}if(h.length<2)continue;let E=h.map(y=>y.key);for(let y of h)y.pageCompositionActionScope={kind:"source-siblings",siblingKeys:E}}}function Dh(e){let t=e.parentPath;return!!(t?.isReturnStatement?.()||t?.isArrowFunctionExpression?.()&&t.node.body===e.node)}function SN(e){return!!(e&&typeof e=="object"&&e.type==="JSXText"&&!(e.value??"").trim())}function EN(e){return!!(e&&typeof e=="object"&&e.type==="JSXElement")}function vN(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 Ao(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function kN(e,t){return Bh(e.startLine,e.startColumn,t.startLine,t.startColumn)<=0&&Bh(e.endLine,e.endColumn,t.endLine,t.endColumn)>=0}function Bh(e,t,n,r){return e!==n?e-n:t-r}function IN(e,t,n,r,o){let i=new Map,s=new Map,a=(u,f)=>{if(s.has(u))return;s.set(u,f);let m=t.elements.get(u);for(let d of m?.childKeys??[])a(d,f)};for(let u of t.regions)if(u.kind==="repeat-region")for(let f of u.childKeys)i.set(f,u.ownerKey),a(f,u.ownerKey);return{getNode(u){let f=c(u),m=t.elements.get(f.baseKey);return m?l(u,m):null},getChildNodes(u){let f=c(u),d=e.documentIndex?.entriesByKey.get(u)?.childKeys;if(d)return d.map(h=>{let S=it(h)??h,E=t.elements.get(S);return E?l(h,E):null}).filter(h=>h!==null);let g=t.elements.get(f.baseKey);return g?g.childKeys.map(h=>{let S=t.elements.get(h);return S?l(h,S):null}).filter(h=>h!==null):[]},getKnownSourceFiles(){return[...r.entries()].map(([u,f])=>({file:u,content:f}))},getRouteEntryFiles(){return[...o.values()].map(u=>u.entryFile)},getCapability(u){let f=c(u),m=n.get(f.baseKey);return m?{...m,key:u,constraints:m.constraints.map(d=>({...d})),...m.editModes?{editModes:{...m.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 f=c(u);return e.detailProjections?.get(f.baseKey)?.componentSemantic??null},getClassNameSource(u){let f=c(u),m=t.elements.get(f.baseKey),d=m?r.get(m.sourceFile):void 0;return!m||d===void 0?null:ya({key:f.baseKey,route:{composition:e.composition,routeId:e.routeId,graph:t,source:d}})},getEditableTextSegmentIndex(u){let f=c(u),d=e.detailProjections?.get(f.baseKey)?.textTargets.keys()?.next();return d&&!d.done?d.value:null},async getTextWriteTarget(u,f){let m=c(u);return Dl(e.detailProjections?.get(m.baseKey)?.textTargets.get(f)??null,m.repeatIndex)},async getElementPropertyWriteTarget(u,f){let m=c(u);return Dl(e.detailProjections?.get(m.baseKey)?.elementPropertyTargets.get(f)??null,m.repeatIndex)},getPropertyState(u,f,m){let d=c(u),g=t.elements.get(d.baseKey);if(!g)return null;let S=e.detailProjections?.get(d.baseKey)?.propertyProvenances.get(f);if(S)return S;let E=g.attributes?.find(y=>y.name===f);return E?E.source?{status:"blocked",owner:"generic",diagnostic:{code:"unsupported-property-source",message:`Property '${f}' has an unresolved value source`}}:{status:"direct",owner:"generic",attribute:E,target:{kind:"jsx-attribute",file:g.sourceFile,sourceRange:E.sourceRange}}:(g.attributeSpreads?.length??0)>0?{status:"blocked",owner:"generic",diagnostic:{code:"ambiguous-property-source",message:`A spread may provide or override property '${f}'`}}:{status:"missing",owner:"generic"}},getRepeatPropertyTarget(u,f,m){let d=c(u),g=t.elements.get(d.baseKey);if(!g)return{ok:!1,errorCode:"repeat-not-found",reason:`Node not found: ${u}`};let h=m?{...m,key:d.baseKey}:d.repeatIndex!==null?{key:d.baseKey,instanceIndex:d.repeatIndex}:void 0;return fl({file:g.sourceFile,source:r.get(g.sourceFile)??"",element:g,propertyName:f,selectionRef:h,graph:t,sources:r})},getTextProvenance(u,f){let m=c(u);return e.detailProjections?.get(m.baseKey)?.provenances.get(f)??null}};function c(u){let f=Hw(u);return f?{baseKey:f.baseKey,repeatIndex:kh(e.document??null,u,f.baseKey,e.documentIndex)??vh(f)}:{baseKey:u,repeatIndex:null}}function l(u,f){let m=it(u)??u,d=e.documentIndex?.entriesByKey.get(u);return{key:u,file:f.sourceFile,component:f.componentName,tag:f.tag,structuralPath:f.identity.structuralPath,sourceRange:f.sourceRange,parentKey:d?.parentKey??f.parentKey??void 0,isRepeatRegion:f.boundaryKind==="repeat-region"||s.has(m),isBoundary:!1,importedFrom:f.importedFrom,exportName:f.exportName,isRepeatItemRoot:i.has(m),repeatOwnerKey:i.get(m)??s.get(m),attributes:f.attributes?.map(g=>({name:g.name,value:g.value,source:g.source?{expression:g.source.expression,base:g.source.base,path:g.source.path.map(h=>({...h}))}:null,resolvedValue:g.resolvedValue}))}}}var CN={"stale-version":K.VERSION_STALE,"capability-denied":K.CAPABILITY_REJECTED,"invalid-params":K.INVALID_PARAMS,"locator-miss":K.LOCATOR_FAILED,"route-not-found":K.ROUTE_NOT_FOUND,"unsupported-operation":K.UNSUPPORTED_OPERATION,"invalid-target":K.INVALID_TARGET,"ast-error":K.AST_PARSE_ERROR,"writeback-failed":K.WRITE_IO_ERROR,"rollback-failed":K.RECOVERY_REQUIRED,unknown:K.INTERNAL_ERROR};function Po(e){return CN[e]}function et(e){return e instanceof Error&&e.message?e.message:String(e)}function jh(e){return/\.(?:[cm]?[jt]sx?|css|scss|sass|mdx|json)$/i.test(e)}function RN(e){let t=Kn(e);if(!Zw.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=>Qw.map(a=>`${s}/${a}`))}function wN(e){let n=Kn(e).startsWith("src/app/")?"src/app":"app";return[`${n}/globals.css`,`${n}/global.css`]}function NN(e){return Kh(e,/\bimport\s+(?:[^'";]+?\s+from\s+)?["']([^"']+\.css(?:\?[^"']*)?)["']/g)}function PN(e){return Kh(e,/@import\s+(?:url\(\s*)?["']([^"']+)["']/g)}function Kh(e,t){let n=[];for(let r of e.matchAll(t)){let o=Uh(r[1]??"");o&&n.push(o)}return n}function $h(e,t){let n=Uh(t);return!n||n.startsWith("tailwindcss")||n.startsWith("http:")||n.startsWith("https:")?null:n.startsWith("@/")?Kn(`src/${n.slice(2)}`):n.startsWith("./")||n.startsWith("../")?Kn(`${AN(e)}/${n}`):n.startsWith("/")?Kn(n.slice(1)):Vl(n)?Kn(n):null}function Uh(e){return e.split(/[?#]/,1)[0]?.trim()??""}function Vl(e){return/\.css$/i.test(e)}function AN(e){let t=Kn(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function TN(e){return Array.from(new Set(e))}function Kn(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 FN(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 ws=class{constructor(t){this.options=t,this.fileSystem=new Ir(t.files),this.engine=this.createEngine(this.fileSystem)}get status(){return this.engine.status}initializeComposition(t){return this.engine.initializeComposition(t)}getDocument(t){return Ko(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 Uo(r?this.engine.getObjectEditContext(t,n,r):this.engine.getObjectEditContext(t,n))}getClassNameSource(t,n){return this.engine.getClassNameSource(t,n)}getSourceTree(t){return zo(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}getSourceFile(t){return Wo(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}resolveSourceLocation(t){return Ho(t,this.engine.getRenderDetail(t.key,t.composition))}async planOperation(t){let n=MN.safeParse(t);if(!n.success)return{result:Vo(t,n.error.issues.map(i=>i.message))};let r=new Ir(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:Cn(i)},a=r.getChangedFiles();if(a.length===0)return{result:s};let c=ON.parse({siteId:t.siteId,baseSnapshotId:t.baseSnapshotId,operationId:t.id,reason:`site-edit:${t.kind}`,patches:a.map(l=>LN(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 Rs({projectRoot:"/snapshot",fileSystem:t,compositions:this.options.compositions,onEvent:r&&this.options.onEvent?o=>{let i=Jo(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 LN(e,t){return e.after===void 0?{path:e.path,operation:"delete",...t||e.before===void 0?{}:{expectedHash:ke(e.before)}}:{path:e.path,operation:e.before===void 0?"create":"update",...t||e.before===void 0?{}:{expectedHash:ke(e.before)},fullContent:e.after}}function DN(e){return new ws(e)}import{SiteEditOperationRequestSchema as $N}from"@vcp-dev/contracts";import wt from"node:fs/promises";import tt from"node:path";import{SITE_EDIT_SOURCE_ALLOWED_DIRS as BN,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as jN}from"@vcp-dev/contracts";var Ns=class{constructor(t){this.options=t,this.fileSystem=this.createFileSystem(),this.engine=Rs({...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 zo(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.engine.getCompositionEntryFiles()})}getSourceFile(t){return Wo(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.engine.getCompositionEntryFiles()})}resolveSourceLocation(t){return Ho(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 wt.readFile(tt.join(n,r),"utf8")},async readFileBytes(r){return wt.readFile(tt.join(n,r))},async getFileInfo(r){let o=tt.join(n,...r.split("/"));try{let i=await wt.lstat(o);return!i.isFile()||i.isSymbolicLink()?null:{path:r,sizeBytes:i.size}}catch{return null}},async writeFile(r,o){await pi(tt.join(n,r),o)},async createExclusive(r,o){let i=tt.join(n,r);await wt.mkdir(tt.dirname(i),{recursive:!0});let s=await wt.open(i,"wx");try{await s.writeFile(o,"utf8")}catch(a){throw await s.close(),await wt.rm(i,{force:!0}),a}await s.close()},async deleteFile(r){await wt.rm(tt.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=tt.join(n,i),a=tt.dirname(tt.join(n,o));for(;a!==s&&a.startsWith(`${s}${tt.sep}`);){try{await wt.rmdir(a)}catch(c){if(c instanceof Error&&"code"in c&&c.code==="ENOENT"){a=tt.dirname(a);continue}break}a=tt.dirname(a)}},async exists(r){try{return await wt.access(tt.join(n,r)),!0}catch{return!1}},async listFiles(r={}){let o=r.roots??[...jN,...BN],i=[],s=new Set,a=new Set,c=0;for(let f of o)await u(f,i,1);let l=i.sort((f,m)=>f.path.localeCompare(m.path));return a.size>0?{files:l,truncated:{reasons:[...a]}}:{files:l};async function u(f,m,d){if(r.maxDepth!==void 0&&d>r.maxDepth){a.add("max-depth");return}let g=tt.join(n,...f.split("/")),h;try{h=await wt.lstat(g)}catch{return}if(h.isSymbolicLink())return;if(h.isFile()){let E=h.ino>0?`${String(h.dev)}:${String(h.ino)}`:null;if(E&&s.has(E))return;if(r.maxFiles!==void 0&&m.length>=r.maxFiles){a.add("max-files");return}if(r.maxTotalBytes!==void 0&&c+h.size>r.maxTotalBytes){a.add("max-total-bytes");return}E&&s.add(E),m.push({path:f,sizeBytes:h.size}),c+=h.size;return}if(!h.isDirectory())return;if(r.maxFiles!==void 0&&m.length>=r.maxFiles){a.add("max-files");return}let S=await wt.readdir(g,{withFileTypes:!0});for(let E of S)E.isSymbolicLink()||await u(`${f}/${E.name}`,m,d+1)}},getVersion(r){return t.get(r)??1},bumpVersion(r){let o=(t.get(r)??1)+1;return t.set(r,o),o}}}};function Kl(e){return new Ns(e)}var Ps=class{constructor(t){this.options=t,this.listeners=new Set,this.engine=Kl({projectRoot:t.projectRoot,fileSystem:t.fileSystem,compositions:t.compositions,onEvent:n=>{let r=Jo(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:Ko(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:Uo(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=$N.safeParse(r);if(!o.success)return Vo(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:Cn(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:Cn(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:Cn(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 VN(e){return new Ps(e)}export{re as FileHistoryStoreError,Qr as PageTemplateManagedSourceError,Ps as PreviewFileSystemSiteEditEngineRuntime,df as SITE_EDIT_RAW_COLOR_LITERAL_RE,ws as SnapshotSiteEditEngineRuntime,Lo as checkComponentI18nHostCompatibility,np as computeManagedPageTemplatePaths,VN as createPreviewSiteEditEngineRuntime,DN as createSiteEditEngineRuntime,qf as decodePageTemplateKey,yc as encodePageTemplateId,Ly as instrumentSiteEditRuntimeAttributes,rp as isManagedPageTemplateSourcePath,$d as openFileHistoryStore,Sy as parseSourceModule,Ey as resolveImportBase,Mk as resolveManagedPageTemplateComposition,$i as scanManagedPageTemplateCandidates,ip as scanSiteEditCompositionsFromFiles,Xr as scanSiteEditThemeStyleViolations};
|