@vcp-dev/site-edit-engine 0.10.33 → 0.10.35
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 +10 -10
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
import*as qh from"@babel/parser";import*as zn from"@babel/types";import*as qt from"node:path";var Ms=[".tsx",".ts",".jsx",".js"],ey=Ms.map(e=>`/index${e}`),ty=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 su(e){let t=e.replace(/[?#].*$/,""),n=/\.([a-z0-9]+)$/i.exec(t);return n!==null&&ty.has(n[1].toLowerCase())}function au(e){let t=[];for(let n of e.program.body)zn.isImportDeclaration(n)&&typeof n.source.value=="string"&&Nt(n.source.value)&&t.push(n.source.value),zn.isExportNamedDeclaration(n)&&n.source&&typeof n.source.value=="string"&&Nt(n.source.value)&&t.push(n.source.value),zn.isExportAllDeclaration(n)&&typeof n.source.value=="string"&&Nt(n.source.value)&&t.push(n.source.value);return Ds(e.program,t),t}function Ds(e,t){if(!e||typeof e!="object")return;let n=e;if(n.type==="CallExpression"&&n.callee?.type==="Import"){let r=n.arguments?.[0];r?.type==="StringLiteral"&&typeof r.value=="string"&&Nt(r.value)&&t.push(r.value)}for(let r of Object.values(n))if(Array.isArray(r))for(let o of r)Ds(o,t);else r&&typeof r=="object"&&Ds(r,t)}function Nt(e){return e.startsWith("./")||e.startsWith("../")||e.startsWith("@/")}function yn(e,t){if(t.startsWith("@/"))return t.slice(2).replace(/\\/g,"/");let n=qt.dirname(e);return qt.join(n,t).replace(/\\/g,"/")}async function ny(e,t){if(Ms.some(n=>e.endsWith(n))&&await t(e))return e;for(let n of Ms){let r=`${e}${n}`;if(await t(r))return r}for(let n of ey){let r=`${e}${n}`;if(await t(r))return r}return null}async function xn(e,t,n){let r=await Oo(e,t,n);return r.ok?r.path:null}async function Oo(e,t,n){let r=yn(e,t);try{if(!ry(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 ny(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 ry(e,t,n){if(!Nt(t)||t.includes("\0")||t.includes("\\")||qt.posix.isAbsolute(n))return!1;let r=qt.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!qt.posix.isAbsolute(e)}import{createHash as iy}from"node:crypto";import*as cu from"@babel/parser";function bn(e,t,n,r){return{code:e,message:t,locatorKind:n,details:r}}function K(e,t,n,r,o){return{ok:!1,source:e,diagnostic:bn(t,n,r,o)}}function Ls(e,t,n,r,o){return{ok:!1,source:e,diagnostic:bn(t,n,r,o)}}var oy={"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:cu.parse(t,{sourceType:"module",plugins:oy[n]})}}catch(r){return{ok:!1,source:t,diagnostic:bn("parse-failed",`AST parse failed: ${r instanceof Error?r.message:String(r)}`)}}}function Bs(e,t){return Pt({source:e,profile:lu(t.kind)})}function kr(e,t){return Pt({source:e,profile:lu(t)})}function lu(e){return"next-app-entry"}function Sn(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 En=(e,t)=>{let n=Pt({source:t,profile:Sn({filePath:e,source:t})});return n.ok?{ok:!0,module:{file:e,source:t,sourceHash:`sha256:${iy("sha256").update(t).digest("hex")}`,ast:n.ast,imports:au(n.ast).map(r=>({specifier:r}))}}:{ok:!1,diagnostic:{path:e,code:"parse-failed",message:n.diagnostic.message}}};function sy(e,t){return En(e,t)}function ay(e,t){return yn(e,t)}import{COMPONENT_I18N_FILE_SUFFIX as cy,parseComponentI18nResourcesJson as ly,resolveSiteTextDirection as uy,SiteLocaleSchema as dy}from"@vcp-dev/contracts";var fy=["i18next","react-i18next"],py="components/ui/site-locale-provider.tsx",my="components/ui/component-i18n-provider.tsx",uu="app/layout.tsx";async function Mo(e){let t=e.files.filter(m=>m.path.endsWith(cy));if(t.length===0)return{ok:!0};for(let m of["package.json",uu,py,my])if(!await e.exists(m))return en(`Target snapshot is missing required i18n host file: ${m}`);let n;try{n=JSON.parse(await e.readFile("package.json"))}catch{return en("Target snapshot package.json is invalid.")}let r=du(n)&&du(n.dependencies)?n.dependencies:{},o=fy.filter(m=>typeof r[m]!="string"||r[m].trim().length===0);if(o.length>0)return en(`Target snapshot must already declare: ${o.join(", ")}.`);let i=await e.readFile(uu),s=js(i,"html","lang"),a=js(i,"html","dir"),c=js(i,"SiteLocaleProvider","locale"),l=dy.safeParse(s);if(!l.success||!a||!c||s!==c||a!==uy(l.data))return en("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 en("Target snapshot root layout is not wired to SiteLocaleProvider.");let d=l.data;if(e.targetLocale&&e.targetLocale!==d)return en("Target snapshot locale does not match the authoritative site language.");let f=d.split("-")[0];for(let m of t){let u=ly(m.content);if(!u.success)return en(`Component i18n resource is invalid: ${m.path}.`);if(!e.deferTargetLocale&&!Object.hasOwn(u.data,d)&&!Object.hasOwn(u.data,f))return en(`Component i18n resource ${m.path} has no locale for ${d} or ${f}.`)}return{ok:!0}}function js(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 du(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function en(e){return{ok:!1,message:e}}import Vs from"@babel/generator";import*as yu from"@babel/parser";import Ks from"@babel/traverse";import*as Ce from"@babel/types";import{computeSiteEditSourceIdentityKey as hy}from"@vcp-dev/contracts";var fu="data-vcp-ui-component",Do="components/ui";function Kt(e){if(!e)return!1;let t=$s(e);return t===Do||t.startsWith(`${Do}/`)||t.includes(`/${Do}/`)||t.endsWith(`/${Do}`)}function vn(e,t){return e?e.startsWith("@/")||e.startsWith("~/")?Kt(e.slice(2)):e.startsWith("./")||e.startsWith("../")?Kt($s(`${gy(t)}/${e}`)):Kt(e):!1}function $s(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 gy(e){let t=$s(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}import{stripSiteEditRepeatInstanceKeys as UN}from"@vcp-dev/contracts";import{isSiteEditRuntimeContainerTag as XN,isSiteEditRuntimeTextTag as zN}from"@vcp-dev/contracts/site-edit-runtime-capability";var pu={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 yy=typeof Vs=="function"?Vs:Vs.default,xy=typeof Ks=="function"?Ks:Ks.default,by=new Set(["base","body","head","html","link","meta","noscript","script","style","template","title"]),Sy="suppressHydrationWarning",Ey=new Set(["SiteEditBootstrap"]);function vy(e){let t=Cy(e.file,e.projectRoot);if(!Iy(e.source)||Kt(t))return{code:e.source,elements:[]};let n=e.attributes??pu,r=yu.parse(e.source,{sourceType:"module",plugins:["jsx","typescript"]}),o=[],i=wy(r,t);return xy(r,{JSXElement(s){let a=s.node.openingElement,c=a.name;if(!Py(c)||xu(a,n.key))return;let l=Ty(s)??"default",d=_y(s),f=hy(t,l,d),m=Bo(c)??"unknown",u=Ry(c)?"jsx":"component-call";if(u==="component-call"&&!Fy(s.node.children)&&Ey.has(m))return;let g=u==="component-call"&&Ny(m,i);Ay(a,n.key,f),g&&mu(a,fu),ky(s)&&mu(a,Sy),o.push({key:f,tag:m,componentName:l,sourceFile:t,sourceKind:u})}}),o.length===0?{code:e.source,elements:o}:{code:yy(r,{jsescOption:{minimal:!0}}).code,elements:o}}function ky(e){return!e.findParent(t=>t.isJSXElement())}function Iy(e){return/(?:^|[=(:,?;\[{>&|\n\r]|return\s+)\s*<(?:[A-Za-z][\w.:-]*|>)(?:\s|>|\/)/m.test(e)}function Cy(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 Ry(e){return Ce.isJSXIdentifier(e)&&/^[a-z]/.test(e.name)}function Bo(e){return Ce.isJSXIdentifier(e)?e.name:Ce.isJSXMemberExpression(e)?Su(e):null}function wy(e,t){let n=new Set;for(let r of e.program.body)if(!(!Ce.isImportDeclaration(r)||!vn(r.source.value,t)))for(let o of r.specifiers)n.add(o.local.name);return n}function Ny(e,t){let n=e.split(".")[0]??e;return t.has(n)}function Py(e){let t=Bo(e);return!t||t==="Fragment"||t.endsWith(".Fragment")?!1:!by.has(t)}function xu(e,t){return e.attributes.some(n=>Ce.isJSXAttribute(n)&&Ce.isJSXIdentifier(n.name,{name:t}))}function Ay(e,t,n){bu(e,Ce.jsxAttribute(Ce.jsxIdentifier(t),Ce.stringLiteral(n)))}function mu(e,t){xu(e,t)||bu(e,Ce.jsxAttribute(Ce.jsxIdentifier(t),null))}function bu(e,t){let n=e.attributes.findIndex(r=>Ce.isJSXSpreadAttribute(r));if(n>=0){e.attributes.splice(n,0,t);return}e.attributes.push(t)}function Su(e){return`${Ce.isJSXIdentifier(e.object)?e.object.name:Su(e.object)}.${e.property.name}`}function Ty(e){let t=e;for(;t;){if(t.isFunctionDeclaration()||t.isClassDeclaration())return t.node.id?.name??null;if(t.isVariableDeclarator()&&Ce.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 Fy(e){return e.some(t=>Ce.isJSXElement(t)||Ce.isJSXFragment(t))}var gu=new WeakMap,Lo=new WeakMap,Us=new WeakMap;function _y(e){let t=gu.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=Oy(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return gu.set(e.node,o),o}function Oy(e){let t=Bo(e.node.openingElement.name);return!t||t==="Fragment"||t.endsWith(".Fragment")?null:/^[A-Z]/.test(t)?`component:${t}#${hu(e,t)}`:`${t}#${hu(e,t)}`}function hu(e,t){let n=Eu(e)??e.getFunctionParent();if(!n)return 0;let r=Us.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=Us.get(n.node);o||(o=new Map,Us.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()?jo(n):My(n);for(let c of a)if(Bo(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 My(e){let t=Lo.get(e.node);if(t)return t;let n=[];return e.traverse({JSXElement(r){r.getFunctionParent()?.node===e.node&&!Eu(r)&&n.push(r)}}),Lo.set(e.node,n),n}function Eu(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 jo(e){let t=Lo.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(...jo(o));continue}o.isJSXExpressionContainer()&&n.push(...kn(o.get("expression")))}return Lo.set(e.node,n),n}function kn(e){if(e.isJSXElement())return[e];if(e.isJSXFragment())return jo(e);if(e.isParenthesizedExpression())return kn(e.get("expression"));if(e.isLogicalExpression()&&e.node.operator==="&&")return kn(e.get("right"));if(e.isConditionalExpression())return[...kn(e.get("consequent")),...kn(e.get("alternate"))];if(e.isCallExpression()&&Ly(e.node)){let t=e.get("arguments")[0];return Dy(t)}return[]}function Dy(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return[t];if(t.isJSXFragment())return jo(t);if(t.isParenthesizedExpression())return kn(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?kn(r):[]}return[]}function Ly(e){return Ce.isMemberExpression(e.callee)&&Ce.isIdentifier(e.callee.property)&&e.callee.property.name==="map"}import{SiteEditOperationRequestSchema as bN,SiteEditPatchPlanSchema as SN}from"@vcp-dev/contracts";function In(e){return{requestId:e.requestId,kind:e.kind,composition:e.composition,target:e.target,resultVersion:e.resultVersion,affectedFiles:e.affectedFiles,...e.output?{output:e.output}:{},...e.selectionRef?{selectionRef:e.selectionRef}:{}}}function $o(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 Vo(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 Ko(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:By(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 Uo(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:In(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 By(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 Pw,computeSiteEditCompositionKey as Aw,getSiteEditSourceDeleteProtectionReason as Tw,isSiteEditTextSourcePath as Fw,parseSiteEditRepeatInstanceKey as _w,SITE_EDIT_SOURCE_DELETE_CAPABILITY as Ow,stripSiteEditRepeatInstanceKeys as ot}from"@vcp-dev/contracts";import ks from"node:path";import{parse as Mw}from"yaml";import Ws from"node:path";import{TextDecoder as $y}from"node:util";import{SITE_EDIT_SOURCE_ALLOWED_APP_FILES as ku,SITE_EDIT_SOURCE_ALLOWED_DIRS as Iu,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as Cu,SiteEditCompositionContextSchema as Vy,SiteEditSourceFileResponseSchema as Js,SiteEditSourceLocationSchema as Ky,SiteEditSourcePathSchema as Jo,SiteEditSourceTreeResponseSchema as Uy,isSiteEditTextSourcePath as Jy}from"@vcp-dev/contracts";import{createHash as jy}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 Ee(e){return`sha256:${jy("sha256").update(e).digest("hex")}`}var Xy=[...Cu,...ku,...Iu];function Gs(e){if(!e.composition)throw new Error("Composition unavailable for source access policy.");return Vy.parse(e.composition)}var Xs=2e3,zs=12,Hs=24*1024*1024,vu=512*1024,zy=new Set(["image/avif","image/gif","image/jpeg","image/png","image/webp","image/x-icon"]),Hy={".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"},Wy={".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"},Gy=new $y("utf-8",{fatal:!0});async function Xo(e,t={}){let n=Gs(t),{files:r,truncated:o}=await nx(e,t),i=ix(r.map(s=>s.metadata));return Uy.parse({composition:n,nodes:i,defaultPath:sx(r.map(s=>s.metadata)),totalFiles:r.length,...o?{truncated:o}:{}})}async function zo(e,t,n={}){let r=Gs(n),o=Jo.parse(t.path),i=await Zy(e,o,n);if(!i)throw new Error(`Source file not found: ${o}`);if(Zs(o)){let a=Nu(o),c=await qy(e,{path:o,sizeBytes:i.sizeBytes,mimeType:a});return Js.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:i.sizeBytes,mimeType:a,readonly:!0,...c})}let s=await Ys(e,o);return s.ok?Js.parse({composition:r,path:o,kind:"text",language:Pu(o),sizeBytes:s.sizeBytes,contentHash:Ee(s.content),readonly:!1,content:s.content}):Js.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:s.sizeBytes,mimeType:"application/octet-stream",readonly:!0,previewUnavailableReason:"unsupported-mime"})}async function Ys(e,t){if(e.readFileBytes){let o=await e.readFileBytes(t),i=Yy(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 Yy(e){if(e.includes(0))return null;try{return Gy.decode(e)}catch{return null}}async function Zy(e,t,n){if(!ex(t,n))return null;let r=await Qy(e,t);return r?{path:t,sizeBytes:r.sizeBytes}:null}async function Qy(e,t){if(e.getFileInfo)return e.getFileInfo(t);if(e.listFiles){let o=Ru(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(Zs(t))return{path:t,sizeBytes:0};let n=await e.readFile(t);return{path:t,sizeBytes:Buffer.byteLength(n,"utf8")}}async function qy(e,t){if(!zy.has(t.mimeType))return{previewUnavailableReason:"unsupported-mime"};if(t.sizeBytes>vu)return{previewUnavailableReason:"too-large"};if(!e.readFileBytes)return{previewUnavailableReason:"bytes-unavailable"};let n=await e.readFileBytes(t.path);return n.byteLength>vu?{previewUnavailableReason:"too-large"}:{contentBase64:Buffer.from(n).toString("base64")}}function ex(e,t){return Cu.some(n=>n===e)||ku.some(n=>n===e)||Iu.some(n=>e===n||e.startsWith(`${n}/`))?!0:!e.startsWith("app/")&&!e.startsWith("src/app/")?!1:(t.routeEntryFiles??[]).some(n=>{let r=Jo.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 Ky.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 Ru(e){return Array.isArray(e)?{files:e}:e}function tx(e){return["max-files","max-depth","max-total-bytes"].filter(n=>e.includes(n))}async function nx(e,t){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let n=Ru(await e.listFiles({roots:rx(t),maxFiles:Xs+1,maxDepth:zs,maxTotalBytes:Hs+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=Jo.safeParse(a.path);if(!c.success)continue;let l=c.data;if(l.split("/").length>zs){o.add("max-depth");continue}if(r.size>=Xs){o.add("max-files");break}if(i+a.sizeBytes>Hs){o.add("max-total-bytes");break}r.set(l,{path:l,sizeBytes:a.sizeBytes,metadata:ox(l,a.sizeBytes,Gs(t))}),i+=a.sizeBytes}return{files:[...r.values()].sort((a,c)=>a.path.localeCompare(c.path)),...o.size>0?{truncated:{reasons:tx([...o]),maxFiles:Xs,maxDepth:zs,maxTotalBytes:Hs}}:{}}}function rx(e){let t=new Set(Xy);for(let n of e.routeEntryFiles??[]){let r=Jo.safeParse(n);r.success&&(r.data.startsWith("app/")||r.data.startsWith("src/app/"))&&t.add(r.data)}return[...t]}function ox(e,t,n){return Zs(e)?{composition:n,path:e,kind:"binary",language:null,sizeBytes:t,mimeType:Nu(e),readonly:!0}:{composition:n,path:e,kind:"text",language:Pu(e),sizeBytes:t,readonly:!1}}function ix(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(d=>d.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 wu(t)}function wu(e){return e.map(t=>t.kind==="directory"?{...t,children:wu(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 Zs(e){return!Jy(e)}function Nu(e){let t=Ws.posix.extname(e).toLowerCase();return!t&&Ws.posix.basename(e).toLowerCase()==="favicon"?"image/x-icon":Hy[t]??"application/octet-stream"}function Pu(e){let t=Ws.posix.extname(e).toLowerCase();return Wy[t]??"plaintext"}import Qs from"@babel/traverse";import*as At from"@babel/types";function Fe(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")&&Au(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())&&Au(r.parentPath)}function Au(e){return e?.isImportDeclaration()===!0&&e.node.source.value==="react"}var tn=typeof Qs=="function"?Qs:Qs.default,Wo=new WeakMap,Go=new WeakMap;function Tt(e,t){let n=Bs(e,t);if(!n.ok)return Ls(e,n.diagnostic.code,n.diagnostic.message,t.kind);let r=ae(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}}:Ls(e,r.diagnostic.code,r.diagnostic.message,t.kind,r.diagnostic.details)}function ae(e,t){return t.kind==="jsx-node"?Ou(e,t):t.kind==="jsx-attribute"?fx(e,t):t.kind==="value"?px(e,t):t.kind==="expression"?mx(e,t):t.kind==="directive"?gx(e,t):t.kind==="export"?hx(e,t):{ok:!1,diagnostic:bn("unsupported-syntax",`Unsupported locator kind: ${t.kind}`)}}function Ou(e,t){return t.strategy==="source-range"?ax(e,t):cx(e,t)}function ax(e,t){let n=null;if(tn(e,{JSXElement(o){if(!Cn(o.node,t.sourceRange))return;let i=Le("jsx-node",o);if(i){if(!n){n=i;return}i.end-i.start<n.end-n.start&&(n=i)}},JSXFragment(o){if(!Cn(o.node,t.sourceRange))return;let i=Le("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXExpressionContainer(o){if(!Cn(o.node,t.sourceRange))return;let i=Le("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXText(o){if(!Cn(o.node,t.sourceRange))return;let i=Le("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&&!Nx(r.path,t.expectedIdentity)?Be("jsx-node","locator-miss","JSX node failed expected identity validation"):{ok:!0,match:r}}function cx(e,t){if(t.structuralPath===""){let r=ux(e,t.component);if(r){let o=dx(r);if(o)return o}}let n=null;return tn(e,{JSXElement(r){if(Rr(r)!==t.component||ea(r)!==t.structuralPath)return;let i=Le("jsx-node",r);i&&(n=i,r.stop())},JSXFragment(r){if(Rr(r)!==t.component||ea(r)!==t.structuralPath)return;let i=Le("jsx-node",r);i&&(n=i,r.stop())}}),!n&&t.expectedRange&&(n=lx(e,t.component,t.expectedRange)),n?{ok:!0,match:n}:Be("jsx-node","locator-miss","JSX node not found for structural-path locator")}function lx(e,t,n){let r=null;return tn(e,{JSXElement(o){if(Rr(o)!==t||!Cn(o.node,n))return;let i=Le("jsx-node",o);i&&(r=i,o.stop())},JSXFragment(o){if(Rr(o)!==t||!Cn(o.node,n))return;let i=Le("jsx-node",o);i&&(r=i,o.stop())}}),r}function ux(e,t){let n=null;return tn(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 dx(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 fx(e,t){let n=Ou(e,t.element);if(!n.ok)return n;let s=n.match.path.get("openingElement").get("attributes").find(c=>Px(c,t.name));if(!s||!s.isJSXAttribute())return Be("jsx-attribute","locator-miss",`JSX attribute '${t.name}' not found`);let a=Le("jsx-attribute",s);return a?{ok:!0,match:a}:Be("jsx-attribute","locator-miss",`JSX attribute '${t.name}' has no source range`)}function px(e,t){let n=yx(e,t);if(!n.ok)return n;let r=xx(n.match.path,t.path??[]);return r.ok?t.expectedRange&&!Jt(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 mx(e,t){let n=null;return tn(e,{Identifier(r){if(!Ix(r))return;let o=Fu(r);if(!o||!_u(o,t))return;let i=Le("expression",r);i&&(t.expectedRange&&!Jt(r.node.loc,t.expectedRange)||(n=i,r.stop()))},MemberExpression(r){let o=Fu(r);if(!o||!_u(o,t))return;let i=Le("expression",r);i&&(t.expectedRange&&!Jt(r.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:Be("expression","locator-miss","Expression not found")}function gx(e,t){let n=null;return tn(e,{Program(r){let i=r.get("directives").find(a=>a.node.value.value===t.value);if(!i||t.expectedRange&&!Jt(i.node.loc,t.expectedRange))return;let s=Le("directive",i);s&&(n=s,r.stop())}}),n?{ok:!0,match:n}:Be("directive","locator-miss",`Directive '${t.value}' not found`)}function hx(e,t){let n=null;return tn(e,{ExportNamedDeclaration(r){if(t.exportKind==="generate-metadata"){let c=r.get("declaration");if(c.isFunctionDeclaration()&&c.node.id?.name==="generateMetadata"){let m=Le("export",c);if(!m||t.expectedRange&&!Jt(c.node.loc,t.expectedRange))return;n=m,r.stop();return}if(!c.isVariableDeclaration())return;let l=ta(c,"generateMetadata");if(!l||!l.isVariableDeclarator())return;let d=l.get("init");if(!d.node)return;let f=Le("export",d);if(!f||t.expectedRange&&!Jt(d.node.loc,t.expectedRange))return;n=f,r.stop();return}let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=ta(o,t.exportKind==="named"?t.name:"metadata");if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node||t.expectedRange&&!Jt(s.node.loc,t.expectedRange))return;let a=Le("export",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(t.exportKind!=="default")return;let o=r.get("declaration"),i=Le("export",o);i&&(t.expectedRange&&!Jt(o.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:Be("export","export-not-found",`Export '${wx(t)}' not found`)}function yx(e,t){let n=null;return tn(e,{Expression(r){if(n||t.root.kind!=="expression"||!Cn(r.node,t.root.sourceRange))return;let o=Le("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 u=r.get("init");if(!u.node)return;let g=Le("value",u);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(u=>u?.type==="Identifier"&&u.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 d=o.hook==="useReducer"?1:0,f=r.get(`init.arguments.${d}`);if(!f||Array.isArray(f)||!f.node)return;let m=Le("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=ta(o,t.root.name);if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node)return;let a=Le("value",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(n||t.root.kind!=="default-export")return;let o=r.get("declaration"),i=Le("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 xx(e,t){let n=qs(e);for(let o of t){if(n=qs(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=>Ax(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=qs(n);let r=Le("value",n);return r?{ok:!0,match:r}:Be("value","locator-miss","Resolved value has no source range")}function qs(e){let t=e;for(;t.isTSAsExpression()||t.isTSSatisfiesExpression()||t.isTSNonNullExpression();)t=t.get("expression");return t}function Le(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 Cn(e,t){return Jt(e.loc,t)}function Jt(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 ea(e){let t=[],n=e,r=e.node;for(;n;){if(n.isJSXElement()){if(!Fe(n)){let o=Du(n.node.openingElement);o&&(/^[A-Z]/.test(o)?t.unshift(`component:${o}#${Tu(n,o)}`):t.unshift(`${o}#${Tu(n,o)}`))}}else n.isJSXFragment()&&n.node===r&&t.unshift("fragment");if(!n.parentPath||vx(n.parentPath)&&!kx(n.parentPath))break;n=n.parentPath}return t.join("/")}function Tu(e,t){let n=Mu(e)??e.getFunctionParent();if(!n)return 0;let r=Wo.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=0,i=Wo.get(n.node)?.get(t);if(!i){let a=Wo.get(n.node);a||(a=new Map,Wo.set(n.node,a)),i=new WeakMap,a.set(t,i)}let s=n.isJSXElement()||n.isJSXFragment()?Cr(n):bx(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 bx(e){let t=Go.get(e.node);if(t)return t;let n=[];return e.traverse({JSXElement(r){r.getFunctionParent()?.node===e.node&&!Mu(r)&&n.push(r)}}),Go.set(e.node,n),n}function Mu(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(Fe(t)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function Cr(e){let t=Go.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(Fe(o)){n.push(...Cr(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...Cr(o));continue}o.isJSXExpressionContainer()&&n.push(...Ut(o.get("expression")))}return Go.set(e.node,n),n}function Ut(e){if(e.isJSXElement())return Fe(e)?Cr(e):[e];if(e.isJSXFragment())return Cr(e);if(e.isParenthesizedExpression())return Ut(e.get("expression"));if(e.isLogicalExpression()&&Sx(e.node.operator))return Ut(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(...Ut(c))}if(s.isReturnStatement()){let a=s.get("argument");a.isExpression()&&i.push(...Ut(a));break}}return i}else if(o.node&&o.isExpression())return Ut(o)}}}}return e.isConditionalExpression()?[...Ut(e.get("consequent")),...Ut(e.get("alternate"))]:e.isArrayExpression()?e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:Ut(t)):[]}function Sx(e){return e==="&&"||e==="||"||e==="??"}function Du(e){return e.name.type==="JSXIdentifier"?e.name.name:e.name.type==="JSXMemberExpression"?Ex(e.name):null}function Ex(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 vx(e){return!!(e.isFunctionDeclaration()||e.isFunctionExpression()||e.isArrowFunctionExpression())}function kx(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 Ix(e){return!(!e.isExpression()||e.parentPath?.isMemberExpression({property:e.node}))}function Fu(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 _u(e,t){return e.base===t.base&&Cx(e.path,t.path??[])}function Cx(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 Rx(e){return e.key.type==="Identifier"?e.key.name:e.key.type==="StringLiteral"?e.key.value:null}function wx(e){return e.exportKind==="named"?e.name:e.exportKind}function Be(e,t,n,r){return{ok:!1,diagnostic:bn(t,n,e,r)}}function Nx(e,t){return Rr(e)!==t.component?!1:ea(e)===t.structuralPath}function Px(e,t){return!e.isJSXAttribute()||e.node.name.type!=="JSXIdentifier"?!1:e.node.name.name===t}function ta(e,t){return e.get("declarations").find(n=>!n.isVariableDeclarator()||n.node.id.type!=="Identifier"?!1:n.node.id.name===t)}function Ax(e,t){return e.isObjectProperty()?Rx(e.node)===t:!1}import*as Bu from"@babel/parser";import{arrayExpression as Mx,booleanLiteral as Dx,identifier as Lx,jsxAttribute as Bx,jsxExpressionContainer as jx,jsxIdentifier as $x,nullLiteral as Vx,numericLiteral as Kx,objectExpression as Ux,objectProperty as Jx,stringLiteral as ra}from"@babel/types";import na from"@babel/generator";var Tx=typeof na=="function"?na:na.default;function Fx(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 Yo(e){let{ast:t,source:n}=e;try{let r=Fx(n),i=Tx(t,{comments:!0,jsescOption:{minimal:!0,quotes:"single"}},n).code;return r!=="2"&&(i=Ox(i,r)),{ok:!0,source:i}}catch(r){return K(n,"printer-failed",`AST print failed: ${r instanceof Error?r.message:String(r)}`)}}function Lu(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:Lu(e),afterSourceHash:Lu(t),inverse:n.inverse}}}function me(e,t,n){let r=Yo({ast:e,source:t});return r.ok?wr(t,r.source,n):r}function Re(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 Zo(e,t){return Yo({ast:e,source:t})}function Xx(e,t,n){let r=ae(e,t);return r.ok?{ok:!0,match:r.match}:{ok:!1,result:{ok:!1,source:n,diagnostic:r.diagnostic}}}function Hn(e,t,n){let r=Xx(e,t,n);return r.ok?r.match.path.isJSXElement()?r:{ok:!1,result:K(n,"unsupported-syntax","JSX locator must resolve to JSXElement","jsx-node")}:r}function nn(e){return typeof e=="string"?ra(e):typeof e=="number"?Kx(e):typeof e=="boolean"?Dx(e):e===null?Vx():Array.isArray(e)?Mx(e.map(t=>nn(t))):Ux(Object.entries(e).map(([t,n])=>{let r=Jx(oa(t),nn(n));return t==="__proto__"&&(r.computed=!0),r}))}function zx(e){return typeof e=="string"?ra(e):jx(nn(e))}function Nr(e,t){return Bx($x(e),zx(t))}function Qo(e,t){try{let r=Bu.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:K(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:K(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function oa(e){return/^[$A-Z_][0-9A-Z_$]*$/i.test(e)?Lx(e):ra(e)}function qo(e){let{source:t,locator:n,segmentIndex:r,newText:o}=e,i=Re(t,"jsx-node");if(!i.ok)return i.result;let s=ae(i.ast,n);if(!s.ok)return{ok:!1,source:t,diagnostic:s.diagnostic};let c=Hx(s.match.path)[r];if(!c)return K(t,"locator-miss",`Text segment ${r} not found`,"jsx-node");switch(c.kind){case"jsx-text":c.path.node.value=Wx(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 me(i.ast,t,{kind:"update-text",target:"jsx-node",inverse:"restore-text"})}function Hx(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=Gx(r.get("expression"));o.length>0&&t.push(...o)}}return t}function Wx(e,t){let n=e.match(/^\s*/)?.[0]??"",r=e.match(/\s*$/)?.[0]??"";return`${n}${t.trim()}${r}`}function Gx(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 ia}from"@babel/types";function Wn(e){let{source:t,locator:n}=e,r=Re(t,"jsx-node");if(!r.ok)return r.result;let o=ae(r.ast,n);return o.ok?(Yx(o.match.path),me(r.ast,t,{kind:"remove-node",target:"jsx-node",inverse:"insert-child"})):{ok:!1,source:t,diagnostic:o.diagnostic}}function Yx(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(ia());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(ia());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(ia());return}e.remove()}import{cloneNode as Zx}from"@babel/types";function ei(e){let t=Re(e.source,"jsx-node");if(!t.ok)return t.result;let n=ae(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(Zx(r.node,!0)),me(t.ast,e.source,{kind:"replace-node",target:"jsx-node",inverse:"replace-node"})):r.result}import{cloneNode as cb}from"@babel/types";import sa from"@babel/traverse";import*as q from"@babel/types";function Pr(e,t,n){return`${e}::${t}::${n}`}var $={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 Qx=typeof sa=="function"?sa:sa.default;function mt(e,t,n,r){if(!e.ok)return e;let o=pt(n,t);if(!o)return e;let i=qx(t,o,r);return i?{...e,selectionRef:i}:e}function qx(e,t,n){let r=eb(e,t);if(!r)return;let o=n.sourceLocator?ju(n.sourceLocator):void 0,i=n.targetParentLocator?ju(n.targetParentLocator):void 0,s=n.file??i?.file??o?.file,a=n.component??nb(r)??i?.component??o?.component;if(!(!s||!a))return{key:Pr(s,a,rb(r))}}function ju(e){return e.strategy==="structural-path"?{file:e.file,component:e.component,structuralPath:e.structuralPath}:e.expectedIdentity}function eb(e,t){let n=Xu(e,t);return!n||n.node.type!=="JSXElement"?null:n}function Xu(e,t){let n=null;return Qx(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 ab(t,e)?$u(e.children,t):e;if(q.isJSXFragment(e))return $u(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 zu(e)?tb(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 $u(e,t){for(let n of e){let r=pt(n,t);if(r)return r}return null}function tb(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=Vu(n.consequent,t);if(r)return r;let o=n.alternate?Vu(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 Vu(e,t){return q.isBlockStatement(e)?Ar(e.body,t):Ar([e],t)}function nb(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 Ku=new WeakMap,Uu=new WeakMap,aa=new WeakMap;function rb(e){let t=Ku.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=ob(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return Ku.set(e.node,o),o}function ob(e){let t=Hu(e.node.openingElement.name);return!t||Fe(e)?null:/^[A-Z]/.test(t)?`component:${t}#${Ju(e,t)}`:`${t}#${Ju(e,t)}`}function Ju(e,t){let n=ib(e);if(!n)return 0;let r=aa.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=aa.get(n.node);o||(o=new Map,aa.set(n.node,o));let i=o.get(t);i||(i=new WeakMap,o.set(t,i));let s=0;for(let a of Rn(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 ib(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(Fe(t)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function Rn(e){let t=Uu.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(Fe(o)){n.push(...Rn(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...Rn(o));continue}o.isJSXExpressionContainer()&&n.push(...Ft(o.get("expression")))}return Uu.set(e.node,n),n}function Ft(e){if(e.isJSXElement())return Fe(e)?Rn(e):[e];if(e.isJSXFragment())return Rn(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())&&zu(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 Fe(t)?Rn(t):[t];if(t.isJSXFragment())return Rn(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 zu(e){let t=e.callee;return(q.isMemberExpression(t)||q.isOptionalMemberExpression(t))&&q.isIdentifier(t.property)&&t.property.name==="map"&&!t.computed}function ab(e,t){let n=Xu(e,t);return n?Fe(n):!1}function Hu(e){return q.isJSXIdentifier(e)?e.name:q.isJSXMemberExpression(e)?Wu(e):q.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function Wu(e){return`${q.isJSXIdentifier(e.object)?e.object.name:Wu(e.object)}.${e.property.name}`}function rn(e,t){if(t.parentPath===e&&t.listKey==="children"&&ca(e))return e;if(!t.parentPath||t.listKey!=="children")return null;let n=t.parentPath;if(!ca(n))return null;let r=n;for(;r&&r!==e;){if(!ca(r)||!Fe(r)||r.listKey!=="children")return null;r=r.parentPath}return r===e?n:null}function ca(e){return e.isJSXElement()||e.isJSXFragment()}function Gn(e){let{source:t,locator:n,node:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=Re(t,"jsx-node");if(!a.ok)return a.result;let c=ae(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};if(!c.match.path.isJSXElement()&&!c.match.path.isJSXFragment())return K(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 K(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let d=Qo(t,r.jsx);if(!d.ok)return d.result;let f=cb(d.node,!0),m=l.node.children,u={...s,targetParentLocator:n},g=v=>s?mt(v,a.ast,f,u):v;if(o==="append")return m.push(f),g(me(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return m.unshift(f),g(me(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(!i)return K(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let h=ae(a.ast,i);if(!h.ok)return{ok:!1,source:t,diagnostic:h.diagnostic};let S=rn(c.match.path,h.match.path);if(!S)return K(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?K(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(E.splice(o==="before"?y:y+1,0,f),g(me(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"})))}import*as Gu from"@babel/parser";import{cloneNode as lb}from"@babel/types";function ti(e){let{source:t,locator:n,expression:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=Re(t,"jsx-node");if(!a.ok)return a.result;let c=ub(t,r);if(!c.ok)return c.result;let l=ae(a.ast,n);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return K(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 K(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let d=l.match.path,f=null;if(i){let E=ae(a.ast,i);if(!E.ok)return{ok:!1,source:t,diagnostic:E.diagnostic};let y=rn(l.match.path,E.match.path);if(!y)return K(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");d=y,f=E.match.path.node}else if(o==="before"||o==="after")return K(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let m=lb(c.node,!0),u=d.node.children,g={...s,targetParentLocator:n},h=E=>s?mt(E,a.ast,m,g):E;if(o==="append")return u.push(m),h(me(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return u.unshift(m),h(me(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));let S=u.findIndex(E=>E===f);return S===-1?K(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(u.splice(o==="before"?S:S+1,0,m),h(me(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"})))}function ub(e,t){try{let r=Gu.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:K(e,"unsupported-syntax","Expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:K(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}import{cloneNode as db,nullLiteral as la}from"@babel/types";import*as on from"@babel/types";import*as Yu from"@babel/types";function Tr(e,t){let n=e.parentPath;if(!n?.isConditionalExpression()||e.key!=="consequent"||!Yu.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=Re(t,"jsx-node");if(!a.ok)return a.result;let c=ae(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};let l=ae(a.ast,r);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return K(t,"unsupported-syntax","move-node target parent must be a JSXElement or JSXFragment","jsx-node");let d=l.match.path;if(l.match.path.isJSXElement()){let v=l.match.path.node;if(!v.closingElement||v.openingElement.selfClosing)return K(t,"self-closing-element","Cannot move child into self-closing element","jsx-node")}let f=null;if(i){let v=ae(a.ast,i);if(!v.ok)return{ok:!1,source:t,diagnostic:v.diagnostic};let I=v.match.path.isJSXElement()?Tr(v.match.path,l.match.path):v.match.path,P=rn(l.match.path,I);if(!P)return K(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");d=P,f=I}else if(o==="before"||o==="after")return K(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let m=f&&typeof f.key=="number"?f.key:-1;if(f&&m===-1)return K(t,"locator-miss","Anchor node does not exist in target parent","jsx-node");let u=c.match.path.isJSXElement()?Tr(c.match.path,l.match.path):c.match.path,g=db(u.node,!0);if(!on.isJSXElement(g)&&!on.isJSXExpressionContainer(g)&&!on.isJSXFragment(g)&&!on.isJSXText(g))return K(t,"unsupported-syntax","move-node source must resolve to a JSX child","jsx-node");let h=u.parentPath?.node===d.node&&typeof u.key=="number"?u.key:-1;if(f&&u.parentPath?.node===f.parentPath?.node&&u.key===f.key)return K(t,"invalid-parent-child-relation","Cannot move a node relative to itself","jsx-node");fb(u);let S=d.node.children,E={...s,sourceLocator:n,targetParentLocator:r};if(o==="append")return S.push(g),mt(Zo(a.ast,t),a.ast,g,E);if(o==="prepend")return S.unshift(g),mt(Zo(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(Zo(a.ast,t),a.ast,g,E)}function fb(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(la());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(la());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(la());return}e.remove()}import*as Zu from"@babel/parser";import{cloneNode as pb,nullLiteral as ua}from"@babel/types";function ni(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,repeatExpression:s,selectionContext:a}=e,c=Re(t,"jsx-node");if(!c.ok)return c.result;let l=mb(t,s);if(!l.ok)return l.result;let d=ae(c.ast,n);if(!d.ok)return{ok:!1,source:t,diagnostic:d.diagnostic};let f=ae(c.ast,r);if(!f.ok)return{ok:!1,source:t,diagnostic:f.diagnostic};if(!f.match.path.isJSXElement()&&!f.match.path.isJSXFragment())return K(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 K(t,"self-closing-element","Cannot move repeat child into self-closing element","jsx-node")}let m=f.match.path,u=null;if(i){let v=ae(c.ast,i);if(!v.ok)return{ok:!1,source:t,diagnostic:v.diagnostic};let I=rn(f.match.path,v.match.path);if(!I)return K(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");m=I,u=v.match.path.node}else if(o==="before"||o==="after")return K(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");if(!d.match.path.isJSXElement())return K(t,"unsupported-syntax","move-repeat-template-child source must be a JSXElement","jsx-node");let g=m.node,h=pb(l.node,!0);gb(d.match.path);let S={...a,sourceLocator:n,targetParentLocator:r},E=g.children;if(o==="append")return E.push(h),mt(me(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(me(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===u);return y===-1?K(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(E.splice(o==="before"?y:y+1,0,h),mt(me(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,h,S))}function mb(e,t){try{let r=Zu.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:K(e,"unsupported-syntax","Repeat expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:K(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function gb(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(ua());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(ua());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(ua());return}e.remove()}import{SiteEditSetPropsParamsSchema as hb,classifySiteEditPropertyName as yb}from"@vcp-dev/contracts";import*as Zn from"@babel/types";function ri(e){let t=hb.safeParse({kind:"set-props",scope:"selection",changes:e.changes});if(!t.success)return K(e.source,"unsupported-syntax","Invalid typed JSX property changes","jsx-node",{issues:t.error.issues});let n=Re(e.source,"jsx-node");if(!n.ok)return n.result;let r=Hn(n.ast,e.locator,e.source);if(!r.ok)return r.result;for(let a of t.data.changes){let c=yb(a.name);if(c.owner!=="generic")return K(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=xb(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 K(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(d=>d!==c));continue}let l=Nr(a.name,a.value).value;c?c.value=l:o.attributes.push(Nr(a.name,a.value))}return me(n.ast,e.source,{kind:"set-props",target:"jsx-node",inverse:"set-props"})}function xb(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 bb}from"@vcp-dev/contracts";import*as z from"@babel/types";var Qu=["prefetch","replace","scroll","locale","onNavigate"],Sb=/^on(?:Click|DoubleClick|AuxClick|MouseDown|MouseUp|PointerDown|PointerUp|TouchStart|TouchEnd|KeyDown|KeyUp|ContextMenu)(?:Capture)?$/;function Eb(e){let t=e;for(;t;){if(t.isJSXElement()&&t.node.openingElement.attributes.some(n=>z.isJSXAttribute(n)&&z.isJSXIdentifier(n.name)&&Sb.test(n.name.name)))return!0;t=t.parentPath}return!1}function oi(e){let t=Re(e.source,"jsx-node");if(!t.ok)return t.result;let n=Hn(t.ast,e.locator,e.source);if(!n.ok)return n.result;let r=bb.safeParse({kind:"set-link-target",scope:"selection",link:e.link,changes:e.changes});if(!r.success||r.data.kind!=="set-link-target")return Xt(e.source,"Invalid typed link-target changes");let o=n.match.path,i=o.node,s=i.openingElement,a=Nb(s.name);if(!a)return Xt(e.source,"Unsupported JSX link tag");if(s.attributes.some(z.isJSXSpreadAttribute))return Xt(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=fa(g);if(!h)return Xt(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 Xt(e.source,"Duplicate JSX attributes cannot be transformed safely");let l=c.get("href")?.[0];if(l&&!wb(l))return Xt(e.source,"Dynamic link href cannot be transformed safely");let d=a==="a",f=d?null:Ib(o,s.name);if(!d&&!f)return Xt(e.source,"Only native anchors and imported next/link components are supported");if(e.link.kind==="none"&&Eb(o))return Xt(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=Cb(t.ast,o);if(!g.ok)return Xt(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")),Rb(t.ast,f,o)}else m&&d&&(s.name=z.jsxIdentifier(m),i.closingElement&&(i.closingElement.name=z.jsxIdentifier(m)));let u=new Set;return e.link.kind==="none"?(u.add("href"),u.add("target"),u.add("rel"),Qu.forEach(g=>u.add(g))):(u.add("href"),e.link.kind==="native-link"&&Qu.forEach(g=>u.add(g))),s.attributes=s.attributes.filter(g=>{if(!z.isJSXAttribute(g))return!0;let h=fa(g);return!h||!u.has(h)}),e.link.kind!=="none"&&s.attributes.push(z.jsxAttribute(z.jsxIdentifier("href"),z.stringLiteral(e.link.href))),vb(s,e.changes),me(t.ast,e.source,{kind:"set-link-target",target:"jsx-node",inverse:"set-link-target"})}function vb(e,t){for(let n of t){let r=e.attributes.find(s=>z.isJSXAttribute(s)&&fa(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(da(n.value)),i=z.jsxAttribute(z.jsxIdentifier(n.name),o);r&&z.isJSXAttribute(r)?r.value=i.value:e.attributes.push(i)}}function da(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=>da(t))):typeof e=="object"?z.objectExpression(Object.entries(e).map(([t,n])=>z.objectProperty(z.isValidIdentifier(t)?z.identifier(t):z.stringLiteral(t),da(n)))):z.nullLiteral()}function kb(e){return z.isImportDefaultSpecifier(e)||z.isImportSpecifier(e)&&e.importKind!=="type"&&(z.isIdentifier(e.imported,{name:"default"})||z.isStringLiteral(e.imported,{value:"default"}))}function qu(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 Ib(e,t){if(!z.isJSXIdentifier(t))return null;let n=e.scope.getBinding(t.name);if(!n||!qu(n.path))return null;let r=n.path.parentPath;return!r?.isImportDeclaration()||r.node.source.value!=="next/link"?null:t.name}function Cb(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(kb);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 Rb(e,t,n){let r=n.scope.getProgramParent();r.crawl();let o=r.getBinding(t);if(!o||!qu(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 wb(e){return!e.value||z.isStringLiteral(e.value)}function Nb(e){return z.isJSXIdentifier(e)?e.name:null}function fa(e){return z.isJSXIdentifier(e.name)?e.name.name:null}function Xt(e,t){return K(e,"unsupported-syntax",t,"jsx-node")}import*as Ke from"@babel/types";import{classifySiteEditPropertyName as ed}from"@vcp-dev/contracts";function ii(e){let t=ed(e.name),n=ed(e.property);if(t.owner!=="generic"||n.owner!=="generic")return K(e.source,"unsupported-syntax","Property binding is only available for generic properties","jsx-node");if(!td(e.object))return K(e.source,"unsupported-syntax","Property binding object must be a single identifier","jsx-node");if(e.property.length===0)return K(e.source,"unsupported-syntax","Property binding requires a non-empty property name","jsx-node");let r=Re(e.source,"jsx-node");if(!r.ok)return r.result;let o=Hn(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)&&Ab(l)===e.name);if(s.length>1)return K(e.source,"unsupported-syntax",`JSX attribute '${e.name}' has multiple sources`,"jsx-node");let a=Pb(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 me(r.ast,e.source,{kind:"set-property-binding",target:"jsx-node",inverse:"restore-property-binding"})}function Pb(e,t){return td(t)?Ke.memberExpression(Ke.identifier(e),Ke.identifier(t)):Ke.memberExpression(Ke.identifier(e),Ke.stringLiteral(t),!0)}function td(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(e)}function Ab(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 Fb,identifier as Fr,importDeclaration as _b,importDefaultSpecifier as Ob,importNamespaceSpecifier as Mb,importSpecifier as Db,isImportDefaultSpecifier as nd,isImportNamespaceSpecifier as rd,isImportSpecifier as od,stringLiteral as Lb}from"@babel/types";function Qn(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(S=>!zb(S));if(o!==-1){let S=r[o],E=S&&typeof S=="object"&&"kind"in S?S.kind:void 0;return K(t,"unsupported-syntax",`Unsupported import spec kind: ${String(E)}`)}let i=Ub(r);if(!i.ok)return K(t,"unsupported-syntax",i.message);let s=Re(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),d=new Set(l.flatMap(S=>S.specifiers.flatMap(E=>{let y=Hb(S,E);return y?[y]:[]}))),f=i.imports.filter(S=>!d.has(ud(S)));if(f.length===0)return wr(t,t,{kind:"add-import",target:"import",inverse:"remove-import"});let m=Jb(c.body),u=f.find(S=>m.has(pa(S)));if(u)return K(t,"unsupported-syntax",`Import local binding already exists: ${pa(u)}`);let g=Kb(f);if(g.reduce((S,E)=>S+E.length,0)!==f.length)return K(t,"unsupported-syntax","Unsupported import specifier grouping");for(let S of g){if(!cd(sd(S)))return K(t,"unsupported-syntax","Unsupported import specifier combination");let E=l.find(y=>Bb(y,S));if(E)jb(E,S);else{let y=_b(id(S),Lb(n));Xb(c.body,y),l.push(y)}}return me(a,t,{kind:"add-import",target:"import",inverse:"remove-import"})}function Bb(e,t){return e.importKind==="type"?!1:cd(Vb($b(e),sd(t)))}function jb(e,t){let n=!1,r=new Set(e.specifiers.map(o=>ma(o)));for(let o of id(t)){let i=ma(o);r.has(i)||(e.specifiers.push(o),r.add(i),n=!0)}return ld(e.specifiers),{changed:n}}function id(e){let t=e.map(n=>{switch(n.kind){case"named":return Db(n.local?Fr(n.local):Fr(n.imported),Fr(n.imported));case"default":return Ob(Fr(n.local));case"namespace":return Mb(Fr(n.local));default:return n}});return ld(t),t}function sd(e){let t=ad();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 $b(e){let t=ad();for(let n of e.specifiers)nd(n)?t.defaultLocals.add(n.local.name):rd(n)?t.namespaceLocals.add(n.local.name):t.hasNamed=!0;return t}function ad(){return{defaultLocals:new Set,hasNamed:!1,namespaceLocals:new Set}}function Vb(e,t){return{defaultLocals:new Set([...e.defaultLocals,...t.defaultLocals]),hasNamed:e.hasNamed||t.hasNamed,namespaceLocals:new Set([...e.namespaceLocals,...t.namespaceLocals])}}function cd(e){return e.defaultLocals.size>1||e.namespaceLocals.size>1?!1:!(e.hasNamed&&e.namespaceLocals.size>0)}function ld(e){let t=[...e.filter(n=>nd(n)),...e.filter(n=>rd(n)),...e.filter(n=>od(n))];e.splice(0,e.length,...t)}function Kb(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 Ub(e){let t=new Map,n=new Map;for(let r of e){let o=ud(r);if(t.has(o))continue;let i=pa(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 Jb(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(Fb(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 Xb(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 zb(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 ud(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 pa(e){return e.kind==="named"?e.local??e.imported:e.local}function Hb(e,t){return e.importKind==="type"||od(t)&&t.importKind==="type"?null:ma(t)}function ma(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(d=>!Gb(d));if(o!==-1){let d=r[o],f=d&&typeof d=="object"&&"kind"in d?d.kind:void 0;return K(t,"unsupported-syntax",`Unsupported remove import spec kind: ${String(f)}`)}let i=Re(t);if(!i.ok)return i.result;let{ast:s}=i,a=s.program,c=a.body.findIndex(d=>d.type==="ImportDeclaration"&&d.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),me(s,t,{kind:"remove-import",target:"import",inverse:"add-import"})):(l.specifiers=l.specifiers.filter(d=>!r.some(f=>Wb(d,f))),l.specifiers.length===0&&a.body.splice(c,1),me(s,t,{kind:"remove-import",target:"import",inverse:"add-import"}))}function Wb(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 Gb(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=li(t,n);return o.ok?(o.path.replaceWith(nn(r)),me(o.ast,t,{kind:"update-value",target:"value",inverse:"restore-value"})):o.result}function si(e){let{source:t,locator:n,index:r,value:o}=e,i=li(t,n);return i.ok?i.path.isArrayExpression()?i.path.node.elements.some(s=>s?.type==="SpreadElement")?K(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>i.path.node.elements.length?K(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(i.path.node.elements.splice(r,0,nn(o)),me(i.ast,t,{kind:"insert-array-element",target:"value",inverse:"remove-array-element"})):K(t,"unsupported-syntax","Array operations require array expression target","value"):i.result}function ai(e){let{source:t,locator:n,index:r}=e,o=li(t,n);return o.ok?o.path.isArrayExpression()?o.path.node.elements.some(i=>i?.type==="SpreadElement")?K(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>=o.path.node.elements.length?K(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(o.path.node.elements.splice(r,1),me(o.ast,t,{kind:"remove-array-element",target:"value",inverse:"insert-array-element"})):K(t,"unsupported-syntax","Array operations require array expression target","value"):o.result}function ci(e){let{source:t,locator:n,fromIndex:r,toIndex:o}=e,i=li(t,n);if(!i.ok)return i.result;if(!i.path.isArrayExpression())return K(t,"unsupported-syntax","Array operations require array expression target","value");if(i.path.node.elements.some(c=>c?.type==="SpreadElement"))return K(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 K(t,"array-index-out-of-range","Array move indices are out of range","value");let[s]=i.path.node.elements.splice(r,1),a=Math.min(o,i.path.node.elements.length);return i.path.node.elements.splice(a,0,s),me(i.ast,t,{kind:"move-array-element",target:"value",inverse:"move-array-element-back"})}function li(e,t){let n=Re(e,"value");if(!n.ok)return{ok:!1,result:n.result};let r=ae(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 ui(e){let t=Re(e.source,"value");if(!t.ok)return t.result;let n=ae(t.ast,e.objectLocator);if(!n.ok)return{ok:!1,source:e.source,diagnostic:n.diagnostic};if(!n.match.path.isObjectExpression())return K(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 K(e.source,"unsupported-syntax","Object property upsert does not support spreads or computed keys","value");let o=r.properties.filter(a=>Xe.isObjectProperty(a)&&Yb(a.key)===e.name);if(o.length>1)return K(e.source,"unsupported-syntax",`Object property '${e.name}' has multiple sources`,"value");let i=e.value.kind==="undefined"?Xe.unaryExpression("void",Xe.numericLiteral(0)):nn(e.value.value),s=o[0];if(s)s.value=i,s.shorthand=!1;else{let a=Xe.objectProperty(oa(e.name),i);e.name==="__proto__"&&(a.computed=!0),r.properties.push(a)}return me(t.ast,e.source,{kind:"upsert-object-property",target:"value",inverse:"restore-object-property"})}function Yb(e){return Xe.isIdentifier(e)?e.name:Xe.isStringLiteral(e)?e.value:Xe.isNumericLiteral(e)?String(e.value):null}import{isSiteEditRuntimeContainerTag as Zb,isSiteEditRuntimeVoidElementTag as Qb}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 qb(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(I=>({kind:I.kind,message:I.reason})),a=i.isOpaque,l=o.parentKey===null&&i.componentName==="Page",d=i.tag.toLowerCase(),f=i.tag!==d,m=!f&&Qb(d),u=f||Zb(d),g=f&&i.childKeys.length>0&&!i.isPublicUiComponent,h=i.textSegments.length>0&&i.textSegments.some(I=>I.editable);m&&!s.some(I=>I.kind==="void-element")&&s.push({kind:"void-element",message:`Element '${i.tag}' is void: children cannot be inserted`}),!m&&!u&&!s.some(I=>I.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&&u&&(!a||g);return{composition:r,key:e,canUpdateText:S,canInsertChild:E,canMove:!l,canRemove:!l,constraints:s}}function dd(e,t){let n=new Map;for(let r of e.nodes.keys())n.set(r,qb(r,e,t));return n}function ga(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:Ee(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Key not found: ${e.key}`}]};let n=eS(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:Ee(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:pd(r),version:{documentVersion:e.route.graph.version,contentHash:Ee(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:fd(e.route.source,o),valueRaw:s?fd(e.route.source,s):null,attrRange:pd(o),diagnostics:[]}}function md(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 eS(e,t){let n=Pt({source:e,profile:Sn({filePath:t.sourceFile,source:e})});if(!n.ok)return null;let r=ae(n.ast,{kind:"jsx-node",strategy:"structural-path",file:t.identity.file,component:t.identity.component,structuralPath:t.identity.structuralPath,expectedRange:tS(t.sourceRange)});return!r.ok||r.match.node.type!=="JSXElement"?null:r.match.node}function gd(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 fd(e,t){return t.start==null||t.end==null?"":e.slice(t.start,t.end)}function pd(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 tS(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function hd(){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 nS}from"node:crypto";import di from"node:fs/promises";import ha from"node:path";import{setTimeout as rS}from"node:timers/promises";var oS={async mkdir(e,t){await di.mkdir(e,t)},async writeFile(e,t,n){await di.writeFile(e,t,n)},async rename(e,t){await di.rename(e,t)},async rm(e,t){await di.rm(e,t)}},iS=new Set(["EACCES","EBUSY","EPERM"]),sS=[10,20,40,80,160];async function aS(e,t,n){for(let r of sS)try{await e.rename(t,n);return}catch(o){if(!cS(o))throw o;await rS(r)}await e.rename(t,n)}function cS(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&iS.has(e.code)}async function fi(e,t,n=oS){let r=ha.dirname(e),o=ha.basename(e),i=ha.join(r,`.${o}.${process.pid}.${nS()}.tmp`),s=!1;try{await n.mkdir(r,{recursive:!0}),await n.writeFile(i,t,"utf8"),await aS(n,i,e),s=!0}finally{if(!s)try{await n.rm(i,{force:!0})}catch{}}}import ya from"@babel/traverse";import*as k from"@babel/types";import*as ue from"@babel/types";function _t(e,t={}){if(ue.isTSAsExpression(e)||ue.isTSSatisfiesExpression(e)||ue.isTSNonNullExpression(e)||ue.isTypeCastExpression(e)||ue.isParenthesizedExpression(e))return _t(e.expression,t);if(ue.isStringLiteral(e))return{status:"resolved",value:e.value};if(ue.isNumericLiteral(e))return Number.isFinite(e.value)?{status:"resolved",value:e.value}:{status:"unresolved"};if(ue.isBooleanLiteral(e))return{status:"resolved",value:e.value};if(ue.isNullLiteral(e))return{status:"resolved",value:null};if(ue.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(ue.isIdentifier(e))return e.name==="undefined"&&!t.resolveIdentifier?{status:"undefined"}:t.resolveIdentifier?.(e.name)??{status:"unresolved"};if(ue.isUnaryExpression(e)&&e.operator==="void"&&ue.isNumericLiteral(e.argument)&&e.argument.value===0)return{status:"undefined"};if(ue.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||ue.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(ue.isObjectExpression(e)){let n=Object.create(null);for(let r of e.properties){if(!ue.isObjectProperty(r)||r.computed||!ue.isExpression(r.value))return{status:"unresolved"};let o=lS(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 ue.isMemberExpression(e)||ue.isOptionalMemberExpression(e)?t.resolveMember?.(e)??{status:"unresolved"}:{status:"unresolved"}}function lS(e){return ue.isIdentifier(e)?e.name:ue.isStringLiteral(e)?e.value:ue.isNumericLiteral(e)?String(e.value):null}var uS=typeof ya=="function"?ya:ya.default;function Ge(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 dS(e){return/^[A-Z]/.test(e)}function va(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 xd(e){return k.isJSXIdentifier(e.name)?e.name.name:k.isJSXMemberExpression(e.name)?bd(e.name):k.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:"unknown"}function bd(e){return k.isJSXIdentifier(e.object)?`${e.object.name}.${e.property.name}`:k.isJSXMemberExpression(e.object)?`${bd(e.object)}.${e.property.name}`:e.property.name}function fS(e){return e.split(".")[0]??e}function pS(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 mS(){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 gS(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 zt(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)?zt(n.value,t):k.isRestElement(n)&&zt(n.argument,t);return t}if(k.isArrayPattern(e)){for(let n of e.elements)n&&(k.isRestElement(n)?zt(n.argument,t):zt(n,t));return t}return k.isAssignmentPattern(e)?(zt(e.left,t),t):(k.isRestElement(e)&&zt(e.argument,t),t)}function Et(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function Or(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 hS(e,t,n){e.set(t,{resolved:!0,value:n})}function ka(e,t){e.set(t,{resolved:!1})}function Sd(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 pi([$e(e.left,t,n),$e(e.right,t,n)]);if(k.isBinaryExpression(e))return pi([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 pi([$e(e.consequent,t,n),$e(e.alternate,t,n)]);if(k.isTemplateLiteral(e))return pi(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=sn(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 pi(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 sn(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=Or(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=sn(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=Or(r.value.name,t.valueScopes);if(s.kind!=="resolved")return;i=s.value}else i=sn(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=Or(n.base,t.valueScopes);if(r.kind!=="resolved")return;let o=Sd(r.value,n.path);return o.kind==="resolved"?o.value:void 0}if(k.isCallExpression(e))return vd(e,t)??void 0}function Ed(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=Or(r.base,t.valueScopes),i=r.kind==="identifier"?o:o.kind==="resolved"?Sd(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 xa(e,t,n,r,o,i){return{file:e,componentName:t,elements:n,regions:r,ordinalTracker:mS(),parentStack:[],valueScopes:i,importMap:o}}function Sa(e,t,n){for(let r of e)for(let o of r.declarations){for(let s of zt(o.id))ka(n,s);if(!k.isIdentifier(o.id)||!o.init||!k.isExpression(o.init))continue;let i=sn(o.init,t);i!==void 0&&hS(n,o.id.name,i)}}function yS(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 xS(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:Ge(i),editable:!0,source:null})}else if(k.isJSXExpressionContainer(i)&&k.isStringLiteral(i.expression))r.push({index:o++,value:i.expression.value,sourceRange:Ge(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:Ge(i),editable:!0,source:null}):r.push({index:o++,value:Et(s,n),sourceRange:Ge(i),editable:!0,source:$e(s,n,t)})}else if(k.isJSXExpressionContainer(i)&&k.isExpression(i.expression)){let s=Ed(i.expression,t,n);s&&r.push({index:o++,value:s.value,sourceRange:Ge(i),editable:!0,source:s.source})}return r}function bS(e,t,n){let r=[];for(let[o,i]of e.attributes.entries()){if(!k.isJSXAttribute(i))continue;let s=ES(i.name);if(!s)continue;let a=Et(i,n);if(k.isStringLiteral(i.value)){r.push({name:s,value:i.value.value,sourceRange:Ge(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:Ge(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=sn(i.value.expression,t);if(s==="className"){let u=typeof c=="string"?c:c===void 0?vd(i.value.expression,t):null;if(u){r.push({name:s,value:u,sourceRange:Ge(i),source:null,resolvedValue:u,syntaxKind:"expression",raw:a,order:o,resolution:{status:"resolved",value:u}});continue}}let l=Ed(i.value.expression,t,n);if(c!==void 0){r.push({name:s,value:NS(c),sourceRange:Ge(i),source:$e(i.value.expression,n,t),resolvedValue:c,syntaxKind:"expression",raw:a,order:o,resolution:{status:"resolved",value:c}});continue}let d=vS(i.value.expression,t),f=$e(i.value.expression,n,t),m=l?.value??Et(i.value.expression,n);r.push({name:s,value:d.status==="undefined"?"undefined":m,sourceRange:Ge(i),source:l?.source??f,syntaxKind:"expression",raw:a,order:o,resolution:d})}}return r}function SS(e,t,n){return e.attributes.flatMap((r,o)=>!k.isJSXSpreadAttribute(r)||!k.isExpression(r.argument)?[]:[{raw:Et(r.argument,n),sourceRange:Ge(r),order:o,source:$e(r.argument,n,t)}])}function ES(e){return k.isJSXIdentifier(e)?e.name:k.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function vS(e,t){return _t(e,{resolveIdentifier(n){let r=Or(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=sn(n,t);return r===void 0?{status:"unresolved"}:{status:"resolved",value:r}}})}function vd(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=sn(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=sn(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=IS(r.key);if(!o)return null;n.push(o)}return n}if(k.isCallExpression(e)){let n=kS(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 kS(e){return k.isIdentifier(e)?e.name:k.isMemberExpression(e)&&k.isIdentifier(e.property)?e.property.name:null}function IS(e){return k.isIdentifier(e)?e.name:k.isStringLiteral(e)?e.value:null}function CS(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 RS(e,t){for(let n of t){let r=CS(e,n);if(r)return r}return null}function wS(e){return k.isJSXIdentifier(e.name)?e.name.name:null}function NS(e){return e===null?"null":typeof e=="boolean"?e?"true":"false":JSON.stringify(e)}function PS(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 ba(e){return k.isArrowFunctionExpression(e)||k.isFunctionExpression(e)}function AS(e){return e==="render"||e==="itemRender"||e==="rowRender"||e==="children"}function TS(e){return e==="empty"||e==="emptyRender"||e==="loading"||e==="loadingRender"||e==="error"||e==="errorRender"||e==="fallback"||e==="headerRender"||e==="footerRender"}function yd(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 Ht(e,t,n){if(!e)return[];if(k.isJSXElement(e)){if(va(e))return xi(e.children,t,n);let r=hi(e,t,n);return r?[r]:[]}return nr(e)?yi(e,t,n):k.isParenthesizedExpression(e)?Ht(e.expression,t,n):k.isExpression(e)?bi(e,t,n):[]}function mi(e,t,n){let r=new Map;for(let o of e.params)for(let i of zt(o))ka(r,i);t.valueScopes.push(r);try{if(!k.isBlockStatement(e.body))return Ht(e.body,t,n);let o=new Map;t.valueScopes.push(o);try{return kd(e.body.body,t,n)}finally{t.valueScopes.pop()}}finally{t.valueScopes.pop()}}function kd(e,t,n){let r=[];for(let o of e){if(k.isVariableDeclaration(o)){let i=t.valueScopes[t.valueScopes.length-1];if(i){Sa([o],t,i);for(let s of o.declarations)k.isIdentifier(s.id)&&(k.isJSXElement(s.init)||k.isJSXFragment(s.init))&&r.push(...Ht(s.init,t,n))}continue}r.push(...Ea(o,t,n))}return r}function Ea(e,t,n){if(k.isReturnStatement(e))return e.argument?Ht(e.argument,t,n):[];if(k.isBlockStatement(e))return wn(e.body,t,n);if(k.isIfStatement(e)){let r=k.isBlockStatement(e.consequent)?wn(e.consequent.body,t,n):Ea(e.consequent,t,n),o=e.alternate?k.isBlockStatement(e.alternate)?wn(e.alternate.body,t,n):Ea(e.alternate,t,n):[];return[...r,...o]}if(k.isSwitchStatement(e))return wn(e.cases.flatMap(r=>r.consequent),t,n);if(k.isTryStatement(e)){let r=wn(e.block.body,t,n);return e.handler&&r.push(...wn(e.handler.body.body,t,n)),e.finalizer&&r.push(...wn(e.finalizer.body,t,n)),r}return[]}function wn(e,t,n){let r=new Map;t.valueScopes.push(r);try{return kd(e,t,n)}finally{t.valueScopes.pop()}}function gi(e,t,n,r,o,i){o.length!==0&&e.regions.push({kind:t,ownerKey:n,childKeys:o,sourceRange:Ge(r),sourceCandidates:i&&i.length>0?i:void 0})}function FS(e,t,n,r){let o=RS(e.openingElement,["items","dataSource","data"]),i={key:t,tag:xd(e.openingElement)};n.parentStack.push(i);try{for(let s of e.openingElement.attributes){if(!k.isJSXAttribute(s))continue;let a=wS(s);if(!a||!k.isJSXExpressionContainer(s.value))continue;let c=s.value.expression;if(!k.isJSXEmptyExpression(c)){if(AS(a)&&ba(c)){let l=mi(c,n,r),d=yd(o,c,r,n);gi(n,"repeat-region",t,s,l,d?[d]:void 0);continue}if(TS(a)){let l=ba(c)?mi(c,n,r):Ht(c,n,r);gi(n,"conditional-region",t,s,l)}}}if(o)for(let s of e.children){if(!k.isJSXExpressionContainer(s)||!ba(s.expression))continue;let a=mi(s.expression,n,r),c=yd(o,s.expression,r,n);gi(n,"repeat-region",t,s,a,c?[c]:void 0)}}finally{n.parentStack.pop()}}function hi(e,t,n){let r=xd(e.openingElement);if(r==="Fragment"||va(e))return xi(e.children,t,n),null;let o=t.parentStack[t.parentStack.length-1]??null,i=o?.key??null,s=dS(r),a;if(s){let I=t.ordinalTracker.getOrdinal(i,r);a=`component:${r}#${I}`}else{let I=t.ordinalTracker.getOrdinal(i,r);a=`${r}#${I}`}let c=o?t.elements.get(o.key)?.identity.structuralPath:void 0,l=c?`${c}/${a}`:a,d=Pr(t.file,t.componentName,l),f={file:t.file,component:t.componentName,structuralPath:l,key:d},m=s?"component-boundary":null,u=xS(e.children,t,n),g=bS(e.openingElement,t,n),h=SS(e.openingElement,t,n),S,E,y=!1;if(s){let I=t.importMap.get(r)??t.importMap.get(fS(r));I&&(S=I.specifier,E=I.exportName,y=vn(I.specifier,t.file))}let v={identity:f,tag:r,componentName:t.componentName,sourceFile:t.file,sourceRange:Ge(e),parentKey:i,childKeys:[],textSegments:u,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(d,v),i&&t.elements.has(i)&&t.elements.get(i).childKeys.push(d),FS(e,d,t,n),(!s||e.children.length>0)&&(t.parentStack.push({key:d,tag:r}),_S(e.children,t,n),t.parentStack.pop()),d}function yi(e,t,n){return xi(e.children,t,n)}function xi(e,t,n){let r=[];for(let o of e)if(k.isJSXElement(o))if(va(o))r.push(...xi(o.children,t,n));else{let i=hi(o,t,n);i&&r.push(i)}else nr(o)?r.push(...yi(o,t,n)):k.isJSXExpressionContainer(o)&&r.push(...bi(o.expression,t,n));return r}function _S(e,t,n){for(let r of e)k.isJSXElement(r)?hi(r,t,n):nr(r)?yi(r,t,n):k.isJSXExpressionContainer(r)&&bi(r.expression,t,n)}function OS(e){return e==="&&"||e==="||"||e==="??"}function bi(e,t,n){if(k.isJSXEmptyExpression(e))return[];let r=PS(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 d=a.params[0],f=a.params[1];k.isIdentifier(d)&&(c.itemParamName=d.name),k.isIdentifier(f)&&(c.indexParamName=f.name)}s.push(c);let l={kind:"repeat-region",ownerKey:i?.key??"",childKeys:[],sourceRange:Ge(o),sourceCandidates:s.length>0?s:void 0};return t.regions.push(l),(k.isArrowFunctionExpression(a)||k.isFunctionExpression(a))&&l.childKeys.push(...mi(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:Ge(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...Ht(e.consequent,t,n)),s.childKeys.push(...Ht(e.alternate,t,n)),s.childKeys}if(k.isLogicalExpression(e)&&OS(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:Ge(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...Ht(e.right,t,n)),s.childKeys}if(k.isParenthesizedExpression(e))return bi(e.expression,t,n);if(k.isJSXElement(e)){let o=hi(e,t,n);return o?[o]:[]}return nr(e)?yi(e,t,n):[]}function MS(e){let t=e.argument;return t&&(k.isExpression(t)||nr(t))?t:null}function Mr(e,t){let n=[];for(let r of e){if(k.isReturnStatement(r)){let o=MS(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(...Mr(o,r.test)),r.alternate){let i=k.isBlockStatement(r.alternate)?r.alternate.body:[r.alternate];n.push(...Mr(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(...Mr(o.consequent,i))}}return n}function Id(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=gS(r);uS(r,{"FunctionDeclaration|FunctionExpression|ArrowFunctionExpression"(f){let m=pS(f);if(!m)return;let u=f.node,g=[];if(k.isArrowFunctionExpression(u))k.isExpression(u.body)||nr(u.body)?g=[{argument:u.body,statement:k.returnStatement(k.isExpression(u.body)?u.body:null)}]:k.isBlockStatement(u.body)&&(g=Mr(u.body.body));else{let I=u.body;k.isBlockStatement(I)&&(g=Mr(I.body))}if(g.length===0){f.skip();return}let h=new Map;Sa(yS(r.program.body),xa(t,m,i,s,l,[h]),h);let S=new Map;for(let I of u.params)for(let P of zt(I))ka(S,P);let E=k.isBlockStatement(u.body)?u.body.body:[],y=g[0]?.statement??null;for(let I of E){if(y&&I===y)break;k.isVariableDeclaration(I)&&Sa([I],xa(t,m,i,s,l,[h,S]),S)}let v=xa(t,m,i,s,l,[h,S]);for(let I of g){let P=Ht(I.argument,v,n);for(let A of P)a.includes(A)||a.push(A);if(I.condition){let A={kind:"conditional-branch",conditionExpression:Et(I.condition,n),conditionSource:$e(I.condition,n,v)};gi(v,"conditional-region","",I.statement,P,[A])}}f.skip()}});let d=[...i.keys()];return d.length>0&&c.set(t,d),{graph:{routeId:t,rootKeys:a,elements:i,regions:s,fileIndex:c,version:1,diagnostics:[]},localImports:o}}function Ia(e,t,n,r){return[...e.map(o=>({...o})),{fromFile:t,specifier:n,targetPath:r}]}function Si(e,t,n){return{...e,details:{...e.details??{},entryFile:t,importStack:n.map(r=>({...r}))}}}async function Cd(e,t,n,r,o={}){let i=o.maxDepth??10,s=o.version??1,a=o.parseModule??En,c=new Map,l=new Map,d=new Map,f=[],m=new Set,u=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:I,diagnosticEntryFile:P,importStack:A}=E;if(h.has(y))continue;h.add(y),c.set(y,v);let R=a(y,v);if(!R.ok){u(Si(R.diagnostic,P,A));continue}d.set(y,R.module);let{graph:T,localImports:F}=Id(R.module);for(let D of T.elements.values())if(D.importedFrom&&Nt(D.importedFrom)){let U=D.importedFrom,ee=await Oo(y,U,r);ee.ok?(D.importedFrom=ee.path,Kt(ee.path)&&(D.isPublicUiComponent=!0)):vn(U,y)||u(Si(ee.diagnostic,P,Ia(A,y,U,ee.diagnostic.path)))}if(l.set(y,T),!(I>=i))for(let D of F){if(su(D))continue;let U=await Oo(y,D,r);if(!U.ok){vn(D,y)||u(Si(U.diagnostic,P,Ia(A,y,D,U.diagnostic.path)));continue}let ee=U.path;if(h.has(ee)||Kt(ee))continue;let we=Ia(A,y,D,ee);try{let Q=await n(ee);g.push({file:ee,source:Q,depth:I+1,diagnosticEntryFile:P,importStack:we})}catch(Q){u(Si({path:ee,code:"import-read-failed",message:`Failed to read imported file: ${ee}`,details:{fromFile:y,specifier:D,reason:Q instanceof Error?Q.message:String(Q)}},P,we))}}}let S=DS(e,l,s,(o.additionalEntries??[]).map(E=>E.file));return S.diagnostics=f,{graph:S,allSources:c,diagnostics:f,parsedModules:d,entryModule:d.get(e)??null}}function DS(e,t,n,r=[]){let o=new Map,i=[],s=new Map,a=[];for(let[c,l]of t){for(let[d,f]of l.elements)o.set(d,f);for(let d of l.regions)i.push(d);for(let[d,f]of l.fileIndex){let m=s.get(d)??[];s.set(d,[...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 dE}from"@vcp-dev/contracts";import{createHash as LS,randomUUID as Oa}from"node:crypto";import _e from"node:fs/promises";import Me from"node:path";var Md=new WeakMap;function rr(e){return Md.get(e)?.()??e.readIndex()}var gt=1,Ra=1,BS=2,jS="index.json",$S="recovery.json",VS="transaction-journal.json",KS="document-version.json",ki={maxEntries:100,maxSessionBytes:512*1024*1024,maxEntryBytes:128*1024*1024},re={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"},oe=class extends Error{constructor(t,n,r){super(n),this.name="FileHistoryStoreError",this.code=t,r?.cause!==void 0&&(this.cause=r.cause)}};function Wt(){return{entries:new Map,blobSizes:new Map}}function Ei(e,t){let n={entries:new Map,blobs:new Map,objectBytes:0};for(let r of e)Dd(n,r,t);return n}function Dd(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 Ld(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 Bd(e,t={}){let n=iE(e),r=lE(t.limits),o=Ca(n),i=sE(n),s=await tt(i),a=await tt(o)||s;a||(await ZS(n),await QS(n)),a||await uE(n);let c=Wt(),l=await Ci(n,c),d=new Set(a?(await Ai(n)).map(y=>y.stageId):[]);a||await Ad(n,l.entryIds,c);let f=l.digest,m=Ei(l.entryIds,c),u=async y=>{let{index:v,sizeBytes:I}=await $r(n);if(Xd(v,y),v.digest!==f){let P=Wt();await Kd(n,v.entryIds,P,I),m=Ei(v.entryIds,P),f=v.digest}return{...Ti(v),totalBytes:m.objectBytes+I}},g=async y=>{Ma(y),await u(),await Nd(n,m,[y.entryId],y.blobIds,y.stageId),await Ii(n,y.stageId)},h=async(y,v)=>{let I=await u(v);$d(y,I.entryIds.length);let P=Wt();for(let A of I.entryIds.slice(Math.min(I.cursor,y)+1,Math.max(I.cursor,y)+1))await Lr(n,A,P);return I},S=async()=>{if(await tt(o)||s)throw new oe(re.RECOVERY_PENDING,"history store requires explicit recovery before accepting writes")},E={rootDir:n,recoveryRequired:a,async readDocumentVersion(){return _d(n)},async writeDocumentVersion(y){if(await S(),!Number.isInteger(y)||y<0)throw new oe(re.INVALID_SCHEMA,"document version must be a non-negative integer");let v=await _d(n);y<=v||await Dr(Gd(n),{schemaVersion:1,version:Math.max(v,y)})},async stageAppend(y,v={}){await S();let I=await XS(y,r),P={schemaVersion:Ra,stageId:Oa(),entryId:I.entryId,blobIds:I.blobs.map(A=>A.digest)};try{await zS(n,I),await WS(n,P,v.durableManifest!==!1)}catch(A){try{await g(P)}catch(R){throw new oe(re.INDEX_CORRUPT,"staged history cleanup failed after preparation error",{cause:R})}throw A}return{stageId:P.stageId,entryId:P.entryId,blobIds:P.blobIds}},async discardStage(y){await S(),Pa(y);let v=await wa(n,y);v&&await g(v)},async previewStagedAppend(y,v){await S();let I=await u(v);return(await Rd(n,r,y,I,m)).transition},async previewCursor(y,v){await S();let I=await h(y,v);return jd(I,I.entryIds,y)},async publishStagedAppend(y,v,I){if(await S(),wi(y,"entryId"),I){Pa(I);let F=await wa(n,I);if(!F||F.entryId!==y)throw new oe(re.INVALID_SCHEMA,"history stage does not match the published entry")}let P=await u(v),A=m,R=await Rd(n,r,y,P,A),T=await Fd({rootDir:n,previousDigest:R.current.digest,entryIds:R.entryIds,cursor:R.cursor,readback:async()=>Td(n,R.usage),afterWrite:async()=>{I?await Ii(n,I):await YS(n,y),await Nd(n,R.usage,[...A.entries.keys()].filter(F=>!R.usage.entries.has(F)),[...A.blobs.keys()].filter(F=>!R.usage.blobs.has(F)))}});return m=R.usage,f=T.digest,T},async append(y){await S();let v=await u(),I=await E.stageAppend(y);try{return await E.publishStagedAppend(I.entryId,v.digest,I.stageId)}catch(P){throw await E.discardStage(I.stageId),P}},async readEntry(y){return wi(y,"entryId"),Lr(n,y)},async readBlob(y){wi(y,"blobId");let v=await Zd(n,y),I=await Br(v,re.NOT_FOUND,"blob");return Wd(I,y,v),I},async readIndex(){let y=Wt(),v=await Ci(n,y);return m=Ei(v.entryIds,y),f=v.digest,v},async readStatus(){let y=await Ri(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 tt(o)||await tt(i)}},async readUndoRedoIds(){let y=await Ri(n);return{undoIds:y.undoIds,redoIds:y.redoIds,currentId:y.currentId}},async setCursor(y,v){await S();let I=await h(y,v),P=await Fd({rootDir:n,previousDigest:I.digest,entryIds:I.entryIds,cursor:y,readback:async()=>Td(n,m)});return f=P.digest,P},async markRecoveryRequired(y){await tt(o)||await Dr(Ca(n),{schemaVersion:gt,reason:aE(y),createdAt:new Date().toISOString()})},async clearRecoveryRequired(){await _e.rm(Ca(n),{force:!0})},async readTransactionJournal(){return await tt(i)?vi(i):null},async writeTransactionJournal(y){await S(),Yd(y);try{await Dr(i,y)}catch(I){let P=await vi(i).catch(()=>null);if(P&&Buffer.from(nt(P)).equals(Buffer.from(nt(y))))return;throw P?new oe(re.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous",{cause:I}):I}let v=await vi(i);if(!Buffer.from(nt(v)).equals(Buffer.from(nt(y))))throw new oe(re.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous")},async clearTransactionJournal(y){let v=await tt(i)?await vi(i):null;if(v&&v.transactionId!==y)throw new oe(re.INVALID_SCHEMA,"transaction journal changed concurrently");try{await _e.rm(i,{force:!0})}catch(I){if(!await tt(i))return;throw I}if(await tt(i))throw new oe(re.INDEX_CORRUPT,"transaction journal clear outcome is ambiguous");s=!1},async cleanupTmp(){await S();for(let I of d)await Ii(n,I),d.delete(I);await qS(n);let y=Wt(),v=await Ci(n,y);await Ad(n,v.entryIds,y),m=Ei(v.entryIds,y),f=v.digest}};return Md.set(E,()=>Ri(n)),E}async function Rd(e,t,n,r,o){wi(n,"entryId");let i=Wt(),s=await Lr(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 d of r.entryIds.slice(r.cursor+1))Ld(a,d);Dd(a,s.id,i),c.push(s.id);let l=HS(c,t,a);return{current:r,entryIds:l.entryIds,cursor:l.cursor,usage:a,transition:jd(r,l.entryIds,l.cursor)}}function jd(e,t,n){return $d(n,t.length),{expectedIndexDigest:e.digest,publishedIndexDigest:US(t,n),publishedCursor:n,publishedCurrentId:t[n]??null}}function US(e,t){return an(nt({schemaVersion:gt,entryIds:e,cursor:t}))}function $d(e,t){if(!Number.isInteger(e)||e<-1||e>=t)throw new oe(re.INVALID_SCHEMA,`history cursor is out of bounds: ${e}`)}function JS(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 XS(e,t){if(!e.kind.trim())throw new oe(re.INVALID_JSON,"history entry kind must not be empty");let n=[],r=[];for(let c of e.blobs??[]){if(!c.name.trim())throw new oe(re.INVALID_JSON,"history blob name must not be empty");let l=oE(c.data),d=an(l);n.push({name:c.name,bytes:l,digest:d,sizeBytes:l.byteLength}),r.push({name:c.name,digest:d,sizeBytes:l.byteLength})}let o={schemaVersion:gt,kind:e.kind,manifest:e.manifest,blobs:r},i=nt({...o}),s=an(i),a=i.byteLength+n.reduce((c,l)=>c+l.sizeBytes,0);if(a>t.maxEntryBytes)throw new oe(re.CAPACITY_EXCEEDED,`history entry exceeds maxEntryBytes (${a} > ${t.maxEntryBytes})`);return{entryBody:o,entryId:s,blobs:n}}async function zS(e,t){let n=ja(e,t.entryId),r={id:t.entryId,...t.entryBody},o=[...t.blobs.map(a=>wd($a(e,a.digest),a.bytes,{kind:"blob",digest:a.digest},Ka(e,a.digest))),wd(n,nt(r),{kind:"entry",digest:t.entryId},Va(e,t.entryId))],s=(await Promise.allSettled(o)).find(a=>a.status==="rejected");if(s)throw s.reason}async function wd(e,t,n,r){let o=await Fa(e)??(r?await Fa(r):null);if(o!==null){if(Buffer.compare(o,t)!==0)throw new oe(n.kind==="blob"?re.BLOB_CORRUPT:re.ENTRY_CORRUPT,`${n.kind} content mismatch for ${n.digest}`);return}await zd(e,t)}function HS(e,t,n){let r=[...e],o=r.length-1;for(;;){if(n.objectBytes+nt(Jd(r,o)).byteLength<=t.maxSessionBytes&&r.length<=t.maxEntries)return{entryIds:r,cursor:o};if(o<=0||r.length===0)throw new oe(re.CAPACITY_EXCEEDED,"history store exceeds capacity limits and the current entry cannot be trimmed");Ld(n,r.shift()),o-=1}}async function WS(e,t,n){Ma(t);let r=Ba(e,t.stageId);if(n){await Dr(r,t);return}await rE(r,t)}async function wa(e,t){let n=await Fa(Ba(e,t));if(n===null)return null;let r=Vr(Buffer.from(n).toString("utf8"),`history stage ${t}`),o=Ma(r);if(o.stageId!==t)throw new oe(re.INVALID_SCHEMA,`history stage id mismatch: ${t}`);return o}async function Ai(e){let t=[];for(let n of await Pi(La(e))){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);Pa(r);let o=await wa(e,r);o&&t.push(o)}return t}async function Nd(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 Ai(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 Pd(ja(e,a),Va(e,a));for(let a of new Set(r))!t.blobs.has(a)&&!s.has(a)&&await Pd($a(e,a),Ka(e,a));await _a(Kr(e)),await _a(Ur(e))}async function Ii(e,t){await Na(Ba(e,t)),await GS(e)}async function GS(e){try{await _e.rmdir(La(e))}catch(t){if(Jr(t)||vt(t)&&t.code==="ENOTEMPTY")return;throw t}}async function YS(e,t){for(let n of await Ai(e))n.entryId===t&&await Ii(e,n.stageId)}async function Na(e){if(await _e.rm(e,{force:!0}),await tt(e))throw new oe(re.INDEX_CORRUPT,`unable to remove staged history object: ${e}`)}async function Pd(e,t){await Na(e),await Na(t)}function Ma(e){if(!vt(e)||e.schemaVersion!==Ra||typeof e.stageId!="string"||!Vd(e.stageId)||!at(e.entryId))throw new oe(re.INVALID_SCHEMA,"history stage schema is invalid");let t=Hd(e.blobIds,"history stage blobIds");return{schemaVersion:Ra,stageId:e.stageId,entryId:e.entryId,blobIds:t}}function Pa(e){if(!Vd(e))throw new oe(re.INVALID_PATH,"history stageId must be a UUID")}function Vd(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 Ad(e,t,n=Wt()){let r=new Set(t),o=new Set;for(let l of t){let d=await Lr(e,l,n);for(let f of d.blobs)o.add(f.digest)}for(let l of await Ai(e)){r.add(l.entryId);for(let d of l.blobIds)o.add(d)}let i=Kr(e),s=await Pi(i);for(let l of s){if(!l.endsWith(".json"))continue;let d=Od(l.slice(0,-5));d&&!r.has(d)&&await Ni(Me.join(i,l))}let a=Ur(e),c=await Pi(a);for(let l of c){let d=Od(l);d&&!o.has(d)&&await Ni(Me.join(a,l))}}async function Ci(e,t=Wt()){let{index:n,sizeBytes:r}=await $r(e),{totalBytes:o}=await Kd(e,n.entryIds,t,r);return{...Ti(n),totalBytes:o}}async function Td(e,t){let{index:n,sizeBytes:r}=await $r(e);return{...Ti(n),totalBytes:t.objectBytes+r}}async function $r(e){let t=Da(e),n=await Br(t,re.NOT_FOUND,"index"),r=Vr(Buffer.from(n).toString("utf8"),"index");return{index:eE(r),sizeBytes:n.byteLength}}async function Ri(e){return Ti((await $r(e)).index)}function Ti(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 Kd(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 Lr(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 Lr(e,t,n=Wt()){let r=n.entries.get(t);if(r)return r.entry;let o=await cE(e,t),i=await Br(o,re.NOT_FOUND,"entry"),s=Vr(Buffer.from(i).toString("utf8"),`entry ${t}`),a=tE(s);if(a.id!==t)throw new oe(re.ENTRY_CORRUPT,`entry id mismatch for ${t}`);if(an(nt({schemaVersion:a.schemaVersion,kind:a.kind,manifest:a.manifest,blobs:a.blobs}))!==t)throw new oe(re.ENTRY_CORRUPT,`entry hash mismatch for ${t}`);for(let l of a.blobs){if(n.blobSizes.has(l.digest))continue;let d=await Zd(e,l.digest),f=await Br(d,re.NOT_FOUND,"blob");Wd(f,l.digest,d),n.blobSizes.set(l.digest,f.byteLength)}return n.entries.set(t,{entry:a,sizeBytes:i.byteLength}),a}async function Ud(e,t,n){await Dr(Da(e),Jd(t,n))}function Jd(e,t){return{schemaVersion:gt,digest:an(nt({schemaVersion:gt,entryIds:e,cursor:t})),entryIds:e,cursor:t}}function Xd(e,t){if(t!==void 0&&e.digest!==t)throw new oe(re.INVALID_SCHEMA,`history index changed concurrently (expected ${t}, current ${e.digest})`)}async function Fd(e){Xd(await Ri(e.rootDir),e.previousDigest);let t=an(nt({schemaVersion:gt,entryIds:e.entryIds,cursor:e.cursor}));try{await Ud(e.rootDir,e.entryIds,e.cursor),await e.afterWrite?.();let n=await e.readback();if(n.digest!==t)throw new oe(re.INDEX_CORRUPT,"history index readback did not match the published transition");return n}catch(n){let r=await Ci(e.rootDir).catch(()=>null);if(r?.digest===t)return r;throw r?.digest===e.previousDigest?n:new oe(re.INDEX_CORRUPT,"history index publish outcome is ambiguous",{cause:n})}}async function ZS(e){await _e.mkdir(e,{recursive:!0}),await _e.mkdir(Kr(e),{recursive:!0}),await _e.mkdir(Ur(e),{recursive:!0}),await _e.mkdir(jr(e),{recursive:!0})}async function QS(e){await _e.rm(jr(e),{recursive:!0,force:!0}),await _e.mkdir(jr(e),{recursive:!0})}async function qS(e){let t=jr(e);await _e.mkdir(t,{recursive:!0});for(let n of await Pi(t))n!=="stages"&&await _e.rm(Me.join(t,n),{recursive:!0,force:!0})}function eE(e){if(!vt(e))throw new oe(re.INDEX_CORRUPT,"index.json must be an object");if(e.schemaVersion!==gt)throw new oe(re.INVALID_SCHEMA,`unsupported index schemaVersion: ${String(e.schemaVersion)}`);let t=Hd(e.entryIds,"index.entryIds"),n=e.cursor;if(!Number.isInteger(n)||n<-1||n>=t.length)throw new oe(re.INDEX_CORRUPT,"index cursor is out of bounds");let r=n,o=e.digest;if(!at(o))throw new oe(re.INDEX_CORRUPT,"index digest is invalid");let i=an(nt({schemaVersion:gt,entryIds:t,cursor:r}));if(o!==i)throw new oe(re.INDEX_CORRUPT,"index digest mismatch");return{schemaVersion:gt,digest:o,entryIds:t,cursor:r}}function tE(e){if(!vt(e))throw new oe(re.ENTRY_CORRUPT,"entry must be an object");if(e.schemaVersion!==gt)throw new oe(re.INVALID_SCHEMA,`unsupported entry schemaVersion: ${String(e.schemaVersion)}`);let t=e.id;if(!at(t))throw new oe(re.ENTRY_CORRUPT,"entry id is invalid");let n=e.kind;if(typeof n!="string"||n.trim().length===0)throw new oe(re.ENTRY_CORRUPT,"entry kind is invalid");let r=Ta(e.manifest,"entry.manifest"),o=nE(e.blobs);return{id:t,schemaVersion:gt,kind:n,manifest:r,blobs:o}}function nE(e){if(!Array.isArray(e))throw new oe(re.ENTRY_CORRUPT,"entry blobs must be an array");return e.map((t,n)=>{if(!vt(t))throw new oe(re.ENTRY_CORRUPT,`entry blob ref ${n} must be an object`);let r=t.name;if(typeof r!="string"||r.trim().length===0)throw new oe(re.ENTRY_CORRUPT,`entry blob ref ${n} name is invalid`);let o=t.digest;if(!at(o))throw new oe(re.ENTRY_CORRUPT,`entry blob ref ${n} digest is invalid`);let i=t.sizeBytes;if(!Number.isInteger(i)||i<0)throw new oe(re.ENTRY_CORRUPT,`entry blob ref ${n} sizeBytes is invalid`);return{name:r,digest:o,sizeBytes:i}})}async function Dr(e,t){await zd(e,nt(t))}async function rE(e,t){let n=Me.dirname(e),r=Me.basename(e),o=Me.join(n,`.${r}.${process.pid}.${Oa()}.tmp`);await _e.mkdir(n,{recursive:!0});try{await _e.writeFile(o,nt(t),{flag:"wx"}),await _e.rename(o,e)}finally{await Ni(o)}}async function zd(e,t){let n=Me.dirname(e),r=Me.basename(e),o=Me.join(n,`.${r}.${process.pid}.${Oa()}.tmp`);await _e.mkdir(n,{recursive:!0});try{let i=await _e.open(o,"wx");try{await i.writeFile(t),await i.sync()}finally{await i.close()}await _e.rename(o,e),await _a(n)}finally{await Ni(o)}}function nt(e){return Buffer.from(JSON.stringify(Aa(e)),"utf8")}function Aa(e){if(Array.isArray(e))return e.map(t=>Aa(t));if(vt(e)){let t={};for(let n of Object.keys(e).sort())t[n]=Aa(e[n]);return t}return e}function Vr(e,t){try{return JSON.parse(e)}catch(n){throw new oe(re.INVALID_JSON,`${t} is not valid JSON`,{cause:n})}}function Ta(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=>Ta(n,t));if(vt(e)){let n={};for(let[r,o]of Object.entries(e))n[r]=Ta(o,t);return n}break}throw new oe(re.INVALID_JSON,`${t} must be JSON-serializable`)}function Hd(e,t){if(!Array.isArray(e))throw new oe(re.INDEX_CORRUPT,`${t} must be an array`);return e.map((n,r)=>{if(!at(n))throw new oe(re.INDEX_CORRUPT,`${t}[${r}] is invalid`);return n})}function wi(e,t){if(!at(e))throw new oe(re.INVALID_PATH,`${t} must be a sha256 digest`)}function at(e){return typeof e=="string"&&/^sha256:[a-f0-9]{64}$/u.test(e)}function an(e){return`sha256:${LS("sha256").update(e).digest("hex")}`}function oE(e){return typeof e=="string"?Buffer.from(e,"utf8"):Buffer.from(e)}async function Br(e,t,n){try{return await _e.readFile(e)}catch(r){throw new oe(t,`${n} not found: ${e}`,{cause:r})}}async function Fa(e){try{return await _e.readFile(e)}catch(t){if(Jr(t))return null;throw t}}function Wd(e,t,n){if(an(e)!==t)throw new oe(re.BLOB_CORRUPT,`blob hash mismatch for ${n}`)}async function tt(e){try{return await _e.access(e),!0}catch(t){if(Jr(t))return!1;throw t}}async function Ni(e){try{await _e.rm(e,{force:!0,recursive:!0})}catch{}}async function _a(e){try{let t=await _e.open(e,"r");try{await t.sync()}finally{await t.close()}}catch{}}async function Pi(e){try{return await _e.readdir(e)}catch(t){if(Jr(t))return[];throw t}}function iE(e){if(typeof e!="string"||e.trim().length===0)throw new oe(re.INVALID_ROOT,"history store rootDir must be a non-empty string");return Me.resolve(e)}function Da(e){return Me.join(e,jS)}function Ca(e){return Me.join(e,$S)}function sE(e){return Me.join(e,VS)}function Gd(e){return Me.join(e,KS)}async function _d(e){try{let t=await _e.readFile(Gd(e),"utf8"),n=Vr(t,"document version");if(!vt(n)||n.schemaVersion!==1||!Number.isInteger(n.version)||n.version<0)throw new oe(re.INVALID_SCHEMA,"document version schema is invalid");return n.version}catch(t){if(Jr(t))return 0;throw t}}async function vi(e){let t=await Br(e,re.RECOVERY_PENDING,"transaction journal"),n=Vr(Buffer.from(t).toString("utf8"),"transaction journal");return Yd(n),n}function Yd(e){if(!vt(e)||e.schemaVersion!==BS||typeof e.transactionId!="string"||e.transactionId.length===0||typeof e.operationId!="string"||e.operationId.length===0||!["prepared","files-written","history-published"].includes(e.phase)||!JS(e.historyTransition)||!Array.isArray(e.files))throw new oe(re.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 oe(re.INVALID_SCHEMA,"transaction journal file digest is invalid")}function aE(e){return e.replace(/[\r\n]+/g," ").slice(0,512)}function Kr(e){return Me.join(e,"entries")}function Ur(e){return Me.join(e,"blobs")}function jr(e){return Me.join(e,"tmp")}function La(e){return Me.join(jr(e),"stages")}function Ba(e,t){return Me.join(La(e),`${t}.json`)}function ja(e,t){return Me.join(Kr(e),`${qd(t)}.json`)}function $a(e,t){return Me.join(Ur(e),qd(t))}function Va(e,t){return Me.join(Kr(e),`${t}.json`)}function Ka(e,t){return Me.join(Ur(e),t)}async function cE(e,t){return Qd(ja(e,t),Va(e,t))}async function Zd(e,t){return Qd($a(e,t),Ka(e,t))}async function Qd(e,t){return await tt(e)?e:await tt(t)?t:e}function qd(e){return e.slice(7)}function Od(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 lE(e){return{maxEntries:e?.maxEntries??ki.maxEntries,maxSessionBytes:e?.maxSessionBytes??ki.maxSessionBytes,maxEntryBytes:e?.maxEntryBytes??ki.maxEntryBytes}}async function uE(e){let t=Da(e);await tt(t)||await Ud(e,[],-1)}var fE={affectedCompositions:[]};function of(e){let t=null,n=new WeakMap;async function r(){return t??=pE(e),t}async function o(i){if(!i)return null;let s=Ua(i);return s?mE(e,s):i}return{async prepareAppend(i){let s=await rr(e),a=await e.stageAppend(nf(i),{durableManifest:!1}),c;try{c=await e.previewStagedAppend(a.entryId,s.digest)}catch(d){throw await e.discardStage(a.stageId),d}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,d=await e.previewCursor(l,a.digest),f={kind:"undo",entry:s,historyTransition:d};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,d=await e.previewCursor(l,a.digest),f={kind:"redo",entry:s,historyTransition:d};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);ef(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(Ua(c.at(-1))!==Ua(i.entry))throw new Error("history state changed before publish");let l=await e.setCursor(s.cursor,s.expectedDigest);ef(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 d=s.entryIds.indexOf(a.historyId);if(d>=0)try{let f=await e.setCursor(d);Object.assign(s,or(f));return}catch(f){throw s.redo.push(i),f}}let c=await e.append(nf(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 ef(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 Ua(e){return typeof e=="string"?e:e?.historyId}async function pE(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 mE(e,t){let n=await e.readEntry(t),r=gE(n),o=r.provenance??fE;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 tf(e,n,r.preSnapshots),postSnapshots:await tf(e,n,r.postSnapshots)}}async function tf(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(xE(r,o.blobName))).toString("utf8"):"";return{file:o.file,content:i,version:o.version,exists:o.exists,...o.sha256?{sha256:o.sha256}:{}}}))}function nf(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 d=`${s}-${c}`;l.blobName=d,t.push({name:d,data:a.content})}return l}),r=hE(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 gE(e){if(!af(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:sf(t.provenance)}:{},preSnapshots:rf(t.preSnapshots,"preSnapshots"),postSnapshots:rf(t.postSnapshots,"postSnapshots")}}function hE(e){if(e.provenance!==void 0)return sf(e.provenance);if(e.composition)return{initiatingComposition:e.composition,affectedCompositions:[]}}function sf(e){let t=dE.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 rf(e,t){return e.map((n,r)=>{if(!af(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&&!yE(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 yE(e){return/^sha256:[0-9a-f]{64}$/.test(e)}function xE(e,t){let n=e.get(t);if(!n)throw new Error(`durable history blob is missing: ${t}`);return n}function af(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{randomBytes as _E}from"node:crypto";import _i from"node:path";import{parse as yf}from"@babel/parser";import OE from"@babel/traverse";import*as xf from"@babel/types";import{COMPONENT_I18N_FILE_SUFFIX as Xa,PageResourceArtifactSchema as ME,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as DE,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as LE,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as BE,parseComponentI18nResourcesJson as jE}from"@vcp-dev/contracts";var lf=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\(/i,uf=/\b(?:bg-black|bg-white|text-white|text-black)(?:\b|\/)/g,bE=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke)-\[#(?:[0-9a-fA-F]{3,8})\](?:\/\d+)?/g,SE=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*#[0-9a-fA-F]{3,8}[^'"]*['"]/g,EE=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*rgba?\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,vE=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,kE=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,IE=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*(?:oklch|lab|lch|hsla?)\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,CE=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*(?:oklch|lab|lch|hsla?)\([^)]+\)[^'"]*['"]/gi,RE=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*color-mix\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,wE=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*color-mix\([^'"]*['"]/gi,NE=/\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,PE=/var\(\s*--(?:_|private-|vcp-)[^)]+\)/gi,AE=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\([^)]*\)/gi;function Xr(e,t){let n=Fi([...ht(e,bE),...ht(e,SE),...ht(e,EE),...ht(e,t.includeRgbBackgroundImage?vE:kE),...t.includeExtendedColorFunctions?[...ht(e,IE),...ht(e,CE)]:[]]),r=Fi([...ht(e,RE),...ht(e,wE)]).filter(o=>t.colorMixPolicy==="always"||lf.test(o));return n.push(...r.filter(o=>!n.includes(o))),t.rejectTailwindPalette&&n.push(...ht(e,NE).filter(o=>!n.includes(o))),t.rejectAnyRawColorLiteral&&n.push(...ht(e,AE).filter(o=>!n.includes(o))),{hardCodedSurfaceHits:Fi(ht(e,uf)),hardCodedSurfaceOccurrences:FE(e),rawColorHits:n,privateTokenHits:t.rejectPrivateTokens?Fi(ht(e,PE)):[]}}function ht(e,t){return e.match(new RegExp(t.source,t.flags))??[]}var cf=160,TE=/((?:[a-z][a-z0-9-]*(?:\[[^\]]*\])?:)+)$/;function FE(e){let t=new RegExp(uf.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),d=
|
|
6
|
-
`,i.index),u=e.slice(n[f]??0,m===-1?void 0:m).trim();o.push({token:a,variant:d?.[1]??"",alpha:c?Number(c[1]):null,line:f+1,snippet:u.length>cf?`${u.slice(0,cf-1)}\u2026`:u})}return o}function Fi(e){return[...new Set(e)]}var za="{{$INSTANCE}}",$E=/\{\{\$PAGE_ROUTE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,VE=/\{\{\$PAGE_TITLE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,Ha="components/site/generated",KE=/\.(?:tsx?|json)$/,UE=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,JE=["react","react/","next","next/","lucide-react","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],XE=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),Ja=OE,zE=typeof Ja=="function"?Ja:Ja.default;async function Wa(e){let t=ME.safeParse(e.artifact);if(!t.success)return Ae("Page resource artifact failed contract validation.");let n=t.data,r=e.randomHex??(()=>_E(4).toString("hex")),o=Math.max(1,Math.min(e.maxAttempts??5,5)),i=tv(r());if(!i)return Ae("Random instance suffix must be 8 lowercase hex chars.");let s=`${nv(n.resource_id)}-${i}`,a=new Map,c=new Map,l=[];for(let v of n.pages){let I=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/${I}/page.tsx`})}let d=[],f=new Set,m=new Set,u=new Map,g=new Map,h=[],S=new Set(n.pages.flatMap(v=>v.components.map(I=>I.component_id)));for(let v of n.components){if(!S.has(v.component_id))continue;let I=df({materialization:v.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c});if(!I.ok)return I;for(let P of I.files){let A=pf(P,f,d);if(A)return A}m.add(I.entry),g.set(I.entry,I.entryExport),u.set(v.component_id,I.entry)}for(let[v,I]of n.pages.entries()){let P=l[v],A=df({materialization:I.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c,pageEntryTarget:P.route_file_path,pageTitle:P.title});if(!A.ok)return A;for(let R of A.files){let T=pf(R,f,d);if(T)return T}m.add(A.entry),g.set(A.entry,A.entryExport),h.push({entry:A.entry,declaredComponentIds:new Set(I.components.map(R=>R.component_id))})}let E=WE(d,m,s,u,h,g);if(!E.ok)return E;for(let v of d)if(await e.exists(v.file))return!v.file.startsWith("app/")&&o>1?Wa({...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=GE(d);return y||(d.sort((v,I)=>v.file.localeCompare(I.file)),{ok:!0,packageInstanceId:s,pages:l,files:d})}function df(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:ff(o.pathTemplate,e.packageInstanceId);if(!s)return Ae("Materialization path cannot be mapped into the package namespace.",o.pathTemplate);let a=HE(o.content,e.packageInstanceId,e.routeByPage,e.titleByPage);if(!a.ok)return a;let c=i&&e.pageTitle!==void 0?ZE(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??ff(t,e.packageInstanceId);return!r||!n.some(o=>o.file===r)?Ae("Materialization entry must match one controlled source file.",t):{ok:!0,files:n,entry:r,entryExport:e.materialization.entry.export}}function HE(e,t,n,r){let o,i=e.replace($E,(c,l)=>{let d=n.get(l);return d||(o=l,c)});if(o)return Ae(`Page route placeholder references unknown template page: ${o}`);let s=i.replace(VE,(c,l)=>{let d=r.get(l);return d?JSON.stringify(d):(o=l,c)});if(o)return Ae(`Page title placeholder references unknown template page: ${o}`);let a=s.replaceAll(za,t);return a.includes("{{$PAGE_ROUTE:")||a.includes("{{$PAGE_TITLE:")||a.includes("{{$INSTANCE}}")?Ae("Materialization contains an unresolved placeholder."):{ok:!0,data:a}}function ff(e,t){let n=`${Ha}/${t}`;if(e.split(za).length>2)return null;let o=e.replace(za,t),i=`${Ha}/${t}/`,s=o.startsWith(i)?o:`${n}/${o}`,a=_i.posix.normalize(s);return a!==s||!a.startsWith(`${n}/`)||!KE.test(a)||UE.test(a)?null:a}function pf(e,t,n){return t.has(e.file)?Ae(`Page resource materializations resolve duplicate target: ${e.file}`,e.file):(t.add(e.file),n.push(e),null)}function WE(e,t,n,r,o,i){let s=new Set(e.map(u=>u.file)),a=`${Ha}/${n}`,c=new Map(e.map(u=>[u.file,new Set])),l=new Map;for(let u of e){if(u.file.endsWith(".json")){try{JSON.parse(u.content)}catch{return Ae("Materialization JSON file must contain valid JSON.",u.file)}if(u.file.endsWith(Xa)&&!jE(u.content).success)return Ae("Materialization component i18n resources are invalid.",u.file);continue}try{let h=yf(u.content,{sourceType:"module",plugins:["jsx","typescript"]});l.set(u.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=qE(u.file,y,s,a);if(!v.allowed)return Ae(`Materialization import is outside the controlled package: ${y}`,u.file);v.internalPath&&c.get(u.file).add(v.internalPath)}let S;if(zE(h,{Identifier(E){E.isReferencedIdentifier()&&XE.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 Ae(`Materialization source uses forbidden capability: ${S}`,u.file)}catch{return Ae("Materialization source must parse as TS/TSX.",u.file)}let g=Xr(u.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 Ae("Materialization source violates the public theme token policy.",u.file)}if([...t].some(u=>!s.has(u)))return Ae("Materialization entry is outside the controlled package.");for(let u of t)if(u.endsWith(".json"))return Ae("Materialization JSON files cannot be package entries.");for(let[u,g]of i){let h=l.get(u);if(!h||!YE(h,g))return Ae("Materialization entry does not declare its contracted export.",u)}let d=new Map([...r].map(([u,g])=>[g,u]));for(let u of o){let g=hf(u.entry,c);for(let h of u.declaredComponentIds){let S=r.get(h);if(!S||!g.has(S))return Ae(`Page entry does not reach declared component: ${h}`,u.entry)}for(let h of g){let S=d.get(h);if(S&&!u.declaredComponentIds.has(S))return Ae(`Page entry imports undeclared component: ${S}`,u.entry)}}let f=new Set;for(let u of t)for(let g of hf(u,c))f.add(g);if(f.size!==e.length)return Ae("Every materialization file must be reachable from a package entry.");let m=ev(e,l,c);return m||{ok:!0}}function GE(e){if(e.length>DE)return Ae("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>LE)return Ae("Page resource file exceeds the content byte limit.",n.file);t+=r}return t>BE?Ae("Page resource exceeds the aggregate content byte limit."):null}function YE(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 ZE(e,t,n){let r;try{r=yf(e,{sourceType:"module",sourceFilename:n,plugins:["jsx","typescript"]})}catch{return Ae("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=mf(s.init);if(a?.type!=="ObjectExpression")return{ok:!0,data:e};let c=a.properties.find(d=>d.type==="ObjectProperty"&&!d.computed&&QE(d.key));if(!c||c.type!=="ObjectProperty")return{ok:!0,data:e};let l=mf(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 mf(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression"||t?.type==="TSNonNullExpression";)t=t.expression;return t&&xf.isExpression(t)?t:null}function QE(e){return e.type==="Identifier"&&e.name==="title"||e.type==="StringLiteral"&&e.value==="title"}function qE(e,t,n,r){if(t.startsWith(`@/${r}/`)){let s=t.slice(2),a=gf(s,n);return a?{allowed:!0,internalPath:a}:{allowed:!1}}if(!t.startsWith("."))return{allowed:JE.some(s=>s.endsWith("/")?t.startsWith(s):t===s)};if(t.includes("\\")||t.includes("\0"))return{allowed:!1};let o=_i.posix.normalize(_i.posix.join(_i.posix.dirname(e),t)),i=gf(o,n);return i&&(i.startsWith(`${r}/`)||i.startsWith("app/"))?{allowed:!0,internalPath:i}:{allowed:!1}}function gf(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 ev(e,t,n){let r=new Set(e.map(o=>o.file));for(let o of e){if(!o.file.endsWith(Xa))continue;let i=o.file.slice(0,-Xa.length),s=[`${i}.tsx`,`${i}.ts`].find(d=>r.has(d));if(!s)return Ae("Component i18n resources require a same-name TS/TSX companion.",o.file);let c=t.get(s)?.program.directives.some(d=>d.value.value==="use client"),l=[...n].filter(([,d])=>d.has(o.file));if(!c||l.length!==1||l[0]?.[0]!==s)return Ae("Component i18n resources must have exactly one same-name Client Component static importer.",s)}return null}function hf(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 tv(e){return/^[a-f0-9]{8}$/.test(e)?e:null}function nv(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"page-resource"}function Ae(e,t){return{ok:!1,code:"MATERIALIZATION_REJECTED",message:e,...t?{path:t}:{}}}import{randomBytes as rv}from"node:crypto";import Gt from"node:path";import{parse as ov}from"@babel/parser";import iv from"@babel/traverse";import{COMPONENT_I18N_FILE_SUFFIX as Oi,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as bf,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as sv,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as av,SiteEditMaterializationSchema as cv,parseComponentI18nResourcesJson as lv}from"@vcp-dev/contracts";var Za="components/site/generated",Sf="{{$INSTANCE}}",Mi=5,uv=/^[a-z][a-z0-9-]{0,48}$/,dv=/^[a-f0-9]{8}$/,Ef=/\.tsx?$/,fv=/\.json$/,pv=/\.(?:tsx?|json)$/,mv=/^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/,gv=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,hv=["react","react/","next","next/","lucide-react","react-i18next","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],Ga=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),Ya=iv,yv=typeof Ya=="function"?Ya:Ya.default;function xv(e){let t=Array.isArray(e.manifest.files)?e.manifest.files:[];if(t.length>bf)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file count exceeds the reusable limit."}};let n=Pv(t);if(n)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Static prefab resolves duplicate target path: ${n}`,path:n}};let r=cv.safeParse(e.manifest);if(!r.success)return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab manifest failed schema validation."}};let o=Rv(e.generatedRoot);if(!o)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Generated root must be ${Za}.`,path:e.generatedRoot}};if(!wf(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=If(r.data.files),s=If(e.controlledFiles);if(!Av(i,s))return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Controlled file list must exactly match the manifest file templates."}};if(i.size>bf)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 d=Buffer.byteLength(l.content,"utf8");if(d>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+=d}return a>av?{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 bv(e){let t=xv(e);if(!t.ok)return t;let n=Object.keys(e.manifest.projectDependencies??{}),r=new Set(e.availableHostDependencies??[]),o=n.find(d=>!mv.test(d)||!r.has(d));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(d=>[d,`${d}/`]),s=[...e.allowedExternalImports??hv,...i],a=t.data.generatedRoot,c=wf(e.manifest.instanceBaseName),l=Math.max(1,Math.min(Mi,e.maxAttempts??Mi));for(let d=0;d<l;d+=1){let f=wv(e.instanceNameGenerator?.()??rv(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}`,u=Pf(a,m),g=Sv({manifest:e.manifest,generatedRoot:a,instanceName:m,instanceRoot:u,allowedExternalImports:s});if(!g.ok)return g;if(!await Ev(e.exists,u,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 Rf(e){let t=Math.max(1,Math.min(Mi,e.maxAttempts??Mi));for(let n=0;n<t;n+=1){let r=await bv({...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 Sv(e){let t=[],n=new Set;for(let i of e.manifest.files){let s=vf({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=vf({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=vv(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 Ev(e,t,n){if(await e(t))return!0;for(let r of n)if(await e(r.path))return!0;return!1}function vf(e){if(e.pathTemplate.split(Sf).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(Sf,e.instanceName),n=Nv(t);return n?Pf(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||!pv.test(n)||gv.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 vv(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(fv.test(f.path)){if(f.path.endsWith(Oi)){let g=lv(f.content);if(!g.success)return Nn("MATERIALIZATION_DATA_UNSUPPORTED",g.error.message,f.path);c.set(f.path,new Set)}else try{JSON.parse(f.content)}catch{return Nn("MATERIALIZATION_DATA_UNSUPPORTED","Static prefab JSON file must contain valid JSON.",f.path)}continue}let m;try{m=ov(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 u=Xr(f.content,{colorMixPolicy:"always",includeExtendedColorFunctions:!0,includeRgbBackgroundImage:!0,rejectAnyRawColorLiteral:!0,rejectPrivateTokens:!0,rejectTailwindPalette:!0});if(u.hardCodedSurfaceHits.length>0||u.rawColorHits.length>0||u.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(!Ef.test(f.path))continue;let m=s.get(f.path),u=null;if(yv(m,{ImportDeclaration(g){let h=kf({importer:f.path,source:g.node.source.value,instanceRoot:t,filePaths:i,allowedExternalImports:o});if(!h.allowed)u??={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=kv({importer:f.path,imported:h.internalPath,source:g.node.source.value,ast:m});S.ok?c.get(h.internalPath).add(f.path):(u??=S.error,g.stop())}},ExportAllDeclaration(g){u??={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=kf({importer:f.path,source:g.node.source.value,instanceRoot:t,filePaths:i,allowedExternalImports:o});!h.allowed||!h.internalPath?(u??={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"){u??={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"&&(u??={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"&&(u??={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"&&(u??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot use import.meta.",file:f.path},g.stop())},MemberExpression(g){let h=Cf(g.node);h&&Ga.has(h)&&(u??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${h}.`,file:f.path},g.stop())},OptionalMemberExpression(g){let h=Cf(g.node);h&&Ga.has(h)&&(u??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${h}.`,file:f.path},g.stop())},Identifier(g){g.isReferencedIdentifier()&&Ga.has(g.node.name)&&(u??={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"&&(u??={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"&&(u??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot declare style elements.",file:f.path},g.stop())}}),u)return{ok:!1,error:u}}if(!Ef.test(n))return Nn("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must be a .ts/.tsx source module.",n);let l=s.get(n);if(!l)return Nn("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must resolve to a controlled source file.",n);if(!Iv(l,r))return Nn("MATERIALIZATION_EXPORT_MISSING","Static prefab entry does not declare the manifest export.",n);for(let[f,m]of c)if(m.size!==1)return Nn("MATERIALIZATION_IMPORT_FORBIDDEN","Each component .i18n.json file must have exactly one same-name Client Component static importer.",f);return Cv(n,a).size!==e.length?Nn("MATERIALIZATION_ENTRY_INVALID","Every controlled source file must be reachable from the entry module.",n):{ok:!0,data:{kind:"static-prefab-materialization",instanceName:"",generatedRoot:Za,instanceRoot:"",entry:{path:"",export:{kind:"default"}},files:[]}}}function kf(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=Gt.posix.normalize(Gt.posix.join(Gt.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 kv(e){let t=Gt.posix.dirname(e.importer),n=Gt.posix.dirname(e.imported),r=Gt.posix.basename(e.importer).replace(/\.tsx?$/,""),o=Gt.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 Iv(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 Cv(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 Nn(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{file:n}:{}}}}function Rv(e){let t=Nf(e);return t===Za?t:null}function wv(e){let t=e.trim().toLowerCase();return dv.test(t)?t:null}function wf(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 uv.test(t)?t:null}function Nf(e){if(!e||e.startsWith("/")||e.includes("\\"))return null;let t=Gt.posix.normalize(e);return t==="."||t.startsWith("../")||t.includes("/../")||t.includes("//")?null:t}function Nv(e){let t=Nf(e);return!t||t!==e?null:t}function Pf(...e){return Gt.posix.join(...e)}function If(e){return new Set(e.map(t=>t.pathTemplate))}function Pv(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 Av(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function Cf(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 fc}from"node:crypto";import ic from"@babel/traverse";function Qa(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(d=>d.anchorSourceRange!==null&&d.members.length>0)??c.find(d=>d.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(d=>d.placementKey)),sourcePlacementKey:l.placementKey})))}return{placementByKey:t,unitByKey:r,placementsByUnitKey:o,sourcePlacementByUnitKey:i}}import{createHash as Tv}from"node:crypto";import Af from"node:path";import*as Mf from"@babel/parser";import qa from"@babel/generator";import*as Ue from"@babel/types";var Tf=typeof qa=="function"?qa:qa.default;function tc(e){let t=Lf(e);if(t)return{ok:!1,error:t};let n=e.projection,r=oc(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=Ov(n,o),s={jsx:`<${e.component.localName} />`},a=Fv(e);if(i){let u=ec(e);return u.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:u.locator,sourceHash:u.sourceHash,node:s,placement:o.relation,replaceOriginal:n.container.kind==="starter-placeholder"}}}:u.result}let c=o.containerSourceRange??n.container.sourceRange,l=o.containerSourceHash??(rc(c,n.container.sourceRange)?n.container.sourceHash:null);if(!c||!l)return zr("Route page composition does not expose a verifiable container boundary.");let d=Wr(c),f=_f(e.source,d,l,"Route page composition container");if(!f.ok)return f.result;let m=o.anchorSourceRange?Wr(o.anchorSourceRange):void 0;if(m){if(!o.anchorSourceHash)return zr("Route page composition placement does not expose a verifiable anchor boundary.");let u=_f(e.source,m,o.anchorSourceHash,"Route page composition anchor");if(!u.ok)return u.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:d,node:s,placement:o.relation,...m?{anchorLocator:m}:{}}}}}function Fv(e){let t=Bv(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 Pn(e.source,"Root expression rewrite requires an exact expression locator.");let t=kr(e.source,"value");if(!t.ok)return Pn(e.source,t.diagnostic.message);let n=ae(t.ast,e.locator);if(!n.ok)return Pn(e.source,n.diagnostic.message);let r=n.match.path;if(!r.isExpression())return Pn(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 Pn(e.source,"Root expression hash no longer matches the current source.");if(e.action.kind==="remove")return r.replaceWith(Ue.nullLiteral()),{ok:!0,source:Tf(t.ast,{}).code};let i;try{i=Mf.parseExpression(e.action.jsx,{plugins:["jsx","typescript"]})}catch(s){return Pn(e.source,s instanceof Error?s.message:String(s))}return!Ue.isJSXElement(i)&&!Ue.isJSXFragment(i)?Pn(e.source,"Root expression rewrite requires a JSX insertion expression."):(e.action.kind==="replace"?r.replaceWith(i):r.replaceWith(_v(r.node,i,e.action.placement,e.action.replaceOriginal)),{ok:!0,source:Tf(t.ast,{}).code})}function _v(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 Pn(e,t){return{ok:!1,source:e,diagnostic:{message:t}}}function nc(e){let t=Lf(e);if(t)return{ok:!1,error:t};let n=e.projection,r=Bf(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(Mv(n,o)){let h=ec(e);return h.ok?e.operation==="remove-node"&&!Ff(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=Wr(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?[]:[Hr(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=ec(e);return h.ok?Ff(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||!Lv(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=oc(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 d=l.placement;if(d.placementUnitKey!==e.targetPlacement.placementUnitKey||d.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=d.containerSourceRange;if(!f||!d.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=Wr(f),u=Tt(e.source,m);if(!u.ok||!u.match.node)return{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:u.ok===!1?u.diagnostic.message:"Route page composition target container could not be resolved.",diagnostics:u.ok?[]:[Hr(u.diagnostic)]}};if(ir(e.source,u.match.node.start??null,u.match.node.end??null)!==d.containerSourceHash)return Of("Route page composition target container hash no longer matches the current source.");if(d.relation==="before"||d.relation==="after"){let h=d.anchorSourceRange,S=d.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=Wr(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?[]:[Hr(y.diagnostic)]}}:ir(e.source,y.match.node.start??null,y.match.node.end??null)!==S?Of("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:d.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:d.relation}}}}function Ff(e,t){for(let n of e.placementUnitByKey.values())if(n.placementUnitKey!==t&&n.members.length>0)return!0;return!1}function Ov(e,t){let n=e.placementUnitByKey.get(t.placementUnitKey);return n&&e.container.kind!=="jsx-container"&&rc(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 Mv(e,t){return e.container.kind!=="jsx-container"&&rc(t.sourceRange,e.mutationTarget.sourceRange)&&t.sourceHash===e.mutationTarget.sourceHash}function ec(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?[]:[Hr(r.diagnostic)]}}}:ir(e.source,r.match.node.start??null,r.match.node.end??null)!==t.sourceHash?{ok:!1,result:Df("Route mutation target hash no longer matches the current source.")}:{ok:!0,locator:n,sourceHash:t.sourceHash}}function _f(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?[]:[Hr(o.diagnostic)]}}}:ir(e,o.match.node.start??null,o.match.node.end??null)!==n?{ok:!1,result:Df(`${r} hash no longer matches the current source.`)}:{ok:!0}}function Df(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 Of(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function Hr(e){return{code:"UNSUPPORTED_PAGE_SHAPE",message:e.message,details:{astCode:e.code}}}function Lf(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&&!Dv(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 Dv(e,t){return e.routeId===t.routeId&&e.effectiveTemplateId===t.effectiveTemplateId}function Lv(e,t){return e.routeId===t.routeId&&e.templateId===t.effectiveTemplateId}function Bv(e,t){let n=Af.posix.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=Af.posix.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function Wr(e){return{kind:"jsx-node",strategy:"source-range",sourceRange:e}}function ir(e,t,n){return t==null||n==null?null:`sha256:${Tv("sha256").update(e.slice(t,n)).digest("hex")}`}function rc(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 jv=typeof ic=="function"?ic:ic.default;function Kf(e){if(!e.ast)return kt(e,[Ve("UNSUPPORTED_PAGE_SHAPE","SourceGraph entry AST is required",{reason:"parsed-ast-required"})]);let t=Hv(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=Gv(t);if(!n.ok)return kt(e,[n.diagnostic]);let r=n.expression;if(r.isIdentifier()){let o=Zv(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(qv(r,t))return kt(e,[Ve("INDIRECT_RETURN_ONLY","Route default export only returns through an indirect function boundary")]);if(r.isNullLiteral())return ac(e,t,"virtual-route-root",r);if(Qv(r)){let o=rk({input:e,source:e.source,expression:r});return sc(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()&&!Fe(r)&&!cn(r)){let o=uc(r),i=Vf({input:e,containerKind:"virtual-route-root",sourceKind:"jsx-element",source:e.source,containerPath:r,members:[o]});return sc(e,t,i,{kind:"virtual-route-root",sourceKind:"jsx-element"},r)}if(r.isJSXElement()||r.isJSXFragment()){let o=tk(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(ek(e.source,r,i.members))return ac(e,t,"starter-placeholder",r);let s=r.isJSXFragment()||Fe(r);if(i.members.length===0&&s)return ac(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=Vf({input:e,containerKind:a,sourceKind:c,source:e.source,containerPath:o.path,members:i.members});return sc(e,t,l,{kind:a,sourceKind:c},r)}return kt(e,[Ve("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")])}function oc(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 Bf(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 Uf(e){return e.ok?$v(e.projection):Vv(e.projection)}function $v(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,d]of t){let f=d.members.flatMap((h,S)=>Jf(e,d,h,S,e.container.placementKey)),m=f.filter(({member:h})=>h.isBusinessMember).map(({sourceMember:h})=>Uv(l,h,d.independent)),u=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,u.map(({sourceMember:h})=>h)),o.set(l,m);let g=u[0]?.sourceMember.key??l;n.push({key:l,containerKey:g,businessMemberKeys:m.map(h=>h.key),isMultiMember:d.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:Kv(e,a),sourceMembers:i,businessMembers:s,placementUnits:n,placements:c}}function Vv(e){let t=e.diagnostics.map(Jv);return{status:"unsupported",version:e.version,composition:e.composition,reason:Xv(e.diagnostics),diagnostics:t}}function Kv(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 Jf(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)=>Jf(e,t,a,c,i))]}function Uv(e,t,n){return{key:`business:${e}:${t.key}`,sourceMemberKey:t.key,containerKey:e,label:t.label,isIndependent:n}}function Jv(e){return{code:zv(e),message:e.message}}function Xv(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 zv(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 Hv(e){let t=null;return jv(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=Wv(o.path);i&&(t=i,n.stop())}}),t}function Wv(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 Gv(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(!Yv(s))return{ok:!1,diagnostic:Ve("UNSUPPORTED_PAGE_SHAPE","Route guard return shape is not statically safe",{reason:"guard-shape"})};continue}if(Xf(s)||zf(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 Yv(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(Xf(o)||zf(o))return null;return r}function Xf(e){return e.isForStatement()||e.isForInStatement()||e.isForOfStatement()||e.isWhileStatement()||e.isDoWhileStatement()||e.isSwitchStatement()||e.isTryStatement()||e.isWithStatement()}function zf(e){let t=!1;return e.traverse({Function(n){n.skip()},ReturnStatement(){t=!0}}),t}function Zv(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 Qv(e){return e.isConditionalExpression()?jf(Yr(e.get("consequent")))&&jf(Yr(e.get("alternate"))):!1}function jf(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 qv(e,t){if(e.isIdentifier())return $f(e.node.name,t);if(e.isCallExpression()){let n=e.get("callee");if(n.isIdentifier())return $f(n.node.name,t)}return!1}function $f(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 ek(e,t,n){return e.includes("DESIGN_PLAN_REPLACE_ME")&&t.isJSXElement()&&n.length>0&&lc(t)}function lc(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(!lc(t))return!1;continue}if(t.isJSXElement()&&!lc(t))return!1}return!0}function tk(e){let t=e;if(e.isJSXFragment()||Fe(e)){let r=Gr(e),o=r[0];if(r.length===1&&o?.isJSXElement()&&cn(o))t=o;else return{ok:!0,path:t}}for(;t.isJSXElement()&&cn(t);){let r=Gr(t);if(r.length!==1)return{ok:!0,path:t};let o=r[0];if(!o?.isJSXElement()||!cn(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()&&(Fe(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:dc(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=cn(o)?sr(o):null;n||=i?.unsupported??!1,t.push({...uc(o,i?.members),sourceRange:yt(r.node.loc),parentSourceRange:yt(e.node.loc)});continue}if(o.isJSXSpreadChild()){n=!0;continue}t.push({memberKey:dc(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()&&Fe(r)){let o=sr(r);n||=o.unsupported,t.push(...o.members);continue}if(r.isJSXElement()){let o=cn(r)?sr(r):null;n||=o?.unsupported??!1,t.push({...uc(r,o?.members),parentSourceRange:yt(e.node.loc)})}}return{members:t,unsupported:n}}function uc(e,t){let n=e.isJSXElement()&&cn(e)?t??sr(e).members:[],r=e.isJSXElement()&&!cn(e)&&!Fe(e);return{memberKey:dc(e.node.type,e.node.start,e.node.end),kind:"jsx-element",nodeType:e.node.type,sourceRange:yt(e.node.loc),businessMemberCount:r?1:Hf(n),parentSourceRange:yt(e.parentPath?.node.loc),children:n,isBusinessMember:r,label:nk(e)}}function cn(e){let t=e.node.openingElement.name;return t.type==="JSXIdentifier"&&t.name[0]===t.name[0]?.toLowerCase()}function nk(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 Hf(e){return e.reduce((t,n)=>t+n.businessMemberCount,0)}function Li(e){return e.length===0?0:Math.max(1,Hf(e))}function Vf(e){let t=yt(e.containerPath.node.loc),n=pc(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:Li(e.members)<=1,memberCount:Li(e.members),sourceRange:t,sourceHash:n,relation:"append",containerSourceRange:t,containerSourceHash:n,anchorSourceRange:null,anchorSourceHash:null,members:e.members}}function rk(e){let t=yt(e.expression.node.loc),n=pc(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 Wf(e,t){let n=yt(t.node.loc),r=pc(e.source,t.node.start,t.node.end);return!n||!r?null:{kind:"expression",documentVersion:e.version,sourceRange:n,sourceHash:r}}function sc(e,t,n,r,o){let i=Wf(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=ok(e,n,s),c=Qa(a),l={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:Yf(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 ok(e,t,n){if(t.members.length===0)return[t];let r=[],o=(l,d,f,m,u,g,h=n)=>({...t,placementKey:d,placementUnitKey:f,containerKey:t.placementKey,independent:Li(g)<=1,memberCount:Li(g),sourceRange:m,sourceHash:m?cc(e.source,m):null,relation:l,containerSourceRange:h,containerSourceHash:h?cc(e.source,h):null,anchorSourceRange:u,anchorSourceHash:u?cc(e.source,u):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 d=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],d)),r.push(o("after",xt(e,f,"after",l.sourceRange),f,l.sourceRange,l.sourceRange,[l],d))}return r.push(o("append",i,c,n,null,[])),r}function ac(e,t,n,r){let o=Wf(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=Qa([a]),l={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:Yf(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 Gf([e.route,e.entryFile,String(e.version),t,n,r?`${r.startLine}:${r.startColumn}-${r.endLine}:${r.endColumn}`:"no-range"])}function dc(e,t,n){return Gf(["member",e,String(t??-1),String(n??-1)])}function Gf(e){return`pc_${fc("sha256").update(e.join("\0")).digest("hex").slice(0,24)}`}function pc(e,t,n){return t==null||n==null?null:`sha256:${fc("sha256").update(e.slice(t,n)).digest("hex")}`}function cc(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:${fc("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 Yf(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 hk}from"@vcp-dev/contracts";import zF from"node:fs";import WF from"node:path";var sk=/^page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function Zr(e){let t=e.map(r=>gk(r.path)),n=ak(t);return n?t.filter(r=>lk(n,r)).map(r=>({routeId:uk(n,r),entryFile:r})).sort((r,o)=>r.routeId.localeCompare(o.routeId)):[]}function mc(e,t=""){let r=((e??"/").trim()||"/").split(/[?#]/,1)[0]||"/",o=r.startsWith("/")?r:`/${r}`,i=mk(t),s=i&&(o===i||o.startsWith(`${i}/`))?o.slice(i.length)||"/":o,a=s.startsWith("/")?s:`/${s}`;return a==="/"?"/":a.replace(/\/+$/,"")}function ak(e){return e.some(r=>r.startsWith("app/")&&!ck(r))?"app":e.some(r=>r.startsWith("src/app/"))?"src/app":null}function ck(e){return/^(?:src\/)?app\/(?:_vcp|\.vcp)/.test(e)}function lk(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 uk(e,t){let n=t.slice(e.length+1).split("/").slice(0,-1).map(fk).filter(r=>!!r);return n.length===0?"/":`/${n.join("/")}`}function dk(e){return e.startsWith("(")&&e.endsWith(")")}function fk(e){return!e||e.startsWith("@")||e.startsWith("_")||dk(e)?null:pk(e)}function pk(e){return e.replace(/^\((?:\.|\.\.|\.\.\.)\)/,"")}function mk(e){let t=e.trim();return!t||t==="/"?"":(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"")}function gk(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 rt(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 gc(e){return hk.safeParse(e).success||rt("invalid-template-id",{templateId:e}),Buffer.from(e,"utf8").toString("base64url")}function Zf(e){/^[A-Za-z0-9_-]{1,255}$/.test(e)||rt("invalid-template-key",{path:e});let t;try{t=new TextDecoder("utf-8",{fatal:!0}).decode(Buffer.from(e,"base64url"))}catch{return rt("invalid-template-key",{path:e})}return gc(t)!==e&&rt("noncanonical-template-key",{path:e}),t}function yk(e){let t=mc(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("(")||xk(r)&&!Qf(r)))&&rt("invalid-public-route",{routeId:e}),t}function xk(e){return e.includes("[")||e.includes("]")}function Qf(e){return/^\[\[\.\.\.[^\[\]]+\]\]$|^\[[^\[\]]+\]$/.test(e)}function qf(e){return e.some(Qf)}function ep(e,t,n="app"){n!=="app"&&n!=="src/app"&&rt("invalid-app-root");let r=yk(e),o=gc(t),i=qf(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))&&rt("path-too-long",{path:a}),{appRoot:n,routeRoot:s,templateKey:o,templateEntryFile:a}}function tp(e){return/^(?:src\/)?app\/\.vcp\/page-templates\//.test(e)}function np(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===".")&&rt("invalid-file-path",{path:i}),n.has(i)&&rt("duplicate-file-path",{path:i}),n.set(i,o)}return n}function ji(e){let t=np(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(!tp(i))continue;let s=/^(app|src\/app)\/\.vcp\/page-templates\/(.+)\/page\.tsx$/.exec(i);s||rt("candidate-must-be-single-page",{path:i});let a=s[1],c=s[2].split("/"),l=qf(c),d=l?c[0]:c.pop(),f=l?c.slice(1):c,m=Zf(d),u=f.length?`/${f.join("/")}`:"/";ep(u,m,a).templateEntryFile!==i&&rt("candidate-path-mismatch",{path:i,routeId:u});let h=r.get(u);(!h||!h.startsWith(`${a}/`))&&rt("canonical-entry-missing",{path:i,routeId:u}),o.push({routeId:u,templateId:m,entryFile:i,canonicalEntryFile:h,appRoot:a})}return o.sort((i,s)=>Bi(i.routeId,s.routeId)||Bi(i.templateId,s.templateId))}function rp(e){let t=np(e.files),n=ji({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)=>Bi(o.context.routeId,i.context.routeId)||(o.context.effectiveTemplateId===void 0?-1:i.context.effectiveTemplateId===void 0?1:Bi(o.context.effectiveTemplateId,i.context.effectiveTemplateId)))}function bk(e){let t=mc(e.selector.routeId),n=rp({files:e.files}),r=n.find(i=>i.context.routeId===t&&i.context.effectiveTemplateId===void 0);(!r||r.entryFile!==e.canonicalEntryFile)&&rt("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||rt("template-selection-not-found",{routeId:t,templateId:e.selector.templateId}),{...o,mode:e.selector.templateId===void 0?"direct":"candidate",effectiveEntryFile:o.entryFile}}function Bi(e,t){return e<t?-1:e>t?1:0}import{HOME_PAGE_URL_PATH as Fk}from"@vcp-dev/contracts";import{parse as G_}from"@babel/parser";import{parse as r_}from"@babel/parser";import{FormBlockIdSchema as i_,FormSpecV1Schema as s_}from"@vcp-dev/contracts";var qr="components/site/generated/forms",a_=`${qr}/vcp-form-runtime.tsx`,$i="[A-Za-z0-9][A-Za-z0-9_-]{0,127}",c_=new RegExp(`^${qr}/form-(${$i})\\.spec\\.ts$`),l_=new RegExp(`^${qr}/form-(${$i})\\.tsx$`),u_=new RegExp(`^@/${qr}/form-(${$i})$`),d_=new RegExp(`(?:^|/)${qr}/form-(${$i})(?:\\.tsx?)?$`);var f_=Symbol("invalid-literal");import{createHash as g_}from"node:crypto";import{posix as y_}from"node:path";import{parse as b_}from"@babel/parser";import{FormSpecV1Schema as E_}from"@vcp-dev/contracts";var v_=Symbol("dynamic");import{parse as Sk}from"@babel/parser";function Vi(e){return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&typeof t.type=="string"):[]}var Ek=/^(?:src\/)?app\/(.*)page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function op(e){let t=Ek.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 vk(e){let t=e;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function ip(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function kk(e){let t=e;for(;t&&(t.type==="TSAsExpression"||t.type==="TSSatisfiesExpression"||t.type==="ParenthesizedExpression");)t=t.expression??null;return t}function hc(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(hc);if(t?.type==="ObjectExpression"){let n={};for(let r of Vi(t.properties)){if(r.type!=="ObjectProperty"||r.computed)throw new Error("dynamic object property");let o=ip(r.key);if(!o)throw new Error("unsupported object key");n[o]=hc(r.value)}return n}throw new Error(`unsupported static value: ${t?.type??"unknown"}`)}function yc(e,t){let n=[],r=op(t);if(r===null)return{found:!1,seo:null,diagnostics:n};let o;try{o=Sk(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 Vi(o.program.body)){let d=l.type==="ExportNamedDeclaration"?l.declaration:l;if(d?.type==="VariableDeclaration")for(let f of Vi(d.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=kk(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 Vi(s.properties)){if(l.type!=="ObjectProperty"||l.computed)continue;let d=ip(l.key);if(!(d!=="path"&&d!=="title"&&d!=="description"&&d!=="keywords"&&d!=="meta_tags_json"&&d!=="schema_json"&&d!=="breadcrumbs_json")){if(d==="path"||d==="title"||d==="description"||d==="keywords"){let f=vk(l.value);if(f===void 0){n.push({code:"page-seo.dynamic-field",message:`PAGE_SEO.${d} is not a static string; skipped`});continue}a[d]=f;continue}try{let f=hc(l.value);d==="meta_tags_json"&&f!==null&&typeof f=="object"&&!Array.isArray(f)?a.meta_tags_json=f:d==="schema_json"&&f!==null&&typeof f=="object"?a.schema_json=f:d==="breadcrumbs_json"&&Array.isArray(f)?a.breadcrumbs_json=f:n.push({code:"page-seo.dynamic-field",message:`PAGE_SEO.${d} has unsupported static shape; skipped`})}catch(f){n.push({code:"page-seo.dynamic-field",message:`PAGE_SEO.${d} 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 Ik}from"@babel/parser";var sp=["page","anchor","external","email","phone","group","file"],Ck=["link","cta"],cp=["description","badge","iconKey"],xc=["label","targetType","href","role","openInNewTab","nofollow","children",...cp],Rk=new Set(xc);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 wk(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function ap(e){let t=e;return t?.type==="BooleanLiteral"&&typeof t.value=="boolean"?t.value:void 0}function bc(e){let t=[],n;try{n=Ik(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=lp(i,`NAV_ITEMS[${s}]`,t);a&&o.push(a)}),{items:o,diagnostics:t}}function lp(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 d=wk(l.key);d&&(r[d]=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||!sp.includes(i))return n.push({severity:"fatal",path:`${t}.targetType`,message:`targetType must be one of ${sp.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 cp){if(r[l]===void 0)continue;let d=eo(r[l]);d!==void 0?s[l]=d: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))Rk.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 ${xc.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((d,f)=>{let m=lp(d,`${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&&(Ck.includes(c)?s.role=c:n.push({severity:"warning",path:`${t}.role`,message:"role ignored: not link/cta"})),r.openInNewTab!==void 0){let l=ap(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=ap(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 Nk}from"@babel/parser";function no(e){return Array.isArray(e)?e:[]}function up(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression";)t=t.expression;return t?.type==="ArrayExpression"?t:void 0}function Pk(e){let t;try{t=Nk(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=up(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 Sc(e,t){let n=dp(t);if(!n)return{status:"unsupported",source:e};let r=Pk(e);if(r.status!=="ok")return{status:r.status,source:e};let o=r.array;if(bc(e).diagnostics.some(({severity:l})=>l==="fatal"))return{status:"unsupported",source:e};let s=[],a=l=>{let d=no(l.elements);for(let[f,m]of d.entries()){if(Tk(m,n)){let g=d[f+1],h=d[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 u=Ak(m);u&&a(u)}};if(a(o),s.length===0)return{status:"not_found",source:e};let c=e;for(let l of s.sort((d,f)=>f.start-d.start))c=c.slice(0,l.start)+c.slice(l.end);return{status:"removed",source:c,removedCount:s.length}}function Ak(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 up(t.value)}}function dp(e){let t=e.trim();return t.startsWith("/")?t==="/"?t:t.replace(/\/+$/,""):null}function Tk(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"&&dp(n??"")===t}import{estimateNavLabelWidth as F_}from"@vcp-dev/contracts";import{parse as M_}from"@babel/parser";var _k="components/site/generated/",ro=[".tsx",".ts",".jsx",".js"];function fp(e){if(e.expectedUrlPath===Fk)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=yc(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=ji({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=Ok(e.files);if(!i.ok)return i.error;let s=i.graph,a=Bk(o,s),c=jk(o,a,s),l=[...a].filter(h=>!c.has(h)).sort((h,S)=>h.localeCompare(S)),d=[...o,...[...c].sort((h,S)=>h.localeCompare(S))],f=new Set(d),m=d.map(h=>({operation:"delete",file:h})),u=[],g=[];for(let[h,S]of Object.entries(e.files))if(!f.has(h)){if(S.includes("NAV_ITEMS")){let E=Sc(S,e.expectedUrlPath);E.status==="removed"?(m.push({operation:"upsert",file:h,content:E.source}),u.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:d,updatedFiles:u,preservedSharedFiles:l,warnings:g}}function Ok(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")||!Mk(r))continue;let s=En(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(Dk(c))continue;let l=yn(r,c),d=Lk(l,t);if(!d)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(d)}n.set(r,a)}return{ok:!0,graph:n}}function Mk(e){let t=e.toLowerCase();return ro.some(n=>t.endsWith(n))}function Dk(e){return!!(/\.([a-z0-9]+)$/i.exec(e)&&!ro.some(n=>e.endsWith(n)))}function Lk(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 Bk(e,t){let n=new Set,r=[...e].flatMap(o=>[...t.get(o)??[]]);for(;r.length>0;){let o=r.pop();!o.startsWith(_k)||n.has(o)||(n.add(o),r.push(...t.get(o)??[]))}return n}function jk(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 fm from"@babel/parser";import*as de from"@babel/types";import*as os from"node:path";import*as xe from"@babel/types";function pp(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 Ot(e){if(e.path.isObjectPattern()||e.path.isArrayPattern())return An(e.path.node,e.identifier.name);if(e.path.isVariableDeclarator()){let n=e.path.node.id;if(xe.isObjectPattern(n)||xe.isArrayPattern(n))return An(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(Vk(e.path,n))return!0}if(t.isFunction()||t.isVariableDeclarator())return!1;t=t.parentPath}return!1}function An(e,t,n=!1){return xe.isIdentifier(e)?e.name===t&&n:xe.isObjectPattern(e)?e.properties.some(r=>xe.isObjectProperty(r)?An(r.value,t,n):An(r.argument,t,n)):xe.isArrayPattern(e)?e.elements.some(r=>{if(!r)return!1;let o=xe.isRestElement(r)?r.argument:r;return An(o,t,n)}):xe.isAssignmentPattern(e)?An(e.left,t,!0):xe.isRestElement(e)?An(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:Ot(e)}}return t?{propName:t.base,remainingPath:t.path,hasDefault:Ot(e)}:null}if(e.path.isVariableDeclarator()){let r=e.path.get("init");if(r?.isExpression()){let o=mp(r),i=!1,s=o?o.initBinding&&Ec(o.initBinding)?(i=Ot(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,...d]=c;return!l||l.kind!=="property"?null:{propName:l.name,remainingPath:[...d,...t?.path??[]],hasDefault:i||Ot(e)}}}}let n=Jk(e);if(n){let r=$k(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||Ot(e)}}if(n.findParent(s=>s.isVariableDeclarator()))return null;let o=Kk(e);if(o){let[s,...a]=o;return!s||s.kind!=="property"?null:{propName:s.name,remainingPath:[...a,...t?.path??[]],hasDefault:Ot(e)}}let i=oo(n.node);return i?{propName:i,remainingPath:t?.path??[],hasDefault:Ot(e)}:null}if(Ec(e)){let[r,...o]=t?.path??[];return!r||r.kind!=="property"?null:{propName:r.name,remainingPath:o,hasDefault:Ot(e)}}return null}function $k(e,t){let n=e.findParent(d=>d.isVariableDeclarator());if(!n?.isVariableDeclarator())return null;let r=n.get("init");if(!r?.isExpression())return null;let o=mp(r);if(!o)return null;let{initBinding:i,initPathPrefix:s}=o;if(!i)return null;let a=!1,c=Ec(i)?(a=Ot(i),[...s]):(()=>{let d=ar(i,{kind:"identifier",expression:i.identifier.name,base:i.identifier.name,path:[]});return a=d?.hasDefault??!1,d?[{kind:"property",name:d.propName},...d.remainingPath,...s]:null})();if(!c)return null;let l=It(n.node.id,t.identifier.name);return l?{path:[...c,...l],hasDefault:a||Ot(t)}:null}function mp(e){if(e.isIdentifier())return{initBinding:e.scope.getBinding(e.node.name),initPathPrefix:[]};if(!e.isMemberExpression())return null;let t=Xk(e.node);return t?{initBinding:e.scope.getBinding(t.base),initPathPrefix:t.path}:null}function Ec(e){return e.path.isIdentifier()&&e.path.key===0&&Array.isArray(e.path.container)&&e.path.parentPath?.isFunction()===!0}function Vk(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function Kk(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 gp(e,t,n){if(e.path.isVariableDeclarator()){let a=e.path.get("id");if(!Array.isArray(a)&&(a.isObjectPattern()||a.isArrayPattern())){let c=Ki(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 d=l.get("right");if(d.isExpression())return{propName:c,componentName:t,expressionPath:d,displayPath:`${t}.${c}.default`}}let r=Uk(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 Ki(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=Ki(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=Ki(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=Ki(r,t);if(o)return o}}return null}function It(e,t,n=[]){if(xe.isIdentifier(e))return e.name===t?n:null;if(xe.isObjectPattern(e)){for(let r of e.properties)if(xe.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(xe.isRestElement(r)){let o=It(r.argument,t,n);if(o)return o}}if(xe.isArrayPattern(e))for(let r=0;r<e.elements.length;r+=1){let o=e.elements[r];if(!o)continue;let i=xe.isRestElement(o)?o.argument:o,s=It(i,t,[...n,{kind:"index",index:r}]);if(s)return s}return xe.isAssignmentPattern(e)?It(e.left,t,n):null}function Uk(e){if(!e.path.isIdentifier())return null;let t=e.path.parentPath;return t?.isAssignmentPattern()&&t.node.left===e.path.node?t:null}function Jk(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:xe.isIdentifier(e.key)?e.key.name:xe.isStringLiteral(e.key)?e.key.value:null}function Xk(e){let t=[],n=e;for(;xe.isMemberExpression(n);){if(n.computed)if(xe.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(xe.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(xe.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return xe.isIdentifier(n)?{base:n.name,path:t}:null}import*as Sp from"@babel/parser";import Ic from"@babel/traverse";import*as cr from"@babel/types";import*as ce from"@babel/types";function Xi(e,t=[]){if(e.isIdentifier()){let n=e.scope.getBinding(e.node.name);return n?Ui(n,t):null}if(e.isMemberExpression()){let n=Zk(e.node),r=zk(e.node);if(!n||r===null)return null;let o=e.scope.getBinding(n);return o?Ui(o,[...r,...t]):null}return e.isAwaitExpression()||kc(e.node)?ln(qk(e.node),t,"awaited or fetched expression"):null}function zk(e){let t=[],n=e;for(;ce.isMemberExpression(n);){if(n.computed)if(ce.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(ce.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(ce.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return ce.isIdentifier(n)?t:null}function Ui(e,t=[]){let n=Hk(e,t);if(n)return n;let r=Wk(e,t);if(r)return r;let o=Gk(e,t);return o||null}function so(e){return e?.kind==="api-source"}function Hk(e,t){if(e.path.isVariableDeclarator()&&ce.isIdentifier(e.path.node.id)){let s=e.path.get("init");if(s?.isCallExpression()&&vc(s.node)&&t[0]?.kind==="property"&&t[0].name==="data")return ln(e.identifier.name,t,"query hook result.data binding")}if(e.path.isVariableDeclarator()&&ce.isObjectPattern(e.path.node.id)){let s=e.path.node.id.properties.find(c=>ce.isObjectProperty(c)&&xp(c)==="data"&&io(c.value,e.identifier.name)),a=e.path.get("init");if(s&&a?.isCallExpression()&&vc(a.node))return ln(e.identifier.name,t,"query hook data binding")}let n=Yk(e);if(!n||xp(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()||!vc(i.node)?null:ln(e.identifier.name,t,"query hook data binding")}function Wk(e,t){if(e.path.isVariableDeclarator()&&ce.isArrayPattern(e.path.node.id)){let a=e.path.get("init");if(!a?.isCallExpression()||!yp(a.node))return null;let[c,l]=e.path.node.id.elements;return!ce.isIdentifier(c)||c.name!==e.identifier.name||!ce.isIdentifier(l)?null:hp(e,l.name)?ln(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()||!yp(o.node)||n.node.elements.findIndex(a=>a===e.path.node)!==0)return null;let s=n.node.elements[1];return ce.isIdentifier(s)&&hp(e,s.name)?ln(e.identifier.name,t,"state setter is updated by API data"):null}function Gk(e,t){let n=e.path.isVariableDeclarator()?e.path:e.path.findParent(o=>o.isVariableDeclarator());if(!n?.isVariableDeclarator())return null;let r=n.get("init");return r?.isExpression()?r.isAwaitExpression()?ln(e.identifier.name,t,"awaited binding result"):kc(r.node)?ln(e.identifier.name,t,"fetch-backed binding result"):null:null}function Yk(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 ce.isIdentifier(e)?e.name===t:ce.isAssignmentPattern(e)?io(e.left,t):ce.isObjectPattern(e)?e.properties.some(n=>ce.isObjectProperty(n)?io(n.value,t):io(n.argument,t)):ce.isArrayPattern(e)?e.elements.some(n=>!!n&&io(ce.isRestElement(n)?n.argument:n,t)):!1}function hp(e,t){let n=!1,r=!1;return e.scope.path.traverse({CallExpression(i){kc(i.node)&&(n=!0),(Qk(i.node.callee,t)||i.node.arguments.some(s=>ce.isIdentifier(s)&&s.name===t))&&(r=!0)}}),n&&r}function vc(e){let t=zi(e.callee);return t==="useQuery"||t==="useSWR"||t==="useSuspenseQuery"}function yp(e){return zi(e.callee)==="useState"}function kc(e){return Ji(e,t=>ce.isCallExpression(t)&&zi(t.callee)==="fetch")}function Zk(e){let t=e;for(;ce.isMemberExpression(t);)t=t.object;return ce.isIdentifier(t)?t.name:null}function xp(e){return e.computed?null:ce.isIdentifier(e.key)?e.key.name:ce.isStringLiteral(e.key)?e.key.value:null}function zi(e){return ce.isIdentifier(e)?e.name:ce.isMemberExpression(e)&&ce.isIdentifier(e.property)?e.property.name:null}function Qk(e,t){return Ji(e,n=>ce.isIdentifier(n)&&n.name===t)}function Ji(e,t){if(t(e))return!0;let n=ce.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(ce.isNode(i)&&Ji(i,t))return!0;continue}if(ce.isNode(o)&&Ji(o,t))return!0}return!1}function qk(e){return ce.isIdentifier(e)?e.name:ce.isCallExpression(e)?zi(e.callee)??"api":ce.isAwaitExpression(e)?"awaited-api":"api"}function ln(e,t,n){return{kind:"api-source",readonly:!0,sourceId:e,displayPath:eI(e,t),reason:n}}function eI(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}var Ep=typeof Ic=="function"?Ic:Ic.default;function vp(e,t){let n=Ip(e);if(!n)return{allowed:!0};let r=!1;return Ep(n,{CallExpression(o){if(!Cp(o.node,t.sourceRange)||!tI(o.node))return;let i=o.get("callee");if(!i.isMemberExpression())return;let s=i.get("object");Array.isArray(s)||!s.isExpression()||so(Xi(s))&&(r=!0,o.stop())}}),r?{allowed:!1,reason:"Cannot add data-backed items to a dynamic API list"}:{allowed:!0}}function kp(e,t){let n=Ip(e);if(!n)return{allowed:!0};let r=!1;return Ep(n,{JSXExpressionContainer(o){Cp(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 Ip(e){try{return Sp.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function tI(e){let t=e.callee;return cr.isMemberExpression(t)&&cr.isIdentifier(t.property)&&t.property.name==="map"}function Cp(e,t){let n=e.loc;return n?bp({line:n.start.line,column:n.start.column},{line:t.startLine,column:t.startColumn})>=0&&bp({line:n.end.line,column:n.end.column},{line:t.endLine,column:t.endColumn})<=0:!1}function bp(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 J from"@babel/types";import*as Rp from"@babel/parser";import Cc from"@babel/traverse";import*as Te from"@babel/types";import*as lr from"node:path";var Ct=typeof Cc=="function"?Cc:Cc.default;function Je(e){try{return Rp.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function Rc(e){return e.computed?Te.isStringLiteral(e.key)||Te.isNumericLiteral(e.key)?String(e.key.value):null:nI(e.key)}function nI(e){return Te.isIdentifier(e)?e.name:Te.isStringLiteral(e)||Te.isNumericLiteral(e)?String(e.value):null}function Tn(e){return Te.isParenthesizedExpression(e)||Te.isTSAsExpression(e)||Te.isTSSatisfiesExpression(e)||Te.isTSNonNullExpression(e)||Te.isTSTypeAssertion(e)?Tn(e.expression):Te.isExpression(e)?e:null}function wc(e){if(Te.isIdentifier(e))return[e.name];if((Te.isMemberExpression(e)||Te.isOptionalMemberExpression(e))&&!e.computed&&Te.isIdentifier(e.property)){let t=Tn(e.object),n=t?wc(t):null;return n?[...n,e.property.name]:null}return null}function Fn(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 Pp(e,t,n){let r=_p(e,t);if(Op(e,r),Mp(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){jp(s,r)&&o.push(s)}}),o.length!==1?{ok:!1,reason:"Cannot move prop-backed repeat child without a single unambiguous component call site"}:Wi(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 Ap(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 rI(i,n))o=r(s)||o}return[...n.values()]}function rI(e,t){let n=[],r=oI(e,t);for(let o of e.ast.program.body){if(J.isExportDefaultDeclaration(o)&&J.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(J.isExportNamedDeclaration(o)&&o.source&&typeof o.source.value=="string"){let i=Fn(e.file,o.source.value);for(let s of o.specifiers){if(J.isExportNamespaceSpecifier(s)){let l=un(s.exported);for(let d of t.values())ct(d.file,i)&&n.push({file:e.file,namespace:Nc(l,d.namespace),exportName:d.exportName});continue}if(!J.isExportSpecifier(s))continue;let a=un(s.local),c=[...t.values()].filter(l=>ct(l.file,i)&&_n(l.namespace,a));if(c.length>0){let l=un(s.exported);for(let d of c){let f=ao(d.namespace,a,l);f&&n.push({file:e.file,namespace:f,exportName:d.exportName})}continue}t.has(dr({file:i,exportName:a}))&&n.push({file:e.file,exportName:un(s.exported)})}continue}if(J.isExportNamedDeclaration(o)&&!o.source){for(let i of o.specifiers){if(!J.isExportSpecifier(i))continue;let s=un(i.local),a=r.get(s)??[];if(a.length>0){let c=un(i.exported);n.push({file:e.file,exportName:c});for(let l of a){let d=ao(l.namespace,s,c);d&&n.push({file:e.file,namespace:d,exportName:l.exportName})}}}continue}if(J.isExportAllDeclaration(o)&&typeof o.source.value=="string"){let i=Fn(e.file,o.source.value),s=o.exported;if(s){let a=un(s);for(let c of t.values())ct(c.file,i)&&n.push({file:e.file,namespace:Nc(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 Nc(e,t){return t?`${e}.${t}`:e}function _n(e,t){return e===t||e?.startsWith(`${t}.`)===!0}function ao(e,t,n){return!_n(e,t)||!e?null:e===t?n:`${n}${e.slice(t.length)}`}function oI(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(!J.isImportDeclaration(i)||typeof i.source.value!="string")continue;let s=Fn(e.file,i.source.value);for(let a of i.specifiers){if(J.isImportDefaultSpecifier(a)){let c=t.get(dr({file:s,exportName:"default"}));c&&r(a.local.name,c);let l=[...t.values()].filter(d=>ct(d.file,s)&&_n(d.namespace,"default"));for(let d of l){let f=ao(d.namespace,"default",a.local.name);f&&r(a.local.name,{...d,namespace:f})}continue}if(J.isImportSpecifier(a)){let c=un(a.imported),l=[...t.values()].filter(f=>ct(f.file,s)&&_n(f.namespace,c));for(let f of l)r(a.local.name,f);let d=t.get(dr({file:s,exportName:c}));d&&r(a.local.name,d);continue}if(J.isImportNamespaceSpecifier(a))for(let c of t.values())ct(c.file,s)&&r(a.local.name,{...c,namespace:Nc(a.local.name,c.namespace)})}}let o=!0;for(;o;){o=!1;for(let i of e.ast.program.body)if(J.isVariableDeclaration(i))for(let s of i.declarations){if(!J.isIdentifier(s.id)||!s.init)continue;let a=Tn(s.init);if(!a||!J.isIdentifier(a))continue;let c=n.get(a.name)??[];if(c.length===0)continue;let l=n.get(s.id.name)??[],d=new Set(l.map(dr));for(let f of c){let m=ao(f.namespace,a.name,s.id.name),u=m?{...f,namespace:m}:f,g=dr(u);d.has(g)||(r(s.id.name,u),d.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 un(e){return J.isIdentifier(e)?e.name:e.value}function Tp(e,t){for(let n of e.program.body){if(J.isExportDefaultDeclaration(n)){let o=n.declaration;if((J.isFunctionDeclaration(o)||J.isClassDeclaration(o))&&o.id?.name===t)return{exportName:"default"};if(J.isIdentifier(o)&&o.name===t)return{exportName:"default"}}if(!J.isExportNamedDeclaration(n))continue;let r=n.declaration;if((J.isFunctionDeclaration(r)||J.isClassDeclaration(r))&&r.id?.name===t)return{exportName:t};if(J.isVariableDeclaration(r)){for(let o of r.declarations)if(J.isIdentifier(o.id,{name:t}))return{exportName:t}}for(let o of n.specifiers){if(!J.isExportSpecifier(o)||o.local.name!==t)continue;return{exportName:J.isIdentifier(o.exported)?o.exported.name:o.exported.value}}}return null}function Ac(e){let t=iI(e),n=[],r=Mp(e.ast,t);return Ct(e.ast,{JSXElement(o){ct(e.file,e.sourceFile)&&Wi(o)===e.sourceComponent||jp(o,t)&&n.push({file:e.file,path:o})}}),{callSites:n,hasUnsafeReference:r}}function Fp(){return{localBindings:new Set,namespaceMembers:new Map,hasUnsupportedAlias:!1}}function _p(e,t){let n=Fp();return Ct(e,{Program(r){let o=r.scope.getBinding(t);o&&n.localBindings.add(o),r.stop()}}),n}function iI(e){let t=Fp();return ct(e.file,e.sourceFile)&&sI(t,_p(e.ast,e.sourceComponent)),Ct(e.ast,{ImportDeclaration(n){let r=n.node,o=r.source.value;if(typeof o!="string")return;let i=Fn(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(J.isImportDefaultSpecifier(a)&&s.some(l=>l.exportName==="default")&&t.localBindings.add(c),J.isImportDefaultSpecifier(a)){let l=s.filter(d=>_n(d.namespace,"default"));if(l.length>0){let d=t.namespaceMembers.get(c)??new Set;for(let f of l){let m=Np(f,"default");m&&d.add(m)}t.namespaceMembers.set(c,d)}continue}if(J.isImportSpecifier(a)){let l=J.isIdentifier(a.imported)?a.imported.name:a.imported.value,d=s.filter(f=>_n(f.namespace,l));if(d.length>0){let f=t.namespaceMembers.get(c)??new Set;for(let m of d){let u=Np(m,l);u&&f.add(u)}t.namespaceMembers.set(c,f);continue}s.some(f=>!f.namespace&&f.exportName===l)&&t.localBindings.add(c);continue}if(J.isImportNamespaceSpecifier(a))for(let l of s){let d=l.namespace?`${l.namespace}.${l.exportName}`:l.exportName,f=t.namespaceMembers.get(c)??new Set;f.add(d),t.namespaceMembers.set(c,f)}}}}}),Op(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 Op(e,t){Ct(e,{VariableDeclarator(n){if(!n.node.init)return;let r=Tn(n.node.init);if(r){if(J.isIdentifier(n.node.id)){let o=On(r,t,n),i=n.scope.getBinding(n.node.id.name);o&&i&&Pc(t,i,o);return}if(J.isObjectPattern(n.node.id)){let o=On(r,t,n);o?.unsupported||o?.local?t.hasUnsupportedAlias=!0:o&&o.namespaceMembers.size>0&&Bp(n.node.id,o.namespaceMembers,t,n)}}}})}function Mp(e,t){if(t.hasUnsupportedAlias)return!0;let n=!1;return Ct(e,{ReferencedIdentifier(r){if(n){r.stop();return}aI(r)||!r.isIdentifier()||!Dp(r,t)||cI(r,t)||lI(r)||(n=!0,r.stop())}}),n}function aI(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 Dp(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 cI(e,t){let n=e.findParent(c=>c.isVariableDeclarator());if(!n?.isVariableDeclarator())return!1;let r=n.get("init");if(!r?.isExpression()||!wp(e,r))return!1;let o=Dp(e,t);if(!o)return!1;if(Tn(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()&&wp(e,a)&&!!On(a.node,t,a)}function lI(e){let t=e.parentPath;return t?.isExportDefaultDeclaration()&&t.node.declaration===e.node?!0:!!(t?.isExportSpecifier()&&t.node.local===e.node)}function wp(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function On(e,t,n){let r=Tn(e);if(!r)return null;if(J.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(J.isObjectExpression(r))return uI(r,t,n);let o=wc(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?Lp(s,o.slice(1).join(".")):null}function uI(e,t,n){let r=new Set,o=!1;for(let i of e.properties){if(!J.isObjectProperty(i))continue;let s=Rc(i);if(!s||!J.isExpression(i.value)){J.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 Lp(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 Pc(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 Bp(e,t,n,r){for(let o of e.properties){if(J.isRestElement(o)){if(J.isIdentifier(o.argument)){let c=r.scope.getBinding(o.argument.name);c&&Pc(n,c,{local:!1,namespaceMembers:new Set(t),unsupported:!1})}else n.hasUnsupportedAlias=!0;continue}if(!J.isObjectProperty(o))continue;let i=Rc(o);if(!i){n.hasUnsupportedAlias=!0;continue}let s=Lp(t,i);if(!s)continue;n.hasUnsupportedAlias||=s.unsupported;let a=J.isAssignmentPattern(o.value)?o.value.left:o.value;if(J.isIdentifier(a)){let c=r.scope.getBinding(a.name);c&&Pc(n,c,s);continue}if(J.isObjectPattern(a)&&s.namespaceMembers.size>0){Bp(a,s.namespaceMembers,n,r);continue}n.hasUnsupportedAlias=!0}}function Np(e,t){if(!_n(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 jp(e,t){let n=e.node.openingElement.name;if(J.isJSXIdentifier(n)){let o=e.scope.getBinding(n.name);return!!(o&&t.localBindings.has(o))}let r=$p(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 $p(e){if(J.isJSXIdentifier(e))return[e.name];if(J.isJSXMemberExpression(e)){let t=$p(e.object);return t?[...t,e.property.name]:null}return null}function Wi(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()&&J.isIdentifier(n.node.id))return n.node.id.name}return null}function Vp(e,t){let n=Je(e);if(!n||!t.tag||!t.importedFrom||!t.exportName)return Number.POSITIVE_INFINITY;let r=Ac({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 he(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 ge(e){return typeof e.start=="number"&&typeof e.end=="number"?{start:e.start,end:e.end}:null}function Mt(e,t){let n=ge(e);return!!(n&<(t,n))}function lt(e,t){return t.start>=e.start&&t.end<=e.end}function bt(e,t){let n=ae(e,he(t));return n.ok&&n.match.path.isJSXElement()?n.match.path:Gi(e,t)}function fr(e,t){let n=ge(t);return n?e.slice(n.start,n.end):""}function Kp(e,t){return e.start===t.start&&e.end===t.end}function Gi(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 Yi(e,t){return Tc(e,t).length>0}function Zi(e,t){let n=ge(e.node),r=ge(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()&&!dI(o,n,r)))return!0;o=o.parentPath}return!1}function dI(e,t,n){let r=ge(e.node.consequent);if(r&<(r,t)&&!lt(r,n))return!1;let o=e.node.alternate?ge(e.node.alternate):null;return!(o&<(o,t)&&!lt(o,n))}function Tc(e,t){let n=ge(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=ge(o.node.consequent),a=ge(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()&&Fc(o.node.operator)){let s=ge(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 Fc(e){return e==="&&"||e==="||"||e==="??"}function Up(e,t){let n=ge(e.consequent);if(n&<(n,t))return n;let r=ge(e.alternate);return r&<(r,t)?r:null}function Jp(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=Tp(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=Ap(r,{file:e.sourceFile,exportName:n.exportName}),i=[];for(let a of r){let c=Ac({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)||Wi(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 yI}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 d=fI(a,l,o?.instanceCount);if(!d)return co();c=d}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 fI(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 Dt from"@babel/types";import{SiteEditSetPropsParamsSchema as pI}from"@vcp-dev/contracts";function Xp(e){let t=e.changes??(e.change?[e.change]:[]);if(!pI.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=Re(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=ae(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?mI(r):gI(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 mI(e){return e.operation==="set"?{kind:"value",value:e.value}:{kind:"undefined"}}function gI(e,t){let n=e.properties.filter(i=>Dt.isObjectProperty(i)&&hI(i.key)===t);if(n.length>1)return null;let r=n[0];if(!r)return{kind:"undefined"};if(!Dt.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 hI(e){return Dt.isIdentifier(e)?e.name:Dt.isStringLiteral(e)?e.value:Dt.isNumericLiteral(e)?String(e.value):null}function lo(e,t){return{ok:!1,errorCode:e,reason:t}}function zp(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 Wp(e){let t=yI.safeParse({kind:"set-props",scope:e.scope,changes:e.changes});if(!t.success)return dn("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 dn("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 xI(e,r);if(o){if(!o.ok)return dn("owner-plan-failed",o.reason);Hp(n,o.steps);continue}let i=await e.getPropertyState(e.node.key,r.name,e.selectionRef);if(!i)return dn("missing-property-state",`No authoritative property state is available for '${r.name}'`);if(i.status==="blocked")return dn("readonly-property",i.diagnostic?.message??`Property '${r.name}' is not writable`);if(EI(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 dn(a.code,a.reason);let c=a.target;if(c.kind==="value-binding"&&r.operation==="set"){_c(n,{type:"update-value",order:n.length,file:c.file,locator:c.locator,value:r.value});continue}if(c.kind==="repeat-property"){let l=Xp({source:e.getFileContent(c.target.sourceFile),target:c.target,changes:[r]});if(!l.ok)return dn("repeat-target-failed",l.reason);Hp(n,l.steps);continue}_c(n,{type:"set-property-changes",order:n.length,file:e.node.file,locator:bI(e.node),scope:e.scope,changes:[r]})}return n.forEach((r,o)=>{r.order=o}),SI(n)?dn("step-conflict","Property changes resolve to conflicting write steps"):{ok:!0,steps:n}}async function xI(e,t){return t.name!=="className"&&t.name!=="class"?null:zp({node:e.node,change:t,classNameSource:e.classNameSource})}function bI(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 SI(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 Hp(e,t){for(let n of t)_c(e,{...n,order:e.length})}function _c(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 EI(e,t){if(t.operation!=="set"||e.status!=="direct")return!1;let n=e.attribute?.resolution;return n?.status==="resolved"?Oc(n.value,t.value):e.attribute?.source===null&&e.attribute.value===t.value}function Oc(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)=>Oc(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=>Oc(n[i],r[i]))}return!1}function dn(e,t){return{ok:!1,errorCode:e,reason:t}}import*as mr from"@babel/types";import*as G from"@babel/types";function Mc(e,t,n){let r=bt(t,n);return r?Lt(e,r):null}function Lt(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 d=a.get("object"),f=fr(e,d.node),m=r.node.params.map(h=>fr(e,h)),u=ge(i.node),g=ge(r.node);return!f||m.some(h=>h.length===0)||!u||!g?null:{callStart:u.start,callEnd:u.end,callbackStart:g.start,callbackEnd:g.end,collectionExpression:f,callbackParams:m,mapOperator:G.isOptionalMemberExpression(c)&&c.optional?"?.map":".map",collectionNeedsParens:qi(d.node),callbackPath:r,collectionPath:d}}function fo(e,t){return!!(e&&t&&e.callStart===t.callStart&&e.callEnd===t.callEnd&&e.callbackStart===t.callbackStart&&e.callbackEnd===t.callbackEnd)}function vI(e,t){let n=ge(e.node);return n?kI(t).some(r=>{let o=ge(r);return r===e.node||!!(o&&o.start===n.start&&o.end===n.end)}):!1}function kI(e){let t=e.callbackPath.node.body;return G.isBlockStatement(t)?fn(t.body):pn(t)}function fn(e){let t=[];for(let n of e){if(G.isReturnStatement(n)){n.argument&&t.push(...pn(n.argument));continue}if(G.isBlockStatement(n)){t.push(...fn(n.body));continue}if(G.isIfStatement(n)){let r=G.isBlockStatement(n.consequent)?n.consequent.body:[n.consequent];if(t.push(...fn(r)),n.alternate){let o=G.isBlockStatement(n.alternate)?n.alternate.body:[n.alternate];t.push(...fn(o))}continue}if(G.isSwitchStatement(n)){for(let r of n.cases)t.push(...fn(r.consequent));continue}G.isTryStatement(n)&&(t.push(...fn(n.block.body)),n.handler&&t.push(...fn(n.handler.body.body)),n.finalizer&&t.push(...fn(n.finalizer.body)))}return t}function pn(e){return G.isJSXElement(e)?II(e)?Gp(e.children):[e]:G.isJSXFragment(e)?Gp(e.children):G.isParenthesizedExpression(e)||G.isTSAsExpression(e)||G.isTSSatisfiesExpression(e)||G.isTSNonNullExpression(e)||G.isTSTypeAssertion(e)?pn(e.expression):G.isConditionalExpression(e)?[...pn(e.consequent),...pn(e.alternate)]:G.isLogicalExpression(e)&&Fc(e.operator)?pn(e.right):[]}function Gp(e){return e.flatMap(t=>G.isJSXElement(t)||G.isJSXFragment(t)?pn(t):G.isJSXExpressionContainer(t)&&(G.isJSXElement(t.expression)||G.isJSXFragment(t.expression)||G.isConditionalExpression(t.expression)||G.isLogicalExpression(t.expression))?pn(t.expression):[])}function II(e){let t=e.openingElement.name;return G.isJSXIdentifier(t)?t.name==="Fragment":G.isJSXMemberExpression(t)&&t.property.name==="Fragment"}function Yp(e,t){return!!(e&&t&&e.callbackStart<t.callbackStart&&e.callbackEnd>t.callbackEnd)}function qi(e){return!(G.isIdentifier(e)||G.isThisExpression(e)||G.isMemberExpression(e)||G.isOptionalMemberExpression(e)||G.isCallExpression(e)||G.isOptionalCallExpression(e))}function Zp(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=ae(n,he(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:Gi(n,t);if(!o)return t.isRepeatItemRoot===!0;let i=Lt(e,o);return i?vI(o,i):t.isRepeatItemRoot===!0}function Qp(e,t){let n=Je(e);if(!n)return!1;let r=ae(n,he(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:Gi(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 ve from"@babel/types";function Dc(e){if(ve.isJSXIdentifier(e))return/^[A-Z]/.test(e.name)?e.name:null;if(ve.isJSXMemberExpression(e)){let t=e;for(;ve.isJSXMemberExpression(t);)t=t.object;return t.name}return null}function CI(e,t){let n=ge(e.node);if(!n)return[];let r=new Set,o=(i,s)=>{let a=s.scope.getBinding(i);!a||Mt(a.path.node,n)||mn(a,i,t)||r.add(i)};return e.traverse({ReferencedIdentifier(i){o(i.node.name,i)},JSXOpeningElement(i){let s=Dc(i.node.name);s&&o(s,i)}}),[...r].sort()}function Lc(e,t,n){let r=Je(e);if(!r)return{ok:!0};let o=ae(r,he(t));if(!o.ok||!o.match.path.isJSXElement())return{ok:!0};let i=ae(r,he(n));if(!i.ok||!i.match.path.isJSXElement())return{ok:!0};let s=Tr(o.match.path,i.match.path);if(Yi(s,i.match.path))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let a=CI(s,i.match.path);return a.length>0?{ok:!1,bindingNames:a}:{ok:!0}}function em(e){let t=e;for(;ve.isTSQualifiedName(t);)t=t.left;return ve.isIdentifier(t)?t.name:null}function po(e,t){e.isIdentifier()&&e.isReferencedIdentifier()&&t(e),e.traverse({ReferencedIdentifier(n){n.isIdentifier()&&t(n)}})}function es(e){let t=[],n=r=>{if(r){if(ve.isIdentifier(r)){t.push(r.name);return}if(ve.isObjectPattern(r)){for(let o of r.properties){if(ve.isRestElement(o)){n(o.argument);continue}ve.isObjectProperty(o)&&n(o.value)}return}if(ve.isArrayPattern(r)){for(let o of r.elements)n(o);return}if(ve.isAssignmentPattern(r)){n(r.left);return}if(ve.isRestElement(r)){n(r.argument);return}ve.isTSParameterProperty(r)&&n(r.parameter)}};return n(e),t}function Bc(e,t){let n=ge(e.node),r=ge(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=qp(e),i=qp(t);if(!o||!i||!Kp(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=Up(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=ge(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())&&Zp(s)){let a=ge(s.node.body)??ge(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 qp(e){let t=e;for(;t;){if(t.isReturnStatement())return t.node.argument?ge(t.node.argument):null;if(t.isArrowFunctionExpression()&&(ve.isJSXElement(t.node.body)||ve.isJSXFragment(t.node.body)||ve.isConditionalExpression(t.node.body)||ve.isLogicalExpression(t.node.body)))return ge(t.node.body);t=t.parentPath}return null}function mn(e,t,n){return n.scope.getBinding(t)===e}function jc(e,t,n,r={}){if(!r.preserveConditionalBoundary&&Yi(e,t))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let o=ge(e.node);if(!o)return{ok:!0};let i=new Set(n.callbackPath.node.params.flatMap(c=>es(c)).map(c=>n.callbackPath.scope.getBinding(c)?.path.node).filter(Boolean)),s=new Set,a=(c,l)=>{let d=l.scope.getBinding(c);!d||Mt(d.path.node,o)||i.has(d.path.node)||mn(d,c,t)||s.add(c)};return e.traverse({ReferencedIdentifier(c){a(c.node.name,c)},JSXOpeningElement(c){let l=Dc(c.node.name);l&&a(l,c)}}),s.size>0?{ok:!1,bindingNames:[...s].sort()}:{ok:!0}}function $c(e,t,n){let r=ge(e.node);if(!r)return{ok:!0};let o=new Set(n.callbackPath.node.params.flatMap(s=>es(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||Mt(a.path.node,r)||o.has(a.path.node)||mn(a,s.node.name,t)||i.add(s.node.name)}),i.size>0?{ok:!1,bindingNames:[...i].sort()}:{ok:!0}}function tm(e,t){let n=new Set(e.callbackPath.node.params.flatMap(a=>es(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)||mn(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 d=em(l);d&&o(d,c)}}});return r.size>0?{ok:!1,bindingNames:[...r].sort()}:{ok:!0}}function Vc(e,t){let n=ge(e.node),r=new Set;return po(e,o=>{let i=o.scope.getBinding(o.node.name);i&&(n&&Mt(i.path.node,n)||mn(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 nm(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 rm(e,t){return{...e,callbackParams:t}}function Kc(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 om(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 Mn(e){return{file:e.file,component:e.component}}function RI(e){return e.target.kind==="node"?e.target.key:null}function wI(e){return"kind"in e}function ts(e){return!wI(e)}function Hc(e,t){let n=os.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=os.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function Uc(e,t){let n=e.getFileContent(t.file);if(!n)return;let r=Tt(n,he(t));if(r.ok)return n.slice(r.match.start,r.match.end)}function Gc(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 NI(e){if(e.isNumericLiteral())return!0;if(!e.isUnaryExpression({operator:"-"}))return!1;let t=e.get("argument");return!Array.isArray(t)&&t.isNumericLiteral()}function PI(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 Jc(e){return e==="Cannot edit repeat-backed child node structure with a generic node operation"}function AI(e){let t=Pp(e.ast,e.sourceNode.component,e.targetParent.component);if(!t.ok)return{ok:!1,reason:t.reason};let n=Bc(t.path,e.targetParentPath);if(!n.ok)return{ok:!1,reason:n.reason};let r=TI({source:e.source,sourceContext:e.sourceContext,callSitePath:t.path,targetParentPath:e.targetParentPath});if(!r.ok)return r;let o=pm(r.collectionExpression);return{ok:!0,context:{...e.sourceContext,collectionExpression:r.collectionExpression,collectionNeedsParens:o?qi(o):!0}}}function TI(e){let t=ge(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||Mt(a.path.node,t))return;let c=OI(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=DI(e.callSitePath,c.propName,e.source);if(!l.ok){o=l.reason;return}let d=FI(l.expression,c.remainingPath);if(!d){o="Cannot move prop-backed repeat child because the mapped prop path is not a portable expression";return}let f=Vc(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:d});return}mn(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:LI(e.source,t,[...n.values()])}}function FI(e,t){if(t.length===0)return e;let n=pm(e);if(!n)return null;let r=qi(n)?`(${e})`:e;for(let o of t){if(o.kind==="property"){r=_I(o.name)?`${r}.${o.name}`:`${r}[${JSON.stringify(o.name)}]`;continue}r=`${r}[${o.index}]`}return r}function _I(e){return/^[$A-Z_a-z][$\w]*$/.test(e)}function OI(e,t,n){let r=MI(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??ge(e.node);return s?{propName:i.propName,remainingPath:i.remainingPath,hasDefault:i.hasDefault,range:s}:null}function MI(e,t){let n=e.parentPath;if(!n||!n.isMemberExpression()&&!n.isOptionalMemberExpression()||n.node.object!==e.node||!Mt(n.node,t)||n.node.computed||!de.isIdentifier(n.node.property))return null;let r=ge(n.node);return r?{propertyName:n.node.property.name,range:r}:null}function DI(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()&&de.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 LI(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 pm(e){try{let n=fm.parse(`const __VD_EXPR__ = (${e});`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0],r=de.isVariableDeclaration(n)?n.declarations[0]?.init:null;return r&&de.isExpression(r)?r:null}catch{return null}}function BI(e){let t=ge(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||Mt(s.path.node,t))return;let a=im(s,e.sourceFile,e.targetFile);if(a){let c=e.targetParentPath.scope.getBinding(a.localName);if(c){let d=im(c,e.targetFile,e.targetFile);(!d||d.moduleFile!==a.moduleFile||!jI(d.importSpec,a.importSpec))&&r.add(a.localName);return}let l=n.get(a.moduleSpecifier)??[];l.some(d=>JSON.stringify(d)===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 jI(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 im(e,t,n){let r=$I(e),o=r?.parentPath;if(!r||!o?.isImportDeclaration())return null;let i=o.node.source.value;if(typeof i!="string")return null;let s=Fn(t,i),a=i.startsWith(".")?Hc(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=de.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 $I(e){let t=e.path;for(;t&&!t.isImportDeclaration();){if(t.isImportSpecifier()||t.isImportDefaultSpecifier()||t.isImportNamespaceSpecifier())return t;t=t.parentPath}return null}function sm(e,t,n,r){let o=Tc(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=VI(a.conditionPath,c);if(s.push(a.conditionPath),a.kind==="logical"){i=`${l} ${a.operator} ${UI(i)}`;continue}i=a.branch==="consequent"?`${l} ? ${i} : null`:`${l} ? null : ${i}`}return{sourceJsx:i,conditionPaths:s}}function VI(e,t){return KI(e.node)?t:`(${t})`}function KI(e){return de.isIdentifier(e)||de.isThisExpression(e)||de.isSuper(e)||de.isMemberExpression(e)||de.isOptionalMemberExpression(e)||de.isCallExpression(e)||de.isOptionalCallExpression(e)||de.isBooleanLiteral(e)||de.isNumericLiteral(e)||de.isStringLiteral(e)||de.isNullLiteral(e)||de.isUnaryExpression(e)}function UI(e){return e.trim().startsWith("<")?e:`(${e})`}var JI={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 ns(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=JI[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 XI(e,t){for(let n of e.program.body){if(!de.isImportDeclaration(n)||n.source.value!==t)continue;let r=n.specifiers.find(o=>de.isImportDefaultSpecifier(o));if(r&&de.isImportDefaultSpecifier(r))return r.local.name}return null}function zI(e,t,n){for(let r of e.program.body){if(!de.isImportDeclaration(r)||r.source.value!==t)continue;let o=r.specifiers.find(i=>de.isImportSpecifier(i)&&(de.isIdentifier(i.imported)?i.imported.name:i.imported.value)===n);if(o&&de.isImportSpecifier(o))return o.local.name}return null}function am(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 cm(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n+=1;return`${e}${n}`}function HI(e,t){if(!e.component)return{localName:"Component"};let n=e.component,r=Gc(e),o=Je(t);if(n.exportName!=="default"){let a=o?zI(o,n.source,n.exportName):null;if(a)return{localName:a};let c=o?cm(r,am(o)):r;return{localName:c,importStep:Xc(e,c)}}if(!o)return{localName:r,importStep:Xc(e,r)};let i=XI(o,n.source);if(i)return{localName:i};let s=cm(r,am(o));return{localName:s,importStep:Xc(e,s)}}function WI(e,t){if(e.kind==="native-tag")return e.text?`<${e.tag}>${e.text}</${e.tag}>`:`<${e.tag} />`;let n=t??Gc(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 GI(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?YI(e.props):void 0;return{kind:e.kind,component:{source:e.component.source,exportName:e.component.exportName},...t?{props:t}:{}}}function YI(e){return Object.fromEntries(Object.entries(e).filter(t=>Wc(t[1])))}function Wc(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(Wc):typeof e=="object"?Object.values(e).every(Wc):!1}function Xc(e,t=Gc(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 lm(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 ZI(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 Yc(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:Yc(e,t.slice(0,n)),index:r.index}}return null}function zc(e,t){return e.locator?e.collectionPathMap?.[t]?Yc(e.locator,e.collectionPathMap[t]):go(e.locator)?qI(e.locator,eC(t,e.collectionIndexMap)):null:null}function QI(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:mm(o,t)}function mm(e,t){let[n,...r]=e;if(!n)return t;if(n.kind!=="property")return;let o=mm(r,t);return o===void 0?void 0:{[n.name]:o}}function qI(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},Yc(e,i)}return null}function eC(e,t){return t?.[e]??e}function um(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 tC(e,t){return nC(e.root,t.root)&&oC(e.path??[],t.path??[])}function nC(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&&rC(e.sourceRange,t.sourceRange)}}function rC(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function oC(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 rs=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(!ts(r.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};let o=lm(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=RI(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):dm(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 dm(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:he(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?Wp({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 d=await this.graph.getElementPropertyWriteTarget?.(r.key,c),f=r.attributes?.find(u=>u.name===c);if((await this.graph.getPropertyState?.(r.key,c,i))?.status==="blocked"||!d&&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(d?.kind==="external-entry")return{ok:!1,errorCode:"capability-denied",reason:`apply-style-draft cannot overwrite readonly external property '${c}'`};if(d?.kind==="value-binding"&&d.locator){let u=d.locator;if(d.sourceKind==="repeat-template"&&typeof i?.instanceIndex=="number"){let g=zc(d,i.instanceIndex);if(!g)return{ok:!1,errorCode:"invalid-params",reason:"apply-style-draft could not resolve the selected repeat item"};u=g}s.push({order:n+s.length,file:d.file,type:"update-value",locator:u,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:he(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=zc(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:he(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=ae(s,n);if(!a.ok)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not resolve the value source`};if(!NI(a.match.path))return{ok:!0,value:r};let c=PI(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=zc(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=ae(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:he(r),removeWhitespace:!0}],d=this.buildRemoveComponentImportStep(r);return d&&l.push({...d,order:l.length}),this.buildPlan(t,n,l,o)}buildRemoveComponentImportStep(t,n=this.graph.getFileContent(t.file)){if(!t.importedFrom||!t.exportName||!t.tag||Vp(n,t)>1)return null;let r=Hc(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(!ts(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 d=await this.planExternalBackedInsertChild(t,n,r,o,i,a);if(d)return d;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 u=vp(this.graph.getFileContent(r.file),r);if(!u.allowed)return{ok:!1,errorCode:"unsupported-operation",reason:u.reason??"Cannot insert child into this node"};let g=ns(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"?HI(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:he(r),node:{jsx:WI(n.params.node,E?.localName)},placement:n.params.position.relation,anchorLocator:i?he(i):void 0}),this.buildPlan(t,n,h,o)}async planExternalBackedInsertChild(t,n,r,o,i,s){if(!ts(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:GI(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(!ts(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=QI(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 d=n.params.position.relation==="prepend"?um(0,a.collectionIndexMap):um(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:d,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:")||Qp(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 d=bt(l,r),f=bt(l,o);if(!d||!f)return null;let m=Lt(c,d),u=Lt(c,f);if(!fo(m,u))return null;if(a&&(s==="before"||s==="after")){let h=bt(l,a),S=h?Lt(c,h):null;if(!fo(m,S))return null}if(Zi(d,f))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child across statement-level conditional branches"};let g=Lc(c,r,o);return g.ok?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:he(r),targetParentLocator:he(o),placement:s,anchorLocator:a?he(a):void 0,selectionContext:Mn(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 d=bt(l,r),f=bt(l,o);if(!d||!f)return null;let m=Lt(c,d);if(!m)return null;let u=Lt(c,f);if(fo(m,u))return null;if(u&&!Yp(u,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=Mc(c,l,a);if(u&&!fo(u,v)||!u&&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=ns(o,{kind:"native-tag",tag:r.tag});if(v)return{ok:!1,errorCode:"unsupported-operation",reason:v}}let g=Uc(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(Zi(d,f))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let h=sm(c,d,f,g);for(let v of h.conditionPaths){let I=$c(v,f,m);if(!I.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its condition depends on bindings outside the target scope: ${I.bindingNames.join(", ")}`}}let S=jc(d,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=tm(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=AI({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=Vc(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:he(r),targetParentLocator:he(o),placement:s,anchorLocator:a?he(a):void 0,repeatExpression:Kc(y,h.sourceJsx),selectionContext:Mn(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),d=Je(c),f=Je(l);if(!d||!f)return null;let m=Jp({knownSourceFiles:this.graph.getKnownSourceFiles?.(),routeEntryFiles:this.graph.getRouteEntryFiles?.(),sourceAst:d,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 u=bt(d,r),g=bt(f,o);if(!u||!g)return null;let h=Bc(m.callSitePath,g);if(!h.ok)return{ok:!1,errorCode:"unsupported-operation",reason:h.reason};let S=Lt(c,u);if(!S)return null;if(Lt(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")&&Mc(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 F=ns(o,{kind:"native-tag",tag:r.tag});if(F)return{ok:!1,errorCode:"unsupported-operation",reason:F}}let y=Uc(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(Zi(u,g))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let v=sm(c,u,g,y);for(let F of v.conditionPaths){let D=$c(F,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 I=jc(u,g,S,{preserveConditionalBoundary:v.conditionPaths.length>0});if(!I.ok)return{ok:!1,errorCode:"unsupported-operation",reason:I.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${I.bindingNames.join(", ")}`};let P=BI({sourceFile:r.file,targetFile:o.file,sourceContext:S,targetParentPath:g});if(!P.ok)return{ok:!1,errorCode:"unsupported-operation",reason:P.reason};let A=nm(S);if(!A.ok)return{ok:!1,errorCode:"unsupported-operation",reason:A.reason};let R=rm(S,A.callbackParams),T=[{order:0,file:r.file,type:"remove-node",locator:he(r),removeWhitespace:!0}];for(let F of P.imports)T.push({order:T.length,file:o.file,type:"add-import",moduleSpecifier:F.moduleSpecifier,imports:F.imports});return T.push({order:T.length,file:o.file,type:"insert-jsx-expression-child",parentLocator:he(o),expression:Kc(R,v.sourceJsx),placement:s,anchorLocator:a?he(a):void 0,selectionContext:Mn(o)}),this.buildPlan(t,n,T,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,I=this.graph.getNode(v.anchorKey);if(!I||r.file!==I.file||r.component!==I.component)return{ok:!1,errorCode:"locator-miss",reason:"Source sibling move requires a sibling in the same component file"};let P=this.graph.getFileVersion(r.file);if(n.documentVersion!==P)return{ok:!1,errorCode:"stale-version",reason:`Document version ${n.documentVersion} is stale or otherwise does not match source sibling file version (current: ${P})`};let A=this.graph.getFileContent(r.file),R=Je(A),T=R?bt(R,r):null,F=R?bt(R,I):null,D=T?.parentPath,U=F?.parentPath;if(!T||!F||!D||!U||D.node!==U.node||!D.isJSXFragment()&&!(D.isJSXElement()&&Fe(D)))return{ok:!1,errorCode:"unsupported-operation",reason:"Source sibling move requires two direct children of the same transparent Fragment"};let ee=D.node.loc;return ee?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:he(r),targetParentLocator:{kind:"jsx-node",strategy:"source-range",sourceRange:{startLine:ee.start.line,startColumn:ee.start.column,endLine:ee.end.line,endColumn:ee.end.column}},placement:v.relation,anchorLocator:he(I),selectionContext:Mn(r)}],o):{ok:!1,errorCode:"locator-miss",reason:"Source Fragment has no stable source range"}}let i=lm(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(ZI(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,I=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:I?.kind==="external-entry"?I.sourceId:null,parentKey:"parentKey"in n.params.target?n.params.target.parentKey:null}}],o)}let l=r.file!==s.file,d=n.params.target.relation,f=i.anchorNode,m=this.graph.getTextProvenance?.(r.key,0)??null,u=mo(r,c,m);if(u&&!Jc(u)&&!om(r,s,c,m))return{ok:!1,errorCode:"unsupported-operation",reason:u};if(r.isRepeatItemRoot&&f?.isRepeatItemRoot&&r.repeatOwnerKey&&r.repeatOwnerKey===f.repeatOwnerKey&&(d==="before"||d==="after")){let v=c,I=await this.graph.getTextWriteTarget(f.key,0);if(v?.kind==="value-binding"&&I?.kind==="value-binding"&&v.locator&&I.locator){let P=go(v.locator),A=go(I.locator);if(P&&A&&v.file===I.file&&tC(P.locator,A.locator)){let R=P.index,T=A.index,F=d==="before"?T-(R<T?1:0):T+(R<T?0:1);return this.buildPlan(t,n,[{order:0,file:v.file,type:"move-array-item",locator:P.locator,fromIndex:R,toIndex:F}],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=Jc(u)?u:g;if(h&&Jc(h)){let v=this.planRepeatTemplateInternalMove(t,n,r,s,o,d,f);if(v)return v;let I=this.planRepeatTemplateHoistMove(t,n,r,s,o,d,f);if(I)return I;let P=this.planCrossFileRepeatTemplateHoistMove(t,n,r,s,o,d,f);return P||{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=ns(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,d,f);let E=Lc(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:he(r),targetParentLocator:he(s),placement:d,anchorLocator:f?he(f):void 0,selectionContext:Mn(s)}];return this.buildPlan(t,n,y,o)}planCrossFileMove(t,n,r,o,i,s,a){let c=[],l=0,d=this.graph.getFileContent(r.file),f=Uc(this.graph,r)??`<${r.component} />`,m=kp(d,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:he(r),removeWhitespace:!0}),r.importedFrom&&r.exportName){let g=r.tag??r.component,S={moduleSpecifier:Hc(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:he(o),node:{jsx:f},placement:s,anchorLocator:a?he(a):void 0,selectionContext:Mn(o)})}else c.push({order:l++,file:o.file,type:"insert-child",parentLocator:he(o),node:{jsx:f},placement:s,anchorLocator:a?he(a):void 0,selectionContext:Mn(o)});let u=this.buildRemoveComponentImportStep(r,d);return u&&c.push({...u,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:Ee(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 dm(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 tl from"@babel/generator";import{parse as bC}from"@babel/parser";import nl from"@babel/traverse";import*as w from"@babel/types";import*as jt from"@babel/types";import Zc from"@babel/generator";import*as be from"@babel/types";var iC=typeof Zc=="function"?Zc:Zc.default,sC=/(?:token|secret|key|password|authorization|cookie|signature|credential)/i,aC=/^((?:https?:)?\/\/)[^/@\s]+@/i,cC=/(\/(?:token|secret|api[-_]?key|password|credential|signature)\/)[^/?#]+/gi;function hm(e,t){let n=Bt(e.callee);if(!n)return null;if(n==="fetch")return Qc(e.arguments[0],"GET",t,["fetch call"]);if(n.startsWith("axios.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(gm(r))return Qc(e.arguments[0],r,t,["axios client contract"])}if(n.startsWith("ky.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(gm(r))return Qc(e.arguments[0],r,t,["ky client contract"])}return null}function Qc(e,t,n,r){if(!e||be.isSpreadElement(e)||be.isJSXNamespacedName(e))return fC(t,n,r,"missing url argument");let o=ho(e);return{sourceKind:dC(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(be.isStringLiteral(e))return is(e.value);if(be.isTemplateLiteral(e))return is(lC(e));if(be.isBinaryExpression(e)&&e.operator==="+"){let t=ho(e.left),n=ho(e.right);return!t&&!n?void 0:is(`${t??qc(e.left)}${n??qc(e.right)}`)}if(be.isMemberExpression(e)){let t=ym(e);if(t)return`env:${t}`}if(!(be.isCallExpression(e)&&Bt(e.callee)==="new URL")){if(be.isNewExpression(e)&&be.isIdentifier(e.callee,{name:"URL"})){let[t,n]=e.arguments,r=t&&!be.isSpreadElement(t)?ho(t):void 0,o=n&&!be.isSpreadElement(n)?ho(n):void 0;return o&&r?is(`${o} + ${r}`):r??o}if(be.isIdentifier(e))return`:${e.name}`}}function lC(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+=qc(r))}return t}function qc(e){if(be.isIdentifier(e))return`:${e.name}`;if(be.isMemberExpression(e)){let t=ym(e);if(t)return`env:${t}`}return`:${uC(e)}`}function uC(e){return iC(e,{comments:!1}).code.replace(/[^a-zA-Z0-9_$]+/g,"_").replace(/^_+|_+$/g,"")||"param"}function is(e){let[t]=e.split("#"),[n,r]=t.split("?"),o=n.replace(aC,"$1<redacted>@").replace(cC,"$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 dC(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 fC(e,t,n,r){return{sourceKind:"unknown-api",method:e,confidence:"partial",evidence:[{file:t.file,reason:[...n,r].join("; ")}]}}function gm(e){return["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(e)}function ym(e){return!be.isMemberExpression(e.object)||!be.isIdentifier(e.object.object,{name:"process"})||!pC(e.object.property,"env")?null:be.isIdentifier(e.property)?e.property.name:be.isStringLiteral(e.property)?e.property.value:null}function pC(e,t){return be.isIdentifier(e)&&e.name===t}function Bt(e){if(be.isIdentifier(e))return e.name;if(be.isMemberExpression(e)){let t=Bt(e.object),n=be.isIdentifier(e.property)?e.property.name:be.isStringLiteral(e.property)?e.property.value:null;if(t&&n)return`${t}.${n}`}return null}var mC=new Set(["list","listStrict","get","getStrict","getByUrl","getByUrlStrict","schema","categories"]),gC=new Set(["getConfig","submit"]);function xm(e,t){let n=hC(Bt(e.callee),t);if(!n)return null;let r="cms.collections.";if(n.startsWith(r)){let i=n.slice(r.length);if(!mC.has(i))return null;let s=el(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(!gC.has(i))return null;let s=el(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=el(e,0)??yC(e,0,"path")??"/cms/:path",s=xC(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 hC(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 bm(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 Sm(e){let t=Bt(e.callee);return typeof t=="string"&&t.startsWith("cms.field.")}function el(e,t){let n=e.arguments[t];return jt.isStringLiteral(n)?n.value:null}function yC(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 xC(e){return/^\/collections\/([^/]+)(?:\/|$)/.exec(e)?.[1]??null}var ol=typeof nl=="function"?nl:nl.default,_M=typeof tl=="function"?tl:tl.default,SC={maxFunctionDepth:8,maxImportDepth:6},EC=new Set(["src","href","alt","poster","content","title","aria-label"]);async function Rm(e){let t=e.fileCache??new Map,n=al(e.file,e.source,t),r={file:e.file,analysis:n,readFile:e.readFile,exists:e.exists,fileCache:t,options:{...SC,...e.options},variableCache:new Map,functionDepth:0,importDepth:0,paramSources:new Map,resolvingVariables:new Set,resolvingComponentProps:new Set,scopeVariables:$m(n,e.element.componentName)};await wm(e.element.componentName,e.graph,r);let o=[];o.push(...await RC(e.element,e.graph,r),...await wC(e.element,e.graph,r));for(let s of e.element.textSegments){let a=await NC(s,e.element,e.graph,r);a&&o.push(cs(a,"text","children"))}for(let s of e.element.attributes??[]){let a=CC(s,e.element);if(!a)continue;let c=await Am(s.source,e.element,e.graph,r);c&&o.push(cs(c,a,s.name))}let i=UC(o).sort(Bm);return{hasDynamicData:i.length>0,bindings:i}}async function wm(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 t.elements.values()){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 Nm(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 d=`${n.file}#${e}<-${l.identity.key}`;if(!n.resolvingComponentProps.has(d)){n.resolvingComponentProps.add(d);try{let f=await Pm(l.sourceFile,n);if(!f)continue;let m=us(f,n,{importDepth:n.importDepth+1});m.paramSources.clear(),m.scopeVariables=$m(f,l.componentName),await wm(l.componentName,t,m);let u=await vC(l,m);for(let[g,h]of u){if(!h)continue;let S=a.get(g)??[];S.push(h),a.set(g,S)}}finally{n.resolvingComponentProps.delete(d)}}}let c=new Map;for(let[l,d]of a){let f=Dm(d);f.length===1&&c.set(l,f[0])}IC(o,c,n)}async function Nm(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 Pm(e,r))?.imports.get(t);if(!s||!Nt(s.source))return!1;let a=await Um(e,s.source,r.exists);return a?a===n?!0:Nm(a,s.importedName,n,r,o):!1}async function vC(e,t){let n=new Map;ol(t.analysis.ast,{JSXElement(o){if(kC(o.node,e.sourceRange)){for(let i of o.node.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);o.stop()}}});let r=new Map;for(let[o,i]of n){let s=await je(i,t);s&&r.set(o,s)}return r}function kC(e,t){return e.loc?.start.line===t.startLine&&e.loc.start.column===t.startColumn&&e.loc.end.line===t.endLine&&e.loc.end.column===t.endColumn}async function Pm(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 al(e,r,t.fileCache)}function IC(e,t,n){if(w.isIdentifier(e)){t.size>0&&n.paramSources.set(e.name,sl(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 CC(e,t){return e.name==="dangerouslySetInnerHTML"?"richtext":EC.has(e.name)?"attribute":t.importedFrom||/^[A-Z]/.test(t.tag)?"component-prop":null}async function RC(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 ls(i.collectionSource,n);s&&r.push(cs(Dn(s),"repeat-region",i.collectionExpression))}return r}async function wC(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 ls(i.conditionSource,n);s&&r.push(cs(Dn(s),"conditional-region",i.conditionExpression))}return r}async function NC(e,t,n,r){return Am(e.source,t,n,r)}async function Am(e,t,n,r){let o=await PC(e,t,n,r);return o||ls(e,r)}async function PC(e,t,n,r){if(!e)return null;let o=AC(e.base,t,n);if(!o)return null;let i=await ls(o.collectionSource,r);return i?So(i,e.path,!0):null}function AC(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 ls(e,t){if(!e)return null;let n=await Tm(e.base,t);return n?So(n,e.path,!1):null}async function Tm(e,t){let n=t.paramSources.get(e);if(n)return ze(n);if(t.variableCache.has(e))return JC(t.variableCache.get(e)??null);if(t.resolvingVariables.has(e))return null;t.resolvingVariables.add(e);let r=await TC(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 Vm(i,t);if(s){let a=us(s,t,{importDepth:t.importDepth+1}),c=Km(i,s);if(c){let f=(await Ln(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 d=await je(l,a);return t.variableCache.set(e,d?ze(d):null),t.resolvingVariables.delete(e),d}}}return t.variableCache.set(e,null),t.resolvingVariables.delete(e),null}async function TC(e,t){let n=t.analysis.stateSetters.get(e);if(!n)return null;let r=[];ol(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 Tm(e.name,t);if(w.isMemberExpression(e)||w.isOptionalMemberExpression(e)){let n=w.isMemberExpression(e)?bm(e,{file:t.file}):null;if(n)return Mm(n);let r=await FC(e,t);if(!r)return null;let o=VC(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 Fm(e,t);if(w.isObjectExpression(e)){let n=await _m(e,t);return Object.keys(n).length>0?sl(n,t.file):null}if(w.isConditionalExpression(e)){let n=await je(e.consequent,t),r=await je(e.alternate,t);return bo(vm(n,r))}if(w.isLogicalExpression(e)){let n=await je(e.left,t),r=await je(e.right,t);return bo(vm(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 FC(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 Fm(e,t){let n=xm(e,{file:t.file,imports:t.analysis.imports});if(n)return Mm(n);if(Sm(e)){let f=e.arguments[0];if(f&&w.isExpression(f))return bo(await je(f,t))}let r=await _C(e,t);if(r)return r;let o=hm(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 DC(e,t);if(i)return i;let s=await LC(e,t);if(s)return s;let a=await BC(e,t);if(a)return a;let c=await jC(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 d=Dm(l);return d.length===1?bo(d[0]):null}async function _C(e,t){let n=Bt(e.callee);if(n!=="useQuery"&&n!=="useSuspenseQuery"&&n!=="useInfiniteQuery"&&n!=="useSWR")return null;if(n==="useSWR"){let i=MC(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 Ln(a.node,i?[i]:[],a.context)).returnSource??i}return i}let r=e.arguments[0];if(!w.isObjectExpression(r))return ss(t.file,`${n} without static options`);let o=OC(r,"queryFn");if(!o)return ss(t.file,`${n} without queryFn`);if(w.isIdentifier(o)){let i=await xo(o.name,t);return i?(await Ln(i.node,[],i.context)).returnSource:ss(t.file,`${n} queryFn unresolved`)}return w.isArrowFunctionExpression(o)||w.isFunctionExpression(o)?(await Ln(o,[],t)).returnSource:w.isCallExpression(o)?Fm(o,t):null}function OC(e,t){for(let n of e.properties){if(!w.isObjectProperty(n)||!w.isExpression(n.value))continue;if(Om(n)===t)return n.value}return null}function MC(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 DC(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 Ln(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 Ln(o,[r],t);return{...Dn(r),...i.objectReturnMap??i.returnSource?.fieldMap?{fieldMap:i.objectReturnMap??i.returnSource.fieldMap}:{}}}return Dn(r)}async function LC(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 BC(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 jC(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(ss(t.file,`unsupported argument for ${e.callee.name}`));continue}let s=await je(i,t);r.push(s)}return(await Ln(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 Vm(r,t);if(!o)return null;let i=us(o,t,{importDepth:t.importDepth+1}),s=Km(r,o);return s?{node:s,context:i}:xo(r.importedName,i)}async function Ln(e,t,n){if(n.functionDepth>=n.options.maxFunctionDepth)return{returnSource:null};let r=us(n.analysis,n,{functionDepth:n.functionDepth+1});r.scopeVariables=n.analysis.functionVariables.get(e),e.params.forEach((c,l)=>{let d=t[l];d&&rl(c,KC(d),r)});let o=$C(e),i=null,s,a=!1;for(let c of o){if(w.isObjectExpression(c)){s={...s??{},...await _m(c,r)},i=i??sl(s,n.file);continue}let l=await je(c,r);if(l){if(!i){i=l;continue}let d=il(i,l);if(!d){a=!0,i=null;continue}i=d}}return{returnSource:a?null:i,...s?{objectReturnMap:s}:{}}}function rl(e,t,n){if(w.isIdentifier(e)){n.paramSources.set(e.name,ze(t));return}if(w.isAssignmentPattern(e)){rl(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;rl(i,o,n)}}function $C(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 _m(e,t){let n={};for(let r of e.properties){if(!w.isObjectProperty(r))continue;let o=Om(r);if(!o||!w.isExpression(r.value))continue;let i=await je(r.value,t);i&&(n[o]=i)}return n}function Om(e){return w.isIdentifier(e.key)&&!e.computed?e.key.name:w.isStringLiteral(e.key)?e.key.value:null}function VC(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,Em(t)),o)}return o.valuePath=yo(o.valuePath,Em(t)),o}function Em(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 Mm(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 KC(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 vm(e,t){return e?t?il(e,t):ze(e):t?ze(t):null}function il(e,t){if(as(e)!==as(t))return null;let n=jm(e.confidence,t.confidence)<=0?e.confidence:t.confidence;return{...e,confidence:n,evidence:[...e.evidence,...t.evidence]}}function Dm(e){let t=new Map;for(let n of e){let r=as(n),o=t.get(r);t.set(r,o?il(o,n):ze(n))}return[...t.values()]}function as(e){let t=e.fieldMap?Object.fromEntries(Object.entries(e.fieldMap).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>[n,as(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 sl(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 ss(e,t){return{sourceKind:"unknown-api",sourceType:"api-field",confidence:"unknown",readonly:!0,evidence:[{file:e,reason:t}]}}function cs(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 Lm(e){let t=[...e].sort(Bm),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 UC(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 Bm(e,t){return km(e.targetKind)-km(t.targetKind)||jm(e.confidence,t.confidence)||Im(e.sourceKind)-Im(t.sourceKind)||e.targetName.localeCompare(t.targetName)}function km(e){return{"repeat-region":0,"conditional-region":1,text:2,richtext:3,attribute:4,"component-prop":5}[e]}function Im(e){return e.startsWith("vcp-cms-")?0:e==="site-api-route"?1:e==="external-api"?2:3}function jm(e,t){let n={exact:0,"safe-derived":1,partial:2,unknown:3};return n[e]-n[t]}function al(e,t,n){let r=n.get(e);if(r?.source===t)return r;let o=bC(t,{sourceType:"module",plugins:["jsx","typescript"]}),i={file:e,source:t,ast:o,variables:new Map,functions:new Map,imports:new Map,stateSetters:new Map,functionVariables:new WeakMap};return ol(o,{ImportDeclaration(s){let a=s.node.source.value;for(let c of s.node.specifiers)w.isImportSpecifier(c)&&w.isIdentifier(c.local)?i.imports.set(c.local.name,{source:a,importedName:w.isIdentifier(c.imported)?c.imported.name:c.imported.value,localName:c.local.name,isDefault:!1}):w.isImportDefaultSpecifier(c)&&i.imports.set(c.local.name,{source:a,importedName:"default",localName:c.local.name,isDefault:!0})},FunctionDeclaration(s){s.node.id?.name&&i.functions.set(s.node.id.name,s.node)},VariableDeclarator(s){let a=s.getFunctionParent(),c=a&&(w.isFunctionDeclaration(a.node)||w.isFunctionExpression(a.node)||w.isArrowFunctionExpression(a.node))?a.node:null,l=c?i.functionVariables.get(c)??new Map:i.variables;c&&!i.functionVariables.has(c)&&i.functionVariables.set(c,l);for(let d of hr(s.node.id))l.set(d,w.isExpression(s.node.init)?s.node.init:null);if(w.isArrayPattern(s.node.id)&&w.isCallExpression(s.node.init)&&Bt(s.node.init.callee)==="useState"){let[d,f]=s.node.id.elements;w.isIdentifier(d)&&w.isIdentifier(f)&&i.stateSetters.set(d.name,f.name)}w.isIdentifier(s.node.id)&&Cm(s.node.init)&&i.functions.set(s.node.id.name,s.node.init)},ExportNamedDeclaration(s){let a=s.node.declaration,c=s.node.source?.value;if(c)for(let l of s.node.specifiers){if(!w.isExportSpecifier(l))continue;let d=w.isIdentifier(l.exported)?l.exported.name:l.exported.value,f=l.local.name;i.imports.set(d,{source:c,importedName:f,localName:d,isDefault:f==="default"})}if(w.isFunctionDeclaration(a)&&a.id?.name&&i.functions.set(a.id.name,a),w.isVariableDeclaration(a))for(let l of a.declarations)w.isIdentifier(l.id)&&Cm(l.init)&&i.functions.set(l.id.name,l.init)},ExportDefaultDeclaration(s){let a=s.node.declaration;if((w.isFunctionDeclaration(a)||w.isFunctionExpression(a)||w.isArrowFunctionExpression(a))&&i.functions.set("default",a),w.isIdentifier(a)){let c=i.functions.get(a.name);c&&i.functions.set("default",c)}}}),n.set(e,i),i}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 Cm(e){return w.isFunctionExpression(e)||w.isArrowFunctionExpression(e)}function $m(e,t){let n=e.functions.get(t)??e.functions.get("default");return n?e.functionVariables.get(n):void 0}async function Vm(e,t){let n=await Um(t.file,e.source,t.exists);if(!n)return null;let r=await t.readFile(n);return al(n,r,t.fileCache)}function Km(e,t){return e.isDefault?t.functions.get("default")??t.functions.get(e.localName)??null:t.functions.get(e.importedName)??null}async function Um(e,t,n){return Nt(t)?xn(e,t,n):null}function us(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 JC(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 ll from"@babel/parser";import cl from"@babel/traverse";import*as Y from"@babel/types";import{classifySiteEditPropertyName as XC}from"@vcp-dev/contracts";var ul=typeof cl=="function"?cl:cl.default;function dl(e){let t=XC(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=ll.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=zC(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=HC(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=[],d=[];for(let[S,E]of s.elements.entries()){if(!E||!Y.isObjectExpression(E)||!Gm(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),d.push({kind:"value",root:a.root,path:y})}let f=d.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 u=s.elements[m];if(!u||!Y.isObjectExpression(u))return ut("unsafe-collection","Selected repeat item is not an object");let g=qC(e.element,e.propertyName),h=ZC(u,e.propertyName);return h?{ok:!0,sourceFile:c,templateFile:e.file,collectionLocator:a,parentObjectLocators:d,selectedParentObjectLocator:d[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:QC(u,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 zC(e,t){let n=[];return ul(e,{CallExpression(r){let o=Jm(r.node);o&&zm(o.callback,t)&&n.push({...o,span:Xm(r.node)})},OptionalCallExpression(r){let o=Jm(r.node);o&&zm(o.callback,t)&&n.push({...o,span:Xm(r.node)})}}),n.sort((r,o)=>r.span-o.span),n[0]??null}function Jm(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 HC(e,t,n,r){let o=Eo(t);if(o&&Y.isArrayExpression(o))return{array:o,locator:{kind:"value",root:{kind:"expression",sourceRange:Zm(o)}},sourceFile:n};if(!Y.isIdentifier(t))return null;let i=[];if(ul(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 WC(e,t.name,n,r)}function WC(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=YC(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=ll.parse(c,{sourceType:"module",plugins:["typescript","jsx"]})}catch{return null}let d=GC(l,a),f=d?Eo(d):null;return!f||!Y.isArrayExpression(f)?null:{array:f,locator:{kind:"value",root:{kind:"binding",name:a}},sourceFile:s}}return null}function GC(e,t){let n=null;return ul(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 YC(e,t,n){let r=yn(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)?Wm(e.typeAnnotation)?Eo(e.expression):null:Y.isTSSatisfiesExpression(e)?null:e}function Wm(e){return Y.isTSTypeReference(e)&&Y.isIdentifier(e.typeName)&&e.typeName.name==="const"}function Gm(e){return e.properties.every(t=>!Y.isObjectProperty(t)||t.computed||!Y.isExpression(t.value)?!1:ds(t.value))}function ds(e){if(Y.isTSAsExpression(e)&&Wm(e.typeAnnotation))return ds(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:ds(n));if(Y.isObjectExpression(e))return Gm(e);let t=_t(e);return t.status==="resolved"||t.status==="undefined"}function ZC(e,t){let n=e.properties.filter(o=>Y.isObjectProperty(o)&&Ym(o.key)===t);if(n.length>1)return null;let r=n[0];return r?Y.isExpression(r.value)?ds(r.value)?"static":Y.isIdentifier(r.value)||Y.isMemberExpression(r.value)?"binding":null:null:"missing"}function QC(e,t){let n=e.properties.filter(o=>Y.isObjectProperty(o)&&Ym(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 qC(e,t){let n=e.attributes?.filter(r=>r.name===t)??[];return n.length===1?n[0]:void 0}function Ym(e){return Y.isIdentifier(e)?e.name:Y.isStringLiteral(e)?e.value:Y.isNumericLiteral(e)?String(e.value):null}function Zm(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 Xm(e){return e.start==null||e.end==null?Number.MAX_SAFE_INTEGER:e.end-e.start}function zm(e,t){let n=Zm(e);return Hm(n.startLine,n.startColumn,t.startLine,t.startColumn)<=0&&Hm(n.endLine,n.endColumn,t.endLine,t.endColumn)>=0}function Hm(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 jR}from"@vcp-dev/contracts";import*as Z from"@babel/types";import Co from"node:path";import*as j from"@babel/types";import*as ng from"@babel/parser";import fl from"@babel/traverse";import*as ne from"@babel/types";function fs(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 Qm(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}function qm(e){let{resolveBindingTarget:t}=e;async function n(i,s,a,c,l,d,f){if(ne.isStringLiteral(i)||ne.isNumericLiteral(i)||ne.isBooleanLiteral(i))return i.value;if(ne.isNullLiteral(i))return null;if(ne.isTemplateLiteral(i))return i.expressions.length===0&&i.quasis.length===1?i.quasis[0].value.cooked??i.quasis[0].value.raw:void 0;if(ne.isTSAsExpression(i)||ne.isTSSatisfiesExpression(i)||ne.isTSNonNullExpression(i))return await n(i.expression,s,a,c,l,d,f);if(ne.isIdentifier(i)){let m=s.getBinding(i.name);if(!m)return;let u=await t({currentFile:a,binding:m,readFile:c,exists:l,fileCache:d,visited:f});return u?.kind==="static"?u.value:void 0}if(ne.isArrayExpression(i)){let m=[];for(let u of i.elements){if(!u||ne.isSpreadElement(u))return;let g=await r(u,s,a,c,l,d,f);if(g===void 0)return;m.push(g)}return m}if(ne.isObjectExpression(i)){let m={};for(let u of i.properties){if(!ne.isObjectProperty(u)||u.computed)return;let g=null;if(ne.isIdentifier(u.key)?g=u.key.name:ne.isStringLiteral(u.key)&&(g=u.key.value),!g)return;if(u.shorthand){if(!ne.isIdentifier(u.value))return;let S=await r(u.value,s,a,c,l,d,f);if(S===void 0)return;m[g]=S;continue}if(!ne.isExpression(u.value))return;let h=await r(u.value,s,a,c,l,d,f);h!==void 0&&(m[g]=h)}return m}if(ne.isMemberExpression(i)){let m=await o(i,s,a,c,l,d,f);if(!m)return;let u=s.getBinding(m.base);if(!u)return;let g=await t({currentFile:a,binding:u,readFile:c,exists:l,fileCache:d,visited:f});return!g||g.kind!=="static"?void 0:Qe(g.value,m.path)}}async function r(i,s,a,c,l,d,f){if(!ne.isSpreadElement(i))return await n(i,s,a,c,l,d,f)}async function o(i,s,a,c,l,d,f){if(ne.isIdentifier(i))return{base:i.name,path:[]};if(!ne.isMemberExpression(i))return null;let m=[],u=i;for(;ne.isMemberExpression(u);){if(u.computed){let g=u.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,d,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(u.property))return null;m.unshift({kind:"property",name:u.property.name})}u=u.object}return ne.isIdentifier(u)?{base:u.name,path:m}:null}return{normalizeExpressionWithScope:o,evaluateStaticExpression:n}}var rg=typeof fl=="function"?fl:fl.default,eg=new WeakMap;function og(e){try{return ng.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function ps(e,t,n){let r=e.get(t);if(r?.source===n)return r.ast;let o=og(n);return e.set(t,{source:n,ast:o}),o}function ms(e,t){let n=null,r=-1;for(let o of vo(e).expressions){let i=o.node.loc;if(!i||!ml(i,t))continue;let s=(o.node.end??0)-(o.node.start??0);s>=r&&(n=o,r=s)}return n}function ig(e,t){let n=null,r=Number.POSITIVE_INFINITY;for(let o of vo(e).expressions){if(!eR(o.node.loc,t))continue;let i=(o.node.end??0)-(o.node.start??0);i<=r&&(n=o,r=i)}return n}function pl(e,t){let n=null,r=Number.POSITIVE_INFINITY;for(let o of vo(e).jsxElements){let i=o.node.loc;if(!i||!ml(i,t))continue;let s=(o.node.end??0)-(o.node.start??0);s<=r&&(n=o,r=s)}return n}function vo(e){let t=eg.get(e);if(t)return t;let n={expressions:[],jsxElements:[]};return rg(e,{Expression(r){n.expressions.push(r)},JSXElement(r){n.jsxElements.push(r)}}),eg.set(e,n),n}function eR(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 ml(e,t){let n=tg({line:e.start.line,column:e.start.column},{line:t.startLine,column:t.startColumn}),r=tg({line:e.end.line,column:e.end.column},{line:t.endLine,column:t.endColumn});return n>=0&&r<=0}function gs(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 tg(e,t){return e.line!==t.line?e.line<t.line?-1:1:e.column!==t.column?e.column<t.column?-1:1:0}function yr(e,t){if(t)return gl(e,t);let n=Qm(e);return n?n.path.reduce((r,o)=>o.kind==="property"?`${r}.${o.name}`:`${r}[${o.index}]`,n.base):""}function gl(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function ko(e,t,n){let r=null,o=Number.POSITIVE_INFINITY;for(let i of vo(e).expressions){if(gl(i.node,t)!==n)continue;let s=(i.node.end??0)-(i.node.start??0);s<=o&&(r=i,o=s)}return r}function sg(e,t,n,r){let o=null,i=Number.POSITIVE_INFINITY;for(let s of vo(e).expressions){if(gl(s.node,t)!==n)continue;let a=s.node.loc;if(!a||!ml(a,r))continue;let c=(s.node.end??0)-(s.node.start??0);c<=i&&(o=s,i=c)}return o}function xr(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}function Io(e){let t=null;if(rg(e,{Program(n){t=n.scope,n.stop()}}),!t)throw new Error("Unable to determine program scope");return t}async function $t(e,t,n){let r=n.get(e);if(r)return r;let o=await t(e),i=og(o),s={source:o,ast:i};return n.set(e,s),s}function tR(e){return j.isIdentifier(e.callee)&&(e.callee.name==="useState"||e.callee.name==="useReducer")?e.callee.name:j.isMemberExpression(e.callee)&&j.isIdentifier(e.callee.property)&&(e.callee.property.name==="useState"||e.callee.property.name==="useReducer")?e.callee.property.name:null}function nR(e){if(!j.isNewExpression(e)||!j.isIdentifier(e.callee,{name:"Proxy"})||e.arguments.length!==2||!j.isIdentifier(e.arguments[0])||!j.isObjectExpression(e.arguments[1])||e.arguments[1].properties.length!==1)return null;let[t]=e.arguments[1].properties;if(!j.isObjectMethod(t)||t.kind!=="method"||t.computed||t.async||t.generator||!j.isIdentifier(t.key,{name:"get"})||t.params.length!==3||!t.params.every(j.isIdentifier)||t.body.body.length!==2)return null;let[n,r,o]=t.params,[i,s]=t.body.body;if(j.isIfStatement(i)&&j.isBlockStatement(i.consequent)&&i.consequent.body.length!==1)return null;let a=j.isIfStatement(i)?i.test:null,c=a&&j.isLogicalExpression(a,{operator:"&&"})?a.right:null,l=j.isIfStatement(i)?j.isBlockStatement(i.consequent)?i.consequent.body[0]:i.consequent:null,d=j.isReturnStatement(s)?s.argument:null;return!a||!j.isLogicalExpression(a,{operator:"&&"})||!j.isBinaryExpression(a.left,{operator:"==="})||!j.isUnaryExpression(a.left.left,{operator:"typeof"})||!j.isIdentifier(a.left.left.argument,{name:r.name})||!j.isStringLiteral(a.left.right,{value:"string"})||!j.isUnaryExpression(c,{operator:"!"})||!j.isBinaryExpression(c.argument,{operator:"in"})||!j.isIdentifier(c.argument.left,{name:r.name})||!j.isIdentifier(c.argument.right,{name:n.name})||!j.isReturnStatement(l)||!j.isIfStatement(i)||i.alternate||!j.isCallExpression(d)||!j.isMemberExpression(d.callee)||!j.isIdentifier(d.callee.object,{name:"Reflect"})||!j.isIdentifier(d.callee.property,{name:"get"})||d.arguments.length!==3||!j.isIdentifier(d.arguments[0],{name:n.name})||!j.isIdentifier(d.arguments[1],{name:r.name})||!j.isIdentifier(d.arguments[2],{name:o.name})?null:e.arguments[0].name}function rR(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()||!j.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 oR(e,t){let n=rR(e.path);if(!n)return null;let r=ar(e,t);return r?{...n,...r}:null}function iR(e,t,n,r){return e.importedFrom===t?r?e.exportName===r:!0:e.sourceFile===t&&e.tag===n}function hl(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 yl(e,t){for(let n of e.program.body){if(t==="default"&&j.isExportDefaultDeclaration(n))return j.isExpression(n.declaration)?{kind:"default-expression",expression:n.declaration}:(j.isFunctionDeclaration(n.declaration)||j.isClassDeclaration(n.declaration))&&n.declaration.id?{kind:"default-binding",name:n.declaration.id.name}:null;if(j.isExportNamedDeclaration(n)){if(n.declaration){if(j.isVariableDeclaration(n.declaration)){for(let r of n.declaration.declarations)if(j.isIdentifier(r.id)&&r.id.name===t)return{kind:"local-binding",name:r.id.name}}if((j.isFunctionDeclaration(n.declaration)||j.isClassDeclaration(n.declaration))&&n.declaration.id&&n.declaration.id.name===t)return{kind:"local-binding",name:t}}for(let r of n.specifiers)if((j.isIdentifier(r.exported)?r.exported.name:r.exported.value)===t&&j.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 ag(e){let{resolveExternalExpression:t,resolveCollectionCallTarget:n,evaluateStaticExpression:r,resolveSourceInfoProvenance:o,buildExpressionSourceInfo:i}=e;async function s(u){let{currentFile:g,binding:h,readFile:S,exists:E,fileCache:y,visited:v}=u,I=`${g}::${h.kind}::${h.identifier.name}`;if(v.has(I))return null;v.add(I);try{let P=await a({currentFile:g,binding:h,readFile:S,exists:E,fileCache:y,visited:v});if(P)return P;if(h.path.isImportSpecifier()||h.path.isImportDefaultSpecifier())return await f({currentFile:g,binding:h,readFile:S,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,fileCache:y,visited:v});if(h.kind==="param")return null;if(h.path.isVariableDeclarator()){let A=h.path.node.init;if(!A||!j.isExpression(A))return null;let R=nR(A);if(R&&!h.path.scope.getBinding("Proxy")&&!h.path.scope.getBinding("Reflect")){let D=h.path.scope.getBinding(R),U=D?await s({...u,binding:D}):null;if(U?.kind==="static"&&U.value!==null&&!Array.isArray(U.value)&&typeof U.value=="object")return U}let T=h.path.get("init");if(T&&!Array.isArray(T)&&T.isExpression()){let D=await t({currentFile:g,expressionPath:T,readFile:S,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:y,visited:v});if(D)return D;if(T.isCallExpression()){let U=await n({currentFile:g,callPath:T,readFile:S,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:y,visited:v});if(U)return U}}let F=await r(A,h.path.scope,g,S,E,y,v);return F===void 0?null:{kind:"static",file:g,root:{kind:"binding",name:h.identifier.name},value:F,sourceKind:"binding"}}if(h.path.isIdentifier()&&h.path.parentPath?.isExportDefaultDeclaration()){let A=h.path.parentPath.node.declaration;if(!j.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(I)}}async function a(u){let{currentFile:g,binding:h,readFile:S,exists:E,fileCache:y,visited:v}=u;if(!h.path.isVariableDeclarator()||!h.path.get("id").isArrayPattern())return null;let I=h.path,P=I.node.init;if(!P||!j.isCallExpression(P))return null;let A=tR(P);if(!A||!j.isArrayPattern(I.node.id)||I.node.id.elements.findIndex(U=>j.isIdentifier(U)&&U.name===h.identifier.name)!==0)return null;let T=A==="useReducer"?1:0,F=P.arguments[T];if(!F||!j.isExpression(F))return null;let D=await r(F,I.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(u){let g=oR(u.binding,u.sourceInfo);if(!g||!u.graph)return null;let h=[...u.graph.elements.values()].filter(A=>iR(A,u.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:u.readFile,fileCache:u.fileCache});if(A)return hl(A,{componentName:g.componentName,propName:g.propName,file:S.sourceFile})}if(!E?.source){let A=await d({caller:S,propName:g.propName,remainingPath:g.remainingPath,readFile:u.readFile,exists:u.exists,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:u.fileCache,visited:u.visited});if(A)return hl(A,{componentName:g.componentName,propName:g.propName,file:S.sourceFile});let R=gp(u.binding,g.componentName,g.propName);if(!R||R.propName!==g.propName)return null;let T=await r(R.expressionPath.node,R.expressionPath.scope,u.currentFile,u.readFile,u.exists,u.fileCache,u.visited);if(T===void 0)return null;let F=g.remainingPath;return F.length>0&&Qe(T,F)===void 0?null:{kind:"value",file:u.currentFile,root:{kind:"binding",name:g.propName},path:F,sourceKind:"binding",semanticKind:"component-prop",displayExpression:R.displayPath,chainPrefix:[{kind:"component-prop",file:u.currentFile,displayName:R.displayPath,canEditHere:!0}],editMode:"upstream",diagnostics:[]}}let y=await $t(S.sourceFile,u.readFile,u.fileCache);if(!y.ast)return null;let v=sg(y.ast,y.source,E.source.expression,E.sourceRange)??ko(y.ast,y.source,E.source.expression);if(!v)return null;let I={...E.source,expression:xr(E.source.expression,g.remainingPath),path:[...E.source.path,...g.remainingPath]},P=await o({currentFile:S.sourceFile,expressionPath:v,sourceInfo:I,readFile:u.readFile,exists:u.exists,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:u.fileCache,visited:u.visited});return P?hl(P.kind==="external"?P:{...P,displayExpression:I.expression},{componentName:g.componentName,propName:g.propName,file:S.sourceFile}):null}async function l(u){let g=await $t(u.caller.sourceFile,u.readFile,u.fileCache);if(!g.ast)return null;let h=pl(g.ast,u.caller.sourceRange);if(!h)return null;let S=h.get("openingElement").get("attributes").find(I=>I.isJSXAttribute()&&I.node.name.type==="JSXIdentifier"&&I.node.name.name===u.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=gs(y.node);return v?{kind:"value",file:u.caller.sourceFile,root:{kind:"expression",sourceRange:v},path:u.remainingPath,sourceKind:"binding",semanticKind:"component-prop",displayExpression:u.propName,editMode:"upstream",diagnostics:[]}:null}async function d(u){let g=await $t(u.caller.sourceFile,u.readFile,u.fileCache);if(!g.ast)return null;let h=pl(g.ast,u.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:u.caller.sourceFile,readFile:u.readFile,exists:u.exists,fileCache:u.fileCache,visited:u.visited});if(!v)continue;let I=[{kind:"property",name:u.propName},...u.remainingPath],P={...v,expression:xr(v.expression,I),path:[...v.path,...I]},A=await o({currentFile:u.caller.sourceFile,expressionPath:y,sourceInfo:P,readFile:u.readFile,exists:u.exists,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:u.fileCache,visited:u.visited});if(A)return A.kind==="external"?A:{...A,displayExpression:P.expression}}return null}async function f(u){let{currentFile:g,binding:h,readFile:S,exists:E,fileCache:y,visited:v}=u,I=h.path.parentPath;if(!I||!I.isImportDeclaration())return null;let P=I.node.source.value;if(typeof P!="string")return null;let A=await xn(g,P,E);if(!A)return null;if(h.path.isImportDefaultSpecifier()){let ee=await $t(A,S,y),we=ee.ast?yl(ee.ast,"default"):null,Q=await m({file:A,exportName:"default",readFile:S,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:y,visited:v});return!Q||Q.kind!=="static"?null:{kind:"static",file:we?.kind==="default-expression"?Q.file:A,root:we?.kind==="default-expression"?Q.root:{kind:"default-export"},value:Q.value,sourceKind:"imported-binding"}}if(!h.path.isImportSpecifier())return null;let R=h.path.node.imported,T=j.isIdentifier(R)?R.name:R.value,F=await $t(A,S,y),D=F.ast?yl(F.ast,T):null,U=await m({file:A,exportName:T,readFile:S,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:y,visited:v});return U?U.kind==="external"?U:{kind:"static",file:D?.kind==="re-export"?U.file:A,root:D?.kind==="re-export"||U.root.kind==="binding"&&U.root.name!==D?.name?U.root:{kind:"named-export",name:T},value:U.value,sourceKind:"imported-binding"}:null}async function m(u){let{file:g,exportName:h,readFile:S,exists:E,fileCache:y,visited:v}=u,I=`export::${g}::${h}`;if(!v.has(I)){v.add(I);try{let P=await $t(g,S,y);if(!P.ast)return;let A=yl(P.ast,h);if(!A)return;if(A.kind==="default-expression"){let D=A.expression;if(!D||!j.isIdentifier(D))return;let U=Io(P.ast).getBinding(D.name);return U?await s({currentFile:g,binding:U,readFile:S,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:y,visited:v})??void 0:void 0}if(A.kind==="re-export"){if(!A.source||!A.name)return;let D=await xn(g,A.source,E);return D?m({...u,file:D,exportName:A.name}):void 0}let R=A.name;if(!R)return;let T=Io(P.ast).getBinding(R);return T?await s({currentFile:g,binding:T,readFile:S,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:y,visited:v})??void 0:void 0}finally{v.delete(I)}}}return{resolveExportValue:m,resolveComponentPropBinding:c,resolveBindingTarget:s}}import*as W from"@babel/types";function bl(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!W.isMemberExpression(n)||!W.isIdentifier(n.property)||n.property.name!=="map"?!1:e.node.arguments.some(r=>r===t.node)}function ug(e,t){let n=e.get("callee");if(!n.isMemberExpression())return null;let r=n.get("object");return Array.isArray(r)||!r.isExpression()?null:Xi(r,t)}function cg(e,t){return e?W.isNumericLiteral(e)&&Number.isInteger(e.value)?e.value:null:t}function lg(e,t,n,r,o){let i=W.isExpression(e.body)?e.body:e.body.body.find(a=>W.isReturnStatement(a))?.argument;if(!i||!W.isExpression(i))return;let s=xl(i,t,n,r,o);return typeof s=="number"?s:void 0}function xl(e,t,n,r,o){if(W.isNumericLiteral(e)||W.isStringLiteral(e)||W.isBooleanLiteral(e))return e.value;if(W.isIdentifier(e))return e.name===t?r:e.name===n?o:void 0;if(W.isMemberExpression(e)){let i=fs(e,t);if(i)return Qe(r,i);let s=fs(e,n);return s?Qe(o,s):void 0}if(W.isBinaryExpression(e)&&e.operator==="-"){let i=W.isExpression(e.left)?xl(e.left,t,n,r,o):void 0,s=W.isExpression(e.right)?xl(e.right,t,n,r,o):void 0;return typeof i=="number"&&typeof s=="number"?i-s:void 0}}function aR(e){if(W.isExpression(e.body))return e.body;for(let t of e.body.body)if(W.isReturnStatement(t)&&t.argument&&W.isExpression(t.argument))return t.argument;return null}function cR(e,t,n){let r=Bn(e,t,n);return typeof r=="boolean"?r:void 0}function Bn(e,t,n){if(W.isStringLiteral(e)||W.isNumericLiteral(e)||W.isBooleanLiteral(e))return e.value;if(W.isNullLiteral(e))return null;if(W.isIdentifier(e))return e.name===t?n:void 0;if(W.isMemberExpression(e)){let r=fs(e,t);return r?Qe(n,r):void 0}if(W.isUnaryExpression(e)&&e.operator==="!"){let r=Bn(e.argument,t,n);return r===void 0?void 0:!r}if(W.isLogicalExpression(e)){let r=Bn(e.left,t,n);if(r===void 0)return;if(e.operator==="&&")return r&&Bn(e.right,t,n);if(e.operator==="||")return r||Bn(e.right,t,n)}if(W.isBinaryExpression(e)){let r=W.isExpression(e.left)?Bn(e.left,t,n):void 0,o=W.isExpression(e.right)?Bn(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 dg(e){let t=[],n=e;for(;W.isMemberExpression(n)||W.isOptionalMemberExpression(n);){let r=n.property;if(n.computed)if(W.isNumericLiteral(r))t.unshift({kind:"index",index:r.value});else if(W.isStringLiteral(r))t.unshift({kind:"property",name:r.value});else if(W.isExpression(r))t.unshift({kind:"dynamic",expression:r});else return null;else if(W.isIdentifier(r))t.unshift({kind:"property",name:r.name});else return null;n=n.object}return W.isIdentifier(n)?{base:n.name,segments:t}:null}function fg(e){return e.some(t=>t.kind==="dynamic")}function lR(e){return typeof e=="string"?{kind:"property",name:e}:Number.isInteger(e)?{kind:"index",index:e}:null}function pg(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 uR(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 mg(e){let{resolveBindingTarget:t,evaluateStaticExpression:n,buildExpressionSourceInfo:r,resolveSourceInfoProvenance:o}=e;async function i(u){let{currentFile:g,callPath:h,readFile:S,exists:E,fileCache:y,visited:v}=u,I=h.node.callee;if(!W.isMemberExpression(I)||!W.isIdentifier(I.property)||I.property.name!=="map")return null;let P=h.get("callee");if(!P.isMemberExpression())return null;let A=P.get("object");if(Array.isArray(A)||!A.isExpression())return null;let R=await s({currentFile:g,expressionPath:A,readFile:S,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:y,visited:v});return!R||!Array.isArray(R.value)||R.value.length===0?null:R}async function s(u){let{currentFile:g,expressionPath:h,readFile:S,exists:E,fileCache:y,visited:v}=u;if(h.isIdentifier()){let I=h.scope.getBinding(h.node.name);if(!I)return null;let P=await t({currentFile:g,binding:I,readFile:S,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:y,visited:v});return P?.kind==="static"?P:null}if(h.isCallExpression())return c({currentFile:g,callPath:h,readFile:S,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:y,visited:v});if(h.isTSAsExpression()||h.isTSSatisfiesExpression()||h.isTSNonNullExpression()){let I=h.get("expression");if(!Array.isArray(I)&&I.isExpression())return s({...u,expressionPath:I})}if(h.isArrayExpression()){let I=gs(h.node);if(!I)return null;let P=await n(h.node,h.scope,g,S,E,y,v);return Array.isArray(P)?{kind:"static",file:g,root:{kind:"expression",sourceRange:I},value:P,sourceKind:"binding"}:null}if(h.isMemberExpression()){let I=await r({expression:h.node,scope:h.scope,currentFile:g,readFile:S,exists:E,fileCache:y,visited:v});if(!I)return null;let P=await o({currentFile:g,expressionPath:h,sourceInfo:I,readFile:S,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:y,visited:v});if(!P||P.kind==="external")return null;let A=await a({currentFile:g,expressionPath:h,provenance:P,readFile:S,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:y,visited:v});if(!A||A.kind!=="static")return null;if(P.collectionPathMap?.length){let T=uR(A.value,P.collectionPathMap);if(T)return{kind:"static",file:P.file,root:P.root,value:T.value,sourceKind:P.sourceKind,collectionPathMap:T.collectionPathMap}}let R=Qe(A.value,P.path);return Array.isArray(R)?{kind:"static",file:P.file,root:P.root,value:R,sourceKind:P.sourceKind,pathPrefix:P.path,collectionIndexMap:P.collectionIndexMap,collectionPathMap:P.collectionPathMap}:null}return null}async function a(u){let{provenance:g}=u;if(g.root.kind==="binding"){let y=u.expressionPath.scope.getBinding(g.root.name);if(!y&&g.file!==u.currentFile){let v=await $t(g.file,u.readFile,u.fileCache);y=v.ast?Io(v.ast).getBinding(g.root.name):void 0}return y?await t({currentFile:g.file,binding:y,readFile:u.readFile,exists:u.exists,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:u.fileCache,visited:u.visited}):null}if(g.root.kind!=="expression")return null;let h=await $t(g.file,u.readFile,u.fileCache);if(!h.ast)return null;let S=ig(h.ast,g.root.sourceRange);if(!S)return null;let E=await n(S.node,S.scope,g.file,u.readFile,u.exists,u.fileCache,u.visited);return E===void 0?null:{kind:"static",file:g.file,root:g.root,value:E,sourceKind:g.sourceKind}}async function c(u){return await l(u)??await d(u)??await f(u)}async function l(u){let{callPath:g}=u,h=g.node.callee;if(!W.isMemberExpression(h)||!W.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:u.currentFile,expressionPath:E,readFile:u.readFile,exists:u.exists,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:u.fileCache,visited:u.visited});if(!y||!Array.isArray(y.value))return null;let[v]=g.node.arguments;if(!W.isArrowFunctionExpression(v)&&!W.isFunctionExpression(v))return null;let I=v.params[0];if(!W.isIdentifier(I))return null;let P=aR(v);if(!P)return null;let A=[],R=[],T=[];for(let[F,D]of y.value.entries()){let U=cR(P,I.name,D);if(typeof U!="boolean")return null;if(U){A.push(D),R.push(y.collectionIndexMap?.[F]??F);let ee=y.collectionPathMap?.[F];ee&&T.push(ee)}}return{...y,value:A,pathPrefix:y.pathPrefix,collectionIndexMap:R,...T.length>0?{collectionPathMap:T}:{}}}async function d(u){let{callPath:g}=u,h=g.node.callee;if(!W.isMemberExpression(h)||!W.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:u.currentFile,expressionPath:E,readFile:u.readFile,exists:u.exists,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:u.fileCache,visited:u.visited});if(!y||!Array.isArray(y.value))return null;let[v,I]=g.node.arguments,P=cg(v,0),A=cg(I,y.value.length);if(P===null||A===null)return null;let R=Math.max(0,P<0?y.value.length+P:P),T=Math.max(0,A<0?y.value.length+A:A),F=y.value.map((U,ee)=>y.collectionIndexMap?.[ee]??ee).slice(R,T),D=y.collectionPathMap?.slice(R,T);return{...y,value:y.value.slice(R,T),pathPrefix:y.pathPrefix,collectionIndexMap:F,...D?{collectionPathMap:D}:{}}}async function f(u){let{callPath:g}=u,h=g.node.callee;if(!W.isMemberExpression(h)||!W.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:u.currentFile,expressionPath:E,readFile:u.readFile,exists:u.exists,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:u.fileCache,visited:u.visited});if(!y||!Array.isArray(y.value))return null;let[v]=g.node.arguments;if(!W.isArrowFunctionExpression(v)&&!W.isFunctionExpression(v))return null;let[I,P]=v.params;if(!W.isIdentifier(I)||!W.isIdentifier(P))return null;let A=y.value.map((T,F)=>({value:T,sourceIndex:y.collectionIndexMap?.[F]??F,originalIndex:F})),R=[...A];for(let T of A)for(let F of A)if(lg(v,I.name,P.name,T.value,F.value)===void 0)return null;return R.sort((T,F)=>{let D=lg(v,I.name,P.name,T.value,F.value)??0;return D===0?T.originalIndex-F.originalIndex:D}),{...y,value:R.map(T=>T.value),pathPrefix:y.pathPrefix,collectionIndexMap:R.map(T=>T.sourceIndex),...y.collectionPathMap?{collectionPathMap:R.map(T=>y.collectionPathMap?.[T.originalIndex]).filter(T=>!!T)}:{}}}async function m(u){let g=null,h,S=[];for(let y of u.segments){if(y.kind!=="dynamic")continue;let v=await r({expression:y.expression,scope:u.expressionPath.scope,source:u.fileCache.get(u.currentFile)?.source,currentFile:u.currentFile,readFile:u.readFile,exists:u.exists,fileCache:u.fileCache,visited:u.visited});if(!v)return null;let I=bl(u.expressionPath,v.base);if(!I)return null;let P=await i({currentFile:u.currentFile,callPath:I.callPath,readFile:u.readFile,exists:u.exists,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:u.fileCache,visited:u.visited});if(!P||!Array.isArray(P.value))return null;let A=P.value.map((R,T)=>{let F=Qe(P.value,[{kind:"index",index:T},...I.basePath,...v.path]);return lR(F)});if(A.some(R=>R===null)||g!==null&&g!==A.length)return null;g=A.length,h??=P.collectionIndexMap,S.push(A)}if(g===null||g===0)return null;let E=[];for(let y=0;y<g;y+=1){let v=[...u.rootPath],I=0;for(let P of u.segments){if(P.kind==="dynamic"){let A=S[I]?.[y];if(!A)return null;v.push(A),I+=1;continue}v.push({...P})}E.push(v)}return{...h?{collectionIndexMap:h}:{},collectionPathMap:E}}return{resolveRepeatCollectionTarget:i,resolveCollectionCallTarget:c,resolveDynamicMemberPathMap:m}}var{normalizeExpressionWithScope:dR,evaluateStaticExpression:hs}=qm({resolveBindingTarget:e=>ys(e)}),{resolveRepeatCollectionTarget:fR,resolveCollectionCallTarget:pR,resolveDynamicMemberPathMap:mR}=mg({resolveBindingTarget:e=>ys(e),evaluateStaticExpression:hs,buildExpressionSourceInfo:Vt,resolveSourceInfoProvenance:St}),{resolveExportValue:gR,resolveComponentPropBinding:hR,resolveBindingTarget:ys}=ag({resolveExternalExpression:Rl,resolveCollectionCallTarget:pR,evaluateStaticExpression:hs,resolveSourceInfoProvenance:St,buildExpressionSourceInfo:Vt});function vg(e){return new Map([...e].map(t=>[t.file,{source:t.source,ast:t.ast}]))}function gg(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 kg(e){let{file:t,source:n,segment:r,readFile:o,exists:i}=e,s=e.fileCache??new Map,a=ps(s,t,n);if(!a)return null;let c=ms(a,r.sourceRange);if(!c)return null;let l=await Vt({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:o,exists:i,fileCache:s,visited:new Set});if(!l){let m=await Al({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?vl(m,yr(c.node,n)):null}let d=new Set,f=await BR({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:d});return f?vl(f,l.expression):null}async function br(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=ps(i,t,n);if(!s)return null;let a=e.sourceRange?ms(s,e.sourceRange):e.expression!==void 0?ko(s,n,e.expression):null;if(!a)return null;let c=xs(a);if(!c.isIdentifier()&&!c.isMemberExpression())return null;let l=new Set,d=await Vt({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:r,exists:o,fileCache:i,visited:l}),f=d?await St({currentFile:t,expressionPath:c,sourceInfo:d,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:l}):await Tg({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 vl(f,e.expression??yr(c.node,n))}async function Cl(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=ps(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"?yR({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}):xR({file:t,source:n,ast:s,candidate:e.target.candidate,readFile:r,exists:o,graph:e.graph,fileCache:i,visited:a})}async function Vt(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 dR(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 vl(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 yR(e){let{file:t,source:n,ast:r,segment:o,readFile:i,exists:s,fileCache:a,visited:c}=e,l=ms(r,o.sourceRange),d=l?await Vt({expression:l.node,scope:l.scope,source:n,currentFile:t,readFile:i,exists:s,fileCache:a,visited:c}):null;if(!d){if(!l||l.isStringLiteral()||l.isTemplateLiteral()&&l.node.expressions.length===0)return hg(t,o.value);let m=await Al({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"?Eg(t,m):Il(t,yr(l.node,n),m):bR({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:d,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:c});if(!f){let m=kl(l.node);if(m)return dt(m.code,m.message);let u=l.scope.getBinding(d.base);if(u?.path.isVariableDeclarator()){let g=kl(u.path.node.init);if(g)return dt(g.code,g.message)}return u?.path.isVariableDeclarator()&&Z.isCallExpression(u.path.node.init)?SR("unsupported-expression",Ng(u.path.node.init,e.functionCallContracts)):dt("unsupported-expression",`Unable to resolve provenance for expression "${d.expression}"`)}return f.kind==="external"?Eg(t,f):Il(t,d.expression,f)}async function xR(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=ko(r,n,o.conditionExpression);if(!l)return dt("conditional-branch-unresolved",`Unable to locate conditional expression "${o.conditionExpression}"`);let d=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(!d)return dt("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);if(d.kind==="external")return dt("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let f=Il(t,o.conditionExpression,d);return f.finalSource?{...f,finalSource:{...f.finalSource,kind:"conditional-branch",displayPath:o.conditionExpression},chain:[...f.chain,{kind:"conditional-branch",file:d.file,displayName:o.conditionExpression,canEditHere:!0}]}:f}function hg(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 bR(e){let t=await Cg(e);if(t.length===0)return dt("unsupported-expression",`Unsupported expression type: ${e.expression.type}`);if(ER(e.expression))return Ig(t);if(wg(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 SR(e,t){return Ig([{code:e,message:t}])}function Ig(e){return{finalSource:null,chain:[],confidence:"partial",editMode:"readonly",diagnostics:e}}function ER(e){return Z.isCallExpression(e)||Z.isConditionalExpression(e)||Z.isLogicalExpression(e)||Z.isBinaryExpression(e)}function Ro(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 Cg(e){let{expression:t,scope:n,currentFile:r,readFile:o,exists:i,fileCache:s,visited:a,functionCallContracts:c}=e,l=kl(t);if(l)return[l];if(Z.isCallExpression(t))return[{code:"unsupported-expression",message:Ng(t,c)}];if(Z.isMemberExpression(t)&&t.computed){let d=t.property;if(!Z.isNumericLiteral(d)&&!Z.isStringLiteral(d)){if(!Z.isExpression(d))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}];let m=await hs(d,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)?Ro([...await Sl(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)?Ro([...await Sl(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)?Ro([...await Sl(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 kl(e){return wg(e)?yg("i18n helpers require a static message id string"):RR(e)?yg("CMS helpers require static entry id and field path string arguments"):null}async function Sl(...e){let t=e[e.length-1],n=e.slice(0,-1),r=[];for(let o of n)r.push(...await Cg({...t,expression:o}));return r}function vR(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:[kR(e.sourceType)]}}async function Rl(e){for(let n of AR){if(!xg(e.expressionPath,n.helperNames))continue;let r=await n.resolve(e);if(r)return Sg(bg(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(!xg(e.expressionPath,n.helperNames))continue;let r=await n.resolve(t);if(r)return Sg(bg(r),e.externalAdapters)}return null}function kR(e){return{code:"missing-adapter",message:`No external adapter is registered for ${e}`}}function IR(e){return{code:"external-source-readonly",message:e}}function yg(e){return{code:"unsupported-expression",message:e}}function wl(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 xg(e,t){if(!t||t.length===0)return!0;let n=wl(e.node);return n?t.includes(n):!1}function bg(e){return"match"in e?{match:e.match,editMode:e.editMode,diagnostics:Ro(e.diagnostics??[])}:{match:e,diagnostics:[]}}function Sg(e,t){let n=vR(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:Ro([...e.diagnostics,...e.editMode==="readonly"||n.editMode==="readonly"?n.diagnostics:[]])}}function CR(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 RR(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 Rg(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 wg(e){return Rg(e)===null}async function wR(e,t,n){let r=new Set,o=Co.posix.dirname(e);for(;r.add(o),!(o==="."||o==="/");){let i=Co.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"]:[Co.posix.join(i,"locales"),Co.posix.join(i,"messages")];for(let a of s){let c=Co.posix.join(a,`${t}.json`);if(await n(c))return c}}return null}async function NR(e){let t=Rg(e.expressionPath.node);if(typeof t!="string"||t.length===0)return null;let n="en",r=await wR(e.currentFile,n,e.exists);return r?{sourceType:"i18n-message",sourceId:`${n}:${t}`,file:r,displayPath:t}:null}async function PR(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 hs(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:[IR("API mapping transforms must stay readonly until a reversible mapping strategy is registered")]}:i}var AR=[{helperNames:["getCmsField"],resolve:({expressionPath:e})=>CR(e)},{helperNames:["apiField"],resolve:e=>PR(e)},{helperNames:["t","intl.formatMessage"],resolve:({currentFile:e,expressionPath:t,exists:n})=>NR({currentFile:e,expressionPath:t,exists:n})}];function Nl(e){return{...e,editMode:"readonly",diagnostics:[{code:"unsupported-expression",message:"Derived display values are readonly because no identity-preserving write target exists"}]}}function Eg(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 Il(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=LR(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 TR=[{helperName:"formatPrice",purity:"pure",sourceArgIndex:0},{helperName:"formatDate",purity:"pure",sourceArgIndex:0},{helperName:"pickLabel",purity:"pure",sourceArgIndex:0}];function Pl(e,t){let n=[...TR,...t??[]];for(let r=n.length-1;r>=0;r-=1){let o=n[r];if(o?.helperName===e)return o}return null}function Ng(e,t){let n=e.callee;return Z.isIdentifier(n)&&Pl(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 Al(e){let t=await Rl(e);if(t)return t;let n=await Pg({...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 Vt({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 MR(e)}async function Pg(e){let t=await Rt({...e,allowComposed:!1});if(t?.kind!=="source")return null;let n=xs(e.expressionPath);return n.isIdentifier()||n.isMemberExpression()?t.provenance:Nl(t.provenance)}async function Rt(e){let t=xs(e.expressionPath),n=OR(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 Vt({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 Vt({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 El(s,a,c)}if(t.isCallExpression())return FR({...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 El(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 El(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 xs(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 FR(e){let t=wl(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 El(...e){let t=null;for(let n of e){if(!n)return null;if(n.kind!=="none"){if(!t){t=n.provenance;continue}if(!_R(t,n.provenance))return null}}return t?{kind:"source",provenance:t}:{kind:"none"}}function _R(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 OR(e,t){return t.start==null||t.end==null?null:`safe-derived:${e}:${t.start}:${t.end}`}async function MR(e){if(!e.expressionPath.isCallExpression())return null;let t=wl(e.expressionPath.node);if(!t)return null;let n=Pl(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 Ag({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?Nl(i):null}async function Ag(e){let t=await Rl({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 Vt({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 Al({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 DR(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=Pl(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 Ag({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?Nl(a):null}function LR(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 BR(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=bl(e.expressionPath,t.base);if(n){let l=await fR({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=ug(n.callPath,[...n.basePath,...t.path]);return so(h)?gg(e.currentFile,h.sourceId,h.displayPath):null}let d=pg(l,[...n.basePath,...t.path]),f=l.collectionIndexMap?.[0]??0,m=[...l.pathPrefix??[],{kind:"index",index:f},...n.basePath,...t.path],u=[{kind:"index",index:0},...n.basePath,...t.path];return Qe(l.value,u)===void 0?null:{kind:"value",file:l.file,root:l.root,path:d?.[0]??m,sourceKind:"repeat-template",collectionIndexMap:l.collectionIndexMap,...d?{collectionPathMap:d}:{}}}let r=e.expressionPath.scope.getBinding(t.base);if(!r)return null;if(r.path.isImportNamespaceSpecifier()){let l=t.path[0],d=r.path.parentPath;if(!l||l.kind!=="property"||!d?.isImportDeclaration())return null;let f=await xn(e.currentFile,d.node.source.value,e.exists);if(!f)return null;let m=await gR({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 u=t.path.slice(1);return Qe(m.value,u)===void 0?null:{kind:"value",file:m.file,root:m.root,path:u,sourceKind:"imported-binding",collectionIndexMap:m.collectionIndexMap}}let o=pp(r);if(o){let l=o.expressionPath,d=await Vt({expression:l.node,scope:l.scope,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(d){let f=await St({...e,expressionPath:l,sourceInfo:{...d,expression:xr(d.expression,t.path),path:[...d.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 Tg({...e,expressionPath:xs(l),memberSuffix:t.path});if(m?.kind==="value")return m}finally{e.visited.delete(f)}}if(t.path.length===0){let f=await Pg({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 hR({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 DR({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=Ui(r,t.path);if(so(s))return gg(e.currentFile,s.sourceId,s.displayPath);let a=await ys({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 Tg(e){let t=dg(e.expressionPath.node);if(!t||!fg(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 mR({...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 ys({...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 Fg(e){let t=jR(e.propertyName);if(t.owner==="blocked")return gn(t.owner,t.diagnostic);if(t.owner==="class-name-source"||t.owner==="style")return gn(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 gn("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 VR(e,l)});o.sort((l,d)=>l.order-d.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 gn("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}:gn("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?gn("generic",{code:"remove-exposes-spread",message:`Removing '${e.propertyName}' would expose an earlier spread source`}):$R(e,s.attribute)}async function $R(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}}:gn("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"?gn("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 VR(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:KR(r,e.propertyName)}}function KR(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 gn(e,t){return{status:"blocked",owner:e,...t?{diagnostic:t}:{}}}function _g(e){let{key:t,element:n,graph:r,provenances:o}=e,i=JR(t,n,r),s=i?.tag??(jn(n.tag)?n.tag:n.componentName),a=i?.identity.key??Og(n,r)??t,c=HR(i),l=WR(t,n,r,o,i),d=UR(t,n,r,o,a);return{componentName:s,instanceKey:a,templateOwner:zR(i??n,s),...c.length>0?{variantKeys:c}:{},...l.length>0?{slotKeys:l}:{},editableStrategy:d,impactScope:GR(d),alternativeStrategies:YR(d)}}function UR(e,t,n,r,o){for(let i of r.values())if(i?.editMode==="upstream")return"upstream";return Tl(e,n)?"instance":!jn(t.tag)&&t.sourceFile!==n.routeId&&o!==e?"template":"instance"}function Og(e,t){if(jn(e.tag))return e.identity.key;let n=[...t.elements.values()].filter(r=>r.importedFrom===e.sourceFile&&XR(r,e.componentName));return n.length!==1?null:n[0].identity.key}function JR(e,t,n){if(jn(t.tag))return t;let r=Tl(e,n);if(r)return r;let o=Og(t,n);return o?n.elements.get(o)??null:null}function XR(e,t){return e.exportName===t||e.tag===t||e.exportName==="default"}function zR(e,t){return jn(e.tag)&&e.importedFrom?`${e.importedFrom}#${t}`:`${e.sourceFile}#${t}`}function HR(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 WR(e,t,n,r,o){let i=new Set,s=Tl(e,n);s&&o?.identity.key===s.identity.key&&i.add("children");for(let a of r.values()){let c=a?.chain.find(d=>d.kind==="component-prop");if(!c)continue;let l=c.displayName.split(".").pop();l&&i.add(l)}return i.size===0&&jn(t.tag)&&t.childKeys.length>0&&i.add("children"),[...i]}function Tl(e,t){let n=t.elements.get(e)?.parentKey??null;for(;n;){let r=t.elements.get(n);if(!r)break;if(jn(r.tag))return r;n=r.parentKey}return null}function jn(e){return/^[A-Z]/.test(e)}function GR(e){switch(e){case"template":return"component-template";case"upstream":return"upstream-source";default:return"current-instance"}}function YR(e){switch(e){case"template":return["instance"];case"upstream":return["template"];default:return["template"]}}function Lg(e){let t=e.isRepeat??(e.graph?iw(e.element,e.graph):!1),n=e.propertyProvenance??new Map,r=e.repeatTargets??new Map,o=ow(e.element.attributes??[]),i=[...r.values()].some(d=>d.ok),s=o.map(d=>ZR({attribute:d,element:e.element,isRepeat:t,selectionRef:e.selectionRef,provenance:n.get(d.name),repeatTarget:r.get(d.name)})),a=(e.element.attributeSpreads?.length??0)>0,c=(e.element.attributeSpreads??[]).slice().sort((d,f)=>d.order-f.order).map(d=>({raw:d.raw,sourceRange:sw(d.sourceRange,e.source),order:d.order,diagnostics:d.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 ZR(e){let{attribute:t,provenance:n,repeatTarget:r}=e,o=e.selectionRef?.instanceIndex!==void 0&&r?.ok===!0?r:null,i=QR(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,d=qR(t,n,l,e.isRepeat),f=c?nw(c,e.element,t.name):void 0,m=s.filter(({result:S})=>S.ok).map(({scope:S})=>S),u=m.length>0?tw(n,o,e.element):"unsupported",g=o?"repeat-item":e.isRepeat?"repeat-template":"node",h=rw(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:d,editMode:u,sourceScope:g,allowedWriteScopes:m,...f?{effectiveWriteTarget:f}:{},diagnostics:h}}function QR(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 qR(e,t,n,r){return n?Mg(n.selectedResolution):t?.status==="blocked"?{status:"unresolved"}:r&&t?.status==="binding"?{status:"unresolved"}:Mg(ew(e))}function ew(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 Mg(e){return!e||e.status==="unresolved"?{status:"unresolved"}:e.status==="undefined"?{status:"undefined"}:{status:"resolved",value:e.value}}function tw(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 nw(e,t,n){return e.kind==="repeat-property"?{kind:"value-path",file:e.target.sourceFile,isProxy:e.target.sourceFile!==t.sourceFile,displayPath:Dg({...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:Dg(e.locator)}:{kind:"jsx-node",file:t.sourceFile,isProxy:!1,displayPath:t.componentName+" > "+n}}function rw(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 ow(e){let t=new Set;return e.filter(n=>t.has(n.name)?!1:(t.add(n.name),!0))}function iw(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 Dg(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 sw(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 aw(e){return e==="api-field"||e==="cms-field"||e==="i18n-message"||e==="config-entry"}var cw=160;function Bg(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 jg(e,t,n,r,o,i,s,a,c,l,d){let f=er(t),m=t.elements.get(e),u=n.nodes.get(e),g=r.get(e);if(!m||!u||!g)throw new Error(`Node not found: ${e}`);let h=Jg(m.textSegments,s),S=Xg(e,t,m,g,h),E=h?fw(h):void 0,y=pw(i,h),v=m.textSegments.map(R=>({index:R.index,value:R.value,editable:zg(R,g,s?.get(R.index)??null),source:o.get(R.index)??null})),I=Kg(m,t),P=m.childKeys.map(R=>{let T=t.elements.get(R);return T?{key:R,tag:T.tag,label:T.tag}:null}).filter(R=>R!==null),A=[];if(m.parentKey){let R=t.elements.get(m.parentKey);if(R)for(let T of R.childKeys){if(T===e)continue;let F=t.elements.get(T);F&&A.push({key:T,tag:F.tag,label:F.tag})}}return{composition:f,key:e,tag:m.tag,componentName:m.componentName,sourceFile:m.sourceFile,sourceLocator:Vg(m),label:m.tag,capabilities:S,writeTarget:i,effectiveWriteTarget:y,provenanceChain:E,componentSemantic:c,styleSource:l,conditional:a,...d?{dynamicData:d}:{},textSegments:v,boundaryKind:m.boundaryKind,isOpaque:m.isOpaque,ancestors:I,children:P,siblings:A}}function $g(e,t,n,r,o,i,s,a){let c=er(t),l=t.elements.get(e),d=n.nodes.get(e),f=r.get(e);if(!l||!d||!f)throw new Error(`Node not found: ${e}`);let m=Jg(l.textSegments,i),u=lw(l);return{composition:c,key:e,tag:l.tag,...u?{linkSourceKind:u}:{},componentName:l.componentName,sourceFile:l.sourceFile,sourceLocator:Vg(l),label:l.tag,capabilities:Xg(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:zg(g,f,i?.get(g.index)??null),source:h?{kind:h.kind}:null}}),boundaryKind:l.boundaryKind,isOpaque:l.isOpaque,ancestors:Kg(l,t)}}function lw(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 Vg(e){return{sourceFile:e.sourceFile,componentName:e.componentName,openingElementRange:uw(e.sourceRange),structuralPath:e.identity.structuralPath,...dw(e.textSegments)}}function Kg(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 uw(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function dw(e){let t=e.map(n=>n.value.trim()).filter(Boolean).join(" ").replace(/\s+/g," ").trim();return t?{textPreview:t.slice(0,cw)}:{}}function Ug(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 Jg(e,t){if(!t)return null;for(let n of e){let r=t.get(n.index);if(r)return r}return null}function Xg(e,t,n,r,o){let i=n.identity.structuralPath.includes("#repeat:"),s=t.regions.some(d=>d.kind==="repeat-region"&&d.childKeys.includes(e)),a=o?.diagnostics.find(d=>d.code==="missing-adapter"||d.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&&Hg(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 zg(e,t,n){return!e.editable||!t.canUpdateText?!1:n?Hg(n.editMode):!0}function Hg(e){return e==="direct"||e==="proxy"||e==="upstream"}function fw(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 pw(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}:aw(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 Fl=["set-class-name-source","apply-style-draft"];function Wg(e){let t=e.attributes?.find(n=>n.name==="className");if(!t)return{kind:"class-name-source",className:"",sourceKind:"missing",editable:!0,operationBoundary:Fl,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:Fl,sourcePath:n}}return{kind:"class-name-source",className:t.value,sourceKind:t.resolvedValue===void 0?"static-attribute":"static-expression",editable:!0,operationBoundary:Fl}}function Gg(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}),Yg(i,r,o,t,e)}}return{nodes:t,rootKeys:[...e.rootKeys]}}function Yg(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}),Yg(s,t,n,r,o))}}import Zg 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 qg(e,t,n){let r=[],o=new Set;for(let i of e.intents){let s=yw(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 bs(e){let t=()=>mw(e);return e.mutex?e.mutex.runExclusive(t):t()}async function mw(e){let t=await qg(e.plan,e.overlay,e.exists);if(!t.ok)return{ok:!1,stage:"precheck",reason:t.reason,error:t,recoveryRequired:!1};let n=gw(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 _l({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 _l({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 _l({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 Qg("swap",l,"Live state swap failed after durable publish.")}try{await e.finalizeCandidate?.(c)}catch(l){return Qg("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 gw(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 _l(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:hw(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 Qg(e,t,n){return{ok:!1,stage:e,reason:n,error:t,recoveryRequired:!0}}function hw(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 yw(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)||Zg.isAbsolute(e))return{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`};let t=Zg.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 xw=50,bw=8*1024*1024;function rh(e,t={}){let n=[],r=[],o=t.externalAdapters??[],i=Math.max(0,t.maxUndoEntries??xw),s=Math.max(0,t.maxUndoBytes??bw);return{prepareRewritePlan:a,execute:c,executeFilePlan:l,undo:d,redo:f};async function a(R){let T=[...R.steps].sort((Q,fe)=>Q.order-fe.order),F=T.filter(Q=>Q.type!=="invoke-external-adapter");if(F.length!==T.length)return{ok:!1,errorCode:"unsupported-operation",reason:"External adapter writes require a transactional prepare/commit/rollback contract."};let D=new Set(F.map(Q=>Q.file)),U=await y(D),ee=new Map(U.map(Q=>[Q.file,Q.exists===!1?"":Q.content])),we;for(let Q of F){let fe=nh(Q,ee.get(Q.file)??"");if(!fe.ok)return{ok:!1,errorCode:fe.errorCode,reason:fe.reason};ee.set(Q.file,fe.source),we=fe.selectionRef??we}return{ok:!0,filePlan:{operationId:R.operationId,kind:"source-edit",target:R.target,documentVersion:R.documentVersion,conflictPolicy:"compare-and-swap",edits:[...ee].map(([Q,fe])=>({operation:"upsert",file:Q,content:fe,baseContentHash:U.find(Oe=>Oe.file===Q)?.sha256??null}))},...we?{selectionRef:we}:{}}}async function c(R){let T=[...R.steps].sort((Oe,Yt)=>Oe.order-Yt.order),F=T.filter(Oe=>Oe.type!=="invoke-external-adapter"),D=T.filter(Oe=>Oe.type==="invoke-external-adapter"),U=new Set(F.map(Oe=>Oe.file));if(F.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(F.length===0)return S(R,D);let ee=await y(U),we=new Map;for(let Oe of ee)we.set(Oe.file,Oe.exists===!1?"":Oe.content);let Q;for(let Oe of F){let Yt=we.get(Oe.file)??"",Zt=nh(Oe,Yt);if(!Zt.ok)return{ok:!1,operationId:R.operationId,errorCode:Zt.errorCode,reason:Zt.reason,rolledBack:!1};we.set(Oe.file,Zt.source),Zt.selectionRef&&(Q=Zt.selectionRef)}let fe=await I([...we].map(([Oe,Yt])=>({file:Oe,content:Yt,exists:!0,version:0,sha256:Ee(Yt)})),ee);return fe.ok===!1?{ok:!1,operationId:R.operationId,errorCode:fe.rolledBack?"writeback-failed":"rollback-failed",reason:fe.reason,rolledBack:fe.rolledBack}:(n.push({operationId:R.operationId,preSnapshots:ee,postSnapshots:fe.snapshots,plan:R}),m(),r.length=0,{ok:!0,operationId:R.operationId,kind:R.kind,target:R.target,resultVersion:Math.max(...fe.snapshots.map(Oe=>Oe.version)),affectedFiles:[...U],...Q?{selectionRef:Q}:{}})}async function l(R){let T=new Set(R.edits.map(fe=>fe.file)),F=await y(T),D=E(R,F);if(D)return{ok:!1,operationId:R.operationId,errorCode:"stale-version",reason:D.reason,affectedFiles:[D.file],rolledBack:!1};let U=new Map(F.map(fe=>[fe.file,fe])),ee=R.edits.find(fe=>fe.operation==="create-only"&&U.get(fe.file)?.exists!==!1);if(ee)return{ok:!1,operationId:R.operationId,errorCode:"stale-version",reason:`MATERIALIZATION_INSTANCE_CONFLICT: create-only target already exists: ${ee.file}`,affectedFiles:[ee.file],rolledBack:!1};let we=R.edits.map(fe=>fe.operation==="delete"?{file:fe.file,content:"",exists:!1,version:0}:{file:fe.file,content:fe.content,exists:!0,version:0,sha256:Ee(fe.content)}),Q=await I(we,F,new Set(R.edits.filter(fe=>fe.operation==="create-only").map(fe=>fe.file)));return Q.ok===!1?{ok:!1,operationId:R.operationId,errorCode:Q.rolledBack?"writeback-failed":"rollback-failed",reason:Q.reason,rolledBack:Q.rolledBack}:(n.push({operationId:R.operationId,preSnapshots:F,postSnapshots:Q.snapshots,plan:{operationId:R.operationId,kind:R.kind,target:R.target,documentVersion:R.documentVersion,steps:[],preSnapshots:F}}),m(),r.length=0,{ok:!0,operationId:R.operationId,kind:R.kind,target:R.target,resultVersion:Math.max(...Q.snapshots.map(fe=>fe.version)),affectedFiles:[...T]})}async function d(){let R=n.at(-1);if(!R)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to undo"};let T=await I(R.preSnapshots,R.postSnapshots);return T.ok===!1?{ok:!1,operationId:R.operationId,errorCode:T.rolledBack?"writeback-failed":"rollback-failed",reason:T.reason,rolledBack:T.rolledBack}:(n.pop(),r.push(R),{ok:!0,operationId:R.operationId,kind:R.plan.kind,target:R.plan.target,resultVersion:Math.max(...T.snapshots.map(F=>F.version)),affectedFiles:R.preSnapshots.map(F=>F.file)})}async function f(){let R=r.at(-1);if(!R)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to redo"};let T=await I(R.postSnapshots,R.preSnapshots);return T.ok===!1?{ok:!1,operationId:R.operationId,errorCode:T.rolledBack?"writeback-failed":"rollback-failed",reason:T.reason,rolledBack:T.rolledBack}:(r.pop(),n.push(R),m(),{ok:!0,operationId:R.operationId,kind:R.plan.kind,target:R.plan.target,resultVersion:Math.max(...T.snapshots.map(F=>F.version)),affectedFiles:R.postSnapshots.map(F=>F.file)})}function m(){for(;n.length>i;)n.shift();for(;n.length>0&&u()>s;)n.shift()}function u(){return n.reduce((R,T)=>R+g(T),0)}function g(R){return h(R.preSnapshots)+h(R.postSnapshots)}function h(R){return R.reduce((T,F)=>T+F.file.length+F.content.length,0)}async function S(R,T){let F=[];for(let D of T){let U=D.capability??"write-text",ee=o.find(Q=>Q.sourceType===D.sourceType&&(D.adapterId===void 0||Q.adapterId===D.adapterId)&&(Q.capabilities===void 0||Q.capabilities.includes(U)));if(!ee)return{ok:!1,operationId:R.operationId,errorCode:"unsupported-operation",reason:`No external adapter registered for ${D.sourceType}`,rolledBack:!1};let we=await ee.execute(D);if(!we.ok)return{ok:!1,operationId:R.operationId,errorCode:"writeback-failed",reason:we.reason??`External adapter failed for ${D.sourceType}`,rolledBack:!1};F.push(D.file)}return{ok:!0,operationId:R.operationId,kind:R.kind,target:R.target,resultVersion:0,affectedFiles:F}}function E(R,T){if(R.conflictPolicy!=="compare-and-swap")return null;let F=new Map(T.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 U=F.get(D.file),ee=D.baseContentHash;if(ee===null){if(U?.exists!==!1)return{file:D.file,reason:`Source file ${D.file} was created or changed before save.`};continue}if(!ee)return{file:D.file,reason:`Source file ${D.file} is missing baseContentHash. Reopen the file before saving.`};if(U?.exists===!1||U?.sha256!==ee)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 T=[];for(let F of R)T.push(await v(F));return T}async function v(R){if(!await e.exists(R))return{file:R,content:"",version:0,exists:!1};let F=Math.max(1,e.getVersion(R)),D=await e.readFile(R);return{file:R,content:D,version:F,exists:!0,sha256:Ee(D)}}async function I(R,T,F=new Set){let D=[];try{for(let U of R){if(F.has(U.file)){if(!e.createExclusive)throw new Error("Create-only write requires atomic exclusive-create support.");await e.createExclusive(U.file,U.content)}else await P(U);let ee=e.bumpVersion(U.file);D.push(U.file),U.version=ee}}catch(U){let ee=await A(T.filter(Q=>D.includes(Q.file)));if(ee.ok===!1)return{ok:!1,reason:`Writeback failed, then rollback failed for ${ee.failedFiles.join(", ")}: ${th(U)}`,rolledBack:!1,instanceConflict:eh(U)};let we=eh(U);return{ok:!1,reason:`${we?"MATERIALIZATION_INSTANCE_CONFLICT: ":""}Writeback failed and committed files were restored: ${th(U)}`,rolledBack:!0,instanceConflict:we}}return{ok:!0,snapshots:R.map(Sw)}}async function P(R){if(R.exists===!1){await e.deleteFile(R.file);return}await e.writeFile(R.file,R.content)}async function A(R){let T=[];for(let F of R)try{await P(F),e.bumpVersion(F.file)}catch{T.push(F.file)}return T.length===0?{ok:!0}:{ok:!1,failedFiles:T}}}function eh(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="EEXIST"}function Sw(e){let t=e.exists!==!1;return{file:e.file,content:t?e.content:"",version:e.version,exists:t,...t?{sha256:Ee(e.content)}:{}}}function th(e){return e instanceof Error?e.message:String(e)}function nh(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 He(Qn({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-import":return He(qn({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-node":return He(Wn({source:t,locator:e.locator,removeWhitespace:e.removeWhitespace}));case"insert-child":return He(Gn({source:t,locator:e.parentLocator,node:e.node,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"update-text":return He(qo({source:t,locator:e.locator,segmentIndex:e.segmentIndex,newText:e.newText}));case"update-value":return He(_r({source:t,locator:e.locator,next:e.value}));case"update-array-item":return He(_r({source:t,locator:e.locator,next:e.value}));case"insert-bound-array-item":return He(si({source:t,locator:e.locator,index:e.index,value:e.value}));case"insert-jsx-expression-child":return He(ti({source:t,locator:e.parentLocator,expression:e.expression,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"remove-bound-array-item":return He(ai({source:t,locator:e.locator,index:e.index}));case"move-array-item":return He(ci({source:t,locator:e.locator,fromIndex:e.fromIndex,toIndex:e.toIndex}));case"move-node":return He(Yn({source:t,locator:e.locator,targetParentLocator:e.targetParentLocator,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"move-repeat-template-child":return He(ni({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 Ew(e,t);case"set-property-changes":return He(ri({source:t,locator:e.locator,changes:e.changes}));case"set-link-target":return He(oi({source:t,locator:e.locator,link:e.link,changes:e.changes}));case"set-property-binding":return He(ii({source:t,locator:e.locator,name:e.name,object:e.object,property:e.property}));case"upsert-object-property":return He(ui({source:t,objectLocator:e.locator,name:e.name,value:e.value}));default:return{ok:!1,reason:`Unknown step type: ${e.type}`,errorCode:"unknown"}}}function Ew(e,t){let{request:n}=e;if(n.newAttrRaw!==null&&!gd(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!==Ee(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:md({source:t,oldAttrRange:n.oldAttrRange,openingElementRange:n.openingElementRange,newAttrRaw:n.newAttrRaw})}}function He(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 Ss,SiteEditCompositionContextSchema as vw,SiteEditCompositionSelectorSchema as kw}from"@vcp-dev/contracts";var Ye=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="SiteEditCompositionError"}};function oh(e,t){throw new Ye("INVALID_COMPOSITION",e,{value:t})}function Es(e){let t=vw.safeParse(e);return t.success?t.data:oh("Invalid SiteEditCompositionContext.",e)}function ih(e){let t=[],n=new Map,r=new Map;for(let l of e.compositions){let d=Es(l?.context);if(typeof l.entryFile!="string"||!l.entryFile)throw new Ye("INVALID_COMPOSITION","A registered composition must have a non-empty entryFile.");let f=Ss(d);if(n.has(f))throw new Ye("DUPLICATE_COMPOSITION",`Composition key ${f} is registered more than once.`,{key:f,context:d});let m=r.get(l.entryFile);if(m)throw new Ye("DUPLICATE_COMPOSITION",`Entry file ${l.entryFile} is registered more than once.`,{entryFile:l.entryFile,context:m});let u={context:d,entryFile:l.entryFile,key:f};t.push(u),n.set(f,u),r.set(l.entryFile,f)}if(t.length===0)throw new Ye("INVALID_COMPOSITION","At least one composition must be registered.");let o=new Map;for(let l of e.initialDocumentVersions??[]){let d=Es(l?.composition);if(!Number.isInteger(l?.version)||(l?.version??-1)<0)throw new Ye("INVALID_INITIAL_DOCUMENT_VERSION","Initial document version must be a non-negative integer.",{context:d,version:l?.version});let f=Ss(d);if(!n.has(f))throw new Ye("UNKNOWN_COMPOSITION","Initial document version references an unregistered composition.",{context:d,key:f});if(o.has(f))throw new Ye("DUPLICATE_COMPOSITION","Initial document versions must contain each composition at most once.",{context:d,key:f});o.set(f,l.version)}function i(l){let d=kw.safeParse(l);if(!d.success)return oh("Invalid SiteEditCompositionSelector.",l);let f=t.filter(({context:m})=>m.routeId===d.data.routeId&&(d.data.templateId===void 0?m.effectiveTemplateId===void 0:m.effectiveTemplateId===d.data.templateId));if(f.length===1)return f[0];throw f.length>1?new Ye("AMBIGUOUS_COMPOSITION","The composition selector matches multiple registered contexts.",{selector:d.data}):new Ye("UNKNOWN_COMPOSITION","The composition selector is not registered.",{selector:d.data})}function s(l){let d=Es(l),f=Ss(d),m=n.get(f);if(!m)throw new Ye("UNKNOWN_COMPOSITION","The composition context is not registered.",{context:d,key:f});return m}function a(l){let d=Es(l?.context);if(typeof l.entryFile!="string"||!l.entryFile)throw new Ye("INVALID_COMPOSITION","A registered composition must have a non-empty entryFile.");let f=Ss(d),m=n.get(f);if(m){if(m.entryFile===l.entryFile)return m;throw new Ye("DUPLICATE_COMPOSITION",`Composition key ${f} is registered more than once.`,{key:f,context:d})}let u=[...n.values()].find(h=>h.entryFile===l.entryFile);if(u)throw new Ye("DUPLICATE_COMPOSITION",`Entry file ${l.entryFile} is registered more than once.`,{entryFile:l.entryFile,context:u.context});let g={context:d,entryFile:l.entryFile,key:f};return t.push(g),n.set(f,g),g}function c(l){let d=n.get(l);if(!d)return;n.delete(l);let f=t.findIndex(m=>m.key===l);return f>=0&&t.splice(f,1),o.delete(l),d}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))]}}import{composeSiteEditRepeatInstanceKey as Iw,stripSiteEditRepeatInstanceKeys as sh}from"@vcp-dev/contracts";function ah(e){let t=new Map,n=new Map,r=new Map;for(let o of e.entries){t.set(o.key,o);let i=sh(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 Cw(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 vs(e){return e?.map(t=>({...t}))}function Ml(e,t){if(t===null||e?.kind!=="value-binding"||e.sourceKind!=="repeat-template")return e;let n=e.collectionIndexMap?.[t]??t,r=vs(e.collectionPathMap?.[t])??vs(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:vs(e.path),locator:e.locator?{...e.locator,path:r}:e.locator,collectionIndexMap:e.collectionIndexMap?[...e.collectionIndexMap]:void 0,collectionPathMap:e.collectionPathMap?.map(o=>vs(o)??[])}}function ch(e,t,n){let r=new Set;for(let u of t.regions)if(u.kind==="repeat-region")for(let g of u.childKeys)r.add(g);if(r.size===0)return e;let o=new Map(e.entries.map(u=>[u.key,u])),i=[],s=new Map,a=(u,g)=>Iw(u,g),c=(u,g,h)=>{let S=o.get(u);if(!S)return a(u,h);let E=a(u,h),y={...S,key:E,parentKey:g,childKeys:[]};return i.push(y),y.childKeys=S.childKeys.flatMap(v=>l(v,h,E)),E},l=(u,g,h)=>{if(!r.has(u))return[c(u,h,g)];let S=f(u,g),E=[];for(let y=0;y<S;y+=1)E.push(c(u,h,[...g,y]));return E},d=Array.from(new Set([...e.rootKeys,...e.entries.filter(u=>u.parentKey===null).map(u=>u.key)]));for(let u of d){if(!r.has(u)){c(u,null,[]);continue}let g=f(u,[]);for(let h=0;h<g;h+=1)c(u,null,[h])}return{...e,rootKeys:[...e.rootKeys],entries:i};function f(u,g){let h=new Set;for(let S of m(u)){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 Rw(y))v.length<=g.length||ww(v,g)&&h.add(v[g.length])}}return h.size>0?h.size:Cw(n.get(u))}function m(u){let g=s.get(u);if(g)return g;let h=[u],S=o.get(u);for(let E of S?.childKeys??[])h.push(...m(E));return s.set(u,h),h}}function lh(e){let t=e.parts.at(-1);return typeof t?.repeatIndex=="number"?t.repeatIndex:null}function uh(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((sh(s.key)??s.key)===n){if(s.key===t)return i;i+=1}return null}function Rw(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 ww(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 dh(e,t,n,r){if(!n)return{...e,key:t};let o=r??new Map(n.entries.map(d=>[d.key,d])),i=o.get(t);if(!i)return{...e,key:t};let s=[],a=i.parentKey;for(;a;){let d=o.get(a);if(!d)break;s.push({key:d.key,tag:d.tag,label:d.label}),a=d.parentKey}s.reverse();let c=i.childKeys.map(d=>o.get(d)).filter(d=>d!==void 0).map(d=>({key:d.key,tag:d.tag,label:d.label})),l=i.parentKey===null?[]:(o.get(i.parentKey)?.childKeys??[]).filter(d=>d!==i.key).map(d=>o.get(d)).filter(d=>d!==void 0).map(d=>({key:d.key,tag:d.tag,label:d.label}));return{...e,key:i.key,ancestors:s,children:c,siblings:l}}function fh(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 ph(e){return{path:e.path,code:e.code,message:e.message,...e.details?{details:JSON.parse(JSON.stringify(e.details))}:{}}}function Nw(e){return e.map(t=>`${t.code} (${t.path}): ${t.message}`).join("; ")}var wo=class extends Error{constructor(t){let n=t.map(ph);super(Nw(n)),this.name="RouteBuildDiagnosticsError",this.diagnostics=n}};function mh(e,t){let n=t instanceof Error&&t.message?t.message:String(t);return t instanceof wo?{routeId:e,message:n,diagnostics:t.diagnostics.map(ph)}:{routeId:e,message:n}}function Dl(e){return e.map(({routeId:t,message:n})=>`${t}: ${n}`).join("; ")}function Ll(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 gh(e,t){for(let n of t){if(n.exists===!1){e.delete(n.file);continue}e.set(n.file,n.content)}}function Bl(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 hh(e){let{journal:t,index:n,observedFileDigests:r}=e;if(r.length!==t.files.length)return"ambiguous";let o=t.files.every((l,d)=>l.preDigest===r[d]),i=t.files.every((l,d)=>l.postDigest===r[d]),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 Dw=/^(?:src\/)?app\/.*\/?page\.[cm]?[jt]sx?$/,Lw=["layout.tsx","layout.ts","layout.jsx","layout.js","layout.mjs","layout.cjs"],yh=32,xh=256;function Bw(e){return{expectedIndexDigest:e.digest,publishedIndexDigest:e.digest,publishedCursor:e.cursor,publishedCurrentId:e.currentId}}var bh={maxEntries:50,maxBytes:8*1024*1024};function jw(){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 fi(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 $w(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 Vw(){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>bh.maxEntries||Kw(e)>bh.maxBytes;)e.shift()}}function Kw(e){return e.reduce((t,n)=>t+Uw(n),0)}function Uw(e){return Sh(e.preSnapshots)+Sh(e.postSnapshots)+Jw(e.provenance)}function Jw(e){return e?new TextEncoder().encode(JSON.stringify(e)).byteLength:0}function Sh(e){return e.reduce((t,n)=>t+n.file.length+n.content.length,0)}function Eh(e,t){return{key:Aw(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 Is=class extends Error{constructor(t){super(t.reason),this.result=t}},$n=class extends Error{constructor(t){super(Dl(t)),this.failedRoutes=t}};function vh(e,t){if(!e)return;let n=[...t];if(n.some(o=>o?.entries.some(i=>i.key===e.key)))return e;let r=ot(e.key)??e.key;for(let o of n){let i=o?.entries.find(s=>(ot(s.key)??s.key)===r);if(i)return{...e,key:i.key}}return e}function Xw(e,t,n){if(!n)return;let r=ot(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 zw=/\.(?:[cm]?[jt]sx?)$/i,Hw=/\.json$/i,Ww=/\.(?:css|scss|sass)$/i,Gw=/\.mdx$/i,Yw=/\.ya?ml$/i;function Zw(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 Qw(e){return{kind:e.isProxy?"component-proxy":"jsx-node",file:e.file,componentName:e.componentName,isProxy:e.isProxy}}function qw(e,t){let n=new Map;for(let r of t)n.set(r.path,r.operation==="delete"?{exists:!1}:{exists:!0,content:r.content});return{async readFile(r){let o=n.get(r);if(o){if(!o.exists)throw new Error(`Source file not found: ${r}`);return o.content}return e.readFile(r)},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(r){let o=n.get(r);return o?o.exists:e.exists(r)},async getFileInfo(r){let o=n.get(r);return o?o.exists?{path:r,sizeBytes:Buffer.byteLength(o.content,"utf8")}:null:e.getFileInfo?.(r)??null},async listFiles(r={}){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let o=Nh(await e.listFiles(r)),i=new Map(o.files.map(a=>[a.path,a]));for(let[a,c]of n)if(eN(a,r.roots??[])){if(!c.exists){i.delete(a);continue}i.set(a,{path:a,sizeBytes:Buffer.byteLength(c.content,"utf8")})}let s=[...i.values()].sort((a,c)=>a.path.localeCompare(c.path));return o.truncated?{files:s,truncated:o.truncated}:s},getVersion(r){return e.getVersion(r)},bumpVersion(r){return e.getVersion(r)}}}function eN(e,t){return t.length===0?!0:t.some(n=>e===n||e.startsWith(`${n}/`))}function Nh(e){return Array.isArray(e)?{files:e}:e}function tN(e){if(!Fw(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!==Ow||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=Tw(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(zw.test(e.path)){let t=Pt({source:e.content,profile:Sn({filePath:e.path,source:e.content})});if(!t.ok)return{ok:!1,errorCode:"ast-error",message:t.diagnostic.message,details:{path:e.path}}}if(Hw.test(e.path))try{JSON.parse(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`JSON parse failed: ${qe(t)}`,details:{path:e.path}}}if(Ww.test(e.path)){let t=kh({content:e.content,path:e.path,profile:"css"});if(!t.ok)return t}if(Gw.test(e.path)){let t=kh({content:e.content,path:e.path,profile:"mdx"});if(!t.ok)return t}if(Yw.test(e.path))try{Mw(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`YAML parse failed: ${qe(t)}`,details:{path:e.path}}}return{ok:!0}}function kh({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]??"",u=e[f+1]??"";if(n==="mdx"&&l&&e.startsWith("```",f)){c=!c;let g=e.indexOf(`
|
|
1
|
+
import*as ey from"@babel/parser";import*as Xn from"@babel/types";import*as Zt from"node:path";var Ms=[".tsx",".ts",".jsx",".js"],ty=Ms.map(e=>`/index${e}`),ny=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 su(e){let t=e.replace(/[?#].*$/,""),n=/\.([a-z0-9]+)$/i.exec(t);return n!==null&&ny.has(n[1].toLowerCase())}function au(e){let t=[];for(let n of e.program.body)Xn.isImportDeclaration(n)&&typeof n.source.value=="string"&&wt(n.source.value)&&t.push(n.source.value),Xn.isExportNamedDeclaration(n)&&n.source&&typeof n.source.value=="string"&&wt(n.source.value)&&t.push(n.source.value),Xn.isExportAllDeclaration(n)&&typeof n.source.value=="string"&&wt(n.source.value)&&t.push(n.source.value);return Ds(e.program,t),t}function Ds(e,t){if(!e||typeof e!="object")return;let n=e;if(n.type==="CallExpression"&&n.callee?.type==="Import"){let r=n.arguments?.[0];r?.type==="StringLiteral"&&typeof r.value=="string"&&wt(r.value)&&t.push(r.value)}for(let r of Object.values(n))if(Array.isArray(r))for(let o of r)Ds(o,t);else r&&typeof r=="object"&&Ds(r,t)}function wt(e){return e.startsWith("./")||e.startsWith("../")||e.startsWith("@/")}function hn(e,t){if(t.startsWith("@/"))return t.slice(2).replace(/\\/g,"/");let n=Zt.dirname(e);return Zt.join(n,t).replace(/\\/g,"/")}async function ry(e,t){if(Ms.some(n=>e.endsWith(n))&&await t(e))return e;for(let n of Ms){let r=`${e}${n}`;if(await t(r))return r}for(let n of ty){let r=`${e}${n}`;if(await t(r))return r}return null}async function yn(e,t,n){let r=await Fo(e,t,n);return r.ok?r.path:null}async function Fo(e,t,n){let r=hn(e,t);try{if(!oy(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 ry(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 oy(e,t,n){if(!wt(t)||t.includes("\0")||t.includes("\\")||Zt.posix.isAbsolute(n))return!1;let r=Zt.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!Zt.posix.isAbsolute(e)}import{createHash as sy}from"node:crypto";import*as cu from"@babel/parser";function xn(e,t,n,r){return{code:e,message:t,locatorKind:n,details:r}}function K(e,t,n,r,o){return{ok:!1,source:e,diagnostic:xn(t,n,r,o)}}function Ls(e,t,n,r,o){return{ok:!1,source:e,diagnostic:xn(t,n,r,o)}}var iy={"tsx-module":["jsx","typescript"],"ts-module":["typescript"],"next-app-entry":["jsx","typescript"]};function Nt(e){let{source:t,profile:n}=e;try{return{ok:!0,ast:cu.parse(t,{sourceType:"module",plugins:iy[n]})}}catch(r){return{ok:!1,source:t,diagnostic:xn("parse-failed",`AST parse failed: ${r instanceof Error?r.message:String(r)}`)}}}function Bs(e,t){return Nt({source:e,profile:lu(t.kind)})}function vr(e,t){return Nt({source:e,profile:lu(t)})}function lu(e){return"next-app-entry"}function bn(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 Sn=(e,t)=>{let n=Nt({source:t,profile:bn({filePath:e,source:t})});return n.ok?{ok:!0,module:{file:e,source:t,sourceHash:`sha256:${sy("sha256").update(t).digest("hex")}`,ast:n.ast,imports:au(n.ast).map(r=>({specifier:r}))}}:{ok:!1,diagnostic:{path:e,code:"parse-failed",message:n.diagnostic.message}}};function ay(e,t){return Sn(e,t)}function cy(e,t){return hn(e,t)}import{COMPONENT_I18N_FILE_SUFFIX as ly,parseComponentI18nResourcesJson as uy,resolveSiteTextDirection as dy,SiteLocaleSchema as fy}from"@vcp-dev/contracts";var py=["i18next","react-i18next"],my="components/ui/site-locale-provider.tsx",gy="components/ui/component-i18n-provider.tsx",uu="app/layout.tsx";async function _o(e){let t=e.files.filter(m=>m.path.endsWith(ly));if(t.length===0)return{ok:!0};for(let m of["package.json",uu,my,gy])if(!await e.exists(m))return Qt(`Target snapshot is missing required i18n host file: ${m}`);let n;try{n=JSON.parse(await e.readFile("package.json"))}catch{return Qt("Target snapshot package.json is invalid.")}let r=du(n)&&du(n.dependencies)?n.dependencies:{},o=py.filter(m=>typeof r[m]!="string"||r[m].trim().length===0);if(o.length>0)return Qt(`Target snapshot must already declare: ${o.join(", ")}.`);let i=await e.readFile(uu),s=js(i,"html","lang"),a=js(i,"html","dir"),c=js(i,"SiteLocaleProvider","locale"),l=fy.safeParse(s);if(!l.success||!a||!c||s!==c||a!==dy(l.data))return Qt("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 Qt("Target snapshot root layout is not wired to SiteLocaleProvider.");let d=l.data;if(e.targetLocale&&e.targetLocale!==d)return Qt("Target snapshot locale does not match the authoritative site language.");let f=d.split("-")[0];for(let m of t){let u=uy(m.content);if(!u.success)return Qt(`Component i18n resource is invalid: ${m.path}.`);if(!e.deferTargetLocale&&!Object.hasOwn(u.data,d)&&!Object.hasOwn(u.data,f))return Qt(`Component i18n resource ${m.path} has no locale for ${d} or ${f}.`)}return{ok:!0}}function js(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 du(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Qt(e){return{ok:!1,message:e}}import Vs from"@babel/generator";import*as yu from"@babel/parser";import Ks from"@babel/traverse";import*as ve from"@babel/types";import{computeSiteEditSourceIdentityKey as yy}from"@vcp-dev/contracts";var fu="data-vcp-ui-component",Oo="components/ui";function Vt(e){if(!e)return!1;let t=$s(e);return t===Oo||t.startsWith(`${Oo}/`)||t.includes(`/${Oo}/`)||t.endsWith(`/${Oo}`)}function En(e,t){return e?e.startsWith("@/")||e.startsWith("~/")?Vt(e.slice(2)):e.startsWith("./")||e.startsWith("../")?Vt($s(`${hy(t)}/${e}`)):Vt(e):!1}function $s(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 hy(e){let t=$s(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}import{stripSiteEditRepeatInstanceKeys as JN}from"@vcp-dev/contracts";import{isSiteEditRuntimeContainerTag as zN,isSiteEditRuntimeTextTag as HN}from"@vcp-dev/contracts/site-edit-runtime-capability";var pu={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 xy=typeof Vs=="function"?Vs:Vs.default,by=typeof Ks=="function"?Ks:Ks.default,Sy=new Set(["base","body","head","html","link","meta","noscript","script","style","template","title"]),Ey="suppressHydrationWarning",vy=new Set(["SiteEditBootstrap"]);function ky(e){let t=Ry(e.file,e.projectRoot);if(!Cy(e.source)||Vt(t))return{code:e.source,elements:[]};let n=e.attributes??pu,r=yu.parse(e.source,{sourceType:"module",plugins:["jsx","typescript"]}),o=[],i=Ny(r,t);return by(r,{JSXElement(s){let a=s.node.openingElement,c=a.name;if(!Ay(c)||xu(a,n.key))return;let l=Fy(s)??"default",d=Oy(s),f=yy(t,l,d),m=Do(c)??"unknown",u=wy(c)?"jsx":"component-call";if(u==="component-call"&&!_y(s.node.children)&&vy.has(m))return;let g=u==="component-call"&&Py(m,i);Ty(a,n.key,f),g&&mu(a,fu),Iy(s)&&mu(a,Ey),o.push({key:f,tag:m,componentName:l,sourceFile:t,sourceKind:u})}}),o.length===0?{code:e.source,elements:o}:{code:xy(r,{jsescOption:{minimal:!0}}).code,elements:o}}function Iy(e){return!e.findParent(t=>t.isJSXElement())}function Cy(e){return/(?:^|[=(:,?;\[{>&|\n\r]|return\s+)\s*<(?:[A-Za-z][\w.:-]*|>)(?:\s|>|\/)/m.test(e)}function Ry(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 wy(e){return ve.isJSXIdentifier(e)&&/^[a-z]/.test(e.name)}function Do(e){return ve.isJSXIdentifier(e)?e.name:ve.isJSXMemberExpression(e)?Su(e):null}function Ny(e,t){let n=new Set;for(let r of e.program.body)if(!(!ve.isImportDeclaration(r)||!En(r.source.value,t)))for(let o of r.specifiers)n.add(o.local.name);return n}function Py(e,t){let n=e.split(".")[0]??e;return t.has(n)}function Ay(e){let t=Do(e);return!t||t==="Fragment"||t.endsWith(".Fragment")?!1:!Sy.has(t)}function xu(e,t){return e.attributes.some(n=>ve.isJSXAttribute(n)&&ve.isJSXIdentifier(n.name,{name:t}))}function Ty(e,t,n){bu(e,ve.jsxAttribute(ve.jsxIdentifier(t),ve.stringLiteral(n)))}function mu(e,t){xu(e,t)||bu(e,ve.jsxAttribute(ve.jsxIdentifier(t),null))}function bu(e,t){let n=e.attributes.findIndex(r=>ve.isJSXSpreadAttribute(r));if(n>=0){e.attributes.splice(n,0,t);return}e.attributes.push(t)}function Su(e){return`${ve.isJSXIdentifier(e.object)?e.object.name:Su(e.object)}.${e.property.name}`}function Fy(e){let t=e;for(;t;){if(t.isFunctionDeclaration()||t.isClassDeclaration())return t.node.id?.name??null;if(t.isVariableDeclarator()&&ve.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 _y(e){return e.some(t=>ve.isJSXElement(t)||ve.isJSXFragment(t))}var gu=new WeakMap,Mo=new WeakMap,Us=new WeakMap;function Oy(e){let t=gu.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=My(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return gu.set(e.node,o),o}function My(e){let t=Do(e.node.openingElement.name);return!t||t==="Fragment"||t.endsWith(".Fragment")?null:/^[A-Z]/.test(t)?`component:${t}#${hu(e,t)}`:`${t}#${hu(e,t)}`}function hu(e,t){let n=Eu(e)??e.getFunctionParent();if(!n)return 0;let r=Us.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=Us.get(n.node);o||(o=new Map,Us.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()?Lo(n):Dy(n);for(let c of a)if(Do(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 Dy(e){let t=Mo.get(e.node);if(t)return t;let n=[];return e.traverse({JSXElement(r){r.getFunctionParent()?.node===e.node&&!Eu(r)&&n.push(r)}}),Mo.set(e.node,n),n}function Eu(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 Lo(e){let t=Mo.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(...Lo(o));continue}o.isJSXExpressionContainer()&&n.push(...vn(o.get("expression")))}return Mo.set(e.node,n),n}function vn(e){if(e.isJSXElement())return[e];if(e.isJSXFragment())return Lo(e);if(e.isParenthesizedExpression())return vn(e.get("expression"));if(e.isLogicalExpression()&&e.node.operator==="&&")return vn(e.get("right"));if(e.isConditionalExpression())return[...vn(e.get("consequent")),...vn(e.get("alternate"))];if(e.isCallExpression()&&By(e.node)){let t=e.get("arguments")[0];return Ly(t)}return[]}function Ly(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return[t];if(t.isJSXFragment())return Lo(t);if(t.isParenthesizedExpression())return vn(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?vn(r):[]}return[]}function By(e){return ve.isMemberExpression(e.callee)&&ve.isIdentifier(e.callee.property)&&e.callee.property.name==="map"}import{SiteEditOperationRequestSchema as SN,SiteEditPatchPlanSchema as EN}from"@vcp-dev/contracts";function kn(e){return{requestId:e.requestId,kind:e.kind,composition:e.composition,target:e.target,resultVersion:e.resultVersion,affectedFiles:e.affectedFiles,...e.output?{output:e.output}:{},...e.selectionRef?{selectionRef:e.selectionRef}:{}}}function Bo(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 jo(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 $o(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:jy(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 Vo(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:kn(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 jy(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 Aw,computeSiteEditCompositionKey as Tw,getSiteEditSourceDeleteProtectionReason as Fw,isSiteEditTextSourcePath as _w,parseSiteEditRepeatInstanceKey as Ow,SITE_EDIT_SOURCE_DELETE_CAPABILITY as Mw,stripSiteEditRepeatInstanceKeys as ot}from"@vcp-dev/contracts";import Es from"node:path";import{parse as Dw}from"yaml";import Ws from"node:path";import{TextDecoder as Vy}from"node:util";import{SITE_EDIT_SOURCE_ALLOWED_APP_FILES as ku,SITE_EDIT_SOURCE_ALLOWED_DIRS as Iu,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as Cu,SiteEditCompositionContextSchema as Ky,SiteEditSourceFileResponseSchema as Js,SiteEditSourceLocationSchema as Uy,SiteEditSourcePathSchema as Ko,SiteEditSourceTreeResponseSchema as Jy,isSiteEditTextSourcePath as Xy}from"@vcp-dev/contracts";import{createHash as $y}from"node:crypto";var kr=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 Se(e){return`sha256:${$y("sha256").update(e).digest("hex")}`}var zy=[...Cu,...ku,...Iu];function Gs(e){if(!e.composition)throw new Error("Composition unavailable for source access policy.");return Ky.parse(e.composition)}var Xs=2e3,zs=12,Hs=24*1024*1024,vu=512*1024,Hy=new Set(["image/avif","image/gif","image/jpeg","image/png","image/webp","image/x-icon"]),Wy={".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"},Gy={".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"},Yy=new Vy("utf-8",{fatal:!0});async function Uo(e,t={}){let n=Gs(t),{files:r,truncated:o}=await rx(e,t),i=sx(r.map(s=>s.metadata));return Jy.parse({composition:n,nodes:i,defaultPath:ax(r.map(s=>s.metadata)),totalFiles:r.length,...o?{truncated:o}:{}})}async function Jo(e,t,n={}){let r=Gs(n),o=Ko.parse(t.path),i=await Qy(e,o,n);if(!i)throw new Error(`Source file not found: ${o}`);if(Zs(o)){let a=Nu(o),c=await ex(e,{path:o,sizeBytes:i.sizeBytes,mimeType:a});return Js.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:i.sizeBytes,mimeType:a,readonly:!0,...c})}let s=await Ys(e,o);return s.ok?Js.parse({composition:r,path:o,kind:"text",language:Pu(o),sizeBytes:s.sizeBytes,contentHash:Se(s.content),readonly:!1,content:s.content}):Js.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:s.sizeBytes,mimeType:"application/octet-stream",readonly:!0,previewUnavailableReason:"unsupported-mime"})}async function Ys(e,t){if(e.readFileBytes){let o=await e.readFileBytes(t),i=Zy(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 Zy(e){if(e.includes(0))return null;try{return Yy.decode(e)}catch{return null}}async function Qy(e,t,n){if(!tx(t,n))return null;let r=await qy(e,t);return r?{path:t,sizeBytes:r.sizeBytes}:null}async function qy(e,t){if(e.getFileInfo)return e.getFileInfo(t);if(e.listFiles){let o=Ru(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(Zs(t))return{path:t,sizeBytes:0};let n=await e.readFile(t);return{path:t,sizeBytes:Buffer.byteLength(n,"utf8")}}async function ex(e,t){if(!Hy.has(t.mimeType))return{previewUnavailableReason:"unsupported-mime"};if(t.sizeBytes>vu)return{previewUnavailableReason:"too-large"};if(!e.readFileBytes)return{previewUnavailableReason:"bytes-unavailable"};let n=await e.readFileBytes(t.path);return n.byteLength>vu?{previewUnavailableReason:"too-large"}:{contentBase64:Buffer.from(n).toString("base64")}}function tx(e,t){return Cu.some(n=>n===e)||ku.some(n=>n===e)||Iu.some(n=>e===n||e.startsWith(`${n}/`))?!0:!e.startsWith("app/")&&!e.startsWith("src/app/")?!1:(t.routeEntryFiles??[]).some(n=>{let r=Ko.safeParse(n);return r.success&&r.data===e})}function Xo(e,t){if(!t.sourceLocator)throw new Error(`Source location not available for key: ${e.key}`);return Uy.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 Ru(e){return Array.isArray(e)?{files:e}:e}function nx(e){return["max-files","max-depth","max-total-bytes"].filter(n=>e.includes(n))}async function rx(e,t){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let n=Ru(await e.listFiles({roots:ox(t),maxFiles:Xs+1,maxDepth:zs,maxTotalBytes:Hs+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=Ko.safeParse(a.path);if(!c.success)continue;let l=c.data;if(l.split("/").length>zs){o.add("max-depth");continue}if(r.size>=Xs){o.add("max-files");break}if(i+a.sizeBytes>Hs){o.add("max-total-bytes");break}r.set(l,{path:l,sizeBytes:a.sizeBytes,metadata:ix(l,a.sizeBytes,Gs(t))}),i+=a.sizeBytes}return{files:[...r.values()].sort((a,c)=>a.path.localeCompare(c.path)),...o.size>0?{truncated:{reasons:nx([...o]),maxFiles:Xs,maxDepth:zs,maxTotalBytes:Hs}}:{}}}function ox(e){let t=new Set(zy);for(let n of e.routeEntryFiles??[]){let r=Ko.safeParse(n);r.success&&(r.data.startsWith("app/")||r.data.startsWith("src/app/"))&&t.add(r.data)}return[...t]}function ix(e,t,n){return Zs(e)?{composition:n,path:e,kind:"binary",language:null,sizeBytes:t,mimeType:Nu(e),readonly:!0}:{composition:n,path:e,kind:"text",language:Pu(e),sizeBytes:t,readonly:!1}}function sx(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(d=>d.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 wu(t)}function wu(e){return e.map(t=>t.kind==="directory"?{...t,children:wu(t.children)}:t).sort((t,n)=>t.kind!==n.kind?t.kind==="directory"?-1:1:t.name.localeCompare(n.name))}function ax(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 Zs(e){return!Xy(e)}function Nu(e){let t=Ws.posix.extname(e).toLowerCase();return!t&&Ws.posix.basename(e).toLowerCase()==="favicon"?"image/x-icon":Wy[t]??"application/octet-stream"}function Pu(e){let t=Ws.posix.extname(e).toLowerCase();return Gy[t]??"plaintext"}import Qs from"@babel/traverse";import*as Pt from"@babel/types";function _e(e){if(e.isJSXFragment())return!0;if(!e.isJSXElement())return!1;let t=e.node.openingElement.name;if(Pt.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(Pt.isIdentifier(s)&&s.name==="Fragment"||Pt.isStringLiteral(s)&&s.value==="Fragment")&&Au(i.parentPath)}if(!Pt.isJSXMemberExpression(t)||!Pt.isJSXIdentifier(t.property)||t.property.name!=="Fragment"||!Pt.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())&&Au(r.parentPath)}function Au(e){return e?.isImportDeclaration()===!0&&e.node.source.value==="react"}var qt=typeof Qs=="function"?Qs:Qs.default,zo=new WeakMap,Ho=new WeakMap;function At(e,t){let n=Bs(e,t);if(!n.ok)return Ls(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}}:Ls(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"?px(e,t):t.kind==="value"?mx(e,t):t.kind==="expression"?gx(e,t):t.kind==="directive"?hx(e,t):t.kind==="export"?yx(e,t):{ok:!1,diagnostic:xn("unsupported-syntax",`Unsupported locator kind: ${t.kind}`)}}function Ou(e,t){return t.strategy==="source-range"?cx(e,t):lx(e,t)}function cx(e,t){let n=null;if(qt(e,{JSXElement(o){if(!In(o.node,t.sourceRange))return;let i=Le("jsx-node",o);if(i){if(!n){n=i;return}i.end-i.start<n.end-n.start&&(n=i)}},JSXFragment(o){if(!In(o.node,t.sourceRange))return;let i=Le("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXExpressionContainer(o){if(!In(o.node,t.sourceRange))return;let i=Le("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXText(o){if(!In(o.node,t.sourceRange))return;let i=Le("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&&!Px(r.path,t.expectedIdentity)?Be("jsx-node","locator-miss","JSX node failed expected identity validation"):{ok:!0,match:r}}function lx(e,t){if(t.structuralPath===""){let r=dx(e,t.component);if(r){let o=fx(r);if(o)return o}}let n=null;return qt(e,{JSXElement(r){if(Cr(r)!==t.component||ea(r)!==t.structuralPath)return;let i=Le("jsx-node",r);i&&(n=i,r.stop())},JSXFragment(r){if(Cr(r)!==t.component||ea(r)!==t.structuralPath)return;let i=Le("jsx-node",r);i&&(n=i,r.stop())}}),!n&&t.expectedRange&&(n=ux(e,t.component,t.expectedRange)),n?{ok:!0,match:n}:Be("jsx-node","locator-miss","JSX node not found for structural-path locator")}function ux(e,t,n){let r=null;return qt(e,{JSXElement(o){if(Cr(o)!==t||!In(o.node,n))return;let i=Le("jsx-node",o);i&&(r=i,o.stop())},JSXFragment(o){if(Cr(o)!==t||!In(o.node,n))return;let i=Le("jsx-node",o);i&&(r=i,o.stop())}}),r}function dx(e,t){let n=null;return qt(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 fx(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 px(e,t){let n=Ou(e,t.element);if(!n.ok)return n;let s=n.match.path.get("openingElement").get("attributes").find(c=>Ax(c,t.name));if(!s||!s.isJSXAttribute())return Be("jsx-attribute","locator-miss",`JSX attribute '${t.name}' not found`);let a=Le("jsx-attribute",s);return a?{ok:!0,match:a}:Be("jsx-attribute","locator-miss",`JSX attribute '${t.name}' has no source range`)}function mx(e,t){let n=xx(e,t);if(!n.ok)return n;let r=bx(n.match.path,t.path??[]);return r.ok?t.expectedRange&&!Ut(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 gx(e,t){let n=null;return qt(e,{Identifier(r){if(!Cx(r))return;let o=Fu(r);if(!o||!_u(o,t))return;let i=Le("expression",r);i&&(t.expectedRange&&!Ut(r.node.loc,t.expectedRange)||(n=i,r.stop()))},MemberExpression(r){let o=Fu(r);if(!o||!_u(o,t))return;let i=Le("expression",r);i&&(t.expectedRange&&!Ut(r.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:Be("expression","locator-miss","Expression not found")}function hx(e,t){let n=null;return qt(e,{Program(r){let i=r.get("directives").find(a=>a.node.value.value===t.value);if(!i||t.expectedRange&&!Ut(i.node.loc,t.expectedRange))return;let s=Le("directive",i);s&&(n=s,r.stop())}}),n?{ok:!0,match:n}:Be("directive","locator-miss",`Directive '${t.value}' not found`)}function yx(e,t){let n=null;return qt(e,{ExportNamedDeclaration(r){if(t.exportKind==="generate-metadata"){let c=r.get("declaration");if(c.isFunctionDeclaration()&&c.node.id?.name==="generateMetadata"){let m=Le("export",c);if(!m||t.expectedRange&&!Ut(c.node.loc,t.expectedRange))return;n=m,r.stop();return}if(!c.isVariableDeclaration())return;let l=ta(c,"generateMetadata");if(!l||!l.isVariableDeclarator())return;let d=l.get("init");if(!d.node)return;let f=Le("export",d);if(!f||t.expectedRange&&!Ut(d.node.loc,t.expectedRange))return;n=f,r.stop();return}let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=ta(o,t.exportKind==="named"?t.name:"metadata");if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node||t.expectedRange&&!Ut(s.node.loc,t.expectedRange))return;let a=Le("export",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(t.exportKind!=="default")return;let o=r.get("declaration"),i=Le("export",o);i&&(t.expectedRange&&!Ut(o.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:Be("export","export-not-found",`Export '${Nx(t)}' not found`)}function xx(e,t){let n=null;return qt(e,{Expression(r){if(n||t.root.kind!=="expression"||!In(r.node,t.root.sourceRange))return;let o=Le("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 u=r.get("init");if(!u.node)return;let g=Le("value",u);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(u=>u?.type==="Identifier"&&u.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 d=o.hook==="useReducer"?1:0,f=r.get(`init.arguments.${d}`);if(!f||Array.isArray(f)||!f.node)return;let m=Le("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=ta(o,t.root.name);if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node)return;let a=Le("value",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(n||t.root.kind!=="default-export")return;let o=r.get("declaration"),i=Le("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 bx(e,t){let n=qs(e);for(let o of t){if(n=qs(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=>Tx(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=qs(n);let r=Le("value",n);return r?{ok:!0,match:r}:Be("value","locator-miss","Resolved value has no source range")}function qs(e){let t=e;for(;t.isTSAsExpression()||t.isTSSatisfiesExpression()||t.isTSNonNullExpression();)t=t.get("expression");return t}function Le(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 In(e,t){return Ut(e.loc,t)}function Ut(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 ea(e){let t=[],n=e,r=e.node;for(;n;){if(n.isJSXElement()){if(!_e(n)){let o=Du(n.node.openingElement);o&&(/^[A-Z]/.test(o)?t.unshift(`component:${o}#${Tu(n,o)}`):t.unshift(`${o}#${Tu(n,o)}`))}}else n.isJSXFragment()&&n.node===r&&t.unshift("fragment");if(!n.parentPath||kx(n.parentPath)&&!Ix(n.parentPath))break;n=n.parentPath}return t.join("/")}function Tu(e,t){let n=Mu(e)??e.getFunctionParent();if(!n)return 0;let r=zo.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=0,i=zo.get(n.node)?.get(t);if(!i){let a=zo.get(n.node);a||(a=new Map,zo.set(n.node,a)),i=new WeakMap,a.set(t,i)}let s=n.isJSXElement()||n.isJSXFragment()?Ir(n):Sx(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 Sx(e){let t=Ho.get(e.node);if(t)return t;let n=[];return e.traverse({JSXElement(r){r.getFunctionParent()?.node===e.node&&!Mu(r)&&n.push(r)}}),Ho.set(e.node,n),n}function Mu(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(_e(t)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function Ir(e){let t=Ho.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(_e(o)){n.push(...Ir(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...Ir(o));continue}o.isJSXExpressionContainer()&&n.push(...Kt(o.get("expression")))}return Ho.set(e.node,n),n}function Kt(e){if(e.isJSXElement())return _e(e)?Ir(e):[e];if(e.isJSXFragment())return Ir(e);if(e.isParenthesizedExpression())return Kt(e.get("expression"));if(e.isLogicalExpression()&&Ex(e.node.operator))return Kt(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(...Kt(c))}if(s.isReturnStatement()){let a=s.get("argument");a.isExpression()&&i.push(...Kt(a));break}}return i}else if(o.node&&o.isExpression())return Kt(o)}}}}return e.isConditionalExpression()?[...Kt(e.get("consequent")),...Kt(e.get("alternate"))]:e.isArrayExpression()?e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:Kt(t)):[]}function Ex(e){return e==="&&"||e==="||"||e==="??"}function Du(e){return e.name.type==="JSXIdentifier"?e.name.name:e.name.type==="JSXMemberExpression"?vx(e.name):null}function vx(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 Cr(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 kx(e){return!!(e.isFunctionDeclaration()||e.isFunctionExpression()||e.isArrowFunctionExpression())}function Ix(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 Cx(e){return!(!e.isExpression()||e.parentPath?.isMemberExpression({property:e.node}))}function Fu(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 _u(e,t){return e.base===t.base&&Rx(e.path,t.path??[])}function Rx(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 wx(e){return e.key.type==="Identifier"?e.key.name:e.key.type==="StringLiteral"?e.key.value:null}function Nx(e){return e.exportKind==="named"?e.name:e.exportKind}function Be(e,t,n,r){return{ok:!1,diagnostic:xn(t,n,e,r)}}function Px(e,t){return Cr(e)!==t.component?!1:ea(e)===t.structuralPath}function Ax(e,t){return!e.isJSXAttribute()||e.node.name.type!=="JSXIdentifier"?!1:e.node.name.name===t}function ta(e,t){return e.get("declarations").find(n=>!n.isVariableDeclarator()||n.node.id.type!=="Identifier"?!1:n.node.id.name===t)}function Tx(e,t){return e.isObjectProperty()?wx(e.node)===t:!1}import*as Bu from"@babel/parser";import{arrayExpression as Dx,booleanLiteral as Lx,identifier as Bx,jsxAttribute as jx,jsxExpressionContainer as $x,jsxIdentifier as Vx,nullLiteral as Kx,numericLiteral as Ux,objectExpression as Jx,objectProperty as Xx,stringLiteral as ra}from"@babel/types";import na from"@babel/generator";var Fx=typeof na=="function"?na:na.default;function _x(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 Ox(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 Mx(e,t){return e.split(`
|
|
3
|
+
`).map(r=>Ox(r,t)).join(`
|
|
4
|
+
`)}function Wo(e){let{ast:t,source:n}=e;try{let r=_x(n),i=Fx(t,{comments:!0,jsescOption:{minimal:!0,quotes:"single"}},n).code;return r!=="2"&&(i=Mx(i,r)),{ok:!0,source:i}}catch(r){return K(n,"printer-failed",`AST print failed: ${r instanceof Error?r.message:String(r)}`)}}function Lu(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 Rr(e,t,n){return{ok:!0,source:t,operation:{type:n.kind,nodeId:n.target,kind:n.kind,target:n.target,beforeSourceHash:Lu(e),afterSourceHash:Lu(t),inverse:n.inverse}}}function me(e,t,n){let r=Wo({ast:e,source:t});return r.ok?Rr(t,r.source,n):r}function ke(e,t){let n=vr(e,t);return n.ok?{ok:!0,ast:n.ast}:{ok:!1,result:{ok:!1,source:e,diagnostic:n.diagnostic}}}function Go(e,t){return Wo({ast:e,source:t})}function zx(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 zn(e,t,n){let r=zx(e,t,n);return r.ok?r.match.path.isJSXElement()?r:{ok:!1,result:K(n,"unsupported-syntax","JSX locator must resolve to JSXElement","jsx-node")}:r}function en(e){return typeof e=="string"?ra(e):typeof e=="number"?Ux(e):typeof e=="boolean"?Lx(e):e===null?Kx():Array.isArray(e)?Dx(e.map(t=>en(t))):Jx(Object.entries(e).map(([t,n])=>{let r=Xx(oa(t),en(n));return t==="__proto__"&&(r.computed=!0),r}))}function Hx(e){return typeof e=="string"?ra(e):$x(en(e))}function wr(e,t){return jx(Vx(e),Hx(t))}function Yo(e,t){try{let r=Bu.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:K(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:K(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function oa(e){return/^[$A-Z_][0-9A-Z_$]*$/i.test(e)?Bx(e):ra(e)}function Zo(e){let{source:t,locator:n,segmentIndex:r,newText:o}=e,i=ke(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=Wx(s.match.path)[r];if(!c)return K(t,"locator-miss",`Text segment ${r} not found`,"jsx-node");switch(c.kind){case"jsx-text":c.path.node.value=Gx(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 me(i.ast,t,{kind:"update-text",target:"jsx-node",inverse:"restore-text"})}function Wx(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=Yx(r.get("expression"));o.length>0&&t.push(...o)}}return t}function Gx(e,t){let n=e.match(/^\s*/)?.[0]??"",r=e.match(/\s*$/)?.[0]??"";return`${n}${t.trim()}${r}`}function Yx(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 ia}from"@babel/types";function Hn(e){let{source:t,locator:n}=e,r=ke(t,"jsx-node");if(!r.ok)return r.result;let o=se(r.ast,n);return o.ok?(Zx(o.match.path),me(r.ast,t,{kind:"remove-node",target:"jsx-node",inverse:"insert-child"})):{ok:!1,source:t,diagnostic:o.diagnostic}}function Zx(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(ia());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(ia());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(ia());return}e.remove()}import{cloneNode as Qx}from"@babel/types";function Qo(e){let t=ke(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=Yo(e.source,e.node.jsx);return r.ok?(n.match.path.replaceWith(Qx(r.node,!0)),me(t.ast,e.source,{kind:"replace-node",target:"jsx-node",inverse:"replace-node"})):r.result}import{cloneNode as lb}from"@babel/types";import sa from"@babel/traverse";import*as q from"@babel/types";function Nr(e,t,n){return`${e}::${t}::${n}`}var V={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 qx=typeof sa=="function"?sa:sa.default;function pt(e,t,n,r){if(!e.ok)return e;let o=ft(n,t);if(!o)return e;let i=eb(t,o,r);return i?{...e,selectionRef:i}:e}function eb(e,t,n){let r=tb(e,t);if(!r)return;let o=n.sourceLocator?ju(n.sourceLocator):void 0,i=n.targetParentLocator?ju(n.targetParentLocator):void 0,s=n.file??i?.file??o?.file,a=n.component??rb(r)??i?.component??o?.component;if(!(!s||!a))return{key:Nr(s,a,ob(r))}}function ju(e){return e.strategy==="structural-path"?{file:e.file,component:e.component,structuralPath:e.structuralPath}:e.expectedIdentity}function tb(e,t){let n=Xu(e,t);return!n||n.node.type!=="JSXElement"?null:n}function Xu(e,t){let n=null;return qx(e,{JSXElement(r){r.node===t&&(n=r,r.stop())},JSXFragment(r){r.node===t&&(n=r,r.stop())}}),n}function ft(e,t){if(!e)return null;if(q.isJSXElement(e))return cb(t,e)?$u(e.children,t):e;if(q.isJSXFragment(e))return $u(e.children,t);if(q.isJSXExpressionContainer(e)||q.isParenthesizedExpression(e)||q.isTSAsExpression(e)||q.isTSSatisfiesExpression(e)||q.isTSTypeAssertion(e)||q.isTSNonNullExpression(e))return ft(e.expression,t);if(q.isLogicalExpression(e))return ft(e.right,t);if(q.isConditionalExpression(e))return ft(e.consequent,t)??ft(e.alternate,t);if(q.isCallExpression(e)||q.isOptionalCallExpression(e))return zu(e)?nb(e.arguments[0],t):null;if(q.isArrayExpression(e))for(let n of e.elements){if(!n)continue;let r=ft(n,t);if(r)return r}return null}function $u(e,t){for(let n of e){let r=ft(n,t);if(r)return r}return null}function nb(e,t){return!e||!q.isArrowFunctionExpression(e)&&!q.isFunctionExpression(e)?null:q.isBlockStatement(e.body)?Pr(e.body.body,t):ft(e.body,t)}function Pr(e,t){for(let n of e){if(q.isReturnStatement(n)){let r=ft(n.argument,t);if(r)return r;continue}if(q.isBlockStatement(n)){let r=Pr(n.body,t);if(r)return r;continue}if(q.isIfStatement(n)){let r=Vu(n.consequent,t);if(r)return r;let o=n.alternate?Vu(n.alternate,t):null;if(o)return o;continue}if(q.isSwitchStatement(n))for(let r of n.cases){let o=Pr(r.consequent,t);if(o)return o}}return null}function Vu(e,t){return q.isBlockStatement(e)?Pr(e.body,t):Pr([e],t)}function rb(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 Ku=new WeakMap,Uu=new WeakMap,aa=new WeakMap;function ob(e){let t=Ku.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=ib(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return Ku.set(e.node,o),o}function ib(e){let t=Hu(e.node.openingElement.name);return!t||_e(e)?null:/^[A-Z]/.test(t)?`component:${t}#${Ju(e,t)}`:`${t}#${Ju(e,t)}`}function Ju(e,t){let n=sb(e);if(!n)return 0;let r=aa.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=aa.get(n.node);o||(o=new Map,aa.set(n.node,o));let i=o.get(t);i||(i=new WeakMap,o.set(t,i));let s=0;for(let a of Cn(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 sb(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(_e(t)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function Cn(e){let t=Uu.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(_e(o)){n.push(...Cn(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...Cn(o));continue}o.isJSXExpressionContainer()&&n.push(...Tt(o.get("expression")))}return Uu.set(e.node,n),n}function Tt(e){if(e.isJSXElement())return _e(e)?Cn(e):[e];if(e.isJSXFragment())return Cn(e);if(e.isParenthesizedExpression())return Tt(e.get("expression"));if(e.isLogicalExpression())return Tt(e.get("right"));if(e.isConditionalExpression())return[...Tt(e.get("consequent")),...Tt(e.get("alternate"))];if(e.isArrayExpression())return e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:Tt(t));if((e.isCallExpression()||e.isOptionalCallExpression())&&zu(e.node)){let t=e.get("arguments"),n=Array.isArray(t)?t[0]:void 0;return n?ab(n):[]}return[]}function ab(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return _e(t)?Cn(t):[t];if(t.isJSXFragment())return Cn(t);if(t.isParenthesizedExpression())return Tt(t.get("expression"));if(t.isLogicalExpression()||t.isConditionalExpression())return Tt(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(...Tt(s))}if(!r.isReturnStatement())continue;let o=r.get("argument");return o.node&&n.push(...Tt(o)),n}return n}function zu(e){let t=e.callee;return(q.isMemberExpression(t)||q.isOptionalMemberExpression(t))&&q.isIdentifier(t.property)&&t.property.name==="map"&&!t.computed}function cb(e,t){let n=Xu(e,t);return n?_e(n):!1}function Hu(e){return q.isJSXIdentifier(e)?e.name:q.isJSXMemberExpression(e)?Wu(e):q.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function Wu(e){return`${q.isJSXIdentifier(e.object)?e.object.name:Wu(e.object)}.${e.property.name}`}function tn(e,t){if(t.parentPath===e&&t.listKey==="children"&&ca(e))return e;if(!t.parentPath||t.listKey!=="children")return null;let n=t.parentPath;if(!ca(n))return null;let r=n;for(;r&&r!==e;){if(!ca(r)||!_e(r)||r.listKey!=="children")return null;r=r.parentPath}return r===e?n:null}function ca(e){return e.isJSXElement()||e.isJSXFragment()}function Wn(e){let{source:t,locator:n,node:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=ke(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 K(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 K(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let d=Yo(t,r.jsx);if(!d.ok)return d.result;let f=lb(d.node,!0),m=l.node.children,u={...s,targetParentLocator:n},g=v=>s?pt(v,a.ast,f,u):v;if(o==="append")return m.push(f),g(me(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return m.unshift(f),g(me(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(!i)return K(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=tn(c.match.path,h.match.path);if(!S)return K(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?K(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(E.splice(o==="before"?y:y+1,0,f),g(me(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"})))}import*as Gu from"@babel/parser";import{cloneNode as ub}from"@babel/types";function qo(e){let{source:t,locator:n,expression:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=ke(t,"jsx-node");if(!a.ok)return a.result;let c=db(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 K(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 K(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let d=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=tn(l.match.path,E.match.path);if(!y)return K(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");d=y,f=E.match.path.node}else if(o==="before"||o==="after")return K(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let m=ub(c.node,!0),u=d.node.children,g={...s,targetParentLocator:n},h=E=>s?pt(E,a.ast,m,g):E;if(o==="append")return u.push(m),h(me(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return u.unshift(m),h(me(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));let S=u.findIndex(E=>E===f);return S===-1?K(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(u.splice(o==="before"?S:S+1,0,m),h(me(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"})))}function db(e,t){try{let r=Gu.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:K(e,"unsupported-syntax","Expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:K(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}import{cloneNode as fb,nullLiteral as la}from"@babel/types";import*as nn from"@babel/types";import*as Yu from"@babel/types";function Ar(e,t){let n=e.parentPath;if(!n?.isConditionalExpression()||e.key!=="consequent"||!Yu.isNullLiteral(n.node.alternate))return e;let r=n.parentPath;return!r?.isJSXExpressionContainer()||r.parentPath?.node!==t.node||r.listKey!=="children"?e:r}function Gn(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=ke(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 K(t,"unsupported-syntax","move-node target parent must be a JSXElement or JSXFragment","jsx-node");let d=l.match.path;if(l.match.path.isJSXElement()){let v=l.match.path.node;if(!v.closingElement||v.openingElement.selfClosing)return K(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()?Ar(v.match.path,l.match.path):v.match.path,N=tn(l.match.path,C);if(!N)return K(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");d=N,f=C}else if(o==="before"||o==="after")return K(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let m=f&&typeof f.key=="number"?f.key:-1;if(f&&m===-1)return K(t,"locator-miss","Anchor node does not exist in target parent","jsx-node");let u=c.match.path.isJSXElement()?Ar(c.match.path,l.match.path):c.match.path,g=fb(u.node,!0);if(!nn.isJSXElement(g)&&!nn.isJSXExpressionContainer(g)&&!nn.isJSXFragment(g)&&!nn.isJSXText(g))return K(t,"unsupported-syntax","move-node source must resolve to a JSX child","jsx-node");let h=u.parentPath?.node===d.node&&typeof u.key=="number"?u.key:-1;if(f&&u.parentPath?.node===f.parentPath?.node&&u.key===f.key)return K(t,"invalid-parent-child-relation","Cannot move a node relative to itself","jsx-node");pb(u);let S=d.node.children,E={...s,sourceLocator:n,targetParentLocator:r};if(o==="append")return S.push(g),pt(Go(a.ast,t),a.ast,g,E);if(o==="prepend")return S.unshift(g),pt(Go(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),pt(Go(a.ast,t),a.ast,g,E)}function pb(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(la());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(la());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(la());return}e.remove()}import*as Zu from"@babel/parser";import{cloneNode as mb,nullLiteral as ua}from"@babel/types";function ei(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,repeatExpression:s,selectionContext:a}=e,c=ke(t,"jsx-node");if(!c.ok)return c.result;let l=gb(t,s);if(!l.ok)return l.result;let d=se(c.ast,n);if(!d.ok)return{ok:!1,source:t,diagnostic:d.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 K(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 K(t,"self-closing-element","Cannot move repeat child into self-closing element","jsx-node")}let m=f.match.path,u=null;if(i){let v=se(c.ast,i);if(!v.ok)return{ok:!1,source:t,diagnostic:v.diagnostic};let C=tn(f.match.path,v.match.path);if(!C)return K(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");m=C,u=v.match.path.node}else if(o==="before"||o==="after")return K(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");if(!d.match.path.isJSXElement())return K(t,"unsupported-syntax","move-repeat-template-child source must be a JSXElement","jsx-node");let g=m.node,h=mb(l.node,!0);hb(d.match.path);let S={...a,sourceLocator:n,targetParentLocator:r},E=g.children;if(o==="append")return E.push(h),pt(me(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),pt(me(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===u);return y===-1?K(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(E.splice(o==="before"?y:y+1,0,h),pt(me(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,h,S))}function gb(e,t){try{let r=Zu.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:K(e,"unsupported-syntax","Repeat expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:K(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function hb(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(ua());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(ua());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(ua());return}e.remove()}import{SiteEditSetPropsParamsSchema as yb,classifySiteEditPropertyName as xb}from"@vcp-dev/contracts";import*as Yn from"@babel/types";function ti(e){let t=yb.safeParse({kind:"set-props",scope:"selection",changes:e.changes});if(!t.success)return K(e.source,"unsupported-syntax","Invalid typed JSX property changes","jsx-node",{issues:t.error.issues});let n=ke(e.source,"jsx-node");if(!n.ok)return n.result;let r=zn(n.ast,e.locator,e.source);if(!r.ok)return r.result;for(let a of t.data.changes){let c=xb(a.name);if(c.owner!=="generic")return K(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(Yn.isJSXAttribute),s=new Map;for(let a of i){let c=bb(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 K(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(d=>d!==c));continue}let l=wr(a.name,a.value).value;c?c.value=l:o.attributes.push(wr(a.name,a.value))}return me(n.ast,e.source,{kind:"set-props",target:"jsx-node",inverse:"set-props"})}function bb(e){return Yn.isJSXIdentifier(e.name)?e.name.name:Yn.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:null}import{SiteEditOperationParamsSchema as Sb}from"@vcp-dev/contracts";import*as z from"@babel/types";var Qu=["prefetch","replace","scroll","locale","onNavigate"],Eb=/^on(?:Click|DoubleClick|AuxClick|MouseDown|MouseUp|PointerDown|PointerUp|TouchStart|TouchEnd|KeyDown|KeyUp|ContextMenu)(?:Capture)?$/;function vb(e){let t=e;for(;t;){if(t.isJSXElement()&&t.node.openingElement.attributes.some(n=>z.isJSXAttribute(n)&&z.isJSXIdentifier(n.name)&&Eb.test(n.name.name)))return!0;t=t.parentPath}return!1}function ni(e){let t=ke(e.source,"jsx-node");if(!t.ok)return t.result;let n=zn(t.ast,e.locator,e.source);if(!n.ok)return n.result;let r=Sb.safeParse({kind:"set-link-target",scope:"selection",link:e.link,changes:e.changes});if(!r.success||r.data.kind!=="set-link-target")return Jt(e.source,"Invalid typed link-target changes");let o=n.match.path,i=o.node,s=i.openingElement,a=Pb(s.name);if(!a)return Jt(e.source,"Unsupported JSX link tag");if(s.attributes.some(z.isJSXSpreadAttribute))return Jt(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=fa(g);if(!h)return Jt(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 Jt(e.source,"Duplicate JSX attributes cannot be transformed safely");let l=c.get("href")?.[0];if(l&&!Nb(l))return Jt(e.source,"Dynamic link href cannot be transformed safely");let d=a==="a",f=d?null:Cb(o,s.name);if(!d&&!f)return Jt(e.source,"Only native anchors and imported next/link components are supported");if(e.link.kind==="none"&&vb(o))return Jt(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=Rb(t.ast,o);if(!g.ok)return Jt(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")),wb(t.ast,f,o)}else m&&d&&(s.name=z.jsxIdentifier(m),i.closingElement&&(i.closingElement.name=z.jsxIdentifier(m)));let u=new Set;return e.link.kind==="none"?(u.add("href"),u.add("target"),u.add("rel"),Qu.forEach(g=>u.add(g))):(u.add("href"),e.link.kind==="native-link"&&Qu.forEach(g=>u.add(g))),s.attributes=s.attributes.filter(g=>{if(!z.isJSXAttribute(g))return!0;let h=fa(g);return!h||!u.has(h)}),e.link.kind!=="none"&&s.attributes.push(z.jsxAttribute(z.jsxIdentifier("href"),z.stringLiteral(e.link.href))),kb(s,e.changes),me(t.ast,e.source,{kind:"set-link-target",target:"jsx-node",inverse:"set-link-target"})}function kb(e,t){for(let n of t){let r=e.attributes.find(s=>z.isJSXAttribute(s)&&fa(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(da(n.value)),i=z.jsxAttribute(z.jsxIdentifier(n.name),o);r&&z.isJSXAttribute(r)?r.value=i.value:e.attributes.push(i)}}function da(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=>da(t))):typeof e=="object"?z.objectExpression(Object.entries(e).map(([t,n])=>z.objectProperty(z.isValidIdentifier(t)?z.identifier(t):z.stringLiteral(t),da(n)))):z.nullLiteral()}function Ib(e){return z.isImportDefaultSpecifier(e)||z.isImportSpecifier(e)&&e.importKind!=="type"&&(z.isIdentifier(e.imported,{name:"default"})||z.isStringLiteral(e.imported,{value:"default"}))}function qu(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 Cb(e,t){if(!z.isJSXIdentifier(t))return null;let n=e.scope.getBinding(t.name);if(!n||!qu(n.path))return null;let r=n.path.parentPath;return!r?.isImportDeclaration()||r.node.source.value!=="next/link"?null:t.name}function Rb(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(Ib);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 wb(e,t,n){let r=n.scope.getProgramParent();r.crawl();let o=r.getBinding(t);if(!o||!qu(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 Nb(e){return!e.value||z.isStringLiteral(e.value)}function Pb(e){return z.isJSXIdentifier(e)?e.name:null}function fa(e){return z.isJSXIdentifier(e.name)?e.name.name:null}function Jt(e,t){return K(e,"unsupported-syntax",t,"jsx-node")}import*as Ke from"@babel/types";import{classifySiteEditPropertyName as ed}from"@vcp-dev/contracts";function ri(e){let t=ed(e.name),n=ed(e.property);if(t.owner!=="generic"||n.owner!=="generic")return K(e.source,"unsupported-syntax","Property binding is only available for generic properties","jsx-node");if(!td(e.object))return K(e.source,"unsupported-syntax","Property binding object must be a single identifier","jsx-node");if(e.property.length===0)return K(e.source,"unsupported-syntax","Property binding requires a non-empty property name","jsx-node");let r=ke(e.source,"jsx-node");if(!r.ok)return r.result;let o=zn(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)&&Tb(l)===e.name);if(s.length>1)return K(e.source,"unsupported-syntax",`JSX attribute '${e.name}' has multiple sources`,"jsx-node");let a=Ab(e.object,e.property),c=s[0];if(c)c.value=Ke.jsxExpressionContainer(a);else{let l=wr(e.name,"");l.value=Ke.jsxExpressionContainer(a),i.attributes.push(l)}return me(r.ast,e.source,{kind:"set-property-binding",target:"jsx-node",inverse:"restore-property-binding"})}function Ab(e,t){return td(t)?Ke.memberExpression(Ke.identifier(e),Ke.identifier(t)):Ke.memberExpression(Ke.identifier(e),Ke.stringLiteral(t),!0)}function td(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(e)}function Tb(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 _b,identifier as Tr,importDeclaration as Ob,importDefaultSpecifier as Mb,importNamespaceSpecifier as Db,importSpecifier as Lb,isImportDefaultSpecifier as nd,isImportNamespaceSpecifier as rd,isImportSpecifier as od,stringLiteral as Bb}from"@babel/types";function Zn(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(S=>!Hb(S));if(o!==-1){let S=r[o],E=S&&typeof S=="object"&&"kind"in S?S.kind:void 0;return K(t,"unsupported-syntax",`Unsupported import spec kind: ${String(E)}`)}let i=Jb(r);if(!i.ok)return K(t,"unsupported-syntax",i.message);let s=ke(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),d=new Set(l.flatMap(S=>S.specifiers.flatMap(E=>{let y=Wb(S,E);return y?[y]:[]}))),f=i.imports.filter(S=>!d.has(ud(S)));if(f.length===0)return Rr(t,t,{kind:"add-import",target:"import",inverse:"remove-import"});let m=Xb(c.body),u=f.find(S=>m.has(pa(S)));if(u)return K(t,"unsupported-syntax",`Import local binding already exists: ${pa(u)}`);let g=Ub(f);if(g.reduce((S,E)=>S+E.length,0)!==f.length)return K(t,"unsupported-syntax","Unsupported import specifier grouping");for(let S of g){if(!cd(sd(S)))return K(t,"unsupported-syntax","Unsupported import specifier combination");let E=l.find(y=>jb(y,S));if(E)$b(E,S);else{let y=Ob(id(S),Bb(n));zb(c.body,y),l.push(y)}}return me(a,t,{kind:"add-import",target:"import",inverse:"remove-import"})}function jb(e,t){return e.importKind==="type"?!1:cd(Kb(Vb(e),sd(t)))}function $b(e,t){let n=!1,r=new Set(e.specifiers.map(o=>ma(o)));for(let o of id(t)){let i=ma(o);r.has(i)||(e.specifiers.push(o),r.add(i),n=!0)}return ld(e.specifiers),{changed:n}}function id(e){let t=e.map(n=>{switch(n.kind){case"named":return Lb(n.local?Tr(n.local):Tr(n.imported),Tr(n.imported));case"default":return Mb(Tr(n.local));case"namespace":return Db(Tr(n.local));default:return n}});return ld(t),t}function sd(e){let t=ad();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 Vb(e){let t=ad();for(let n of e.specifiers)nd(n)?t.defaultLocals.add(n.local.name):rd(n)?t.namespaceLocals.add(n.local.name):t.hasNamed=!0;return t}function ad(){return{defaultLocals:new Set,hasNamed:!1,namespaceLocals:new Set}}function Kb(e,t){return{defaultLocals:new Set([...e.defaultLocals,...t.defaultLocals]),hasNamed:e.hasNamed||t.hasNamed,namespaceLocals:new Set([...e.namespaceLocals,...t.namespaceLocals])}}function cd(e){return e.defaultLocals.size>1||e.namespaceLocals.size>1?!1:!(e.hasNamed&&e.namespaceLocals.size>0)}function ld(e){let t=[...e.filter(n=>nd(n)),...e.filter(n=>rd(n)),...e.filter(n=>od(n))];e.splice(0,e.length,...t)}function Ub(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 Jb(e){let t=new Map,n=new Map;for(let r of e){let o=ud(r);if(t.has(o))continue;let i=pa(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 Xb(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(_b(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 zb(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 Hb(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 ud(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 pa(e){return e.kind==="named"?e.local??e.imported:e.local}function Wb(e,t){return e.importKind==="type"||od(t)&&t.importKind==="type"?null:ma(t)}function ma(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(d=>!Yb(d));if(o!==-1){let d=r[o],f=d&&typeof d=="object"&&"kind"in d?d.kind:void 0;return K(t,"unsupported-syntax",`Unsupported remove import spec kind: ${String(f)}`)}let i=ke(t);if(!i.ok)return i.result;let{ast:s}=i,a=s.program,c=a.body.findIndex(d=>d.type==="ImportDeclaration"&&d.source.value===n);if(c===-1)return Rr(t,t,{kind:"remove-import",target:"import",inverse:"add-import"});let l=a.body[c];return r.length===0?(a.body.splice(c,1),me(s,t,{kind:"remove-import",target:"import",inverse:"add-import"})):(l.specifiers=l.specifiers.filter(d=>!r.some(f=>Gb(d,f))),l.specifiers.length===0&&a.body.splice(c,1),me(s,t,{kind:"remove-import",target:"import",inverse:"add-import"}))}function Gb(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 Yb(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 Fr(e){let{source:t,locator:n,next:r}=e,o=ai(t,n);return o.ok?(o.path.replaceWith(en(r)),me(o.ast,t,{kind:"update-value",target:"value",inverse:"restore-value"})):o.result}function oi(e){let{source:t,locator:n,index:r,value:o}=e,i=ai(t,n);return i.ok?i.path.isArrayExpression()?i.path.node.elements.some(s=>s?.type==="SpreadElement")?K(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>i.path.node.elements.length?K(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(i.path.node.elements.splice(r,0,en(o)),me(i.ast,t,{kind:"insert-array-element",target:"value",inverse:"remove-array-element"})):K(t,"unsupported-syntax","Array operations require array expression target","value"):i.result}function ii(e){let{source:t,locator:n,index:r}=e,o=ai(t,n);return o.ok?o.path.isArrayExpression()?o.path.node.elements.some(i=>i?.type==="SpreadElement")?K(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>=o.path.node.elements.length?K(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(o.path.node.elements.splice(r,1),me(o.ast,t,{kind:"remove-array-element",target:"value",inverse:"insert-array-element"})):K(t,"unsupported-syntax","Array operations require array expression target","value"):o.result}function si(e){let{source:t,locator:n,fromIndex:r,toIndex:o}=e,i=ai(t,n);if(!i.ok)return i.result;if(!i.path.isArrayExpression())return K(t,"unsupported-syntax","Array operations require array expression target","value");if(i.path.node.elements.some(c=>c?.type==="SpreadElement"))return K(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 K(t,"array-index-out-of-range","Array move indices are out of range","value");let[s]=i.path.node.elements.splice(r,1),a=Math.min(o,i.path.node.elements.length);return i.path.node.elements.splice(a,0,s),me(i.ast,t,{kind:"move-array-element",target:"value",inverse:"move-array-element-back"})}function ai(e,t){let n=ke(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 ze from"@babel/types";function ci(e){let t=ke(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 K(e.source,"unsupported-syntax","Object property upsert requires an ObjectExpression parent","value");let r=n.match.path.node;if(r.properties.some(a=>ze.isSpreadElement(a)||ze.isObjectProperty(a)&&a.computed))return K(e.source,"unsupported-syntax","Object property upsert does not support spreads or computed keys","value");let o=r.properties.filter(a=>ze.isObjectProperty(a)&&Zb(a.key)===e.name);if(o.length>1)return K(e.source,"unsupported-syntax",`Object property '${e.name}' has multiple sources`,"value");let i=e.value.kind==="undefined"?ze.unaryExpression("void",ze.numericLiteral(0)):en(e.value.value),s=o[0];if(s)s.value=i,s.shorthand=!1;else{let a=ze.objectProperty(oa(e.name),i);e.name==="__proto__"&&(a.computed=!0),r.properties.push(a)}return me(t.ast,e.source,{kind:"upsert-object-property",target:"value",inverse:"restore-object-property"})}function Zb(e){return ze.isIdentifier(e)?e.name:ze.isStringLiteral(e)?e.value:ze.isNumericLiteral(e)?String(e.value):null}import{isSiteEditRuntimeContainerTag as Qb,isSiteEditRuntimeVoidElementTag as qb}from"@vcp-dev/contracts/site-edit-runtime-capability";function qn(e){if(!e.composition)throw new Error("Composition unavailable for render source graph.");return e.composition}function eS(e,t,n){let r=qn(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",d=i.tag.toLowerCase(),f=i.tag!==d,m=!f&&qb(d),u=f||Qb(d),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&&!u&&!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&&u&&(!a||g);return{composition:r,key:e,canUpdateText:S,canInsertChild:E,canMove:!l,canRemove:!l,constraints:s}}function dd(e,t){let n=new Map;for(let r of e.nodes.keys())n.set(r,eS(r,e,t));return n}function ga(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:Se(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Key not found: ${e.key}`}]};let n=tS(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:Se(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:pd(r),version:{documentVersion:e.route.graph.version,contentHash:Se(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:fd(e.route.source,o),valueRaw:s?fd(e.route.source,s):null,attrRange:pd(o),diagnostics:[]}}function md(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 tS(e,t){let n=Nt({source:e,profile:bn({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:nS(t.sourceRange)});return!r.ok||r.match.node.type!=="JSXElement"?null:r.match.node}function gd(e){let t=Nt({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 fd(e,t){return t.start==null||t.end==null?"":e.slice(t.start,t.end)}function pd(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 nS(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function hd(){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 rS}from"node:crypto";import li from"node:fs/promises";import ha from"node:path";import{setTimeout as oS}from"node:timers/promises";var iS={async mkdir(e,t){await li.mkdir(e,t)},async writeFile(e,t,n){await li.writeFile(e,t,n)},async rename(e,t){await li.rename(e,t)},async rm(e,t){await li.rm(e,t)}},sS=new Set(["EACCES","EBUSY","EPERM"]),aS=[10,20,40,80,160];async function cS(e,t,n){for(let r of aS)try{await e.rename(t,n);return}catch(o){if(!lS(o))throw o;await oS(r)}await e.rename(t,n)}function lS(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&sS.has(e.code)}async function ui(e,t,n=iS){let r=ha.dirname(e),o=ha.basename(e),i=ha.join(r,`.${o}.${process.pid}.${rS()}.tmp`),s=!1;try{await n.mkdir(r,{recursive:!0}),await n.writeFile(i,t,"utf8"),await cS(n,i,e),s=!0}finally{if(!s)try{await n.rm(i,{force:!0})}catch{}}}import ya from"@babel/traverse";import*as k from"@babel/types";import*as le from"@babel/types";function Ft(e,t={}){if(le.isTSAsExpression(e)||le.isTSSatisfiesExpression(e)||le.isTSNonNullExpression(e)||le.isTypeCastExpression(e)||le.isParenthesizedExpression(e))return Ft(e.expression,t);if(le.isStringLiteral(e))return{status:"resolved",value:e.value};if(le.isNumericLiteral(e))return Number.isFinite(e.value)?{status:"resolved",value:e.value}:{status:"unresolved"};if(le.isBooleanLiteral(e))return{status:"resolved",value:e.value};if(le.isNullLiteral(e))return{status:"resolved",value:null};if(le.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(le.isIdentifier(e))return e.name==="undefined"&&!t.resolveIdentifier?{status:"undefined"}:t.resolveIdentifier?.(e.name)??{status:"unresolved"};if(le.isUnaryExpression(e)&&e.operator==="void"&&le.isNumericLiteral(e.argument)&&e.argument.value===0)return{status:"undefined"};if(le.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||le.isSpreadElement(r))return{status:"unresolved"};let o=Ft(r,t);if(o.status!=="resolved")return{status:"unresolved"};n.push(o.value)}return{status:"resolved",value:n}}if(le.isObjectExpression(e)){let n=Object.create(null);for(let r of e.properties){if(!le.isObjectProperty(r)||r.computed||!le.isExpression(r.value))return{status:"unresolved"};let o=uS(r.key);if(o===null)return{status:"unresolved"};let i=Ft(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 le.isMemberExpression(e)||le.isOptionalMemberExpression(e)?t.resolveMember?.(e)??{status:"unresolved"}:{status:"unresolved"}}function uS(e){return le.isIdentifier(e)?e.name:le.isStringLiteral(e)?e.value:le.isNumericLiteral(e)?String(e.value):null}var dS=typeof ya=="function"?ya:ya.default;function Ge(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 fS(e){return/^[A-Z]/.test(e)}function va(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 tr(e){return k.isJSXFragment(e)}function xd(e){return k.isJSXIdentifier(e.name)?e.name.name:k.isJSXMemberExpression(e.name)?bd(e.name):k.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:"unknown"}function bd(e){return k.isJSXIdentifier(e.object)?`${e.object.name}.${e.property.name}`:k.isJSXMemberExpression(e.object)?`${bd(e.object)}.${e.property.name}`:e.property.name}function pS(e){return e.split(".")[0]??e}function mS(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 gS(){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 hS(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 Xt(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)?Xt(n.value,t):k.isRestElement(n)&&Xt(n.argument,t);return t}if(k.isArrayPattern(e)){for(let n of e.elements)n&&(k.isRestElement(n)?Xt(n.argument,t):Xt(n,t));return t}return k.isAssignmentPattern(e)?(Xt(e.left,t),t):(k.isRestElement(e)&&Xt(e.argument,t),t)}function St(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function _r(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 yS(e,t,n){e.set(t,{resolved:!0,value:n})}function ka(e,t){e.set(t,{resolved:!1})}function Sd(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 di([$e(e.left,t,n),$e(e.right,t,n)]);if(k.isBinaryExpression(e))return di([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 di([$e(e.consequent,t,n),$e(e.alternate,t,n)]);if(k.isTemplateLiteral(e))return di(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=rn(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:St(e,t),base:o.name,path:r}:null}function di(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 rn(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=_r(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=rn(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=_r(r.value.name,t.valueScopes);if(s.kind!=="resolved")return;i=s.value}else i=rn(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=_r(n.base,t.valueScopes);if(r.kind!=="resolved")return;let o=Sd(r.value,n.path);return o.kind==="resolved"?o.value:void 0}if(k.isCallExpression(e))return vd(e,t)??void 0}function Ed(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:St(e,n),source:null}:null;let o=_r(r.base,t.valueScopes),i=r.kind==="identifier"?o:o.kind==="resolved"?Sd(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 xa(e,t,n,r,o,i){return{file:e,componentName:t,elements:n,regions:r,ordinalTracker:gS(),parentStack:[],valueScopes:i,importMap:o}}function Sa(e,t,n){for(let r of e)for(let o of r.declarations){for(let s of Xt(o.id))ka(n,s);if(!k.isIdentifier(o.id)||!o.init||!k.isExpression(o.init))continue;let i=rn(o.init,t);i!==void 0&&yS(n,o.id.name,i)}}function xS(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 bS(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:Ge(i),editable:!0,source:null})}else if(k.isJSXExpressionContainer(i)&&k.isStringLiteral(i.expression))r.push({index:o++,value:i.expression.value,sourceRange:Ge(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:Ge(i),editable:!0,source:null}):r.push({index:o++,value:St(s,n),sourceRange:Ge(i),editable:!0,source:$e(s,n,t)})}else if(k.isJSXExpressionContainer(i)&&k.isExpression(i.expression)){let s=Ed(i.expression,t,n);s&&r.push({index:o++,value:s.value,sourceRange:Ge(i),editable:!0,source:s.source})}return r}function SS(e,t,n){let r=[];for(let[o,i]of e.attributes.entries()){if(!k.isJSXAttribute(i))continue;let s=vS(i.name);if(!s)continue;let a=St(i,n);if(k.isStringLiteral(i.value)){r.push({name:s,value:i.value.value,sourceRange:Ge(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:Ge(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=rn(i.value.expression,t);if(s==="className"){let u=typeof c=="string"?c:c===void 0?vd(i.value.expression,t):null;if(u){r.push({name:s,value:u,sourceRange:Ge(i),source:null,resolvedValue:u,syntaxKind:"expression",raw:a,order:o,resolution:{status:"resolved",value:u}});continue}}let l=Ed(i.value.expression,t,n);if(c!==void 0){r.push({name:s,value:PS(c),sourceRange:Ge(i),source:$e(i.value.expression,n,t),resolvedValue:c,syntaxKind:"expression",raw:a,order:o,resolution:{status:"resolved",value:c}});continue}let d=kS(i.value.expression,t),f=$e(i.value.expression,n,t),m=l?.value??St(i.value.expression,n);r.push({name:s,value:d.status==="undefined"?"undefined":m,sourceRange:Ge(i),source:l?.source??f,syntaxKind:"expression",raw:a,order:o,resolution:d})}}return r}function ES(e,t,n){return e.attributes.flatMap((r,o)=>!k.isJSXSpreadAttribute(r)||!k.isExpression(r.argument)?[]:[{raw:St(r.argument,n),sourceRange:Ge(r),order:o,source:$e(r.argument,n,t)}])}function vS(e){return k.isJSXIdentifier(e)?e.name:k.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function kS(e,t){return Ft(e,{resolveIdentifier(n){let r=_r(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=rn(n,t);return r===void 0?{status:"unresolved"}:{status:"resolved",value:r}}})}function vd(e,t){let n=er(e,t);return n&&n.map(o=>o.trim()).filter(Boolean).join(" ")||null}function er(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=rn(e,t);return typeof n=="string"?[n]:null}if(k.isConditionalExpression(e)){let n=er(e.consequent,t),r=er(e.alternate,t);return!n||!r?null:[...n,...r]}if(k.isLogicalExpression(e)){if(e.operator!=="&&")return null;let n=rn(e.left,t);return n===!1||n===null?[]:er(e.right,t)}if(k.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||k.isSpreadElement(r))return null;let o=er(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=CS(r.key);if(!o)return null;n.push(o)}return n}if(k.isCallExpression(e)){let n=IS(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=er(o,t);if(!i)return null;r.push(...i)}return r}return null}function IS(e){return k.isIdentifier(e)?e.name:k.isMemberExpression(e)&&k.isIdentifier(e.property)?e.property.name:null}function CS(e){return k.isIdentifier(e)?e.name:k.isStringLiteral(e)?e.value:null}function RS(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 wS(e,t){for(let n of t){let r=RS(e,n);if(r)return r}return null}function NS(e){return k.isJSXIdentifier(e.name)?e.name.name:null}function PS(e){return e===null?"null":typeof e=="boolean"?e?"true":"false":JSON.stringify(e)}function AS(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 ba(e){return k.isArrowFunctionExpression(e)||k.isFunctionExpression(e)}function TS(e){return e==="render"||e==="itemRender"||e==="rowRender"||e==="children"}function FS(e){return e==="empty"||e==="emptyRender"||e==="loading"||e==="loadingRender"||e==="error"||e==="errorRender"||e==="fallback"||e==="headerRender"||e==="footerRender"}function yd(e,t,n,r){if(!e||!k.isExpression(e))return null;let o={kind:"repeat-template",collectionExpression:St(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 zt(e,t,n){if(!e)return[];if(k.isJSXElement(e)){if(va(e))return hi(e.children,t,n);let r=mi(e,t,n);return r?[r]:[]}return tr(e)?gi(e,t,n):k.isParenthesizedExpression(e)?zt(e.expression,t,n):k.isExpression(e)?yi(e,t,n):[]}function fi(e,t,n){let r=new Map;for(let o of e.params)for(let i of Xt(o))ka(r,i);t.valueScopes.push(r);try{if(!k.isBlockStatement(e.body))return zt(e.body,t,n);let o=new Map;t.valueScopes.push(o);try{return kd(e.body.body,t,n)}finally{t.valueScopes.pop()}}finally{t.valueScopes.pop()}}function kd(e,t,n){let r=[];for(let o of e){if(k.isVariableDeclaration(o)){let i=t.valueScopes[t.valueScopes.length-1];if(i){Sa([o],t,i);for(let s of o.declarations)k.isIdentifier(s.id)&&(k.isJSXElement(s.init)||k.isJSXFragment(s.init))&&r.push(...zt(s.init,t,n))}continue}r.push(...Ea(o,t,n))}return r}function Ea(e,t,n){if(k.isReturnStatement(e))return e.argument?zt(e.argument,t,n):[];if(k.isBlockStatement(e))return Rn(e.body,t,n);if(k.isIfStatement(e)){let r=k.isBlockStatement(e.consequent)?Rn(e.consequent.body,t,n):Ea(e.consequent,t,n),o=e.alternate?k.isBlockStatement(e.alternate)?Rn(e.alternate.body,t,n):Ea(e.alternate,t,n):[];return[...r,...o]}if(k.isSwitchStatement(e))return Rn(e.cases.flatMap(r=>r.consequent),t,n);if(k.isTryStatement(e)){let r=Rn(e.block.body,t,n);return e.handler&&r.push(...Rn(e.handler.body.body,t,n)),e.finalizer&&r.push(...Rn(e.finalizer.body,t,n)),r}return[]}function Rn(e,t,n){let r=new Map;t.valueScopes.push(r);try{return kd(e,t,n)}finally{t.valueScopes.pop()}}function pi(e,t,n,r,o,i){o.length!==0&&e.regions.push({kind:t,ownerKey:n,childKeys:o,sourceRange:Ge(r),sourceCandidates:i&&i.length>0?i:void 0})}function _S(e,t,n,r){let o=wS(e.openingElement,["items","dataSource","data"]),i={key:t,tag:xd(e.openingElement)};n.parentStack.push(i);try{for(let s of e.openingElement.attributes){if(!k.isJSXAttribute(s))continue;let a=NS(s);if(!a||!k.isJSXExpressionContainer(s.value))continue;let c=s.value.expression;if(!k.isJSXEmptyExpression(c)){if(TS(a)&&ba(c)){let l=fi(c,n,r),d=yd(o,c,r,n);pi(n,"repeat-region",t,s,l,d?[d]:void 0);continue}if(FS(a)){let l=ba(c)?fi(c,n,r):zt(c,n,r);pi(n,"conditional-region",t,s,l)}}}if(o)for(let s of e.children){if(!k.isJSXExpressionContainer(s)||!ba(s.expression))continue;let a=fi(s.expression,n,r),c=yd(o,s.expression,r,n);pi(n,"repeat-region",t,s,a,c?[c]:void 0)}}finally{n.parentStack.pop()}}function mi(e,t,n){let r=xd(e.openingElement);if(r==="Fragment"||va(e))return hi(e.children,t,n),null;let o=t.parentStack[t.parentStack.length-1]??null,i=o?.key??null,s=fS(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,d=Nr(t.file,t.componentName,l),f={file:t.file,component:t.componentName,structuralPath:l,key:d},m=s?"component-boundary":null,u=bS(e.children,t,n),g=SS(e.openingElement,t,n),h=ES(e.openingElement,t,n),S,E,y=!1;if(s){let C=t.importMap.get(r)??t.importMap.get(pS(r));C&&(S=C.specifier,E=C.exportName,y=En(C.specifier,t.file))}let v={identity:f,tag:r,componentName:t.componentName,sourceFile:t.file,sourceRange:Ge(e),parentKey:i,childKeys:[],textSegments:u,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(d,v),i&&t.elements.has(i)&&t.elements.get(i).childKeys.push(d),_S(e,d,t,n),(!s||e.children.length>0)&&(t.parentStack.push({key:d,tag:r}),OS(e.children,t,n),t.parentStack.pop()),d}function gi(e,t,n){return hi(e.children,t,n)}function hi(e,t,n){let r=[];for(let o of e)if(k.isJSXElement(o))if(va(o))r.push(...hi(o.children,t,n));else{let i=mi(o,t,n);i&&r.push(i)}else tr(o)?r.push(...gi(o,t,n)):k.isJSXExpressionContainer(o)&&r.push(...yi(o.expression,t,n));return r}function OS(e,t,n){for(let r of e)k.isJSXElement(r)?mi(r,t,n):tr(r)?gi(r,t,n):k.isJSXExpressionContainer(r)&&yi(r.expression,t,n)}function MS(e){return e==="&&"||e==="||"||e==="??"}function yi(e,t,n){if(k.isJSXEmptyExpression(e))return[];let r=AS(e);if(r){let o=r.call,i=t.parentStack[t.parentStack.length-1]??null,s=[],a=r.callback,c={kind:"repeat-template",collectionExpression:St(r.collection,n),collectionSource:$e(r.collection,n,t)};if(k.isArrowFunctionExpression(a)||k.isFunctionExpression(a)){let d=a.params[0],f=a.params[1];k.isIdentifier(d)&&(c.itemParamName=d.name),k.isIdentifier(f)&&(c.indexParamName=f.name)}s.push(c);let l={kind:"repeat-region",ownerKey:i?.key??"",childKeys:[],sourceRange:Ge(o),sourceCandidates:s.length>0?s:void 0};return t.regions.push(l),(k.isArrowFunctionExpression(a)||k.isFunctionExpression(a))&&l.childKeys.push(...fi(a,t,n)),l.childKeys}if(k.isConditionalExpression(e)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:St(e.test,n),conditionSource:$e(e.test,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:Ge(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...zt(e.consequent,t,n)),s.childKeys.push(...zt(e.alternate,t,n)),s.childKeys}if(k.isLogicalExpression(e)&&MS(e.operator)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:St(e.left,n),conditionSource:$e(e.left,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:Ge(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...zt(e.right,t,n)),s.childKeys}if(k.isParenthesizedExpression(e))return yi(e.expression,t,n);if(k.isJSXElement(e)){let o=mi(e,t,n);return o?[o]:[]}return tr(e)?gi(e,t,n):[]}function DS(e){let t=e.argument;return t&&(k.isExpression(t)||tr(t))?t:null}function Or(e,t){let n=[];for(let r of e){if(k.isReturnStatement(r)){let o=DS(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 Id(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=hS(r);dS(r,{"FunctionDeclaration|FunctionExpression|ArrowFunctionExpression"(f){let m=mS(f);if(!m)return;let u=f.node,g=[];if(k.isArrowFunctionExpression(u))k.isExpression(u.body)||tr(u.body)?g=[{argument:u.body,statement:k.returnStatement(k.isExpression(u.body)?u.body:null)}]:k.isBlockStatement(u.body)&&(g=Or(u.body.body));else{let C=u.body;k.isBlockStatement(C)&&(g=Or(C.body))}if(g.length===0){f.skip();return}let h=new Map;Sa(xS(r.program.body),xa(t,m,i,s,l,[h]),h);let S=new Map;for(let C of u.params)for(let N of Xt(C))ka(S,N);let E=k.isBlockStatement(u.body)?u.body.body:[],y=g[0]?.statement??null;for(let C of E){if(y&&C===y)break;k.isVariableDeclaration(C)&&Sa([C],xa(t,m,i,s,l,[h,S]),S)}let v=xa(t,m,i,s,l,[h,S]);for(let C of g){let N=zt(C.argument,v,n);for(let A of N)a.includes(A)||a.push(A);if(C.condition){let A={kind:"conditional-branch",conditionExpression:St(C.condition,n),conditionSource:$e(C.condition,n,v)};pi(v,"conditional-region","",C.statement,N,[A])}}f.skip()}});let d=[...i.keys()];return d.length>0&&c.set(t,d),{graph:{routeId:t,rootKeys:a,elements:i,regions:s,fileIndex:c,version:1,diagnostics:[]},localImports:o}}function Ia(e,t,n,r){return[...e.map(o=>({...o})),{fromFile:t,specifier:n,targetPath:r}]}function xi(e,t,n){return{...e,details:{...e.details??{},entryFile:t,importStack:n.map(r=>({...r}))}}}async function Cd(e,t,n,r,o={}){let i=o.maxDepth??10,s=o.version??1,a=o.parseModule??Sn,c=new Map,l=new Map,d=new Map,f=[],m=new Set,u=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){u(xi(R.diagnostic,N,A));continue}d.set(y,R.module);let{graph:T,localImports:O}=Id(R.module);for(let M of T.elements.values())if(M.importedFrom&&wt(M.importedFrom)){let U=M.importedFrom,ee=await Fo(y,U,r);ee.ok?(M.importedFrom=ee.path,Vt(ee.path)&&(M.isPublicUiComponent=!0)):En(U,y)||u(xi(ee.diagnostic,N,Ia(A,y,U,ee.diagnostic.path)))}if(l.set(y,T),!(C>=i))for(let M of O){if(su(M))continue;let U=await Fo(y,M,r);if(!U.ok){En(M,y)||u(xi(U.diagnostic,N,Ia(A,y,M,U.diagnostic.path)));continue}let ee=U.path;if(h.has(ee)||Vt(ee))continue;let Re=Ia(A,y,M,ee);try{let Q=await n(ee);g.push({file:ee,source:Q,depth:C+1,diagnosticEntryFile:N,importStack:Re})}catch(Q){u(xi({path:ee,code:"import-read-failed",message:`Failed to read imported file: ${ee}`,details:{fromFile:y,specifier:M,reason:Q instanceof Error?Q.message:String(Q)}},N,Re))}}}let S=LS(e,l,s,(o.additionalEntries??[]).map(E=>E.file));return S.diagnostics=f,{graph:S,allSources:c,diagnostics:f,parsedModules:d,entryModule:d.get(e)??null}}function LS(e,t,n,r=[]){let o=new Map,i=[],s=new Map,a=[];for(let[c,l]of t){for(let[d,f]of l.elements)o.set(d,f);for(let d of l.regions)i.push(d);for(let[d,f]of l.fileIndex){let m=s.get(d)??[];s.set(d,[...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 fE}from"@vcp-dev/contracts";import{createHash as BS,randomUUID as Oa}from"node:crypto";import Oe from"node:fs/promises";import Me from"node:path";var Md=new WeakMap;function nr(e){return Md.get(e)?.()??e.readIndex()}var mt=1,Ra=1,jS=2,$S="index.json",VS="recovery.json",KS="transaction-journal.json",US="document-version.json",Ei={maxEntries:100,maxSessionBytes:512*1024*1024,maxEntryBytes:128*1024*1024},re={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"},oe=class extends Error{constructor(t,n,r){super(n),this.name="FileHistoryStoreError",this.code=t,r?.cause!==void 0&&(this.cause=r.cause)}};function Ht(){return{entries:new Map,blobSizes:new Map}}function bi(e,t){let n={entries:new Map,blobs:new Map,objectBytes:0};for(let r of e)Dd(n,r,t);return n}function Dd(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 Ld(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 Bd(e,t={}){let n=sE(e),r=uE(t.limits),o=Ca(n),i=aE(n),s=await tt(i),a=await tt(o)||s;a||(await QS(n),await qS(n)),a||await dE(n);let c=Ht(),l=await ki(n,c),d=new Set(a?(await Ni(n)).map(y=>y.stageId):[]);a||await Ad(n,l.entryIds,c);let f=l.digest,m=bi(l.entryIds,c),u=async y=>{let{index:v,sizeBytes:C}=await jr(n);if(Xd(v,y),v.digest!==f){let N=Ht();await Kd(n,v.entryIds,N,C),m=bi(v.entryIds,N),f=v.digest}return{...Pi(v),totalBytes:m.objectBytes+C}},g=async y=>{Ma(y),await u(),await Nd(n,m,[y.entryId],y.blobIds,y.stageId),await vi(n,y.stageId)},h=async(y,v)=>{let C=await u(v);$d(y,C.entryIds.length);let N=Ht();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 tt(o)||s)throw new oe(re.RECOVERY_PENDING,"history store requires explicit recovery before accepting writes")},E={rootDir:n,recoveryRequired:a,async readDocumentVersion(){return _d(n)},async writeDocumentVersion(y){if(await S(),!Number.isInteger(y)||y<0)throw new oe(re.INVALID_SCHEMA,"document version must be a non-negative integer");let v=await _d(n);y<=v||await Mr(Gd(n),{schemaVersion:1,version:Math.max(v,y)})},async stageAppend(y,v={}){await S();let C=await zS(y,r),N={schemaVersion:Ra,stageId:Oa(),entryId:C.entryId,blobIds:C.blobs.map(A=>A.digest)};try{await HS(n,C),await GS(n,N,v.durableManifest!==!1)}catch(A){try{await g(N)}catch(R){throw new oe(re.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(),Pa(y);let v=await wa(n,y);v&&await g(v)},async previewStagedAppend(y,v){await S();let C=await u(v);return(await Rd(n,r,y,C,m)).transition},async previewCursor(y,v){await S();let C=await h(y,v);return jd(C,C.entryIds,y)},async publishStagedAppend(y,v,C){if(await S(),Ci(y,"entryId"),C){Pa(C);let O=await wa(n,C);if(!O||O.entryId!==y)throw new oe(re.INVALID_SCHEMA,"history stage does not match the published entry")}let N=await u(v),A=m,R=await Rd(n,r,y,N,A),T=await Fd({rootDir:n,previousDigest:R.current.digest,entryIds:R.entryIds,cursor:R.cursor,readback:async()=>Td(n,R.usage),afterWrite:async()=>{C?await vi(n,C):await ZS(n,y),await Nd(n,R.usage,[...A.entries.keys()].filter(O=>!R.usage.entries.has(O)),[...A.blobs.keys()].filter(O=>!R.usage.blobs.has(O)))}});return m=R.usage,f=T.digest,T},async append(y){await S();let v=await u(),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 Ci(y,"entryId"),Dr(n,y)},async readBlob(y){Ci(y,"blobId");let v=await Zd(n,y),C=await Lr(v,re.NOT_FOUND,"blob");return Wd(C,y,v),C},async readIndex(){let y=Ht(),v=await ki(n,y);return m=bi(v.entryIds,y),f=v.digest,v},async readStatus(){let y=await Ii(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 tt(o)||await tt(i)}},async readUndoRedoIds(){let y=await Ii(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 Fd({rootDir:n,previousDigest:C.digest,entryIds:C.entryIds,cursor:y,readback:async()=>Td(n,m)});return f=N.digest,N},async markRecoveryRequired(y){await tt(o)||await Mr(Ca(n),{schemaVersion:mt,reason:cE(y),createdAt:new Date().toISOString()})},async clearRecoveryRequired(){await Oe.rm(Ca(n),{force:!0})},async readTransactionJournal(){return await tt(i)?Si(i):null},async writeTransactionJournal(y){await S(),Yd(y);try{await Mr(i,y)}catch(C){let N=await Si(i).catch(()=>null);if(N&&Buffer.from(nt(N)).equals(Buffer.from(nt(y))))return;throw N?new oe(re.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous",{cause:C}):C}let v=await Si(i);if(!Buffer.from(nt(v)).equals(Buffer.from(nt(y))))throw new oe(re.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous")},async clearTransactionJournal(y){let v=await tt(i)?await Si(i):null;if(v&&v.transactionId!==y)throw new oe(re.INVALID_SCHEMA,"transaction journal changed concurrently");try{await Oe.rm(i,{force:!0})}catch(C){if(!await tt(i))return;throw C}if(await tt(i))throw new oe(re.INDEX_CORRUPT,"transaction journal clear outcome is ambiguous");s=!1},async cleanupTmp(){await S();for(let C of d)await vi(n,C),d.delete(C);await eE(n);let y=Ht(),v=await ki(n,y);await Ad(n,v.entryIds,y),m=bi(v.entryIds,y),f=v.digest}};return Md.set(E,()=>Ii(n)),E}async function Rd(e,t,n,r,o){Ci(n,"entryId");let i=Ht(),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 d of r.entryIds.slice(r.cursor+1))Ld(a,d);Dd(a,s.id,i),c.push(s.id);let l=WS(c,t,a);return{current:r,entryIds:l.entryIds,cursor:l.cursor,usage:a,transition:jd(r,l.entryIds,l.cursor)}}function jd(e,t,n){return $d(n,t.length),{expectedIndexDigest:e.digest,publishedIndexDigest:JS(t,n),publishedCursor:n,publishedCurrentId:t[n]??null}}function JS(e,t){return on(nt({schemaVersion:mt,entryIds:e,cursor:t}))}function $d(e,t){if(!Number.isInteger(e)||e<-1||e>=t)throw new oe(re.INVALID_SCHEMA,`history cursor is out of bounds: ${e}`)}function XS(e){if(!Et(e))return!1;let t=e.publishedCursor,n=e.publishedCurrentId;return!st(e.expectedIndexDigest)||!st(e.publishedIndexDigest)||!Number.isInteger(t)||t<-1||n!==null&&!st(n)?!1:t===-1?n===null:st(n)}async function zS(e,t){if(!e.kind.trim())throw new oe(re.INVALID_JSON,"history entry kind must not be empty");let n=[],r=[];for(let c of e.blobs??[]){if(!c.name.trim())throw new oe(re.INVALID_JSON,"history blob name must not be empty");let l=iE(c.data),d=on(l);n.push({name:c.name,bytes:l,digest:d,sizeBytes:l.byteLength}),r.push({name:c.name,digest:d,sizeBytes:l.byteLength})}let o={schemaVersion:mt,kind:e.kind,manifest:e.manifest,blobs:r},i=nt({...o}),s=on(i),a=i.byteLength+n.reduce((c,l)=>c+l.sizeBytes,0);if(a>t.maxEntryBytes)throw new oe(re.CAPACITY_EXCEEDED,`history entry exceeds maxEntryBytes (${a} > ${t.maxEntryBytes})`);return{entryBody:o,entryId:s,blobs:n}}async function HS(e,t){let n=ja(e,t.entryId),r={id:t.entryId,...t.entryBody},o=[...t.blobs.map(a=>wd($a(e,a.digest),a.bytes,{kind:"blob",digest:a.digest},Ka(e,a.digest))),wd(n,nt(r),{kind:"entry",digest:t.entryId},Va(e,t.entryId))],s=(await Promise.allSettled(o)).find(a=>a.status==="rejected");if(s)throw s.reason}async function wd(e,t,n,r){let o=await Fa(e)??(r?await Fa(r):null);if(o!==null){if(Buffer.compare(o,t)!==0)throw new oe(n.kind==="blob"?re.BLOB_CORRUPT:re.ENTRY_CORRUPT,`${n.kind} content mismatch for ${n.digest}`);return}await zd(e,t)}function WS(e,t,n){let r=[...e],o=r.length-1;for(;;){if(n.objectBytes+nt(Jd(r,o)).byteLength<=t.maxSessionBytes&&r.length<=t.maxEntries)return{entryIds:r,cursor:o};if(o<=0||r.length===0)throw new oe(re.CAPACITY_EXCEEDED,"history store exceeds capacity limits and the current entry cannot be trimmed");Ld(n,r.shift()),o-=1}}async function GS(e,t,n){Ma(t);let r=Ba(e,t.stageId);if(n){await Mr(r,t);return}await oE(r,t)}async function wa(e,t){let n=await Fa(Ba(e,t));if(n===null)return null;let r=$r(Buffer.from(n).toString("utf8"),`history stage ${t}`),o=Ma(r);if(o.stageId!==t)throw new oe(re.INVALID_SCHEMA,`history stage id mismatch: ${t}`);return o}async function Ni(e){let t=[];for(let n of await wi(La(e))){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);Pa(r);let o=await wa(e,r);o&&t.push(o)}return t}async function Nd(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 Ni(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 Pd(ja(e,a),Va(e,a));for(let a of new Set(r))!t.blobs.has(a)&&!s.has(a)&&await Pd($a(e,a),Ka(e,a));await _a(Vr(e)),await _a(Kr(e))}async function vi(e,t){await Na(Ba(e,t)),await YS(e)}async function YS(e){try{await Oe.rmdir(La(e))}catch(t){if(Ur(t)||Et(t)&&t.code==="ENOTEMPTY")return;throw t}}async function ZS(e,t){for(let n of await Ni(e))n.entryId===t&&await vi(e,n.stageId)}async function Na(e){if(await Oe.rm(e,{force:!0}),await tt(e))throw new oe(re.INDEX_CORRUPT,`unable to remove staged history object: ${e}`)}async function Pd(e,t){await Na(e),await Na(t)}function Ma(e){if(!Et(e)||e.schemaVersion!==Ra||typeof e.stageId!="string"||!Vd(e.stageId)||!st(e.entryId))throw new oe(re.INVALID_SCHEMA,"history stage schema is invalid");let t=Hd(e.blobIds,"history stage blobIds");return{schemaVersion:Ra,stageId:e.stageId,entryId:e.entryId,blobIds:t}}function Pa(e){if(!Vd(e))throw new oe(re.INVALID_PATH,"history stageId must be a UUID")}function Vd(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 Ad(e,t,n=Ht()){let r=new Set(t),o=new Set;for(let l of t){let d=await Dr(e,l,n);for(let f of d.blobs)o.add(f.digest)}for(let l of await Ni(e)){r.add(l.entryId);for(let d of l.blobIds)o.add(d)}let i=Vr(e),s=await wi(i);for(let l of s){if(!l.endsWith(".json"))continue;let d=Od(l.slice(0,-5));d&&!r.has(d)&&await Ri(Me.join(i,l))}let a=Kr(e),c=await wi(a);for(let l of c){let d=Od(l);d&&!o.has(d)&&await Ri(Me.join(a,l))}}async function ki(e,t=Ht()){let{index:n,sizeBytes:r}=await jr(e),{totalBytes:o}=await Kd(e,n.entryIds,t,r);return{...Pi(n),totalBytes:o}}async function Td(e,t){let{index:n,sizeBytes:r}=await jr(e);return{...Pi(n),totalBytes:t.objectBytes+r}}async function jr(e){let t=Da(e),n=await Lr(t,re.NOT_FOUND,"index"),r=$r(Buffer.from(n).toString("utf8"),"index");return{index:tE(r),sizeBytes:n.byteLength}}async function Ii(e){return Pi((await jr(e)).index)}function Pi(e){let t=[...e.entryIds],n=t.slice(0,e.cursor+1).reverse(),r=t.slice(e.cursor+1);return{schemaVersion:mt,digest:e.digest,entryIds:t,cursor:e.cursor,currentId:t[e.cursor]??null,undoIds:n,redoIds:r}}async function Kd(e,t,n,r){let o=0,i=new Set;o+=r??(await jr(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=Ht()){let r=n.entries.get(t);if(r)return r.entry;let o=await lE(e,t),i=await Lr(o,re.NOT_FOUND,"entry"),s=$r(Buffer.from(i).toString("utf8"),`entry ${t}`),a=nE(s);if(a.id!==t)throw new oe(re.ENTRY_CORRUPT,`entry id mismatch for ${t}`);if(on(nt({schemaVersion:a.schemaVersion,kind:a.kind,manifest:a.manifest,blobs:a.blobs}))!==t)throw new oe(re.ENTRY_CORRUPT,`entry hash mismatch for ${t}`);for(let l of a.blobs){if(n.blobSizes.has(l.digest))continue;let d=await Zd(e,l.digest),f=await Lr(d,re.NOT_FOUND,"blob");Wd(f,l.digest,d),n.blobSizes.set(l.digest,f.byteLength)}return n.entries.set(t,{entry:a,sizeBytes:i.byteLength}),a}async function Ud(e,t,n){await Mr(Da(e),Jd(t,n))}function Jd(e,t){return{schemaVersion:mt,digest:on(nt({schemaVersion:mt,entryIds:e,cursor:t})),entryIds:e,cursor:t}}function Xd(e,t){if(t!==void 0&&e.digest!==t)throw new oe(re.INVALID_SCHEMA,`history index changed concurrently (expected ${t}, current ${e.digest})`)}async function Fd(e){Xd(await Ii(e.rootDir),e.previousDigest);let t=on(nt({schemaVersion:mt,entryIds:e.entryIds,cursor:e.cursor}));try{await Ud(e.rootDir,e.entryIds,e.cursor),await e.afterWrite?.();let n=await e.readback();if(n.digest!==t)throw new oe(re.INDEX_CORRUPT,"history index readback did not match the published transition");return n}catch(n){let r=await ki(e.rootDir).catch(()=>null);if(r?.digest===t)return r;throw r?.digest===e.previousDigest?n:new oe(re.INDEX_CORRUPT,"history index publish outcome is ambiguous",{cause:n})}}async function QS(e){await Oe.mkdir(e,{recursive:!0}),await Oe.mkdir(Vr(e),{recursive:!0}),await Oe.mkdir(Kr(e),{recursive:!0}),await Oe.mkdir(Br(e),{recursive:!0})}async function qS(e){await Oe.rm(Br(e),{recursive:!0,force:!0}),await Oe.mkdir(Br(e),{recursive:!0})}async function eE(e){let t=Br(e);await Oe.mkdir(t,{recursive:!0});for(let n of await wi(t))n!=="stages"&&await Oe.rm(Me.join(t,n),{recursive:!0,force:!0})}function tE(e){if(!Et(e))throw new oe(re.INDEX_CORRUPT,"index.json must be an object");if(e.schemaVersion!==mt)throw new oe(re.INVALID_SCHEMA,`unsupported index schemaVersion: ${String(e.schemaVersion)}`);let t=Hd(e.entryIds,"index.entryIds"),n=e.cursor;if(!Number.isInteger(n)||n<-1||n>=t.length)throw new oe(re.INDEX_CORRUPT,"index cursor is out of bounds");let r=n,o=e.digest;if(!st(o))throw new oe(re.INDEX_CORRUPT,"index digest is invalid");let i=on(nt({schemaVersion:mt,entryIds:t,cursor:r}));if(o!==i)throw new oe(re.INDEX_CORRUPT,"index digest mismatch");return{schemaVersion:mt,digest:o,entryIds:t,cursor:r}}function nE(e){if(!Et(e))throw new oe(re.ENTRY_CORRUPT,"entry must be an object");if(e.schemaVersion!==mt)throw new oe(re.INVALID_SCHEMA,`unsupported entry schemaVersion: ${String(e.schemaVersion)}`);let t=e.id;if(!st(t))throw new oe(re.ENTRY_CORRUPT,"entry id is invalid");let n=e.kind;if(typeof n!="string"||n.trim().length===0)throw new oe(re.ENTRY_CORRUPT,"entry kind is invalid");let r=Ta(e.manifest,"entry.manifest"),o=rE(e.blobs);return{id:t,schemaVersion:mt,kind:n,manifest:r,blobs:o}}function rE(e){if(!Array.isArray(e))throw new oe(re.ENTRY_CORRUPT,"entry blobs must be an array");return e.map((t,n)=>{if(!Et(t))throw new oe(re.ENTRY_CORRUPT,`entry blob ref ${n} must be an object`);let r=t.name;if(typeof r!="string"||r.trim().length===0)throw new oe(re.ENTRY_CORRUPT,`entry blob ref ${n} name is invalid`);let o=t.digest;if(!st(o))throw new oe(re.ENTRY_CORRUPT,`entry blob ref ${n} digest is invalid`);let i=t.sizeBytes;if(!Number.isInteger(i)||i<0)throw new oe(re.ENTRY_CORRUPT,`entry blob ref ${n} sizeBytes is invalid`);return{name:r,digest:o,sizeBytes:i}})}async function Mr(e,t){await zd(e,nt(t))}async function oE(e,t){let n=Me.dirname(e),r=Me.basename(e),o=Me.join(n,`.${r}.${process.pid}.${Oa()}.tmp`);await Oe.mkdir(n,{recursive:!0});try{await Oe.writeFile(o,nt(t),{flag:"wx"}),await Oe.rename(o,e)}finally{await Ri(o)}}async function zd(e,t){let n=Me.dirname(e),r=Me.basename(e),o=Me.join(n,`.${r}.${process.pid}.${Oa()}.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 _a(n)}finally{await Ri(o)}}function nt(e){return Buffer.from(JSON.stringify(Aa(e)),"utf8")}function Aa(e){if(Array.isArray(e))return e.map(t=>Aa(t));if(Et(e)){let t={};for(let n of Object.keys(e).sort())t[n]=Aa(e[n]);return t}return e}function $r(e,t){try{return JSON.parse(e)}catch(n){throw new oe(re.INVALID_JSON,`${t} is not valid JSON`,{cause:n})}}function Ta(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=>Ta(n,t));if(Et(e)){let n={};for(let[r,o]of Object.entries(e))n[r]=Ta(o,t);return n}break}throw new oe(re.INVALID_JSON,`${t} must be JSON-serializable`)}function Hd(e,t){if(!Array.isArray(e))throw new oe(re.INDEX_CORRUPT,`${t} must be an array`);return e.map((n,r)=>{if(!st(n))throw new oe(re.INDEX_CORRUPT,`${t}[${r}] is invalid`);return n})}function Ci(e,t){if(!st(e))throw new oe(re.INVALID_PATH,`${t} must be a sha256 digest`)}function st(e){return typeof e=="string"&&/^sha256:[a-f0-9]{64}$/u.test(e)}function on(e){return`sha256:${BS("sha256").update(e).digest("hex")}`}function iE(e){return typeof e=="string"?Buffer.from(e,"utf8"):Buffer.from(e)}async function Lr(e,t,n){try{return await Oe.readFile(e)}catch(r){throw new oe(t,`${n} not found: ${e}`,{cause:r})}}async function Fa(e){try{return await Oe.readFile(e)}catch(t){if(Ur(t))return null;throw t}}function Wd(e,t,n){if(on(e)!==t)throw new oe(re.BLOB_CORRUPT,`blob hash mismatch for ${n}`)}async function tt(e){try{return await Oe.access(e),!0}catch(t){if(Ur(t))return!1;throw t}}async function Ri(e){try{await Oe.rm(e,{force:!0,recursive:!0})}catch{}}async function _a(e){try{let t=await Oe.open(e,"r");try{await t.sync()}finally{await t.close()}}catch{}}async function wi(e){try{return await Oe.readdir(e)}catch(t){if(Ur(t))return[];throw t}}function sE(e){if(typeof e!="string"||e.trim().length===0)throw new oe(re.INVALID_ROOT,"history store rootDir must be a non-empty string");return Me.resolve(e)}function Da(e){return Me.join(e,$S)}function Ca(e){return Me.join(e,VS)}function aE(e){return Me.join(e,KS)}function Gd(e){return Me.join(e,US)}async function _d(e){try{let t=await Oe.readFile(Gd(e),"utf8"),n=$r(t,"document version");if(!Et(n)||n.schemaVersion!==1||!Number.isInteger(n.version)||n.version<0)throw new oe(re.INVALID_SCHEMA,"document version schema is invalid");return n.version}catch(t){if(Ur(t))return 0;throw t}}async function Si(e){let t=await Lr(e,re.RECOVERY_PENDING,"transaction journal"),n=$r(Buffer.from(t).toString("utf8"),"transaction journal");return Yd(n),n}function Yd(e){if(!Et(e)||e.schemaVersion!==jS||typeof e.transactionId!="string"||e.transactionId.length===0||typeof e.operationId!="string"||e.operationId.length===0||!["prepared","files-written","history-published"].includes(e.phase)||!XS(e.historyTransition)||!Array.isArray(e.files))throw new oe(re.INVALID_SCHEMA,"transaction journal schema is invalid");for(let t of e.files)if(!Et(t)||typeof t.path!="string"||t.path.length===0||t.preDigest!==null&&!st(t.preDigest)||t.postDigest!==null&&!st(t.postDigest))throw new oe(re.INVALID_SCHEMA,"transaction journal file digest is invalid")}function cE(e){return e.replace(/[\r\n]+/g," ").slice(0,512)}function Vr(e){return Me.join(e,"entries")}function Kr(e){return Me.join(e,"blobs")}function Br(e){return Me.join(e,"tmp")}function La(e){return Me.join(Br(e),"stages")}function Ba(e,t){return Me.join(La(e),`${t}.json`)}function ja(e,t){return Me.join(Vr(e),`${qd(t)}.json`)}function $a(e,t){return Me.join(Kr(e),qd(t))}function Va(e,t){return Me.join(Vr(e),`${t}.json`)}function Ka(e,t){return Me.join(Kr(e),t)}async function lE(e,t){return Qd(ja(e,t),Va(e,t))}async function Zd(e,t){return Qd($a(e,t),Ka(e,t))}async function Qd(e,t){return await tt(e)?e:await tt(t)?t:e}function qd(e){return e.slice(7)}function Od(e){let t=e.startsWith("sha256:")?e:`sha256:${e}`;return st(t)?t:null}function Et(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ur(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function uE(e){return{maxEntries:e?.maxEntries??Ei.maxEntries,maxSessionBytes:e?.maxSessionBytes??Ei.maxSessionBytes,maxEntryBytes:e?.maxEntryBytes??Ei.maxEntryBytes}}async function dE(e){let t=Da(e);await tt(t)||await Ud(e,[],-1)}var pE={affectedCompositions:[]};function of(e){let t=null,n=new WeakMap;async function r(){return t??=mE(e),t}async function o(i){if(!i)return null;let s=Ua(i);return s?gE(e,s):i}return{async prepareAppend(i){let s=await nr(e),a=await e.stageAppend(nf(i),{durableManifest:!1}),c;try{c=await e.previewStagedAppend(a.entryId,s.digest)}catch(d){throw await e.discardStage(a.stageId),d}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 nr(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,d=await e.previewCursor(l,a.digest),f={kind:"undo",entry:s,historyTransition:d};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 nr(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,d=await e.previewCursor(l,a.digest),f={kind:"redo",entry:s,historyTransition:d};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);ef(c,i.historyTransition),i.entry.historyId=s.entryId,Object.assign(a,rr(c))}else{if(s.cursor===void 0)throw new Error("prepared cursor is missing");let c=i.kind==="undo"?a.undo:a.redo;if(Ua(c.at(-1))!==Ua(i.entry))throw new Error("history state changed before publish");let l=await e.setCursor(s.cursor,s.expectedDigest);ef(l,i.historyTransition),Object.assign(a,rr(l))}n.delete(i)},async discardPrepared(i){let s=n.get(i);if(!s)return;let a=i.historyTransition;if(a){let c=await nr(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 d=s.entryIds.indexOf(a.historyId);if(d>=0)try{let f=await e.setCursor(d);Object.assign(s,rr(f));return}catch(f){throw s.redo.push(i),f}}let c=await e.append(nf(i)),l=c.currentId;if(!l)throw new Error("history store did not publish an entry");i.historyId=l,Object.assign(s,rr(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,rr(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 ef(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 Ua(e){return typeof e=="string"?e:e?.historyId}async function mE(e){let t=await nr(e);return rr(t)}function rr(e){return{undo:[...e.undoIds].reverse(),redo:[...e.redoIds].reverse(),entryIds:[...e.entryIds],cursor:e.cursor}}async function gE(e,t){let n=await e.readEntry(t),r=hE(n),o=r.provenance??pE;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 tf(e,n,r.preSnapshots),postSnapshots:await tf(e,n,r.postSnapshots)}}async function tf(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(bE(r,o.blobName))).toString("utf8"):"";return{file:o.file,content:i,version:o.version,exists:o.exists,...o.sha256?{sha256:o.sha256}:{}}}))}function nf(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 d=`${s}-${c}`;l.blobName=d,t.push({name:d,data:a.content})}return l}),r=yE(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 hE(e){if(!af(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:sf(t.provenance)}:{},preSnapshots:rf(t.preSnapshots,"preSnapshots"),postSnapshots:rf(t.postSnapshots,"postSnapshots")}}function yE(e){if(e.provenance!==void 0)return sf(e.provenance);if(e.composition)return{initiatingComposition:e.composition,affectedCompositions:[]}}function sf(e){let t=fE.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 rf(e,t){return e.map((n,r)=>{if(!af(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&&!xE(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 xE(e){return/^sha256:[0-9a-f]{64}$/.test(e)}function bE(e,t){let n=e.get(t);if(!n)throw new Error(`durable history blob is missing: ${t}`);return n}function af(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{randomBytes as OE}from"node:crypto";import Ti from"node:path";import{parse as yf}from"@babel/parser";import ME from"@babel/traverse";import*as xf from"@babel/types";import{COMPONENT_I18N_FILE_SUFFIX as Xa,PageResourceArtifactSchema as DE,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as LE,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as BE,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as jE,parseComponentI18nResourcesJson as $E}from"@vcp-dev/contracts";var lf=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\(/i,uf=/\b(?:bg-black|bg-white|text-white|text-black)(?:\b|\/)/g,SE=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke)-\[#(?:[0-9a-fA-F]{3,8})\](?:\/\d+)?/g,EE=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*#[0-9a-fA-F]{3,8}[^'"]*['"]/g,vE=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*rgba?\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,kE=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,IE=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,CE=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*(?:oklch|lab|lch|hsla?)\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,RE=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*(?:oklch|lab|lch|hsla?)\([^)]+\)[^'"]*['"]/gi,wE=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*color-mix\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,NE=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*color-mix\([^'"]*['"]/gi,PE=/\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,AE=/var\(\s*--(?:_|private-|vcp-)[^)]+\)/gi,TE=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\([^)]*\)/gi;function Jr(e,t){let n=Ai([...gt(e,SE),...gt(e,EE),...gt(e,vE),...gt(e,t.includeRgbBackgroundImage?kE:IE),...t.includeExtendedColorFunctions?[...gt(e,CE),...gt(e,RE)]:[]]),r=Ai([...gt(e,wE),...gt(e,NE)]).filter(o=>t.colorMixPolicy==="always"||lf.test(o));return n.push(...r.filter(o=>!n.includes(o))),t.rejectTailwindPalette&&n.push(...gt(e,PE).filter(o=>!n.includes(o))),t.rejectAnyRawColorLiteral&&n.push(...gt(e,TE).filter(o=>!n.includes(o))),{hardCodedSurfaceHits:Ai(gt(e,uf)),hardCodedSurfaceOccurrences:_E(e),rawColorHits:n,privateTokenHits:t.rejectPrivateTokens?Ai(gt(e,AE)):[]}}function gt(e,t){return e.match(new RegExp(t.source,t.flags))??[]}var cf=160,FE=/((?:[a-z][a-z0-9-]*(?:\[[^\]]*\])?:)+)$/;function _E(e){let t=new RegExp(uf.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),d=FE.exec(l),f=r(i.index),m=e.indexOf(`
|
|
6
|
+
`,i.index),u=e.slice(n[f]??0,m===-1?void 0:m).trim();o.push({token:a,variant:d?.[1]??"",alpha:c?Number(c[1]):null,line:f+1,snippet:u.length>cf?`${u.slice(0,cf-1)}\u2026`:u})}return o}function Ai(e){return[...new Set(e)]}var za="{{$INSTANCE}}",VE=/\{\{\$PAGE_ROUTE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,KE=/\{\{\$PAGE_TITLE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,Ha="components/site/generated",UE=/\.(?:tsx?|json)$/,JE=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,XE=["react","react/","next","next/","lucide-react","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],zE=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),Ja=ME,HE=typeof Ja=="function"?Ja:Ja.default;async function Wa(e){let t=DE.safeParse(e.artifact);if(!t.success)return Pe("Page resource artifact failed contract validation.");let n=t.data,r=e.randomHex??(()=>OE(4).toString("hex")),o=Math.max(1,Math.min(e.maxAttempts??5,5)),i=nv(r());if(!i)return Pe("Random instance suffix must be 8 lowercase hex chars.");let s=`${rv(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 d=[],f=new Set,m=new Set,u=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=df({materialization:v.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c});if(!C.ok)return C;for(let N of C.files){let A=pf(N,f,d);if(A)return A}m.add(C.entry),g.set(C.entry,C.entryExport),u.set(v.component_id,C.entry)}for(let[v,C]of n.pages.entries()){let N=l[v],A=df({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 T=pf(R,f,d);if(T)return T}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=GE(d,m,s,u,h,g);if(!E.ok)return E;for(let v of d)if(await e.exists(v.file))return!v.file.startsWith("app/")&&o>1?Wa({...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=YE(d);return y||(d.sort((v,C)=>v.file.localeCompare(C.file)),{ok:!0,packageInstanceId:s,pages:l,files:d})}function df(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:ff(o.pathTemplate,e.packageInstanceId);if(!s)return Pe("Materialization path cannot be mapped into the package namespace.",o.pathTemplate);let a=WE(o.content,e.packageInstanceId,e.routeByPage,e.titleByPage);if(!a.ok)return a;let c=i&&e.pageTitle!==void 0?QE(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??ff(t,e.packageInstanceId);return!r||!n.some(o=>o.file===r)?Pe("Materialization entry must match one controlled source file.",t):{ok:!0,files:n,entry:r,entryExport:e.materialization.entry.export}}function WE(e,t,n,r){let o,i=e.replace(VE,(c,l)=>{let d=n.get(l);return d||(o=l,c)});if(o)return Pe(`Page route placeholder references unknown template page: ${o}`);let s=i.replace(KE,(c,l)=>{let d=r.get(l);return d?JSON.stringify(d):(o=l,c)});if(o)return Pe(`Page title placeholder references unknown template page: ${o}`);let a=s.replaceAll(za,t);return a.includes("{{$PAGE_ROUTE:")||a.includes("{{$PAGE_TITLE:")||a.includes("{{$INSTANCE}}")?Pe("Materialization contains an unresolved placeholder."):{ok:!0,data:a}}function ff(e,t){let n=`${Ha}/${t}`;if(e.split(za).length>2)return null;let o=e.replace(za,t),i=`${Ha}/${t}/`,s=o.startsWith(i)?o:`${n}/${o}`,a=Ti.posix.normalize(s);return a!==s||!a.startsWith(`${n}/`)||!UE.test(a)||JE.test(a)?null:a}function pf(e,t,n){return t.has(e.file)?Pe(`Page resource materializations resolve duplicate target: ${e.file}`,e.file):(t.add(e.file),n.push(e),null)}function GE(e,t,n,r,o,i){let s=new Set(e.map(u=>u.file)),a=`${Ha}/${n}`,c=new Map(e.map(u=>[u.file,new Set])),l=new Map;for(let u of e){if(u.file.endsWith(".json")){try{JSON.parse(u.content)}catch{return Pe("Materialization JSON file must contain valid JSON.",u.file)}if(u.file.endsWith(Xa)&&!$E(u.content).success)return Pe("Materialization component i18n resources are invalid.",u.file);continue}try{let h=yf(u.content,{sourceType:"module",plugins:["jsx","typescript"]});l.set(u.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=ev(u.file,y,s,a);if(!v.allowed)return Pe(`Materialization import is outside the controlled package: ${y}`,u.file);v.internalPath&&c.get(u.file).add(v.internalPath)}let S;if(HE(h,{Identifier(E){E.isReferencedIdentifier()&&zE.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 Pe(`Materialization source uses forbidden capability: ${S}`,u.file)}catch{return Pe("Materialization source must parse as TS/TSX.",u.file)}let g=Jr(u.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 Pe("Materialization source violates the public theme token policy.",u.file)}if([...t].some(u=>!s.has(u)))return Pe("Materialization entry is outside the controlled package.");for(let u of t)if(u.endsWith(".json"))return Pe("Materialization JSON files cannot be package entries.");for(let[u,g]of i){let h=l.get(u);if(!h||!ZE(h,g))return Pe("Materialization entry does not declare its contracted export.",u)}let d=new Map([...r].map(([u,g])=>[g,u]));for(let u of o){let g=hf(u.entry,c);for(let h of u.declaredComponentIds){let S=r.get(h);if(!S||!g.has(S))return Pe(`Page entry does not reach declared component: ${h}`,u.entry)}for(let h of g){let S=d.get(h);if(S&&!u.declaredComponentIds.has(S))return Pe(`Page entry imports undeclared component: ${S}`,u.entry)}}let f=new Set;for(let u of t)for(let g of hf(u,c))f.add(g);if(f.size!==e.length)return Pe("Every materialization file must be reachable from a package entry.");let m=tv(e,l,c);return m||{ok:!0}}function YE(e){if(e.length>LE)return Pe("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>BE)return Pe("Page resource file exceeds the content byte limit.",n.file);t+=r}return t>jE?Pe("Page resource exceeds the aggregate content byte limit."):null}function ZE(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 QE(e,t,n){let r;try{r=yf(e,{sourceType:"module",sourceFilename:n,plugins:["jsx","typescript"]})}catch{return Pe("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=mf(s.init);if(a?.type!=="ObjectExpression")return{ok:!0,data:e};let c=a.properties.find(d=>d.type==="ObjectProperty"&&!d.computed&&qE(d.key));if(!c||c.type!=="ObjectProperty")return{ok:!0,data:e};let l=mf(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 mf(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression"||t?.type==="TSNonNullExpression";)t=t.expression;return t&&xf.isExpression(t)?t:null}function qE(e){return e.type==="Identifier"&&e.name==="title"||e.type==="StringLiteral"&&e.value==="title"}function ev(e,t,n,r){if(t.startsWith(`@/${r}/`)){let s=t.slice(2),a=gf(s,n);return a?{allowed:!0,internalPath:a}:{allowed:!1}}if(!t.startsWith("."))return{allowed:XE.some(s=>s.endsWith("/")?t.startsWith(s):t===s)};if(t.includes("\\")||t.includes("\0"))return{allowed:!1};let o=Ti.posix.normalize(Ti.posix.join(Ti.posix.dirname(e),t)),i=gf(o,n);return i&&(i.startsWith(`${r}/`)||i.startsWith("app/"))?{allowed:!0,internalPath:i}:{allowed:!1}}function gf(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 tv(e,t,n){let r=new Set(e.map(o=>o.file));for(let o of e){if(!o.file.endsWith(Xa))continue;let i=o.file.slice(0,-Xa.length),s=[`${i}.tsx`,`${i}.ts`].find(d=>r.has(d));if(!s)return Pe("Component i18n resources require a same-name TS/TSX companion.",o.file);let c=t.get(s)?.program.directives.some(d=>d.value.value==="use client"),l=[...n].filter(([,d])=>d.has(o.file));if(!c||l.length!==1||l[0]?.[0]!==s)return Pe("Component i18n resources must have exactly one same-name Client Component static importer.",s)}return null}function hf(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 nv(e){return/^[a-f0-9]{8}$/.test(e)?e:null}function rv(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"page-resource"}function Pe(e,t){return{ok:!1,code:"MATERIALIZATION_REJECTED",message:e,...t?{path:t}:{}}}import{randomBytes as ov}from"node:crypto";import Wt from"node:path";import{parse as iv}from"@babel/parser";import sv from"@babel/traverse";import{COMPONENT_I18N_FILE_SUFFIX as Fi,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as bf,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as av,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as cv,SiteEditMaterializationSchema as lv,parseComponentI18nResourcesJson as uv}from"@vcp-dev/contracts";var Za="components/site/generated",Sf="{{$INSTANCE}}",_i=5,dv=/^[a-z][a-z0-9-]{0,48}$/,fv=/^[a-f0-9]{8}$/,Ef=/\.tsx?$/,pv=/\.json$/,mv=/\.(?:tsx?|json)$/,gv=/^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/,hv=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,yv=["react","react/","next","next/","lucide-react","react-i18next","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],Ga=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),Ya=sv,xv=typeof Ya=="function"?Ya:Ya.default;function bv(e){let t=Array.isArray(e.manifest.files)?e.manifest.files:[];if(t.length>bf)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file count exceeds the reusable limit."}};let n=Av(t);if(n)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Static prefab resolves duplicate target path: ${n}`,path:n}};let r=lv.safeParse(e.manifest);if(!r.success)return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab manifest failed schema validation."}};let o=wv(e.generatedRoot);if(!o)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Generated root must be ${Za}.`,path:e.generatedRoot}};if(!wf(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=If(r.data.files),s=If(e.controlledFiles);if(!Tv(i,s))return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Controlled file list must exactly match the manifest file templates."}};if(i.size>bf)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 d=Buffer.byteLength(l.content,"utf8");if(d>av)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+=d}return a>cv?{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 Sv(e){let t=bv(e);if(!t.ok)return t;let n=Object.keys(e.manifest.projectDependencies??{}),r=new Set(e.availableHostDependencies??[]),o=n.find(d=>!gv.test(d)||!r.has(d));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(d=>[d,`${d}/`]),s=[...e.allowedExternalImports??yv,...i],a=t.data.generatedRoot,c=wf(e.manifest.instanceBaseName),l=Math.max(1,Math.min(_i,e.maxAttempts??_i));for(let d=0;d<l;d+=1){let f=Nv(e.instanceNameGenerator?.()??ov(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}`,u=Pf(a,m),g=Ev({manifest:e.manifest,generatedRoot:a,instanceName:m,instanceRoot:u,allowedExternalImports:s});if(!g.ok)return g;if(!await vv(e.exists,u,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 Rf(e){let t=Math.max(1,Math.min(_i,e.maxAttempts??_i));for(let n=0;n<t;n+=1){let r=await Sv({...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 Ev(e){let t=[],n=new Set;for(let i of e.manifest.files){let s=vf({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=vf({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=kv(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 vv(e,t,n){if(await e(t))return!0;for(let r of n)if(await e(r.path))return!0;return!1}function vf(e){if(e.pathTemplate.split(Sf).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(Sf,e.instanceName),n=Pv(t);return n?Pf(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||!mv.test(n)||hv.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 kv(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(pv.test(f.path)){if(f.path.endsWith(Fi)){let g=uv(f.content);if(!g.success)return wn("MATERIALIZATION_DATA_UNSUPPORTED",g.error.message,f.path);c.set(f.path,new Set)}else try{JSON.parse(f.content)}catch{return wn("MATERIALIZATION_DATA_UNSUPPORTED","Static prefab JSON file must contain valid JSON.",f.path)}continue}let m;try{m=iv(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 u=Jr(f.content,{colorMixPolicy:"always",includeExtendedColorFunctions:!0,includeRgbBackgroundImage:!0,rejectAnyRawColorLiteral:!0,rejectPrivateTokens:!0,rejectTailwindPalette:!0});if(u.hardCodedSurfaceHits.length>0||u.rawColorHits.length>0||u.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(!Ef.test(f.path))continue;let m=s.get(f.path),u=null;if(xv(m,{ImportDeclaration(g){let h=kf({importer:f.path,source:g.node.source.value,instanceRoot:t,filePaths:i,allowedExternalImports:o});if(!h.allowed)u??={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(Fi))){let S=Iv({importer:f.path,imported:h.internalPath,source:g.node.source.value,ast:m});S.ok?c.get(h.internalPath).add(f.path):(u??=S.error,g.stop())}},ExportAllDeclaration(g){u??={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=kf({importer:f.path,source:g.node.source.value,instanceRoot:t,filePaths:i,allowedExternalImports:o});!h.allowed||!h.internalPath?(u??={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"){u??={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"&&(u??={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"&&(u??={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"&&(u??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot use import.meta.",file:f.path},g.stop())},MemberExpression(g){let h=Cf(g.node);h&&Ga.has(h)&&(u??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${h}.`,file:f.path},g.stop())},OptionalMemberExpression(g){let h=Cf(g.node);h&&Ga.has(h)&&(u??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${h}.`,file:f.path},g.stop())},Identifier(g){g.isReferencedIdentifier()&&Ga.has(g.node.name)&&(u??={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"&&(u??={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"&&(u??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot declare style elements.",file:f.path},g.stop())}}),u)return{ok:!1,error:u}}if(!Ef.test(n))return wn("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must be a .ts/.tsx source module.",n);let l=s.get(n);if(!l)return wn("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must resolve to a controlled source file.",n);if(!Cv(l,r))return wn("MATERIALIZATION_EXPORT_MISSING","Static prefab entry does not declare the manifest export.",n);for(let[f,m]of c)if(m.size!==1)return wn("MATERIALIZATION_IMPORT_FORBIDDEN","Each component .i18n.json file must have exactly one same-name Client Component static importer.",f);return Rv(n,a).size!==e.length?wn("MATERIALIZATION_ENTRY_INVALID","Every controlled source file must be reachable from the entry module.",n):{ok:!0,data:{kind:"static-prefab-materialization",instanceName:"",generatedRoot:Za,instanceRoot:"",entry:{path:"",export:{kind:"default"}},files:[]}}}function kf(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=Wt.posix.normalize(Wt.posix.join(Wt.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 Iv(e){let t=Wt.posix.dirname(e.importer),n=Wt.posix.dirname(e.imported),r=Wt.posix.basename(e.importer).replace(/\.tsx?$/,""),o=Wt.posix.basename(e.imported).slice(0,-Fi.length),i=`./${r}${Fi}`;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 Cv(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 Rv(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 wn(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{file:n}:{}}}}function wv(e){let t=Nf(e);return t===Za?t:null}function Nv(e){let t=e.trim().toLowerCase();return fv.test(t)?t:null}function wf(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 dv.test(t)?t:null}function Nf(e){if(!e||e.startsWith("/")||e.includes("\\"))return null;let t=Wt.posix.normalize(e);return t==="."||t.startsWith("../")||t.includes("/../")||t.includes("//")?null:t}function Pv(e){let t=Nf(e);return!t||t!==e?null:t}function Pf(...e){return Wt.posix.join(...e)}function If(e){return new Set(e.map(t=>t.pathTemplate))}function Av(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 Tv(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function Cf(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 fc}from"node:crypto";import ic from"@babel/traverse";function Qa(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(d=>d.anchorSourceRange!==null&&d.members.length>0)??c.find(d=>d.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(d=>d.placementKey)),sourcePlacementKey:l.placementKey})))}return{placementByKey:t,unitByKey:r,placementsByUnitKey:o,sourcePlacementByUnitKey:i}}import{createHash as Fv}from"node:crypto";import Af from"node:path";import*as Mf from"@babel/parser";import qa from"@babel/generator";import*as Ue from"@babel/types";var Tf=typeof qa=="function"?qa:qa.default;function tc(e){let t=Lf(e);if(t)return{ok:!1,error:t};let n=e.projection,r=oc(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=Mv(n,o),s={jsx:`<${e.component.localName} />`},a=_v(e);if(i){let u=ec(e);return u.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:u.locator,sourceHash:u.sourceHash,node:s,placement:o.relation,replaceOriginal:n.container.kind==="starter-placeholder"}}}:u.result}let c=o.containerSourceRange??n.container.sourceRange,l=o.containerSourceHash??(rc(c,n.container.sourceRange)?n.container.sourceHash:null);if(!c||!l)return Xr("Route page composition does not expose a verifiable container boundary.");let d=Hr(c),f=_f(e.source,d,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 Xr("Route page composition placement does not expose a verifiable anchor boundary.");let u=_f(e.source,m,o.anchorSourceHash,"Route page composition anchor");if(!u.ok)return u.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:d,node:s,placement:o.relation,...m?{anchorLocator:m}:{}}}}}function _v(e){let t=jv(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 Oi(e){if(e.locator.root.kind!=="expression"||e.locator.path?.length)return Nn(e.source,"Root expression rewrite requires an exact expression locator.");let t=vr(e.source,"value");if(!t.ok)return Nn(e.source,t.diagnostic.message);let n=se(t.ast,e.locator);if(!n.ok)return Nn(e.source,n.diagnostic.message);let r=n.match.path;if(!r.isExpression())return Nn(e.source,"Resolved value locator does not point to an expression.");let o=or(e.source,r.node.start??null,r.node.end??null);if(!o||o!==e.expectedSourceHash)return Nn(e.source,"Root expression hash no longer matches the current source.");if(e.action.kind==="remove")return r.replaceWith(Ue.nullLiteral()),{ok:!0,source:Tf(t.ast,{}).code};let i;try{i=Mf.parseExpression(e.action.jsx,{plugins:["jsx","typescript"]})}catch(s){return Nn(e.source,s instanceof Error?s.message:String(s))}return!Ue.isJSXElement(i)&&!Ue.isJSXFragment(i)?Nn(e.source,"Root expression rewrite requires a JSX insertion expression."):(e.action.kind==="replace"?r.replaceWith(i):r.replaceWith(Ov(r.node,i,e.action.placement,e.action.replaceOriginal)),{ok:!0,source:Tf(t.ast,{}).code})}function Ov(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 Nn(e,t){return{ok:!1,source:e,diagnostic:{message:t}}}function nc(e){let t=Lf(e);if(t)return{ok:!1,error:t};let n=e.projection,r=Bf(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(Dv(n,o)){let h=ec(e);return h.ok?e.operation==="remove-node"&&!Ff(n,o.placementUnitKey)?Xr("The last editable page unit cannot be deleted."):e.operation==="move-node"?Xr("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=At(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?[]:[zr(a.diagnostic)]}};if(or(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=ec(e);return h.ok?Ff(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}}}:Xr("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||!Bv(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=oc(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 d=l.placement;if(d.placementUnitKey!==e.targetPlacement.placementUnitKey||d.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=d.containerSourceRange;if(!f||!d.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),u=At(e.source,m);if(!u.ok||!u.match.node)return{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:u.ok===!1?u.diagnostic.message:"Route page composition target container could not be resolved.",diagnostics:u.ok?[]:[zr(u.diagnostic)]}};if(or(e.source,u.match.node.start??null,u.match.node.end??null)!==d.containerSourceHash)return Of("Route page composition target container hash no longer matches the current source.");if(d.relation==="before"||d.relation==="after"){let h=d.anchorSourceRange,S=d.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=At(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?[]:[zr(y.diagnostic)]}}:or(e.source,y.match.node.start??null,y.match.node.end??null)!==S?Of("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:d.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:d.relation}}}}function Ff(e,t){for(let n of e.placementUnitByKey.values())if(n.placementUnitKey!==t&&n.members.length>0)return!0;return!1}function Mv(e,t){let n=e.placementUnitByKey.get(t.placementUnitKey);return n&&e.container.kind!=="jsx-container"&&rc(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 Dv(e,t){return e.container.kind!=="jsx-container"&&rc(t.sourceRange,e.mutationTarget.sourceRange)&&t.sourceHash===e.mutationTarget.sourceHash}function ec(e){let t=e.projection.mutationTarget,n={kind:"value",root:{kind:"expression",sourceRange:t.sourceRange}},r=At(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?[]:[zr(r.diagnostic)]}}}:or(e.source,r.match.node.start??null,r.match.node.end??null)!==t.sourceHash?{ok:!1,result:Df("Route mutation target hash no longer matches the current source.")}:{ok:!0,locator:n,sourceHash:t.sourceHash}}function _f(e,t,n,r){let o=At(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?[]:[zr(o.diagnostic)]}}}:or(e,o.match.node.start??null,o.match.node.end??null)!==n?{ok:!1,result:Df(`${r} hash no longer matches the current source.`)}:{ok:!0}}function Df(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function Xr(e){return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:e,diagnostics:[]}}}function Of(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function zr(e){return{code:"UNSUPPORTED_PAGE_SHAPE",message:e.message,details:{astCode:e.code}}}function Lf(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&&!Lv(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 Lv(e,t){return e.routeId===t.routeId&&e.effectiveTemplateId===t.effectiveTemplateId}function Bv(e,t){return e.routeId===t.routeId&&e.templateId===t.effectiveTemplateId}function jv(e,t){let n=Af.posix.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=Af.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 or(e,t,n){return t==null||n==null?null:`sha256:${Fv("sha256").update(e.slice(t,n)).digest("hex")}`}function rc(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 $v=typeof ic=="function"?ic:ic.default;function Kf(e){if(!e.ast)return vt(e,[Ve("UNSUPPORTED_PAGE_SHAPE","SourceGraph entry AST is required",{reason:"parsed-ast-required"})]);let t=Wv(e.ast);if(!t)return vt(e,[Ve("UNSUPPORTED_PAGE_SHAPE","Route default export must resolve to a local function component",{reason:"default-export-unresolved"})]);let n=Yv(t);if(!n.ok)return vt(e,[n.diagnostic]);let r=n.expression;if(r.isIdentifier()){let o=Qv(r,t);if(o.status==="resolved")r=o.expression;else if(o.status==="invalid")return vt(e,[Ve("UNSUPPORTED_PAGE_SHAPE","Route default export local binding is not a supported JSX root")])}if(ek(r,t))return vt(e,[Ve("INDIRECT_RETURN_ONLY","Route default export only returns through an indirect function boundary")]);if(r.isNullLiteral())return ac(e,t,"virtual-route-root",r);if(qv(r)){let o=ok({input:e,source:e.source,expression:r});return sc(e,t,o,{kind:"virtual-route-root",sourceKind:"atomic-expression"},r)}if(r.isConditionalExpression())return vt(e,[Ve("UNSUPPORTED_PAGE_SHAPE","Route conditional root contains an unsupported branch shape",{reason:"ambiguous-placement"})]);if(r.isJSXElement()&&!_e(r)&&!sn(r)){let o=uc(r),i=Vf({input:e,containerKind:"virtual-route-root",sourceKind:"jsx-element",source:e.source,containerPath:r,members:[o]});return sc(e,t,i,{kind:"virtual-route-root",sourceKind:"jsx-element"},r)}if(r.isJSXElement()||r.isJSXFragment()){let o=nk(r);if(!o.ok)return vt(e,[o.diagnostic]);let i=ir(o.path);if(i.unsupported)return vt(e,[Ve("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);if(tk(e.source,r,i.members))return ac(e,t,"starter-placeholder",r);let s=r.isJSXFragment()||_e(r);if(i.members.length===0&&s)return ac(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=Vf({input:e,containerKind:a,sourceKind:c,source:e.source,containerPath:o.path,members:i.members});return sc(e,t,l,{kind:a,sourceKind:c},r)}return vt(e,[Ve("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")])}function oc(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 Bf(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 Uf(e){return e.ok?Vv(e.projection):Kv(e.projection)}function Vv(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,d]of t){let f=d.members.flatMap((h,S)=>Jf(e,d,h,S,e.container.placementKey)),m=f.filter(({member:h})=>h.isBusinessMember).map(({sourceMember:h})=>Jv(l,h,d.independent)),u=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,u.map(({sourceMember:h})=>h)),o.set(l,m);let g=u[0]?.sourceMember.key??l;n.push({key:l,containerKey:g,businessMemberKeys:m.map(h=>h.key),isMultiMember:d.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:Uv(e,a),sourceMembers:i,businessMembers:s,placementUnits:n,placements:c}}function Kv(e){let t=e.diagnostics.map(Xv);return{status:"unsupported",version:e.version,composition:e.composition,reason:zv(e.diagnostics),diagnostics:t}}function Uv(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 Jf(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)=>Jf(e,t,a,c,i))]}function Jv(e,t,n){return{key:`business:${e}:${t.key}`,sourceMemberKey:t.key,containerKey:e,label:t.label,isIndependent:n}}function Xv(e){return{code:Hv(e),message:e.message}}function zv(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 Hv(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 Wv(e){let t=null;return $v(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=Gv(o.path);i&&(t=i,n.stop())}}),t}function Gv(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 Yv(e){let t=e.get("body");if(!t.isBlockStatement()){let s=Gr(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(!Zv(s))return{ok:!1,diagnostic:Ve("UNSUPPORTED_PAGE_SHAPE","Route guard return shape is not statically safe",{reason:"guard-shape"})};continue}if(Xf(s)||zf(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=Gr(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 Zv(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(Xf(o)||zf(o))return null;return r}function Xf(e){return e.isForStatement()||e.isForInStatement()||e.isForOfStatement()||e.isWhileStatement()||e.isDoWhileStatement()||e.isSwitchStatement()||e.isTryStatement()||e.isWithStatement()}function zf(e){let t=!1;return e.traverse({Function(n){n.skip()},ReturnStatement(){t=!0}}),t}function Qv(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=Gr(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 qv(e){return e.isConditionalExpression()?jf(Gr(e.get("consequent")))&&jf(Gr(e.get("alternate"))):!1}function jf(e){return!!(e&&(e.isJSXElement()||e.isJSXFragment()||e.isNullLiteral()))}function Gr(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 ek(e,t){if(e.isIdentifier())return $f(e.node.name,t);if(e.isCallExpression()){let n=e.get("callee");if(n.isIdentifier())return $f(n.node.name,t)}return!1}function $f(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 tk(e,t,n){return e.includes("DESIGN_PLAN_REPLACE_ME")&&t.isJSXElement()&&n.length>0&&lc(t)}function lc(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(!lc(t))return!1;continue}if(t.isJSXElement()&&!lc(t))return!1}return!0}function nk(e){let t=e;if(e.isJSXFragment()||_e(e)){let r=Wr(e),o=r[0];if(r.length===1&&o?.isJSXElement()&&sn(o))t=o;else return{ok:!0,path:t}}for(;t.isJSXElement()&&sn(t);){let r=Wr(t);if(r.length!==1)return{ok:!0,path:t};let o=r[0];if(!o?.isJSXElement()||!sn(o))return{ok:!0,path:t};if(Wr(o).length<=1)return{ok:!0,path:t};t=o}return{ok:!0,path:t}}function Wr(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(...Wr(n));continue}n.isJSXElement()&&(_e(n)?t.push(...Wr(n)):t.push(n))}return t}function ir(e){let t=[],n=!1;for(let r of e.get("children")){if(r.isJSXText()){if(!r.node.value.trim())continue;t.push({memberKey:dc(r.node.type,r.node.start,r.node.end),kind:"text",nodeType:r.node.type,sourceRange:ht(r.node.loc),businessMemberCount:0,parentSourceRange:ht(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=ir(o);n||=i.unsupported,t.push(...i.members);continue}if(o.isJSXElement()){let i=sn(o)?ir(o):null;n||=i?.unsupported??!1,t.push({...uc(o,i?.members),sourceRange:ht(r.node.loc),parentSourceRange:ht(e.node.loc)});continue}if(o.isJSXSpreadChild()){n=!0;continue}t.push({memberKey:dc(o.node.type,o.node.start,o.node.end),kind:"atomic-expression",nodeType:o.node.type,sourceRange:ht(r.node.loc),businessMemberCount:1,parentSourceRange:ht(e.node.loc),children:[],isBusinessMember:!0,label:"atomic-expression"});continue}if(r.isJSXFragment()||r.isJSXElement()&&_e(r)){let o=ir(r);n||=o.unsupported,t.push(...o.members);continue}if(r.isJSXElement()){let o=sn(r)?ir(r):null;n||=o?.unsupported??!1,t.push({...uc(r,o?.members),parentSourceRange:ht(e.node.loc)})}}return{members:t,unsupported:n}}function uc(e,t){let n=e.isJSXElement()&&sn(e)?t??ir(e).members:[],r=e.isJSXElement()&&!sn(e)&&!_e(e);return{memberKey:dc(e.node.type,e.node.start,e.node.end),kind:"jsx-element",nodeType:e.node.type,sourceRange:ht(e.node.loc),businessMemberCount:r?1:Hf(n),parentSourceRange:ht(e.parentPath?.node.loc),children:n,isBusinessMember:r,label:rk(e)}}function sn(e){let t=e.node.openingElement.name;return t.type==="JSXIdentifier"&&t.name[0]===t.name[0]?.toLowerCase()}function rk(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 Hf(e){return e.reduce((t,n)=>t+n.businessMemberCount,0)}function Mi(e){return e.length===0?0:Math.max(1,Hf(e))}function Vf(e){let t=ht(e.containerPath.node.loc),n=pc(e.source,e.containerPath.node.start,e.containerPath.node.end),r=yt(e.input,e.containerKind,e.sourceKind,t),o=yt(e.input,e.containerKind,"placement-unit",t);return{placementKey:r,placementUnitKey:o,version:e.input.version,containerKey:r,independent:Mi(e.members)<=1,memberCount:Mi(e.members),sourceRange:t,sourceHash:n,relation:"append",containerSourceRange:t,containerSourceHash:n,anchorSourceRange:null,anchorSourceHash:null,members:e.members}}function ok(e){let t=ht(e.expression.node.loc),n=pc(e.source,e.expression.node.start,e.expression.node.end),r=yt(e.input,"virtual-route-root","atomic-expression",t),o=yt(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:yt(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 Wf(e,t){let n=ht(t.node.loc),r=pc(e.source,t.node.start,t.node.end);return!n||!r?null:{kind:"expression",documentVersion:e.version,sourceRange:n,sourceHash:r}}function sc(e,t,n,r,o){let i=Wf(e,o);if(!i)return vt(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=ik(e,n,s),c=Qa(a),l={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:Yf(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 ik(e,t,n){if(t.members.length===0)return[t];let r=[],o=(l,d,f,m,u,g,h=n)=>({...t,placementKey:d,placementUnitKey:f,containerKey:t.placementKey,independent:Mi(g)<=1,memberCount:Mi(g),sourceRange:m,sourceHash:m?cc(e.source,m):null,relation:l,containerSourceRange:h,containerSourceHash:h?cc(e.source,h):null,anchorSourceRange:u,anchorSourceHash:u?cc(e.source,u):null,members:g}),i=t.placementKey,s=t.members.map(l=>yt(e,i,"placement-unit",l.sourceRange)),a=s[0]??t.placementUnitKey,c=s.at(-1)??t.placementUnitKey;r.push(o("prepend",yt(e,i,"prepend",n),a,n,null,[]));for(let l of t.members){let d=l.parentSourceRange??n,f=yt(e,i,"placement-unit",l.sourceRange);r.push(o("before",yt(e,f,"before",l.sourceRange),f,l.sourceRange,l.sourceRange,[l],d)),r.push(o("after",yt(e,f,"after",l.sourceRange),f,l.sourceRange,l.sourceRange,[l],d))}return r.push(o("append",i,c,n,null,[])),r}function ac(e,t,n,r){let o=Wf(e,r);if(!o)return vt(e,[Ve("UNSUPPORTED_PAGE_SHAPE","Route default export does not provide an exact mutation target",{reason:"mutation-target-unavailable"})]);let i=yt(e,n,"empty-container",void 0),s=yt(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=Qa([a]),l={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:Yf(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 vt(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 yt(e,t,n,r){return Gf([e.route,e.entryFile,String(e.version),t,n,r?`${r.startLine}:${r.startColumn}-${r.endLine}:${r.endColumn}`:"no-range"])}function dc(e,t,n){return Gf(["member",e,String(t??-1),String(n??-1)])}function Gf(e){return`pc_${fc("sha256").update(e.join("\0")).digest("hex").slice(0,24)}`}function pc(e,t,n){return t==null||n==null?null:`sha256:${fc("sha256").update(e.slice(t,n)).digest("hex")}`}function cc(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:${fc("sha256").update(e.slice(r+t.startColumn,o+t.endColumn)).digest("hex")}`}function ht(e){return e?{startLine:e.start.line,startColumn:e.start.column,endLine:e.end.line,endColumn:e.end.column}:null}function Yf(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 yk}from"@vcp-dev/contracts";import HF from"node:fs";import GF from"node:path";var ak=/^page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function Yr(e){let t=e.map(r=>hk(r.path)),n=ck(t);return n?t.filter(r=>uk(n,r)).map(r=>({routeId:dk(n,r),entryFile:r})).sort((r,o)=>r.routeId.localeCompare(o.routeId)):[]}function mc(e,t=""){let r=((e??"/").trim()||"/").split(/[?#]/,1)[0]||"/",o=r.startsWith("/")?r:`/${r}`,i=gk(t),s=i&&(o===i||o.startsWith(`${i}/`))?o.slice(i.length)||"/":o,a=s.startsWith("/")?s:`/${s}`;return a==="/"?"/":a.replace(/\/+$/,"")}function ck(e){return e.some(r=>r.startsWith("app/")&&!lk(r))?"app":e.some(r=>r.startsWith("src/app/"))?"src/app":null}function lk(e){return/^(?:src\/)?app\/(?:_vcp|\.vcp)/.test(e)}function uk(e,t){if(!t.startsWith(`${e}/`))return!1;let n=t.slice(t.lastIndexOf("/")+1);return ak.test(n)?t.slice(e.length+1,-n.length-1).split("/").filter(Boolean).every(r=>!r.startsWith("_")&&!r.startsWith(".")):!1}function dk(e,t){let n=t.slice(e.length+1).split("/").slice(0,-1).map(pk).filter(r=>!!r);return n.length===0?"/":`/${n.join("/")}`}function fk(e){return e.startsWith("(")&&e.endsWith(")")}function pk(e){return!e||e.startsWith("@")||e.startsWith("_")||fk(e)?null:mk(e)}function mk(e){return e.replace(/^\((?:\.|\.\.|\.\.\.)\)/,"")}function gk(e){let t=e.trim();return!t||t==="/"?"":(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"")}function hk(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}var Zr=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="PageTemplateManagedSourceError"}};function rt(e,t={}){throw new Zr("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Invalid page-template source (${e}): ${t.path??t.routeId??t.templateId??""}`,{reason:e,...t})}function gc(e){return yk.safeParse(e).success||rt("invalid-template-id",{templateId:e}),Buffer.from(e,"utf8").toString("base64url")}function Zf(e){/^[A-Za-z0-9_-]{1,255}$/.test(e)||rt("invalid-template-key",{path:e});let t;try{t=new TextDecoder("utf-8",{fatal:!0}).decode(Buffer.from(e,"base64url"))}catch{return rt("invalid-template-key",{path:e})}return gc(t)!==e&&rt("noncanonical-template-key",{path:e}),t}function xk(e){let t=mc(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("(")||bk(r)&&!Qf(r)))&&rt("invalid-public-route",{routeId:e}),t}function bk(e){return e.includes("[")||e.includes("]")}function Qf(e){return/^\[\[\.\.\.[^\[\]]+\]\]$|^\[[^\[\]]+\]$/.test(e)}function qf(e){return e.some(Qf)}function ep(e,t,n="app"){n!=="app"&&n!=="src/app"&&rt("invalid-app-root");let r=xk(e),o=gc(t),i=qf(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))&&rt("path-too-long",{path:a}),{appRoot:n,routeRoot:s,templateKey:o,templateEntryFile:a}}function tp(e){return/^(?:src\/)?app\/\.vcp\/page-templates\//.test(e)}function np(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===".")&&rt("invalid-file-path",{path:i}),n.has(i)&&rt("duplicate-file-path",{path:i}),n.set(i,o)}return n}function Li(e){let t=np(e.files),n=Yr([...t.keys()].map(i=>({path:i}))),r=new Map;for(let i of n){if(r.has(i.routeId))throw new Zr("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(!tp(i))continue;let s=/^(app|src\/app)\/\.vcp\/page-templates\/(.+)\/page\.tsx$/.exec(i);s||rt("candidate-must-be-single-page",{path:i});let a=s[1],c=s[2].split("/"),l=qf(c),d=l?c[0]:c.pop(),f=l?c.slice(1):c,m=Zf(d),u=f.length?`/${f.join("/")}`:"/";ep(u,m,a).templateEntryFile!==i&&rt("candidate-path-mismatch",{path:i,routeId:u});let h=r.get(u);(!h||!h.startsWith(`${a}/`))&&rt("canonical-entry-missing",{path:i,routeId:u}),o.push({routeId:u,templateId:m,entryFile:i,canonicalEntryFile:h,appRoot:a})}return o.sort((i,s)=>Di(i.routeId,s.routeId)||Di(i.templateId,s.templateId))}function rp(e){let t=np(e.files),n=Li({files:t}),r=Yr([...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)=>Di(o.context.routeId,i.context.routeId)||(o.context.effectiveTemplateId===void 0?-1:i.context.effectiveTemplateId===void 0?1:Di(o.context.effectiveTemplateId,i.context.effectiveTemplateId)))}function Sk(e){let t=mc(e.selector.routeId),n=rp({files:e.files}),r=n.find(i=>i.context.routeId===t&&i.context.effectiveTemplateId===void 0);(!r||r.entryFile!==e.canonicalEntryFile)&&rt("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||rt("template-selection-not-found",{routeId:t,templateId:e.selector.templateId}),{...o,mode:e.selector.templateId===void 0?"direct":"candidate",effectiveEntryFile:o.entryFile}}function Di(e,t){return e<t?-1:e>t?1:0}import{HOME_PAGE_URL_PATH as _k}from"@vcp-dev/contracts";import{parse as Y_}from"@babel/parser";import{parse as o_}from"@babel/parser";import{FormBlockIdSchema as s_,FormSpecV1Schema as a_}from"@vcp-dev/contracts";var Qr="components/site/generated/forms",c_=`${Qr}/vcp-form-runtime.tsx`,Bi="[A-Za-z0-9][A-Za-z0-9_-]{0,127}",l_=new RegExp(`^${Qr}/form-(${Bi})\\.spec\\.ts$`),u_=new RegExp(`^${Qr}/form-(${Bi})\\.tsx$`),d_=new RegExp(`^@/${Qr}/form-(${Bi})$`),f_=new RegExp(`(?:^|/)${Qr}/form-(${Bi})(?:\\.tsx?)?$`);var p_=Symbol("invalid-literal");import{createHash as h_}from"node:crypto";import{posix as x_}from"node:path";import{parse as S_}from"@babel/parser";import{FormSpecV1Schema as v_}from"@vcp-dev/contracts";var k_=Symbol("dynamic");import{parse as Ek}from"@babel/parser";function ji(e){return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&typeof t.type=="string"):[]}var vk=/^(?:src\/)?app\/(.*)page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function op(e){let t=vk.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 kk(e){let t=e;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function ip(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function Ik(e){let t=e;for(;t&&(t.type==="TSAsExpression"||t.type==="TSSatisfiesExpression"||t.type==="ParenthesizedExpression");)t=t.expression??null;return t}function hc(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(hc);if(t?.type==="ObjectExpression"){let n={};for(let r of ji(t.properties)){if(r.type!=="ObjectProperty"||r.computed)throw new Error("dynamic object property");let o=ip(r.key);if(!o)throw new Error("unsupported object key");n[o]=hc(r.value)}return n}throw new Error(`unsupported static value: ${t?.type??"unknown"}`)}function yc(e,t){let n=[],r=op(t);if(r===null)return{found:!1,seo:null,diagnostics:n};let o;try{o=Ek(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 ji(o.program.body)){let d=l.type==="ExportNamedDeclaration"?l.declaration:l;if(d?.type==="VariableDeclaration")for(let f of ji(d.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=Ik(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 ji(s.properties)){if(l.type!=="ObjectProperty"||l.computed)continue;let d=ip(l.key);if(!(d!=="path"&&d!=="title"&&d!=="description"&&d!=="keywords"&&d!=="meta_tags_json"&&d!=="schema_json"&&d!=="breadcrumbs_json")){if(d==="path"||d==="title"||d==="description"||d==="keywords"){let f=kk(l.value);if(f===void 0){n.push({code:"page-seo.dynamic-field",message:`PAGE_SEO.${d} is not a static string; skipped`});continue}a[d]=f;continue}try{let f=hc(l.value);d==="meta_tags_json"&&f!==null&&typeof f=="object"&&!Array.isArray(f)?a.meta_tags_json=f:d==="schema_json"&&f!==null&&typeof f=="object"?a.schema_json=f:d==="breadcrumbs_json"&&Array.isArray(f)?a.breadcrumbs_json=f:n.push({code:"page-seo.dynamic-field",message:`PAGE_SEO.${d} has unsupported static shape; skipped`})}catch(f){n.push({code:"page-seo.dynamic-field",message:`PAGE_SEO.${d} 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 Ck}from"@babel/parser";var sp=["page","anchor","external","email","phone","group","file"],Rk=["link","cta"],cp=["description","badge","iconKey"],xc=["label","targetType","href","role","openInNewTab","nofollow","children",...cp],wk=new Set(xc);function eo(e){return Array.isArray(e)?e:[]}function qr(e){let t=e;return t?.type==="StringLiteral"&&typeof t.value=="string"?t.value:void 0}function Nk(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function ap(e){let t=e;return t?.type==="BooleanLiteral"&&typeof t.value=="boolean"?t.value:void 0}function bc(e){let t=[],n;try{n=Ck(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 eo(n.program.body)){let s=i.type==="ExportNamedDeclaration"?i.declaration:i;if(s?.type==="VariableDeclaration")for(let a of eo(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 eo(r.elements).forEach((i,s)=>{let a=lp(i,`NAV_ITEMS[${s}]`,t);a&&o.push(a)}),{items:o,diagnostics:t}}function lp(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 eo(e.properties)){if(l.type!=="ObjectProperty"||l.computed)continue;let d=Nk(l.key);d&&(r[d]=l.value)}let o=qr(r.label),i=qr(r.targetType);if(!o)return n.push({severity:"fatal",path:`${t}.label`,message:"label must be a static string"}),null;if(!i||!sp.includes(i))return n.push({severity:"fatal",path:`${t}.targetType`,message:`targetType must be one of ${sp.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 cp){if(r[l]===void 0)continue;let d=qr(r[l]);d!==void 0?s[l]=d: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))wk.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 ${xc.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=[];eo(r.children.elements).forEach((d,f)=>{let m=lp(d,`${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=qr(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=qr(r.role);if(c!==void 0&&(Rk.includes(c)?s.role=c:n.push({severity:"warning",path:`${t}.role`,message:"role ignored: not link/cta"})),r.openInNewTab!==void 0){let l=ap(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=ap(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 Pk}from"@babel/parser";function to(e){return Array.isArray(e)?e:[]}function up(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression";)t=t.expression;return t?.type==="ArrayExpression"?t:void 0}function Ak(e){let t;try{t=Pk(e,{sourceType:"module",plugins:["typescript","jsx"],tokens:!0})}catch{return{status:"unsupported"}}let n=[];for(let o of to(t.program.body)){let i=o.type==="ExportNamedDeclaration"?o.declaration:o;if(i?.type==="VariableDeclaration")for(let s of to(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=up(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 Sc(e,t){let n=dp(t);if(!n)return{status:"unsupported",source:e};let r=Ak(e);if(r.status!=="ok")return{status:r.status,source:e};let o=r.array;if(bc(e).diagnostics.some(({severity:l})=>l==="fatal"))return{status:"unsupported",source:e};let s=[],a=l=>{let d=to(l.elements);for(let[f,m]of d.entries()){if(Fk(m,n)){let g=d[f+1],h=d[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 u=Tk(m);u&&a(u)}};if(a(o),s.length===0)return{status:"not_found",source:e};let c=e;for(let l of s.sort((d,f)=>f.start-d.start))c=c.slice(0,l.start)+c.slice(l.end);return{status:"removed",source:c,removedCount:s.length}}function Tk(e){if(e.type==="ObjectExpression")for(let t of to(e.properties)){if(t.type!=="ObjectProperty")continue;let n=t.key;if((n?.name??n?.value)==="children")return up(t.value)}}function dp(e){let t=e.trim();return t.startsWith("/")?t==="/"?t:t.replace(/\/+$/,""):null}function Fk(e,t){if(e.type!=="ObjectExpression")return!1;let n,r;for(let o of to(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"&&dp(n??"")===t}import{estimateNavLabelWidth as __}from"@vcp-dev/contracts";import{parse as D_}from"@babel/parser";var Ok="components/site/generated/",no=[".tsx",".ts",".jsx",".js"];function fp(e){if(e.expectedUrlPath===_k)return{ok:!1,code:"HOME_PAGE_LOCKED",message:"The homepage source is protected from deletion."};let t=new Set(Yr(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=yc(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=Li({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=Mk(e.files);if(!i.ok)return i.error;let s=i.graph,a=jk(o,s),c=$k(o,a,s),l=[...a].filter(h=>!c.has(h)).sort((h,S)=>h.localeCompare(S)),d=[...o,...[...c].sort((h,S)=>h.localeCompare(S))],f=new Set(d),m=d.map(h=>({operation:"delete",file:h})),u=[],g=[];for(let[h,S]of Object.entries(e.files))if(!f.has(h)){if(S.includes("NAV_ITEMS")){let E=Sc(S,e.expectedUrlPath);E.status==="removed"?(m.push({operation:"upsert",file:h,content:E.source}),u.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:d,updatedFiles:u,preservedSharedFiles:l,warnings:g}}function Mk(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")||!Dk(r))continue;let s=Sn(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(Lk(c))continue;let l=hn(r,c),d=Bk(l,t);if(!d)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(d)}n.set(r,a)}return{ok:!0,graph:n}}function Dk(e){let t=e.toLowerCase();return no.some(n=>t.endsWith(n))}function Lk(e){return!!(/\.([a-z0-9]+)$/i.exec(e)&&!no.some(n=>e.endsWith(n)))}function Bk(e,t){let n=e.replace(/\\/g,"/");return(no.some(o=>n.endsWith(o))?[n]:[...no.map(o=>`${n}${o}`),...no.map(o=>`${n}/index${o}`)]).find(o=>t.has(o))??null}function jk(e,t){let n=new Set,r=[...e].flatMap(o=>[...t.get(o)??[]]);for(;r.length>0;){let o=r.pop();!o.startsWith(Ok)||n.has(o)||(n.add(o),r.push(...t.get(o)??[]))}return n}function $k(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 fm from"@babel/parser";import*as ue from"@babel/types";import*as ns from"node:path";import*as xe from"@babel/types";function pp(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 _t(e){if(e.path.isObjectPattern()||e.path.isArrayPattern())return Pn(e.path.node,e.identifier.name);if(e.path.isVariableDeclarator()){let n=e.path.node.id;if(xe.isObjectPattern(n)||xe.isArrayPattern(n))return Pn(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(Kk(e.path,n))return!0}if(t.isFunction()||t.isVariableDeclarator())return!1;t=t.parentPath}return!1}function Pn(e,t,n=!1){return xe.isIdentifier(e)?e.name===t&&n:xe.isObjectPattern(e)?e.properties.some(r=>xe.isObjectProperty(r)?Pn(r.value,t,n):Pn(r.argument,t,n)):xe.isArrayPattern(e)?e.elements.some(r=>{if(!r)return!1;let o=xe.isRestElement(r)?r.argument:r;return Pn(o,t,n)}):xe.isAssignmentPattern(e)?Pn(e.left,t,!0):xe.isRestElement(e)?Pn(e.argument,t,n):!1}function sr(e,t){if(e.path.isObjectPattern()){if(t){let r=kt(e.path.node,t.base),[o,...i]=r??[];if(o?.kind==="property")return{propName:o.name,remainingPath:[...i,...t.path],hasDefault:_t(e)}}return t?{propName:t.base,remainingPath:t.path,hasDefault:_t(e)}:null}if(e.path.isVariableDeclarator()){let r=e.path.get("init");if(r?.isExpression()){let o=mp(r),i=!1,s=o?o.initBinding&&Ec(o.initBinding)?(i=_t(o.initBinding),[...o.initPathPrefix]):o.initBinding?(()=>{let c=sr(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=kt(e.path.node.id,e.identifier.name);if(s&&a){let c=[...s,...a],[l,...d]=c;return!l||l.kind!=="property"?null:{propName:l.name,remainingPath:[...d,...t?.path??[]],hasDefault:i||_t(e)}}}}let n=Xk(e);if(n){let r=Vk(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||_t(e)}}if(n.findParent(s=>s.isVariableDeclarator()))return null;let o=Uk(e);if(o){let[s,...a]=o;return!s||s.kind!=="property"?null:{propName:s.name,remainingPath:[...a,...t?.path??[]],hasDefault:_t(e)}}let i=ro(n.node);return i?{propName:i,remainingPath:t?.path??[],hasDefault:_t(e)}:null}if(Ec(e)){let[r,...o]=t?.path??[];return!r||r.kind!=="property"?null:{propName:r.name,remainingPath:o,hasDefault:_t(e)}}return null}function Vk(e,t){let n=e.findParent(d=>d.isVariableDeclarator());if(!n?.isVariableDeclarator())return null;let r=n.get("init");if(!r?.isExpression())return null;let o=mp(r);if(!o)return null;let{initBinding:i,initPathPrefix:s}=o;if(!i)return null;let a=!1,c=Ec(i)?(a=_t(i),[...s]):(()=>{let d=sr(i,{kind:"identifier",expression:i.identifier.name,base:i.identifier.name,path:[]});return a=d?.hasDefault??!1,d?[{kind:"property",name:d.propName},...d.remainingPath,...s]:null})();if(!c)return null;let l=kt(n.node.id,t.identifier.name);return l?{path:[...c,...l],hasDefault:a||_t(t)}:null}function mp(e){if(e.isIdentifier())return{initBinding:e.scope.getBinding(e.node.name),initPathPrefix:[]};if(!e.isMemberExpression())return null;let t=zk(e.node);return t?{initBinding:e.scope.getBinding(t.base),initPathPrefix:t.path}:null}function Ec(e){return e.path.isIdentifier()&&e.path.key===0&&Array.isArray(e.path.container)&&e.path.parentPath?.isFunction()===!0}function Kk(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function Uk(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=kt(i.node,t);if(a)return a}return null}function gp(e,t,n){if(e.path.isVariableDeclarator()){let a=e.path.get("id");if(!Array.isArray(a)&&(a.isObjectPattern()||a.isArrayPattern())){let c=$i(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=ro(a.node);if(!c||n&&c!==n)continue;let l=a.get("value");if(!l.isAssignmentPattern())continue;let d=l.get("right");if(d.isExpression())return{propName:c,componentName:t,expressionPath:d,displayPath:`${t}.${c}.default`}}let r=Jk(e);if(!r)return null;let o=r.parentPath;if(!o?.isObjectProperty())return null;let i=ro(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 $i(e,t){if(e.isObjectPattern()){for(let n of e.get("properties"))if(n.isObjectProperty()){let r=ro(n.node),o=n.get("value");if(o.isAssignmentPattern()){let i=o.get("left"),s=o.get("right");if(r&&!Array.isArray(i)&&kt(i.node,t)&&!Array.isArray(s)&&s.isExpression())return{propName:r,expressionPath:s}}if(!Array.isArray(o)&&(o.isObjectPattern()||o.isArrayPattern())){let i=$i(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=$i(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=$i(r,t);if(o)return o}}return null}function kt(e,t,n=[]){if(xe.isIdentifier(e))return e.name===t?n:null;if(xe.isObjectPattern(e)){for(let r of e.properties)if(xe.isObjectProperty(r)){let o=ro(r);if(!o)continue;let i=kt(r.value,t,[...n,{kind:"property",name:o}]);if(i)return i}else if(xe.isRestElement(r)){let o=kt(r.argument,t,n);if(o)return o}}if(xe.isArrayPattern(e))for(let r=0;r<e.elements.length;r+=1){let o=e.elements[r];if(!o)continue;let i=xe.isRestElement(o)?o.argument:o,s=kt(i,t,[...n,{kind:"index",index:r}]);if(s)return s}return xe.isAssignmentPattern(e)?kt(e.left,t,n):null}function Jk(e){if(!e.path.isIdentifier())return null;let t=e.path.parentPath;return t?.isAssignmentPattern()&&t.node.left===e.path.node?t:null}function Xk(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 ro(e){return e.computed?null:xe.isIdentifier(e.key)?e.key.name:xe.isStringLiteral(e.key)?e.key.value:null}function zk(e){let t=[],n=e;for(;xe.isMemberExpression(n);){if(n.computed)if(xe.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(xe.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(xe.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return xe.isIdentifier(n)?{base:n.name,path:t}:null}import*as Sp from"@babel/parser";import Ic from"@babel/traverse";import*as ar from"@babel/types";import*as ae from"@babel/types";function Ui(e,t=[]){if(e.isIdentifier()){let n=e.scope.getBinding(e.node.name);return n?Vi(n,t):null}if(e.isMemberExpression()){let n=Qk(e.node),r=Hk(e.node);if(!n||r===null)return null;let o=e.scope.getBinding(n);return o?Vi(o,[...r,...t]):null}return e.isAwaitExpression()||kc(e.node)?an(eI(e.node),t,"awaited or fetched expression"):null}function Hk(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 Vi(e,t=[]){let n=Wk(e,t);if(n)return n;let r=Gk(e,t);if(r)return r;let o=Yk(e,t);return o||null}function io(e){return e?.kind==="api-source"}function Wk(e,t){if(e.path.isVariableDeclarator()&&ae.isIdentifier(e.path.node.id)){let s=e.path.get("init");if(s?.isCallExpression()&&vc(s.node)&&t[0]?.kind==="property"&&t[0].name==="data")return an(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)&&xp(c)==="data"&&oo(c.value,e.identifier.name)),a=e.path.get("init");if(s&&a?.isCallExpression()&&vc(a.node))return an(e.identifier.name,t,"query hook data binding")}let n=Zk(e);if(!n||xp(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()||!vc(i.node)?null:an(e.identifier.name,t,"query hook data binding")}function Gk(e,t){if(e.path.isVariableDeclarator()&&ae.isArrayPattern(e.path.node.id)){let a=e.path.get("init");if(!a?.isCallExpression()||!yp(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:hp(e,l.name)?an(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()||!yp(o.node)||n.node.elements.findIndex(a=>a===e.path.node)!==0)return null;let s=n.node.elements[1];return ae.isIdentifier(s)&&hp(e,s.name)?an(e.identifier.name,t,"state setter is updated by API data"):null}function Yk(e,t){let n=e.path.isVariableDeclarator()?e.path:e.path.findParent(o=>o.isVariableDeclarator());if(!n?.isVariableDeclarator())return null;let r=n.get("init");return r?.isExpression()?r.isAwaitExpression()?an(e.identifier.name,t,"awaited binding result"):kc(r.node)?an(e.identifier.name,t,"fetch-backed binding result"):null:null}function Zk(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 oo(e,t){return ae.isIdentifier(e)?e.name===t:ae.isAssignmentPattern(e)?oo(e.left,t):ae.isObjectPattern(e)?e.properties.some(n=>ae.isObjectProperty(n)?oo(n.value,t):oo(n.argument,t)):ae.isArrayPattern(e)?e.elements.some(n=>!!n&&oo(ae.isRestElement(n)?n.argument:n,t)):!1}function hp(e,t){let n=!1,r=!1;return e.scope.path.traverse({CallExpression(i){kc(i.node)&&(n=!0),(qk(i.node.callee,t)||i.node.arguments.some(s=>ae.isIdentifier(s)&&s.name===t))&&(r=!0)}}),n&&r}function vc(e){let t=Ji(e.callee);return t==="useQuery"||t==="useSWR"||t==="useSuspenseQuery"}function yp(e){return Ji(e.callee)==="useState"}function kc(e){return Ki(e,t=>ae.isCallExpression(t)&&Ji(t.callee)==="fetch")}function Qk(e){let t=e;for(;ae.isMemberExpression(t);)t=t.object;return ae.isIdentifier(t)?t.name:null}function xp(e){return e.computed?null:ae.isIdentifier(e.key)?e.key.name:ae.isStringLiteral(e.key)?e.key.value:null}function Ji(e){return ae.isIdentifier(e)?e.name:ae.isMemberExpression(e)&&ae.isIdentifier(e.property)?e.property.name:null}function qk(e,t){return Ki(e,n=>ae.isIdentifier(n)&&n.name===t)}function Ki(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)&&Ki(i,t))return!0;continue}if(ae.isNode(o)&&Ki(o,t))return!0}return!1}function eI(e){return ae.isIdentifier(e)?e.name:ae.isCallExpression(e)?Ji(e.callee)??"api":ae.isAwaitExpression(e)?"awaited-api":"api"}function an(e,t,n){return{kind:"api-source",readonly:!0,sourceId:e,displayPath:tI(e,t),reason:n}}function tI(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}var Ep=typeof Ic=="function"?Ic:Ic.default;function vp(e,t){let n=Ip(e);if(!n)return{allowed:!0};let r=!1;return Ep(n,{CallExpression(o){if(!Cp(o.node,t.sourceRange)||!nI(o.node))return;let i=o.get("callee");if(!i.isMemberExpression())return;let s=i.get("object");Array.isArray(s)||!s.isExpression()||io(Ui(s))&&(r=!0,o.stop())}}),r?{allowed:!1,reason:"Cannot add data-backed items to a dynamic API list"}:{allowed:!0}}function kp(e,t){let n=Ip(e);if(!n)return{allowed:!0};let r=!1;return Ep(n,{JSXExpressionContainer(o){Cp(o.node,t.sourceRange)&&(ar.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 Ip(e){try{return Sp.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function nI(e){let t=e.callee;return ar.isMemberExpression(t)&&ar.isIdentifier(t.property)&&t.property.name==="map"}function Cp(e,t){let n=e.loc;return n?bp({line:n.start.line,column:n.start.column},{line:t.startLine,column:t.startColumn})>=0&&bp({line:n.end.line,column:n.end.column},{line:t.endLine,column:t.endColumn})<=0:!1}function bp(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 J from"@babel/types";import*as Rp from"@babel/parser";import Cc from"@babel/traverse";import*as Ae from"@babel/types";import*as cr from"node:path";var It=typeof Cc=="function"?Cc:Cc.default;function Je(e){try{return Rp.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function Rc(e){return e.computed?Ae.isStringLiteral(e.key)||Ae.isNumericLiteral(e.key)?String(e.key.value):null:rI(e.key)}function rI(e){return Ae.isIdentifier(e)?e.name:Ae.isStringLiteral(e)||Ae.isNumericLiteral(e)?String(e.value):null}function An(e){return Ae.isParenthesizedExpression(e)||Ae.isTSAsExpression(e)||Ae.isTSSatisfiesExpression(e)||Ae.isTSNonNullExpression(e)||Ae.isTSTypeAssertion(e)?An(e.expression):Ae.isExpression(e)?e:null}function wc(e){if(Ae.isIdentifier(e))return[e.name];if((Ae.isMemberExpression(e)||Ae.isOptionalMemberExpression(e))&&!e.computed&&Ae.isIdentifier(e.property)){let t=An(e.object),n=t?wc(t):null;return n?[...n,e.property.name]:null}return null}function Tn(e,t){return t.startsWith("@/")?t.slice(2).replace(/\\/g,"/"):t.startsWith(".")?cr.normalize(cr.join(cr.dirname(e),t)).replace(/\\/g,"/"):t}function at(e,t){return Xi(e)===Xi(t)}function Xi(e){let t=lr(e);return t.endsWith("/index")?t.slice(0,-6):t}function lr(e){return e.replace(/\.(tsx|ts|jsx|js)$/,"")}function Pp(e,t,n){let r=_p(e,t);if(Op(e,r),Mp(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 It(e,{JSXElement(s){jp(s,r)&&o.push(s)}}),o.length!==1?{ok:!1,reason:"Cannot move prop-backed repeat child without a single unambiguous component call site"}:zi(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 Ap(e,t){let n=new Map,r=i=>{let s=ur(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 oI(i,n))o=r(s)||o}return[...n.values()]}function oI(e,t){let n=[],r=iI(e,t);for(let o of e.ast.program.body){if(J.isExportDefaultDeclaration(o)&&J.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=so(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(J.isExportNamedDeclaration(o)&&o.source&&typeof o.source.value=="string"){let i=Tn(e.file,o.source.value);for(let s of o.specifiers){if(J.isExportNamespaceSpecifier(s)){let l=cn(s.exported);for(let d of t.values())at(d.file,i)&&n.push({file:e.file,namespace:Nc(l,d.namespace),exportName:d.exportName});continue}if(!J.isExportSpecifier(s))continue;let a=cn(s.local),c=[...t.values()].filter(l=>at(l.file,i)&&Fn(l.namespace,a));if(c.length>0){let l=cn(s.exported);for(let d of c){let f=so(d.namespace,a,l);f&&n.push({file:e.file,namespace:f,exportName:d.exportName})}continue}t.has(ur({file:i,exportName:a}))&&n.push({file:e.file,exportName:cn(s.exported)})}continue}if(J.isExportNamedDeclaration(o)&&!o.source){for(let i of o.specifiers){if(!J.isExportSpecifier(i))continue;let s=cn(i.local),a=r.get(s)??[];if(a.length>0){let c=cn(i.exported);n.push({file:e.file,exportName:c});for(let l of a){let d=so(l.namespace,s,c);d&&n.push({file:e.file,namespace:d,exportName:l.exportName})}}}continue}if(J.isExportAllDeclaration(o)&&typeof o.source.value=="string"){let i=Tn(e.file,o.source.value),s=o.exported;if(s){let a=cn(s);for(let c of t.values())at(c.file,i)&&n.push({file:e.file,namespace:Nc(a,c.namespace),exportName:c.exportName});continue}for(let a of t.values())at(a.file,i)&&(a.namespace||a.exportName!=="default")&&n.push({file:e.file,namespace:a.namespace,exportName:a.exportName})}}return n}function Nc(e,t){return t?`${e}.${t}`:e}function Fn(e,t){return e===t||e?.startsWith(`${t}.`)===!0}function so(e,t,n){return!Fn(e,t)||!e?null:e===t?n:`${n}${e.slice(t.length)}`}function iI(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(!J.isImportDeclaration(i)||typeof i.source.value!="string")continue;let s=Tn(e.file,i.source.value);for(let a of i.specifiers){if(J.isImportDefaultSpecifier(a)){let c=t.get(ur({file:s,exportName:"default"}));c&&r(a.local.name,c);let l=[...t.values()].filter(d=>at(d.file,s)&&Fn(d.namespace,"default"));for(let d of l){let f=so(d.namespace,"default",a.local.name);f&&r(a.local.name,{...d,namespace:f})}continue}if(J.isImportSpecifier(a)){let c=cn(a.imported),l=[...t.values()].filter(f=>at(f.file,s)&&Fn(f.namespace,c));for(let f of l)r(a.local.name,f);let d=t.get(ur({file:s,exportName:c}));d&&r(a.local.name,d);continue}if(J.isImportNamespaceSpecifier(a))for(let c of t.values())at(c.file,s)&&r(a.local.name,{...c,namespace:Nc(a.local.name,c.namespace)})}}let o=!0;for(;o;){o=!1;for(let i of e.ast.program.body)if(J.isVariableDeclaration(i))for(let s of i.declarations){if(!J.isIdentifier(s.id)||!s.init)continue;let a=An(s.init);if(!a||!J.isIdentifier(a))continue;let c=n.get(a.name)??[];if(c.length===0)continue;let l=n.get(s.id.name)??[],d=new Set(l.map(ur));for(let f of c){let m=so(f.namespace,a.name,s.id.name),u=m?{...f,namespace:m}:f,g=ur(u);d.has(g)||(r(s.id.name,u),d.add(g),o=!0)}}}return n}function ur(e){let t=e.namespace?`${e.namespace}.${e.exportName}`:e.exportName;return`${Xi(e.file)}#${t}`}function cn(e){return J.isIdentifier(e)?e.name:e.value}function Tp(e,t){for(let n of e.program.body){if(J.isExportDefaultDeclaration(n)){let o=n.declaration;if((J.isFunctionDeclaration(o)||J.isClassDeclaration(o))&&o.id?.name===t)return{exportName:"default"};if(J.isIdentifier(o)&&o.name===t)return{exportName:"default"}}if(!J.isExportNamedDeclaration(n))continue;let r=n.declaration;if((J.isFunctionDeclaration(r)||J.isClassDeclaration(r))&&r.id?.name===t)return{exportName:t};if(J.isVariableDeclaration(r)){for(let o of r.declarations)if(J.isIdentifier(o.id,{name:t}))return{exportName:t}}for(let o of n.specifiers){if(!J.isExportSpecifier(o)||o.local.name!==t)continue;return{exportName:J.isIdentifier(o.exported)?o.exported.name:o.exported.value}}}return null}function Ac(e){let t=sI(e),n=[],r=Mp(e.ast,t);return It(e.ast,{JSXElement(o){at(e.file,e.sourceFile)&&zi(o)===e.sourceComponent||jp(o,t)&&n.push({file:e.file,path:o})}}),{callSites:n,hasUnsafeReference:r}}function Fp(){return{localBindings:new Set,namespaceMembers:new Map,hasUnsupportedAlias:!1}}function _p(e,t){let n=Fp();return It(e,{Program(r){let o=r.scope.getBinding(t);o&&n.localBindings.add(o),r.stop()}}),n}function sI(e){let t=Fp();return at(e.file,e.sourceFile)&&aI(t,_p(e.ast,e.sourceComponent)),It(e.ast,{ImportDeclaration(n){let r=n.node,o=r.source.value;if(typeof o!="string")return;let i=Tn(e.file,o),s=e.componentIdentities.filter(a=>at(a.file,i));if(s.length!==0)for(let a of r.specifiers){let c=n.scope.getBinding(a.local.name);if(c){if(J.isImportDefaultSpecifier(a)&&s.some(l=>l.exportName==="default")&&t.localBindings.add(c),J.isImportDefaultSpecifier(a)){let l=s.filter(d=>Fn(d.namespace,"default"));if(l.length>0){let d=t.namespaceMembers.get(c)??new Set;for(let f of l){let m=Np(f,"default");m&&d.add(m)}t.namespaceMembers.set(c,d)}continue}if(J.isImportSpecifier(a)){let l=J.isIdentifier(a.imported)?a.imported.name:a.imported.value,d=s.filter(f=>Fn(f.namespace,l));if(d.length>0){let f=t.namespaceMembers.get(c)??new Set;for(let m of d){let u=Np(m,l);u&&f.add(u)}t.namespaceMembers.set(c,f);continue}s.some(f=>!f.namespace&&f.exportName===l)&&t.localBindings.add(c);continue}if(J.isImportNamespaceSpecifier(a))for(let l of s){let d=l.namespace?`${l.namespace}.${l.exportName}`:l.exportName,f=t.namespaceMembers.get(c)??new Set;f.add(d),t.namespaceMembers.set(c,f)}}}}}),Op(e.ast,t),t}function aI(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 Op(e,t){It(e,{VariableDeclarator(n){if(!n.node.init)return;let r=An(n.node.init);if(r){if(J.isIdentifier(n.node.id)){let o=_n(r,t,n),i=n.scope.getBinding(n.node.id.name);o&&i&&Pc(t,i,o);return}if(J.isObjectPattern(n.node.id)){let o=_n(r,t,n);o?.unsupported||o?.local?t.hasUnsupportedAlias=!0:o&&o.namespaceMembers.size>0&&Bp(n.node.id,o.namespaceMembers,t,n)}}}})}function Mp(e,t){if(t.hasUnsupportedAlias)return!0;let n=!1;return It(e,{ReferencedIdentifier(r){if(n){r.stop();return}cI(r)||!r.isIdentifier()||!Dp(r,t)||lI(r,t)||uI(r)||(n=!0,r.stop())}}),n}function cI(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 Dp(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)&&_n(r.node,t,r)?r:null}function lI(e,t){let n=e.findParent(c=>c.isVariableDeclarator());if(!n?.isVariableDeclarator())return!1;let r=n.get("init");if(!r?.isExpression()||!wp(e,r))return!1;let o=Dp(e,t);if(!o)return!1;if(An(r.node)===o.node)return!!_n(r.node,t,r);let s=e.findParent(c=>c.isObjectProperty());if(!s?.isObjectProperty())return!1;let a=s.get("value");return a.isExpression()&&wp(e,a)&&!!_n(a.node,t,a)}function uI(e){let t=e.parentPath;return t?.isExportDefaultDeclaration()&&t.node.declaration===e.node?!0:!!(t?.isExportSpecifier()&&t.node.local===e.node)}function wp(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function _n(e,t,n){let r=An(e);if(!r)return null;if(J.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(J.isObjectExpression(r))return dI(r,t,n);let o=wc(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?Lp(s,o.slice(1).join(".")):null}function dI(e,t,n){let r=new Set,o=!1;for(let i of e.properties){if(!J.isObjectProperty(i))continue;let s=Rc(i);if(!s||!J.isExpression(i.value)){J.isExpression(i.value)&&(o||=_n(i.value,t,n)!==null);continue}let a=_n(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 Lp(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 Pc(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 Bp(e,t,n,r){for(let o of e.properties){if(J.isRestElement(o)){if(J.isIdentifier(o.argument)){let c=r.scope.getBinding(o.argument.name);c&&Pc(n,c,{local:!1,namespaceMembers:new Set(t),unsupported:!1})}else n.hasUnsupportedAlias=!0;continue}if(!J.isObjectProperty(o))continue;let i=Rc(o);if(!i){n.hasUnsupportedAlias=!0;continue}let s=Lp(t,i);if(!s)continue;n.hasUnsupportedAlias||=s.unsupported;let a=J.isAssignmentPattern(o.value)?o.value.left:o.value;if(J.isIdentifier(a)){let c=r.scope.getBinding(a.name);c&&Pc(n,c,s);continue}if(J.isObjectPattern(a)&&s.namespaceMembers.size>0){Bp(a,s.namespaceMembers,n,r);continue}n.hasUnsupportedAlias=!0}}function Np(e,t){if(!Fn(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 jp(e,t){let n=e.node.openingElement.name;if(J.isJSXIdentifier(n)){let o=e.scope.getBinding(n.name);return!!(o&&t.localBindings.has(o))}let r=$p(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 $p(e){if(J.isJSXIdentifier(e))return[e.name];if(J.isJSXMemberExpression(e)){let t=$p(e.object);return t?[...t,e.property.name]:null}return null}function zi(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()&&J.isIdentifier(n.node.id))return n.node.id.name}return null}function Vp(e,t){let n=Je(e);if(!n||!t.tag||!t.importedFrom||!t.exportName)return Number.POSITIVE_INFINITY;let r=Ac({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 he(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 ge(e){return typeof e.start=="number"&&typeof e.end=="number"?{start:e.start,end:e.end}:null}function Ot(e,t){let n=ge(e);return!!(n&&ct(t,n))}function ct(e,t){return t.start>=e.start&&t.end<=e.end}function xt(e,t){let n=se(e,he(t));return n.ok&&n.match.path.isJSXElement()?n.match.path:Hi(e,t)}function dr(e,t){let n=ge(t);return n?e.slice(n.start,n.end):""}function Kp(e,t){return e.start===t.start&&e.end===t.end}function Hi(e,t){let n=null;return It(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 Wi(e,t){return Tc(e,t).length>0}function Gi(e,t){let n=ge(e.node),r=ge(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()&&!fI(o,n,r)))return!0;o=o.parentPath}return!1}function fI(e,t,n){let r=ge(e.node.consequent);if(r&&ct(r,t)&&!ct(r,n))return!1;let o=e.node.alternate?ge(e.node.alternate):null;return!(o&&ct(o,t)&&!ct(o,n))}function Tc(e,t){let n=ge(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=ge(o.node.consequent),a=ge(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()&&Fc(o.node.operator)){let s=ge(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 Fc(e){return e==="&&"||e==="||"||e==="??"}function Up(e,t){let n=ge(e.consequent);if(n&&ct(n,t))return n;let r=ge(e.alternate);return r&&ct(r,t)?r:null}function Jp(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=>lr(a.file)));if(!t.has(lr(e.sourceFile))||!t.has(lr(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(lr(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=Tp(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=Ap(r,{file:e.sourceFile,exportName:n.exportName}),i=[];for(let a of r){let c=Ac({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!at(s.file,e.targetFile)||zi(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 xI}from"@vcp-dev/contracts";function Yi(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 ao();let a=s.target,c=a.locator;if(a.sourceKind==="repeat-template"){let l=o?.instanceIndex;if(l===void 0)return ao();let d=pI(a,l,o?.instanceCount);if(!d)return ao();c=d}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"?ao():{ok:!0,target:{kind:"jsx-attribute"}}}function ao(){return{ok:!1,code:"unsupported-binding",reason:"Property does not have a safe typed binding write target for this scope and operation"}}function pI(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 Mt from"@babel/types";import{SiteEditSetPropsParamsSchema as mI}from"@vcp-dev/contracts";function Xp(e){let t=e.changes??(e.change?[e.change]:[]);if(!mI.safeParse({kind:"set-props",scope:"selection",changes:t}).success)return co("invalid-change","Repeat property changes are invalid");if(t.length!==1||t[0].name!==e.target.propertyName)return co("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=ke(e.source,"value");if(!o.ok)return co("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 co("unsupported-object",`Repeat item ${s} is not a writable object expression`);let l=s===e.target.sourceItemIndex?gI(r):hI(c.match.path.node,r.name);if(!l)return co("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 gI(e){return e.operation==="set"?{kind:"value",value:e.value}:{kind:"undefined"}}function hI(e,t){let n=e.properties.filter(i=>Mt.isObjectProperty(i)&&yI(i.key)===t);if(n.length>1)return null;let r=n[0];if(!r)return{kind:"undefined"};if(!Mt.isExpression(r.value))return null;let o=Ft(r.value);return o.status==="undefined"?{kind:"undefined"}:o.status!=="resolved"?null:{kind:"value",value:o.value}}function yI(e){return Mt.isIdentifier(e)?e.name:Mt.isStringLiteral(e)?e.value:Mt.isNumericLiteral(e)?String(e.value):null}function co(e,t){return{ok:!1,errorCode:e,reason:t}}function zp(e){if(e.change.name!=="className"&&e.change.name!=="class")return lo("unsupported-owner",`No specialized property owner is available for '${e.change.name}'`);let t=e.classNameSource;if(!t||t.filePath!==e.node.file)return lo("owner-source-unavailable","className source details are unavailable for the selected node");if(e.change.name==="class"&&t.sourceKind==="missing")return lo("owner-source-unavailable","The class alias requires an existing className source");if(t.sourceKind==="expression")return lo("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 lo("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 lo(e,t){return{ok:!1,errorCode:e,reason:t}}async function Wp(e){let t=xI.safeParse({kind:"set-props",scope:e.scope,changes:e.changes});if(!t.success)return ln("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 ln("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 bI(e,r);if(o){if(!o.ok)return ln("owner-plan-failed",o.reason);Hp(n,o.steps);continue}let i=await e.getPropertyState(e.node.key,r.name,e.selectionRef);if(!i)return ln("missing-property-state",`No authoritative property state is available for '${r.name}'`);if(i.status==="blocked")return ln("readonly-property",i.diagnostic?.message??`Property '${r.name}' is not writable`);if(vI(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=Yi({state:i,scope:e.scope,operation:r.operation,selectionRef:e.selectionRef,repeatTarget:s});if(!a.ok)return ln(a.code,a.reason);let c=a.target;if(c.kind==="value-binding"&&r.operation==="set"){_c(n,{type:"update-value",order:n.length,file:c.file,locator:c.locator,value:r.value});continue}if(c.kind==="repeat-property"){let l=Xp({source:e.getFileContent(c.target.sourceFile),target:c.target,changes:[r]});if(!l.ok)return ln("repeat-target-failed",l.reason);Hp(n,l.steps);continue}_c(n,{type:"set-property-changes",order:n.length,file:e.node.file,locator:SI(e.node),scope:e.scope,changes:[r]})}return n.forEach((r,o)=>{r.order=o}),EI(n)?ln("step-conflict","Property changes resolve to conflicting write steps"):{ok:!0,steps:n}}async function bI(e,t){return t.name!=="className"&&t.name!=="class"?null:zp({node:e.node,change:t,classNameSource:e.classNameSource})}function SI(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 EI(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 Hp(e,t){for(let n of t)_c(e,{...n,order:e.length})}function _c(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 vI(e,t){if(t.operation!=="set"||e.status!=="direct")return!1;let n=e.attribute?.resolution;return n?.status==="resolved"?Oc(n.value,t.value):e.attribute?.source===null&&e.attribute.value===t.value}function Oc(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)=>Oc(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=>Oc(n[i],r[i]))}return!1}function ln(e,t){return{ok:!1,errorCode:e,reason:t}}import*as pr from"@babel/types";import*as W from"@babel/types";function Mc(e,t,n){let r=xt(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(!W.isIdentifier(l)||l.name!=="map"||c.computed)return null;let d=a.get("object"),f=dr(e,d.node),m=r.node.params.map(h=>dr(e,h)),u=ge(i.node),g=ge(r.node);return!f||m.some(h=>h.length===0)||!u||!g?null:{callStart:u.start,callEnd:u.end,callbackStart:g.start,callbackEnd:g.end,collectionExpression:f,callbackParams:m,mapOperator:W.isOptionalMemberExpression(c)&&c.optional?"?.map":".map",collectionNeedsParens:Zi(d.node),callbackPath:r,collectionPath:d}}function uo(e,t){return!!(e&&t&&e.callStart===t.callStart&&e.callEnd===t.callEnd&&e.callbackStart===t.callbackStart&&e.callbackEnd===t.callbackEnd)}function kI(e,t){let n=ge(e.node);return n?II(t).some(r=>{let o=ge(r);return r===e.node||!!(o&&o.start===n.start&&o.end===n.end)}):!1}function II(e){let t=e.callbackPath.node.body;return W.isBlockStatement(t)?un(t.body):dn(t)}function un(e){let t=[];for(let n of e){if(W.isReturnStatement(n)){n.argument&&t.push(...dn(n.argument));continue}if(W.isBlockStatement(n)){t.push(...un(n.body));continue}if(W.isIfStatement(n)){let r=W.isBlockStatement(n.consequent)?n.consequent.body:[n.consequent];if(t.push(...un(r)),n.alternate){let o=W.isBlockStatement(n.alternate)?n.alternate.body:[n.alternate];t.push(...un(o))}continue}if(W.isSwitchStatement(n)){for(let r of n.cases)t.push(...un(r.consequent));continue}W.isTryStatement(n)&&(t.push(...un(n.block.body)),n.handler&&t.push(...un(n.handler.body.body)),n.finalizer&&t.push(...un(n.finalizer.body)))}return t}function dn(e){return W.isJSXElement(e)?CI(e)?Gp(e.children):[e]:W.isJSXFragment(e)?Gp(e.children):W.isParenthesizedExpression(e)||W.isTSAsExpression(e)||W.isTSSatisfiesExpression(e)||W.isTSNonNullExpression(e)||W.isTSTypeAssertion(e)?dn(e.expression):W.isConditionalExpression(e)?[...dn(e.consequent),...dn(e.alternate)]:W.isLogicalExpression(e)&&Fc(e.operator)?dn(e.right):[]}function Gp(e){return e.flatMap(t=>W.isJSXElement(t)||W.isJSXFragment(t)?dn(t):W.isJSXExpressionContainer(t)&&(W.isJSXElement(t.expression)||W.isJSXFragment(t.expression)||W.isConditionalExpression(t.expression)||W.isLogicalExpression(t.expression))?dn(t.expression):[])}function CI(e){let t=e.openingElement.name;return W.isJSXIdentifier(t)?t.name==="Fragment":W.isJSXMemberExpression(t)&&t.property.name==="Fragment"}function Yp(e,t){return!!(e&&t&&e.callbackStart<t.callbackStart&&e.callbackEnd>t.callbackEnd)}function Zi(e){return!(W.isIdentifier(e)||W.isThisExpression(e)||W.isMemberExpression(e)||W.isOptionalMemberExpression(e)||W.isCallExpression(e)||W.isOptionalCallExpression(e))}function Zp(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(W.isMemberExpression(n)||W.isOptionalMemberExpression(n))&&W.isIdentifier(n.property)&&n.property.name==="map"&&!n.computed}function fr(e,t){let n=Je(e);if(!n)return t.isRepeatItemRoot===!0;let r=se(n,he(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:Hi(n,t);if(!o)return t.isRepeatItemRoot===!0;let i=Dt(e,o);return i?kI(o,i):t.isRepeatItemRoot===!0}function Qp(e,t){let n=Je(e);if(!n)return!1;let r=se(n,he(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:Hi(n,t);return o?!!o.findParent(i=>{if(!i.isCallExpression()&&!i.isOptionalCallExpression())return!1;let s=i.node.callee;return(W.isMemberExpression(s)||W.isOptionalMemberExpression(s))&&W.isIdentifier(s.property)&&s.property.name==="map"}):!1}import*as Ee from"@babel/types";function Dc(e){if(Ee.isJSXIdentifier(e))return/^[A-Z]/.test(e.name)?e.name:null;if(Ee.isJSXMemberExpression(e)){let t=e;for(;Ee.isJSXMemberExpression(t);)t=t.object;return t.name}return null}function RI(e,t){let n=ge(e.node);if(!n)return[];let r=new Set,o=(i,s)=>{let a=s.scope.getBinding(i);!a||Ot(a.path.node,n)||fn(a,i,t)||r.add(i)};return e.traverse({ReferencedIdentifier(i){o(i.node.name,i)},JSXOpeningElement(i){let s=Dc(i.node.name);s&&o(s,i)}}),[...r].sort()}function Lc(e,t,n){let r=Je(e);if(!r)return{ok:!0};let o=se(r,he(t));if(!o.ok||!o.match.path.isJSXElement())return{ok:!0};let i=se(r,he(n));if(!i.ok||!i.match.path.isJSXElement())return{ok:!0};let s=Ar(o.match.path,i.match.path);if(Wi(s,i.match.path))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let a=RI(s,i.match.path);return a.length>0?{ok:!1,bindingNames:a}:{ok:!0}}function em(e){let t=e;for(;Ee.isTSQualifiedName(t);)t=t.left;return Ee.isIdentifier(t)?t.name:null}function fo(e,t){e.isIdentifier()&&e.isReferencedIdentifier()&&t(e),e.traverse({ReferencedIdentifier(n){n.isIdentifier()&&t(n)}})}function Qi(e){let t=[],n=r=>{if(r){if(Ee.isIdentifier(r)){t.push(r.name);return}if(Ee.isObjectPattern(r)){for(let o of r.properties){if(Ee.isRestElement(o)){n(o.argument);continue}Ee.isObjectProperty(o)&&n(o.value)}return}if(Ee.isArrayPattern(r)){for(let o of r.elements)n(o);return}if(Ee.isAssignmentPattern(r)){n(r.left);return}if(Ee.isRestElement(r)){n(r.argument);return}Ee.isTSParameterProperty(r)&&n(r.parameter)}};return n(e),t}function Bc(e,t){let n=ge(e.node),r=ge(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=qp(e),i=qp(t);if(!o||!i||!Kp(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=Up(s.node,n);if(a&&!ct(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=ge(s.node.right);if(a&&ct(a,n)&&!ct(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())&&Zp(s)){let a=ge(s.node.body)??ge(s.node);if(a&&!ct(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 qp(e){let t=e;for(;t;){if(t.isReturnStatement())return t.node.argument?ge(t.node.argument):null;if(t.isArrowFunctionExpression()&&(Ee.isJSXElement(t.node.body)||Ee.isJSXFragment(t.node.body)||Ee.isConditionalExpression(t.node.body)||Ee.isLogicalExpression(t.node.body)))return ge(t.node.body);t=t.parentPath}return null}function fn(e,t,n){return n.scope.getBinding(t)===e}function jc(e,t,n,r={}){if(!r.preserveConditionalBoundary&&Wi(e,t))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let o=ge(e.node);if(!o)return{ok:!0};let i=new Set(n.callbackPath.node.params.flatMap(c=>Qi(c)).map(c=>n.callbackPath.scope.getBinding(c)?.path.node).filter(Boolean)),s=new Set,a=(c,l)=>{let d=l.scope.getBinding(c);!d||Ot(d.path.node,o)||i.has(d.path.node)||fn(d,c,t)||s.add(c)};return e.traverse({ReferencedIdentifier(c){a(c.node.name,c)},JSXOpeningElement(c){let l=Dc(c.node.name);l&&a(l,c)}}),s.size>0?{ok:!1,bindingNames:[...s].sort()}:{ok:!0}}function $c(e,t,n){let r=ge(e.node);if(!r)return{ok:!0};let o=new Set(n.callbackPath.node.params.flatMap(s=>Qi(s)).map(s=>n.callbackPath.scope.getBinding(s)?.path.node).filter(Boolean)),i=new Set;return fo(e,s=>{let a=s.scope.getBinding(s.node.name);!a||Ot(a.path.node,r)||o.has(a.path.node)||fn(a,s.node.name,t)||i.add(s.node.name)}),i.size>0?{ok:!1,bindingNames:[...i].sort()}:{ok:!0}}function tm(e,t){let n=new Set(e.callbackPath.node.params.flatMap(a=>Qi(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)||fn(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(pr.isIdentifier(l))o(l.name,c);else{let d=em(l);d&&o(d,c)}}});return r.size>0?{ok:!1,bindingNames:[...r].sort()}:{ok:!0}}function Vc(e,t){let n=ge(e.node),r=new Set;return fo(e,o=>{let i=o.scope.getBinding(o.node.name);i&&(n&&Ot(i.path.node,n)||fn(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 nm(e){let t=[];for(let n of e.callbackPath.node.params){if(pr.isIdentifier(n)){t.push(n.name);continue}if(pr.isRestElement(n)&&pr.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 rm(e,t){return{...e,callbackParams:t}}function Kc(e,t){return`${e.collectionNeedsParens?`(${e.collectionExpression})`:e.collectionExpression}${e.mapOperator}((${e.callbackParams.join(", ")}) => ${t})`}function po(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 om(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 On(e){return{file:e.file,component:e.component}}function wI(e){return e.target.kind==="node"?e.target.key:null}function NI(e){return"kind"in e}function qi(e){return!NI(e)}function Hc(e,t){let n=ns.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=ns.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function Uc(e,t){let n=e.getFileContent(t.file);if(!n)return;let r=At(n,he(t));if(r.ok)return n.slice(r.match.start,r.match.end)}function Gc(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 PI(e){if(e.isNumericLiteral())return!0;if(!e.isUnaryExpression({operator:"-"}))return!1;let t=e.get("argument");return!Array.isArray(t)&&t.isNumericLiteral()}function AI(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 Jc(e){return e==="Cannot edit repeat-backed child node structure with a generic node operation"}function TI(e){let t=Pp(e.ast,e.sourceNode.component,e.targetParent.component);if(!t.ok)return{ok:!1,reason:t.reason};let n=Bc(t.path,e.targetParentPath);if(!n.ok)return{ok:!1,reason:n.reason};let r=FI({source:e.source,sourceContext:e.sourceContext,callSitePath:t.path,targetParentPath:e.targetParentPath});if(!r.ok)return r;let o=pm(r.collectionExpression);return{ok:!0,context:{...e.sourceContext,collectionExpression:r.collectionExpression,collectionNeedsParens:o?Zi(o):!0}}}function FI(e){let t=ge(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=MI(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=LI(e.callSitePath,c.propName,e.source);if(!l.ok){o=l.reason;return}let d=_I(l.expression,c.remainingPath);if(!d){o="Cannot move prop-backed repeat child because the mapped prop path is not a portable expression";return}let f=Vc(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:d});return}fn(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:BI(e.source,t,[...n.values()])}}function _I(e,t){if(t.length===0)return e;let n=pm(e);if(!n)return null;let r=Zi(n)?`(${e})`:e;for(let o of t){if(o.kind==="property"){r=OI(o.name)?`${r}.${o.name}`:`${r}[${JSON.stringify(o.name)}]`;continue}r=`${r}[${o.index}]`}return r}function OI(e){return/^[$A-Z_a-z][$\w]*$/.test(e)}function MI(e,t,n){let r=DI(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=sr(t,o);if(!i)return null;let s=r?.range??ge(e.node);return s?{propName:i.propName,remainingPath:i.remainingPath,hasDefault:i.hasDefault,range:s}:null}function DI(e,t){let n=e.parentPath;if(!n||!n.isMemberExpression()&&!n.isOptionalMemberExpression()||n.node.object!==e.node||!Ot(n.node,t)||n.node.computed||!ue.isIdentifier(n.node.property))return null;let r=ge(n.node);return r?{propertyName:n.node.property.name,range:r}:null}function LI(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()&&ue.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=dr(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 BI(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 pm(e){try{let n=fm.parse(`const __VD_EXPR__ = (${e});`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0],r=ue.isVariableDeclaration(n)?n.declarations[0]?.init:null;return r&&ue.isExpression(r)?r:null}catch{return null}}function jI(e){let t=ge(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=im(s,e.sourceFile,e.targetFile);if(a){let c=e.targetParentPath.scope.getBinding(a.localName);if(c){let d=im(c,e.targetFile,e.targetFile);(!d||d.moduleFile!==a.moduleFile||!$I(d.importSpec,a.importSpec))&&r.add(a.localName);return}let l=n.get(a.moduleSpecifier)??[];l.some(d=>JSON.stringify(d)===JSON.stringify(a.importSpec))||l.push(a.importSpec),n.set(a.moduleSpecifier,l);return}r.add(i.node.name)};return fo(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 $I(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 im(e,t,n){let r=VI(e),o=r?.parentPath;if(!r||!o?.isImportDeclaration())return null;let i=o.node.source.value;if(typeof i!="string")return null;let s=Tn(t,i),a=i.startsWith(".")?Hc(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=ue.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 VI(e){let t=e.path;for(;t&&!t.isImportDeclaration();){if(t.isImportSpecifier()||t.isImportDefaultSpecifier()||t.isImportNamespaceSpecifier())return t;t=t.parentPath}return null}function sm(e,t,n,r){let o=Tc(t,n);if(o.length===0)return{sourceJsx:r,conditionPaths:[]};let i=r,s=[];for(let a of o){let c=dr(e,a.conditionPath.node);if(!c)return{sourceJsx:r,conditionPaths:[]};let l=KI(a.conditionPath,c);if(s.push(a.conditionPath),a.kind==="logical"){i=`${l} ${a.operator} ${JI(i)}`;continue}i=a.branch==="consequent"?`${l} ? ${i} : null`:`${l} ? null : ${i}`}return{sourceJsx:i,conditionPaths:s}}function KI(e,t){return UI(e.node)?t:`(${t})`}function UI(e){return ue.isIdentifier(e)||ue.isThisExpression(e)||ue.isSuper(e)||ue.isMemberExpression(e)||ue.isOptionalMemberExpression(e)||ue.isCallExpression(e)||ue.isOptionalCallExpression(e)||ue.isBooleanLiteral(e)||ue.isNumericLiteral(e)||ue.isStringLiteral(e)||ue.isNullLiteral(e)||ue.isUnaryExpression(e)}function JI(e){return e.trim().startsWith("<")?e:`(${e})`}var XI={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 es(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=XI[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 zI(e,t){for(let n of e.program.body){if(!ue.isImportDeclaration(n)||n.source.value!==t)continue;let r=n.specifiers.find(o=>ue.isImportDefaultSpecifier(o));if(r&&ue.isImportDefaultSpecifier(r))return r.local.name}return null}function HI(e,t,n){for(let r of e.program.body){if(!ue.isImportDeclaration(r)||r.source.value!==t)continue;let o=r.specifiers.find(i=>ue.isImportSpecifier(i)&&(ue.isIdentifier(i.imported)?i.imported.name:i.imported.value)===n);if(o&&ue.isImportSpecifier(o))return o.local.name}return null}function am(e){let t=new Set;return It(e,{Program(n){for(let r of Object.keys(n.scope.bindings))t.add(r);n.stop()}}),t}function cm(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n+=1;return`${e}${n}`}function WI(e,t){if(!e.component)return{localName:"Component"};let n=e.component,r=Gc(e),o=Je(t);if(n.exportName!=="default"){let a=o?HI(o,n.source,n.exportName):null;if(a)return{localName:a};let c=o?cm(r,am(o)):r;return{localName:c,importStep:Xc(e,c)}}if(!o)return{localName:r,importStep:Xc(e,r)};let i=zI(o,n.source);if(i)return{localName:i};let s=cm(r,am(o));return{localName:s,importStep:Xc(e,s)}}function GI(e,t){if(e.kind==="native-tag")return e.text?`<${e.tag}>${e.text}</${e.tag}>`:`<${e.tag} />`;let n=t??Gc(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 YI(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?ZI(e.props):void 0;return{kind:e.kind,component:{source:e.component.source,exportName:e.component.exportName},...t?{props:t}:{}}}function ZI(e){return Object.fromEntries(Object.entries(e).filter(t=>Wc(t[1])))}function Wc(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(Wc):typeof e=="object"?Object.values(e).every(Wc):!1}function Xc(e,t=Gc(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 lm(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 QI(e,t,n){let r=e;for(;r;){if(r===t)return!0;r=n.getNode(r)?.parentKey}return!1}function mr(e,t){return`Operation kind '${e}' does not match params.kind '${t}'`}function Yc(e,t=e.path){return{kind:"value",root:e.root,path:t&&t.length>0?t:void 0,expectedRange:e.expectedRange}}function mo(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:Yc(e,t.slice(0,n)),index:r.index}}return null}function zc(e,t){return e.locator?e.collectionPathMap?.[t]?Yc(e.locator,e.collectionPathMap[t]):mo(e.locator)?eC(e.locator,tC(t,e.collectionIndexMap)):null:null}function qI(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:mm(o,t)}function mm(e,t){let[n,...r]=e;if(!n)return t;if(n.kind!=="property")return;let o=mm(r,t);return o===void 0?void 0:{[n.name]:o}}function eC(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},Yc(e,i)}return null}function tC(e,t){return t?.[e]??e}function um(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 nC(e,t){return rC(e.root,t.root)&&iC(e.path??[],t.path??[])}function rC(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&&oC(e.sourceRange,t.sourceRange)}}function oC(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function iC(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 ts=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:mr(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:mr(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:mr(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:mr(t.kind,t.params.kind)};let r=t;if(!qi(r.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};let o=lm(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:mr(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:mr(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=wI(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):dm(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 dm(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:he(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?Wp({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 d=await this.graph.getElementPropertyWriteTarget?.(r.key,c),f=r.attributes?.find(u=>u.name===c);if((await this.graph.getPropertyState?.(r.key,c,i))?.status==="blocked"||!d&&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(d?.kind==="external-entry")return{ok:!1,errorCode:"capability-denied",reason:`apply-style-draft cannot overwrite readonly external property '${c}'`};if(d?.kind==="value-binding"&&d.locator){let u=d.locator;if(d.sourceKind==="repeat-template"&&typeof i?.instanceIndex=="number"){let g=zc(d,i.instanceIndex);if(!g)return{ok:!1,errorCode:"invalid-params",reason:"apply-style-draft could not resolve the selected repeat item"};u=g}s.push({order:n+s.length,file:d.file,type:"update-value",locator:u,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:he(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=zc(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:he(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(!PI(a.match.path))return{ok:!0,value:r};let c=AI(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=zc(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=mo(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=po(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:he(r),removeWhitespace:!0}],d=this.buildRemoveComponentImportStep(r);return d&&l.push({...d,order:l.length}),this.buildPlan(t,n,l,o)}buildRemoveComponentImportStep(t,n=this.graph.getFileContent(t.file)){if(!t.importedFrom||!t.exportName||!t.tag||Vp(n,t)>1)return null;let r=Hc(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(!qi(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=po(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 d=await this.planExternalBackedInsertChild(t,n,r,o,i,a);if(d)return d;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 u=vp(this.graph.getFileContent(r.file),r);if(!u.allowed)return{ok:!1,errorCode:"unsupported-operation",reason:u.reason??"Cannot insert child into this node"};let g=es(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"?WI(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:he(r),node:{jsx:GI(n.params.node,E?.localName)},placement:n.params.position.relation,anchorLocator:i?he(i):void 0}),this.buildPlan(t,n,h,o)}async planExternalBackedInsertChild(t,n,r,o,i,s){if(!qi(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:YI(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(!qi(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=mo(a.locator);if(!c)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child requires an array-backed target"};let l=qI(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 d=n.params.position.relation==="prepend"?um(0,a.collectionIndexMap):um(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:d,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=po(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 fr(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:")||Qp(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&&fr(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 d=xt(l,r),f=xt(l,o);if(!d||!f)return null;let m=Dt(c,d),u=Dt(c,f);if(!uo(m,u))return null;if(a&&(s==="before"||s==="after")){let h=xt(l,a),S=h?Dt(c,h):null;if(!uo(m,S))return null}if(Gi(d,f))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child across statement-level conditional branches"};let g=Lc(c,r,o);return g.ok?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:he(r),targetParentLocator:he(o),placement:s,anchorLocator:a?he(a):void 0,selectionContext:On(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&&fr(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 d=xt(l,r),f=xt(l,o);if(!d||!f)return null;let m=Dt(c,d);if(!m)return null;let u=Dt(c,f);if(uo(m,u))return null;if(u&&!Yp(u,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=Mc(c,l,a);if(u&&!uo(u,v)||!u&&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=es(o,{kind:"native-tag",tag:r.tag});if(v)return{ok:!1,errorCode:"unsupported-operation",reason:v}}let g=Uc(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(Gi(d,f))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let h=sm(c,d,f,g);for(let v of h.conditionPaths){let C=$c(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=jc(d,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=tm(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=TI({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=Vc(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:he(r),targetParentLocator:he(o),placement:s,anchorLocator:a?he(a):void 0,repeatExpression:Kc(y,h.sourceJsx),selectionContext:On(o)}],i)}planCrossFileRepeatTemplateHoistMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&fr(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),d=Je(c),f=Je(l);if(!d||!f)return null;let m=Jp({knownSourceFiles:this.graph.getKnownSourceFiles?.(),routeEntryFiles:this.graph.getRouteEntryFiles?.(),sourceAst:d,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 u=xt(d,r),g=xt(f,o);if(!u||!g)return null;let h=Bc(m.callSitePath,g);if(!h.ok)return{ok:!1,errorCode:"unsupported-operation",reason:h.reason};let S=Dt(c,u);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")&&Mc(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 O=es(o,{kind:"native-tag",tag:r.tag});if(O)return{ok:!1,errorCode:"unsupported-operation",reason:O}}let y=Uc(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(Gi(u,g))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let v=sm(c,u,g,y);for(let O of v.conditionPaths){let M=$c(O,g,S);if(!M.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its condition depends on bindings outside the target scope: ${M.bindingNames.join(", ")}`}}let C=jc(u,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=jI({sourceFile:r.file,targetFile:o.file,sourceContext:S,targetParentPath:g});if(!N.ok)return{ok:!1,errorCode:"unsupported-operation",reason:N.reason};let A=nm(S);if(!A.ok)return{ok:!1,errorCode:"unsupported-operation",reason:A.reason};let R=rm(S,A.callbackParams),T=[{order:0,file:r.file,type:"remove-node",locator:he(r),removeWhitespace:!0}];for(let O of N.imports)T.push({order:T.length,file:o.file,type:"add-import",moduleSpecifier:O.moduleSpecifier,imports:O.imports});return T.push({order:T.length,file:o.file,type:"insert-jsx-expression-child",parentLocator:he(o),expression:Kc(R,v.sourceJsx),placement:s,anchorLocator:a?he(a):void 0,selectionContext:On(o)}),this.buildPlan(t,n,T,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),T=R?xt(R,r):null,O=R?xt(R,C):null,M=T?.parentPath,U=O?.parentPath;if(!T||!O||!M||!U||M.node!==U.node||!M.isJSXFragment()&&!(M.isJSXElement()&&_e(M)))return{ok:!1,errorCode:"unsupported-operation",reason:"Source sibling move requires two direct children of the same transparent Fragment"};let ee=M.node.loc;return ee?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:he(r),targetParentLocator:{kind:"jsx-node",strategy:"source-range",sourceRange:{startLine:ee.start.line,startColumn:ee.start.column,endLine:ee.end.line,endColumn:ee.end.column}},placement:v.relation,anchorLocator:he(C),selectionContext:On(r)}],o):{ok:!1,errorCode:"locator-miss",reason:"Source Fragment has no stable source range"}}let i=lm(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(QI(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,d=n.params.target.relation,f=i.anchorNode,m=this.graph.getTextProvenance?.(r.key,0)??null,u=po(r,c,m);if(u&&!Jc(u)&&!om(r,s,c,m))return{ok:!1,errorCode:"unsupported-operation",reason:u};if(r.isRepeatItemRoot&&f?.isRepeatItemRoot&&r.repeatOwnerKey&&r.repeatOwnerKey===f.repeatOwnerKey&&(d==="before"||d==="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=mo(v.locator),A=mo(C.locator);if(N&&A&&v.file===C.file&&nC(N.locator,A.locator)){let R=N.index,T=A.index,O=d==="before"?T-(R<T?1:0):T+(R<T?0:1);return this.buildPlan(t,n,[{order:0,file:v.file,type:"move-array-item",locator:N.locator,fromIndex:R,toIndex:O}],o)}}}if(r.isRepeatItemRoot&&fr(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=Jc(u)?u:g;if(h&&Jc(h)){let v=this.planRepeatTemplateInternalMove(t,n,r,s,o,d,f);if(v)return v;let C=this.planRepeatTemplateHoistMove(t,n,r,s,o,d,f);if(C)return C;let N=this.planCrossFileRepeatTemplateHoistMove(t,n,r,s,o,d,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=es(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,d,f);let E=Lc(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:he(r),targetParentLocator:he(s),placement:d,anchorLocator:f?he(f):void 0,selectionContext:On(s)}];return this.buildPlan(t,n,y,o)}planCrossFileMove(t,n,r,o,i,s,a){let c=[],l=0,d=this.graph.getFileContent(r.file),f=Uc(this.graph,r)??`<${r.component} />`,m=kp(d,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:he(r),removeWhitespace:!0}),r.importedFrom&&r.exportName){let g=r.tag??r.component,S={moduleSpecifier:Hc(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:he(o),node:{jsx:f},placement:s,anchorLocator:a?he(a):void 0,selectionContext:On(o)})}else c.push({order:l++,file:o.file,type:"insert-child",parentLocator:he(o),node:{jsx:f},placement:s,anchorLocator:a?he(a):void 0,selectionContext:On(o)});let u=this.buildRemoveComponentImportStep(r,d);return u&&c.push({...u,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:Se(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 dm(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 tl from"@babel/generator";import{parse as SC}from"@babel/parser";import nl from"@babel/traverse";import*as w from"@babel/types";import*as Bt from"@babel/types";import Zc from"@babel/generator";import*as be from"@babel/types";var sC=typeof Zc=="function"?Zc:Zc.default,aC=/(?:token|secret|key|password|authorization|cookie|signature|credential)/i,cC=/^((?:https?:)?\/\/)[^/@\s]+@/i,lC=/(\/(?:token|secret|api[-_]?key|password|credential|signature)\/)[^/?#]+/gi;function hm(e,t){let n=Lt(e.callee);if(!n)return null;if(n==="fetch")return Qc(e.arguments[0],"GET",t,["fetch call"]);if(n.startsWith("axios.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(gm(r))return Qc(e.arguments[0],r,t,["axios client contract"])}if(n.startsWith("ky.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(gm(r))return Qc(e.arguments[0],r,t,["ky client contract"])}return null}function Qc(e,t,n,r){if(!e||be.isSpreadElement(e)||be.isJSXNamespacedName(e))return pC(t,n,r,"missing url argument");let o=go(e);return{sourceKind:fC(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 go(e){if(be.isStringLiteral(e))return rs(e.value);if(be.isTemplateLiteral(e))return rs(uC(e));if(be.isBinaryExpression(e)&&e.operator==="+"){let t=go(e.left),n=go(e.right);return!t&&!n?void 0:rs(`${t??qc(e.left)}${n??qc(e.right)}`)}if(be.isMemberExpression(e)){let t=ym(e);if(t)return`env:${t}`}if(!(be.isCallExpression(e)&&Lt(e.callee)==="new URL")){if(be.isNewExpression(e)&&be.isIdentifier(e.callee,{name:"URL"})){let[t,n]=e.arguments,r=t&&!be.isSpreadElement(t)?go(t):void 0,o=n&&!be.isSpreadElement(n)?go(n):void 0;return o&&r?rs(`${o} + ${r}`):r??o}if(be.isIdentifier(e))return`:${e.name}`}}function uC(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+=qc(r))}return t}function qc(e){if(be.isIdentifier(e))return`:${e.name}`;if(be.isMemberExpression(e)){let t=ym(e);if(t)return`env:${t}`}return`:${dC(e)}`}function dC(e){return sC(e,{comments:!1}).code.replace(/[^a-zA-Z0-9_$]+/g,"_").replace(/^_+|_+$/g,"")||"param"}function rs(e){let[t]=e.split("#"),[n,r]=t.split("?"),o=n.replace(cC,"$1<redacted>@").replace(lC,"$1<redacted>");if(!r)return o;let i=r.split("&").map(s=>{let[a]=s.split("=");return a?aC.test(a)?`${a}=<redacted>`:`${a}=:${a}`:""}).filter(Boolean).join("&");return i?`${o}?${i}`:o}function fC(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 pC(e,t,n,r){return{sourceKind:"unknown-api",method:e,confidence:"partial",evidence:[{file:t.file,reason:[...n,r].join("; ")}]}}function gm(e){return["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(e)}function ym(e){return!be.isMemberExpression(e.object)||!be.isIdentifier(e.object.object,{name:"process"})||!mC(e.object.property,"env")?null:be.isIdentifier(e.property)?e.property.name:be.isStringLiteral(e.property)?e.property.value:null}function mC(e,t){return be.isIdentifier(e)&&e.name===t}function Lt(e){if(be.isIdentifier(e))return e.name;if(be.isMemberExpression(e)){let t=Lt(e.object),n=be.isIdentifier(e.property)?e.property.name:be.isStringLiteral(e.property)?e.property.value:null;if(t&&n)return`${t}.${n}`}return null}var gC=new Set(["list","listStrict","get","getStrict","getByUrl","getByUrlStrict","schema","categories"]),hC=new Set(["getConfig","submit"]);function xm(e,t){let n=yC(Lt(e.callee),t);if(!n)return null;let r="cms.collections.";if(n.startsWith(r)){let i=n.slice(r.length);if(!gC.has(i))return null;let s=el(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(!hC.has(i))return null;let s=el(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=el(e,0)??xC(e,0,"path")??"/cms/:path",s=bC(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 yC(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 bm(e,t){let n=Lt(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 Sm(e){let t=Lt(e.callee);return typeof t=="string"&&t.startsWith("cms.field.")}function el(e,t){let n=e.arguments[t];return Bt.isStringLiteral(n)?n.value:null}function xC(e,t,n){let r=e.arguments[t];if(!Bt.isObjectExpression(r))return null;for(let o of r.properties)if(Bt.isObjectProperty(o)&&!o.computed&&(Bt.isIdentifier(o.key)&&o.key.name===n||Bt.isStringLiteral(o.key)&&o.key.value===n)&&Bt.isStringLiteral(o.value))return o.value.value;return null}function bC(e){return/^\/collections\/([^/]+)(?:\/|$)/.exec(e)?.[1]??null}var ol=typeof nl=="function"?nl:nl.default,OM=typeof tl=="function"?tl:tl.default,EC={maxFunctionDepth:8,maxImportDepth:6},vC=new Set(["src","href","alt","poster","content","title","aria-label"]);async function Rm(e){let t=e.fileCache??new Map,n=al(e.file,e.source,t),r={file:e.file,analysis:n,readFile:e.readFile,exists:e.exists,fileCache:t,options:{...EC,...e.options},variableCache:new Map,functionDepth:0,importDepth:0,paramSources:new Map,resolvingVariables:new Set,resolvingComponentProps:new Set,scopeVariables:$m(n,e.element.componentName)};await wm(e.element.componentName,e.graph,r);let o=[];o.push(...await wC(e.element,e.graph,r),...await NC(e.element,e.graph,r));for(let s of e.element.textSegments){let a=await PC(s,e.element,e.graph,r);a&&o.push(ss(a,"text","children"))}for(let s of e.element.attributes??[]){let a=RC(s,e.element);if(!a)continue;let c=await Am(s.source,e.element,e.graph,r);c&&o.push(ss(c,a,s.name))}let i=JC(o).sort(Bm);return{hasDynamicData:i.length>0,bindings:i}}async function wm(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 t.elements.values()){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 Nm(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 d=`${n.file}#${e}<-${l.identity.key}`;if(!n.resolvingComponentProps.has(d)){n.resolvingComponentProps.add(d);try{let f=await Pm(l.sourceFile,n);if(!f)continue;let m=cs(f,n,{importDepth:n.importDepth+1});m.paramSources.clear(),m.scopeVariables=$m(f,l.componentName),await wm(l.componentName,t,m);let u=await kC(l,m);for(let[g,h]of u){if(!h)continue;let S=a.get(g)??[];S.push(h),a.set(g,S)}}finally{n.resolvingComponentProps.delete(d)}}}let c=new Map;for(let[l,d]of a){let f=Dm(d);f.length===1&&c.set(l,f[0])}CC(o,c,n)}async function Nm(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 Pm(e,r))?.imports.get(t);if(!s||!wt(s.source))return!1;let a=await Um(e,s.source,r.exists);return a?a===n?!0:Nm(a,s.importedName,n,r,o):!1}async function kC(e,t){let n=new Map;ol(t.analysis.ast,{JSXElement(o){if(IC(o.node,e.sourceRange)){for(let i of o.node.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);o.stop()}}});let r=new Map;for(let[o,i]of n){let s=await je(i,t);s&&r.set(o,s)}return r}function IC(e,t){return e.loc?.start.line===t.startLine&&e.loc.start.column===t.startColumn&&e.loc.end.line===t.endLine&&e.loc.end.column===t.endColumn}async function Pm(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 al(e,r,t.fileCache)}function CC(e,t,n){if(w.isIdentifier(e)){t.size>0&&n.paramSources.set(e.name,sl(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,He(o))}}function RC(e,t){return e.name==="dangerouslySetInnerHTML"?"richtext":vC.has(e.name)?"attribute":t.importedFrom||/^[A-Z]/.test(t.tag)?"component-prop":null}async function wC(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 as(i.collectionSource,n);s&&r.push(ss(Mn(s),"repeat-region",i.collectionExpression))}return r}async function NC(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 as(i.conditionSource,n);s&&r.push(ss(Mn(s),"conditional-region",i.conditionExpression))}return r}async function PC(e,t,n,r){return Am(e.source,t,n,r)}async function Am(e,t,n,r){let o=await AC(e,t,n,r);return o||as(e,r)}async function AC(e,t,n,r){if(!e)return null;let o=TC(e.base,t,n);if(!o)return null;let i=await as(o.collectionSource,r);return i?bo(i,e.path,!0):null}function TC(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 as(e,t){if(!e)return null;let n=await Tm(e.base,t);return n?bo(n,e.path,!1):null}async function Tm(e,t){let n=t.paramSources.get(e);if(n)return He(n);if(t.variableCache.has(e))return XC(t.variableCache.get(e)??null);if(t.resolvingVariables.has(e))return null;t.resolvingVariables.add(e);let r=await FC(e,t);if(r)return t.variableCache.set(e,He(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?He(s):null),t.resolvingVariables.delete(e),s}let i=t.analysis.imports.get(e);if(i&&t.importDepth<t.options.maxImportDepth){let s=await Vm(i,t);if(s){let a=cs(s,t,{importDepth:t.importDepth+1}),c=Km(i,s);if(c){let f=(await Dn(c,[],a)).returnSource;return t.variableCache.set(e,f?He(f):null),t.resolvingVariables.delete(e),f}let l=s.variables.get(i.importedName);if(l){let d=await je(l,a);return t.variableCache.set(e,d?He(d):null),t.resolvingVariables.delete(e),d}}}return t.variableCache.set(e,null),t.resolvingVariables.delete(e),null}async function FC(e,t){let n=t.analysis.stateSetters.get(e);if(!n)return null;let r=[];ol(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 Tm(e.name,t);if(w.isMemberExpression(e)||w.isOptionalMemberExpression(e)){let n=w.isMemberExpression(e)?bm(e,{file:t.file}):null;if(n)return Mm(n);let r=await _C(e,t);if(!r)return null;let o=KC(e);return bo(r,o,!1)}if(w.isAwaitExpression(e))return w.isExpression(e.argument)?je(e.argument,t):null;if(w.isCallExpression(e))return Fm(e,t);if(w.isObjectExpression(e)){let n=await _m(e,t);return Object.keys(n).length>0?sl(n,t.file):null}if(w.isConditionalExpression(e)){let n=await je(e.consequent,t),r=await je(e.alternate,t);return xo(vm(n,r))}if(w.isLogicalExpression(e)){let n=await je(e.left,t),r=await je(e.right,t);return xo(vm(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 _C(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 Fm(e,t){let n=xm(e,{file:t.file,imports:t.analysis.imports});if(n)return Mm(n);if(Sm(e)){let f=e.arguments[0];if(f&&w.isExpression(f))return xo(await je(f,t))}let r=await OC(e,t);if(r)return r;let o=hm(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 LC(e,t);if(i)return i;let s=await BC(e,t);if(s)return s;let a=await jC(e,t);if(a)return a;let c=await $C(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 d=Dm(l);return d.length===1?xo(d[0]):null}async function OC(e,t){let n=Lt(e.callee);if(n!=="useQuery"&&n!=="useSuspenseQuery"&&n!=="useInfiniteQuery"&&n!=="useSWR")return null;if(n==="useSWR"){let i=DC(e.arguments[0],t.file,"SWR key"),s=e.arguments[1];if(w.isIdentifier(s)){let a=await yo(s.name,t);if(a)return(await Dn(a.node,i?[i]:[],a.context)).returnSource??i}return i}let r=e.arguments[0];if(!w.isObjectExpression(r))return os(t.file,`${n} without static options`);let o=MC(r,"queryFn");if(!o)return os(t.file,`${n} without queryFn`);if(w.isIdentifier(o)){let i=await yo(o.name,t);return i?(await Dn(i.node,[],i.context)).returnSource:os(t.file,`${n} queryFn unresolved`)}return w.isArrowFunctionExpression(o)||w.isFunctionExpression(o)?(await Dn(o,[],t)).returnSource:w.isCallExpression(o)?Fm(o,t):null}function MC(e,t){for(let n of e.properties){if(!w.isObjectProperty(n)||!w.isExpression(n.value))continue;if(Om(n)===t)return n.value}return null}function DC(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 LC(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 Mn(r);let o=e.arguments[0];if(w.isIdentifier(o)){let i=await yo(o.name,t);if(!i)return Mn(r);let s=await Dn(i.node,[r],i.context);return{...Mn(r),...s.objectReturnMap??s.returnSource?.fieldMap?{fieldMap:s.objectReturnMap??s.returnSource.fieldMap}:{}}}if(w.isArrowFunctionExpression(o)||w.isFunctionExpression(o)){let i=await Dn(o,[r],t);return{...Mn(r),...i.objectReturnMap??i.returnSource?.fieldMap?{fieldMap:i.objectReturnMap??i.returnSource.fieldMap}:{}}}return Mn(r)}async function BC(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 jC(e,t){return!w.isMemberExpression(e.callee)||!w.isIdentifier(e.callee.property,{name:"then"})||!w.isExpression(e.callee.object)?null:xo(await je(e.callee.object,t))}async function $C(e,t){if(!w.isIdentifier(e.callee))return null;let n=await yo(e.callee.name,t);if(!n)return null;let r=[];for(let i of e.arguments){if(!w.isExpression(i)){r.push(os(t.file,`unsupported argument for ${e.callee.name}`));continue}let s=await je(i,t);r.push(s)}return(await Dn(n.node,r,n.context)).returnSource}async function yo(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 Vm(r,t);if(!o)return null;let i=cs(o,t,{importDepth:t.importDepth+1}),s=Km(r,o);return s?{node:s,context:i}:yo(r.importedName,i)}async function Dn(e,t,n){if(n.functionDepth>=n.options.maxFunctionDepth)return{returnSource:null};let r=cs(n.analysis,n,{functionDepth:n.functionDepth+1});r.scopeVariables=n.analysis.functionVariables.get(e),e.params.forEach((c,l)=>{let d=t[l];d&&rl(c,UC(d),r)});let o=VC(e),i=null,s,a=!1;for(let c of o){if(w.isObjectExpression(c)){s={...s??{},...await _m(c,r)},i=i??sl(s,n.file);continue}let l=await je(c,r);if(l){if(!i){i=l;continue}let d=il(i,l);if(!d){a=!0,i=null;continue}i=d}}return{returnSource:a?null:i,...s?{objectReturnMap:s}:{}}}function rl(e,t,n){if(w.isIdentifier(e)){n.paramSources.set(e.name,He(t));return}if(w.isAssignmentPattern(e)){rl(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=bo(t,[{kind:"property",name:r.key.name}],!0),i=w.isAssignmentPattern(r.value)?r.value.left:r.value;rl(i,o,n)}}function VC(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 _m(e,t){let n={};for(let r of e.properties){if(!w.isObjectProperty(r))continue;let o=Om(r);if(!o||!w.isExpression(r.value))continue;let i=await je(r.value,t);i&&(n[o]=i)}return n}function Om(e){return w.isIdentifier(e.key)&&!e.computed?e.key.name:w.isStringLiteral(e.key)?e.key.value:null}function KC(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 bo(e,t,n){if(t.length===0)return He(e);let r=t[0];if(r?.kind==="property"&&e.fieldMap?.[r.name])return bo(e.fieldMap[r.name],t.slice(1),n);let o=He(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=ho(o.valuePath,"data.items[]"),o.cmsFieldRoot=!1,o):i[0]==="fields"?(o.fieldPath=ho(o.fieldPath,i.slice(1).join(".")),o.cmsFieldRoot=!0,o):o.cmsFieldRoot||n||o.fieldMap?(o.fieldPath=ho(o.fieldPath,i.join(".")),o):(o.valuePath=ho(o.valuePath,Em(t)),o)}return o.valuePath=ho(o.valuePath,Em(t)),o}function Em(e){return e.map(t=>t.kind==="property"?t.name:`[${t.index}]`).join(".").replace(/\.\[/g,"[")}function ho(e,t){return t?e?t.startsWith("[")?`${e}${t}`:`${e}.${t}`:t:e}function Mm(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 Mn(e){let t=He(e);return t.sourceType==="cms-field"&&!t.valuePath&&(t.valuePath="items[]"),t}function UC(e){let t=He(e);return t.valuePath=void 0,t.sourceType==="cms-field"&&(t.cmsFieldRoot=!1),t}function xo(e){return e?{...He(e),confidence:e.confidence==="unknown"?"unknown":"safe-derived",evidence:[...e.evidence,{file:e.evidence[0]?.file??"unknown",reason:"safe derived expression"}]}:null}function vm(e,t){return e?t?il(e,t):He(e):t?He(t):null}function il(e,t){if(is(e)!==is(t))return null;let n=jm(e.confidence,t.confidence)<=0?e.confidence:t.confidence;return{...e,confidence:n,evidence:[...e.evidence,...t.evidence]}}function Dm(e){let t=new Map;for(let n of e){let r=is(n),o=t.get(r);t.set(r,o?il(o,n):He(n))}return[...t.values()]}function is(e){let t=e.fieldMap?Object.fromEntries(Object.entries(e.fieldMap).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>[n,is(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 sl(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 os(e,t){return{sourceKind:"unknown-api",sourceType:"api-field",confidence:"unknown",readonly:!0,evidence:[{file:e,reason:t}]}}function ss(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 Lm(e){let t=[...e].sort(Bm),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 JC(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 Bm(e,t){return km(e.targetKind)-km(t.targetKind)||jm(e.confidence,t.confidence)||Im(e.sourceKind)-Im(t.sourceKind)||e.targetName.localeCompare(t.targetName)}function km(e){return{"repeat-region":0,"conditional-region":1,text:2,richtext:3,attribute:4,"component-prop":5}[e]}function Im(e){return e.startsWith("vcp-cms-")?0:e==="site-api-route"?1:e==="external-api"?2:3}function jm(e,t){let n={exact:0,"safe-derived":1,partial:2,unknown:3};return n[e]-n[t]}function al(e,t,n){let r=n.get(e);if(r?.source===t)return r;let o=SC(t,{sourceType:"module",plugins:["jsx","typescript"]}),i={file:e,source:t,ast:o,variables:new Map,functions:new Map,imports:new Map,stateSetters:new Map,functionVariables:new WeakMap};return ol(o,{ImportDeclaration(s){let a=s.node.source.value;for(let c of s.node.specifiers)w.isImportSpecifier(c)&&w.isIdentifier(c.local)?i.imports.set(c.local.name,{source:a,importedName:w.isIdentifier(c.imported)?c.imported.name:c.imported.value,localName:c.local.name,isDefault:!1}):w.isImportDefaultSpecifier(c)&&i.imports.set(c.local.name,{source:a,importedName:"default",localName:c.local.name,isDefault:!0})},FunctionDeclaration(s){s.node.id?.name&&i.functions.set(s.node.id.name,s.node)},VariableDeclarator(s){let a=s.getFunctionParent(),c=a&&(w.isFunctionDeclaration(a.node)||w.isFunctionExpression(a.node)||w.isArrowFunctionExpression(a.node))?a.node:null,l=c?i.functionVariables.get(c)??new Map:i.variables;c&&!i.functionVariables.has(c)&&i.functionVariables.set(c,l);for(let d of gr(s.node.id))l.set(d,w.isExpression(s.node.init)?s.node.init:null);if(w.isArrayPattern(s.node.id)&&w.isCallExpression(s.node.init)&&Lt(s.node.init.callee)==="useState"){let[d,f]=s.node.id.elements;w.isIdentifier(d)&&w.isIdentifier(f)&&i.stateSetters.set(d.name,f.name)}w.isIdentifier(s.node.id)&&Cm(s.node.init)&&i.functions.set(s.node.id.name,s.node.init)},ExportNamedDeclaration(s){let a=s.node.declaration,c=s.node.source?.value;if(c)for(let l of s.node.specifiers){if(!w.isExportSpecifier(l))continue;let d=w.isIdentifier(l.exported)?l.exported.name:l.exported.value,f=l.local.name;i.imports.set(d,{source:c,importedName:f,localName:d,isDefault:f==="default"})}if(w.isFunctionDeclaration(a)&&a.id?.name&&i.functions.set(a.id.name,a),w.isVariableDeclaration(a))for(let l of a.declarations)w.isIdentifier(l.id)&&Cm(l.init)&&i.functions.set(l.id.name,l.init)},ExportDefaultDeclaration(s){let a=s.node.declaration;if((w.isFunctionDeclaration(a)||w.isFunctionExpression(a)||w.isArrowFunctionExpression(a))&&i.functions.set("default",a),w.isIdentifier(a)){let c=i.functions.get(a.name);c&&i.functions.set("default",c)}}}),n.set(e,i),i}function gr(e){return!e||w.isVoidPattern(e)?[]:w.isIdentifier(e)?[e.name]:w.isObjectPattern(e)?e.properties.flatMap(t=>w.isObjectProperty(t)?gr(t.value):gr(t.argument)):w.isArrayPattern(e)?e.elements.flatMap(t=>t?gr(w.isRestElement(t)?t.argument:t):[]):w.isAssignmentPattern(e)?gr(e.left):w.isRestElement(e)?gr(e.argument):[]}function Cm(e){return w.isFunctionExpression(e)||w.isArrowFunctionExpression(e)}function $m(e,t){let n=e.functions.get(t)??e.functions.get("default");return n?e.functionVariables.get(n):void 0}async function Vm(e,t){let n=await Um(t.file,e.source,t.exists);if(!n)return null;let r=await t.readFile(n);return al(n,r,t.fileCache)}function Km(e,t){return e.isDefault?t.functions.get("default")??t.functions.get(e.localName)??null:t.functions.get(e.importedName)??null}async function Um(e,t,n){return wt(t)?yn(e,t,n):null}function cs(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 XC(e){return e?He(e):null}function He(e){return{...e,evidence:e.evidence.map(t=>({...t})),...e.fieldMap?{fieldMap:Object.fromEntries(Object.entries(e.fieldMap).map(([t,n])=>[t,He(n)]))}:{}}}import*as ll from"@babel/parser";import cl from"@babel/traverse";import*as Y from"@babel/types";import{classifySiteEditPropertyName as zC}from"@vcp-dev/contracts";var ul=typeof cl=="function"?cl:cl.default;function dl(e){let t=zC(e.propertyName);if(t.owner!=="generic")return lt("invalid-property",t.diagnostic?.message??`Property '${e.propertyName}' is not a generic property`);let n=e.selectionRef;if(!n)return lt("missing-selection-ref","A repeat property target requires a complete selection reference");if(n.key!==e.element.identity.key)return lt("selection-mismatch","Selection reference does not identify the requested element");if(n.instanceIndex===void 0)return lt("missing-instance-index","A repeat property target requires an instance index");let r;try{r=ll.parse(e.source,{sourceType:"module",plugins:["typescript","jsx"]})}catch(S){return lt("repeat-not-found",`Unable to parse repeat source: ${S instanceof Error?S.message:String(S)}`)}let o=HC(r,e.element.sourceRange);if(!o)return lt("repeat-not-found","The selected element is not inside a supported map repeat");if(!Y.isIdentifier(o.callback.params[0]))return lt("unsupported-callback","Repeat property materialization requires an identifier callback item");let i=WC(r,o.collection,e.file,e.sources);if(!i)return lt("collection-not-found","The repeat collection is not a visible local static array");let{array:s,locator:a,sourceFile:c}=i,l=[],d=[];for(let[S,E]of s.elements.entries()){if(!E||!Y.isObjectExpression(E)||!Gm(E))return lt("unsafe-collection","Repeat materialization requires an array of local static objects without spreads");let y=[{kind:"index",index:S}];l.push(y),d.push({kind:"value",root:a.root,path:y})}let f=d.length;if(n.instanceCount!==void 0&&n.instanceCount!==f)return lt("count-mismatch",`Selection reports ${n.instanceCount} instances but the source collection has ${f}`);let m=n.instanceIndex;if(m>=f)return lt("index-out-of-range",`Selected repeat instance ${m} is outside the source collection`);let u=s.elements[m];if(!u||!Y.isObjectExpression(u))return lt("unsafe-collection","Selected repeat item is not an object");let g=eR(e.element,e.propertyName),h=QC(u,e.propertyName);return h?{ok:!0,sourceFile:c,templateFile:e.file,collectionLocator:a,parentObjectLocators:d,selectedParentObjectLocator:d[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:qC(u,e.propertyName),...g?{property:g}:{},selectionRef:n}:lt("unsafe-property-source",`Property '${e.propertyName}' has a dynamic or unsupported source in the repeat item`)}function HC(e,t){let n=[];return ul(e,{CallExpression(r){let o=Jm(r.node);o&&zm(o.callback,t)&&n.push({...o,span:Xm(r.node)})},OptionalCallExpression(r){let o=Jm(r.node);o&&zm(o.callback,t)&&n.push({...o,span:Xm(r.node)})}}),n.sort((r,o)=>r.span-o.span),n[0]??null}function Jm(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 WC(e,t,n,r){let o=So(t);if(o&&Y.isArrayExpression(o))return{array:o,locator:{kind:"value",root:{kind:"expression",sourceRange:Zm(o)}},sourceFile:n};if(!Y.isIdentifier(t))return null;let i=[];if(ul(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=So(i[0].init);return!s||!Y.isArrayExpression(s)?null:{array:s,locator:{kind:"value",root:{kind:"binding",name:t.name}},sourceFile:n}}return GC(e,t.name,n,r)}function GC(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=ZC(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=ll.parse(c,{sourceType:"module",plugins:["typescript","jsx"]})}catch{return null}let d=YC(l,a),f=d?So(d):null;return!f||!Y.isArrayExpression(f)?null:{array:f,locator:{kind:"value",root:{kind:"binding",name:a}},sourceFile:s}}return null}function YC(e,t){let n=null;return ul(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 ZC(e,t,n){let r=hn(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 So(e){return Y.isParenthesizedExpression(e)?So(e.expression):Y.isTSAsExpression(e)?Wm(e.typeAnnotation)?So(e.expression):null:Y.isTSSatisfiesExpression(e)?null:e}function Wm(e){return Y.isTSTypeReference(e)&&Y.isIdentifier(e.typeName)&&e.typeName.name==="const"}function Gm(e){return e.properties.every(t=>!Y.isObjectProperty(t)||t.computed||!Y.isExpression(t.value)?!1:ls(t.value))}function ls(e){if(Y.isTSAsExpression(e)&&Wm(e.typeAnnotation))return ls(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:ls(n));if(Y.isObjectExpression(e))return Gm(e);let t=Ft(e);return t.status==="resolved"||t.status==="undefined"}function QC(e,t){let n=e.properties.filter(o=>Y.isObjectProperty(o)&&Ym(o.key)===t);if(n.length>1)return null;let r=n[0];return r?Y.isExpression(r.value)?ls(r.value)?"static":Y.isIdentifier(r.value)||Y.isMemberExpression(r.value)?"binding":null:null:"missing"}function qC(e,t){let n=e.properties.filter(o=>Y.isObjectProperty(o)&&Ym(o.key)===t);if(n.length>1)return{status:"unresolved"};let r=n[0];return!r||!Y.isExpression(r.value)?{status:"undefined"}:Ft(r.value)}function eR(e,t){let n=e.attributes?.filter(r=>r.name===t)??[];return n.length===1?n[0]:void 0}function Ym(e){return Y.isIdentifier(e)?e.name:Y.isStringLiteral(e)?e.value:Y.isNumericLiteral(e)?String(e.value):null}function Zm(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 Xm(e){return e.start==null||e.end==null?Number.MAX_SAFE_INTEGER:e.end-e.start}function zm(e,t){let n=Zm(e);return Hm(n.startLine,n.startColumn,t.startLine,t.startColumn)<=0&&Hm(n.endLine,n.endColumn,t.endLine,t.endColumn)>=0}function Hm(e,t,n,r){return e===n?t-r:e-n}function lt(e,t){return{ok:!1,errorCode:e,reason:t}}import{classifySiteEditPropertyName as $R}from"@vcp-dev/contracts";import*as Z from"@babel/types";import Io from"node:path";import*as $ from"@babel/types";import*as ng from"@babel/parser";import fl from"@babel/traverse";import*as ne from"@babel/types";function us(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 Qm(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}function qm(e){let{resolveBindingTarget:t}=e;async function n(i,s,a,c,l,d,f){if(ne.isStringLiteral(i)||ne.isNumericLiteral(i)||ne.isBooleanLiteral(i))return i.value;if(ne.isNullLiteral(i))return null;if(ne.isTemplateLiteral(i))return i.expressions.length===0&&i.quasis.length===1?i.quasis[0].value.cooked??i.quasis[0].value.raw:void 0;if(ne.isTSAsExpression(i)||ne.isTSSatisfiesExpression(i)||ne.isTSNonNullExpression(i))return await n(i.expression,s,a,c,l,d,f);if(ne.isIdentifier(i)){let m=s.getBinding(i.name);if(!m)return;let u=await t({currentFile:a,binding:m,readFile:c,exists:l,fileCache:d,visited:f});return u?.kind==="static"?u.value:void 0}if(ne.isArrayExpression(i)){let m=[];for(let u of i.elements){if(!u||ne.isSpreadElement(u))return;let g=await r(u,s,a,c,l,d,f);if(g===void 0)return;m.push(g)}return m}if(ne.isObjectExpression(i)){let m={};for(let u of i.properties){if(!ne.isObjectProperty(u)||u.computed)return;let g=null;if(ne.isIdentifier(u.key)?g=u.key.name:ne.isStringLiteral(u.key)&&(g=u.key.value),!g)return;if(u.shorthand){if(!ne.isIdentifier(u.value))return;let S=await r(u.value,s,a,c,l,d,f);if(S===void 0)return;m[g]=S;continue}if(!ne.isExpression(u.value))return;let h=await r(u.value,s,a,c,l,d,f);h!==void 0&&(m[g]=h)}return m}if(ne.isMemberExpression(i)){let m=await o(i,s,a,c,l,d,f);if(!m)return;let u=s.getBinding(m.base);if(!u)return;let g=await t({currentFile:a,binding:u,readFile:c,exists:l,fileCache:d,visited:f});return!g||g.kind!=="static"?void 0:Qe(g.value,m.path)}}async function r(i,s,a,c,l,d,f){if(!ne.isSpreadElement(i))return await n(i,s,a,c,l,d,f)}async function o(i,s,a,c,l,d,f){if(ne.isIdentifier(i))return{base:i.name,path:[]};if(!ne.isMemberExpression(i))return null;let m=[],u=i;for(;ne.isMemberExpression(u);){if(u.computed){let g=u.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,d,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(u.property))return null;m.unshift({kind:"property",name:u.property.name})}u=u.object}return ne.isIdentifier(u)?{base:u.name,path:m}:null}return{normalizeExpressionWithScope:o,evaluateStaticExpression:n}}var rg=typeof fl=="function"?fl:fl.default,eg=new WeakMap;function og(e){try{return ng.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function ds(e,t,n){let r=e.get(t);if(r?.source===n)return r.ast;let o=og(n);return e.set(t,{source:n,ast:o}),o}function fs(e,t){let n=null,r=-1;for(let o of Eo(e).expressions){let i=o.node.loc;if(!i||!ml(i,t))continue;let s=(o.node.end??0)-(o.node.start??0);s>=r&&(n=o,r=s)}return n}function ig(e,t){let n=null,r=Number.POSITIVE_INFINITY;for(let o of Eo(e).expressions){if(!tR(o.node.loc,t))continue;let i=(o.node.end??0)-(o.node.start??0);i<=r&&(n=o,r=i)}return n}function pl(e,t){let n=null,r=Number.POSITIVE_INFINITY;for(let o of Eo(e).jsxElements){let i=o.node.loc;if(!i||!ml(i,t))continue;let s=(o.node.end??0)-(o.node.start??0);s<=r&&(n=o,r=s)}return n}function Eo(e){let t=eg.get(e);if(t)return t;let n={expressions:[],jsxElements:[]};return rg(e,{Expression(r){n.expressions.push(r)},JSXElement(r){n.jsxElements.push(r)}}),eg.set(e,n),n}function tR(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 ml(e,t){let n=tg({line:e.start.line,column:e.start.column},{line:t.startLine,column:t.startColumn}),r=tg({line:e.end.line,column:e.end.column},{line:t.endLine,column:t.endColumn});return n>=0&&r<=0}function ps(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 tg(e,t){return e.line!==t.line?e.line<t.line?-1:1:e.column!==t.column?e.column<t.column?-1:1:0}function hr(e,t){if(t)return gl(e,t);let n=Qm(e);return n?n.path.reduce((r,o)=>o.kind==="property"?`${r}.${o.name}`:`${r}[${o.index}]`,n.base):""}function gl(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function vo(e,t,n){let r=null,o=Number.POSITIVE_INFINITY;for(let i of Eo(e).expressions){if(gl(i.node,t)!==n)continue;let s=(i.node.end??0)-(i.node.start??0);s<=o&&(r=i,o=s)}return r}function sg(e,t,n,r){let o=null,i=Number.POSITIVE_INFINITY;for(let s of Eo(e).expressions){if(gl(s.node,t)!==n)continue;let a=s.node.loc;if(!a||!ml(a,r))continue;let c=(s.node.end??0)-(s.node.start??0);c<=i&&(o=s,i=c)}return o}function yr(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}function ko(e){let t=null;if(rg(e,{Program(n){t=n.scope,n.stop()}}),!t)throw new Error("Unable to determine program scope");return t}async function jt(e,t,n){let r=n.get(e);if(r)return r;let o=await t(e),i=og(o),s={source:o,ast:i};return n.set(e,s),s}function nR(e){return $.isIdentifier(e.callee)&&(e.callee.name==="useState"||e.callee.name==="useReducer")?e.callee.name:$.isMemberExpression(e.callee)&&$.isIdentifier(e.callee.property)&&(e.callee.property.name==="useState"||e.callee.property.name==="useReducer")?e.callee.property.name:null}function rR(e){if(!$.isNewExpression(e)||!$.isIdentifier(e.callee,{name:"Proxy"})||e.arguments.length!==2||!$.isIdentifier(e.arguments[0])||!$.isObjectExpression(e.arguments[1])||e.arguments[1].properties.length!==1)return null;let[t]=e.arguments[1].properties;if(!$.isObjectMethod(t)||t.kind!=="method"||t.computed||t.async||t.generator||!$.isIdentifier(t.key,{name:"get"})||t.params.length!==3||!t.params.every($.isIdentifier)||t.body.body.length!==2)return null;let[n,r,o]=t.params,[i,s]=t.body.body;if($.isIfStatement(i)&&$.isBlockStatement(i.consequent)&&i.consequent.body.length!==1)return null;let a=$.isIfStatement(i)?i.test:null,c=a&&$.isLogicalExpression(a,{operator:"&&"})?a.right:null,l=$.isIfStatement(i)?$.isBlockStatement(i.consequent)?i.consequent.body[0]:i.consequent:null,d=$.isReturnStatement(s)?s.argument:null;return!a||!$.isLogicalExpression(a,{operator:"&&"})||!$.isBinaryExpression(a.left,{operator:"==="})||!$.isUnaryExpression(a.left.left,{operator:"typeof"})||!$.isIdentifier(a.left.left.argument,{name:r.name})||!$.isStringLiteral(a.left.right,{value:"string"})||!$.isUnaryExpression(c,{operator:"!"})||!$.isBinaryExpression(c.argument,{operator:"in"})||!$.isIdentifier(c.argument.left,{name:r.name})||!$.isIdentifier(c.argument.right,{name:n.name})||!$.isReturnStatement(l)||!$.isIfStatement(i)||i.alternate||!$.isCallExpression(d)||!$.isMemberExpression(d.callee)||!$.isIdentifier(d.callee.object,{name:"Reflect"})||!$.isIdentifier(d.callee.property,{name:"get"})||d.arguments.length!==3||!$.isIdentifier(d.arguments[0],{name:n.name})||!$.isIdentifier(d.arguments[1],{name:r.name})||!$.isIdentifier(d.arguments[2],{name:o.name})?null:e.arguments[0].name}function oR(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()||!$.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 iR(e,t){let n=oR(e.path);if(!n)return null;let r=sr(e,t);return r?{...n,...r}:null}function sR(e,t,n,r){return e.importedFrom===t?r?e.exportName===r:!0:e.sourceFile===t&&e.tag===n}function hl(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 yl(e,t){for(let n of e.program.body){if(t==="default"&&$.isExportDefaultDeclaration(n))return $.isExpression(n.declaration)?{kind:"default-expression",expression:n.declaration}:($.isFunctionDeclaration(n.declaration)||$.isClassDeclaration(n.declaration))&&n.declaration.id?{kind:"default-binding",name:n.declaration.id.name}:null;if($.isExportNamedDeclaration(n)){if(n.declaration){if($.isVariableDeclaration(n.declaration)){for(let r of n.declaration.declarations)if($.isIdentifier(r.id)&&r.id.name===t)return{kind:"local-binding",name:r.id.name}}if(($.isFunctionDeclaration(n.declaration)||$.isClassDeclaration(n.declaration))&&n.declaration.id&&n.declaration.id.name===t)return{kind:"local-binding",name:t}}for(let r of n.specifiers)if(($.isIdentifier(r.exported)?r.exported.name:r.exported.value)===t&&$.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 ag(e){let{resolveExternalExpression:t,resolveCollectionCallTarget:n,evaluateStaticExpression:r,resolveSourceInfoProvenance:o,buildExpressionSourceInfo:i}=e;async function s(u){let{currentFile:g,binding:h,readFile:S,exists:E,fileCache:y,visited:v}=u,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:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,fileCache:y,visited:v});if(h.kind==="param")return null;if(h.path.isVariableDeclarator()){let A=h.path.node.init;if(!A||!$.isExpression(A))return null;let R=rR(A);if(R&&!h.path.scope.getBinding("Proxy")&&!h.path.scope.getBinding("Reflect")){let M=h.path.scope.getBinding(R),U=M?await s({...u,binding:M}):null;if(U?.kind==="static"&&U.value!==null&&!Array.isArray(U.value)&&typeof U.value=="object")return U}let T=h.path.get("init");if(T&&!Array.isArray(T)&&T.isExpression()){let M=await t({currentFile:g,expressionPath:T,readFile:S,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:y,visited:v});if(M)return M;if(T.isCallExpression()){let U=await n({currentFile:g,callPath:T,readFile:S,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:y,visited:v});if(U)return U}}let O=await r(A,h.path.scope,g,S,E,y,v);return O===void 0?null:{kind:"static",file:g,root:{kind:"binding",name:h.identifier.name},value:O,sourceKind:"binding"}}if(h.path.isIdentifier()&&h.path.parentPath?.isExportDefaultDeclaration()){let A=h.path.parentPath.node.declaration;if(!$.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(u){let{currentFile:g,binding:h,readFile:S,exists:E,fileCache:y,visited:v}=u;if(!h.path.isVariableDeclarator()||!h.path.get("id").isArrayPattern())return null;let C=h.path,N=C.node.init;if(!N||!$.isCallExpression(N))return null;let A=nR(N);if(!A||!$.isArrayPattern(C.node.id)||C.node.id.elements.findIndex(U=>$.isIdentifier(U)&&U.name===h.identifier.name)!==0)return null;let T=A==="useReducer"?1:0,O=N.arguments[T];if(!O||!$.isExpression(O))return null;let M=await r(O,C.scope,g,S,E,y,v);return M===void 0?null:{kind:"static",file:g,root:{kind:"hook-state",name:h.identifier.name,hook:A},value:M,sourceKind:"binding"}}async function c(u){let g=iR(u.binding,u.sourceInfo);if(!g||!u.graph)return null;let h=[...u.graph.elements.values()].filter(A=>sR(A,u.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:u.readFile,fileCache:u.fileCache});if(A)return hl(A,{componentName:g.componentName,propName:g.propName,file:S.sourceFile})}if(!E?.source){let A=await d({caller:S,propName:g.propName,remainingPath:g.remainingPath,readFile:u.readFile,exists:u.exists,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:u.fileCache,visited:u.visited});if(A)return hl(A,{componentName:g.componentName,propName:g.propName,file:S.sourceFile});let R=gp(u.binding,g.componentName,g.propName);if(!R||R.propName!==g.propName)return null;let T=await r(R.expressionPath.node,R.expressionPath.scope,u.currentFile,u.readFile,u.exists,u.fileCache,u.visited);if(T===void 0)return null;let O=g.remainingPath;return O.length>0&&Qe(T,O)===void 0?null:{kind:"value",file:u.currentFile,root:{kind:"binding",name:g.propName},path:O,sourceKind:"binding",semanticKind:"component-prop",displayExpression:R.displayPath,chainPrefix:[{kind:"component-prop",file:u.currentFile,displayName:R.displayPath,canEditHere:!0}],editMode:"upstream",diagnostics:[]}}let y=await jt(S.sourceFile,u.readFile,u.fileCache);if(!y.ast)return null;let v=sg(y.ast,y.source,E.source.expression,E.sourceRange)??vo(y.ast,y.source,E.source.expression);if(!v)return null;let C={...E.source,expression:yr(E.source.expression,g.remainingPath),path:[...E.source.path,...g.remainingPath]},N=await o({currentFile:S.sourceFile,expressionPath:v,sourceInfo:C,readFile:u.readFile,exists:u.exists,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:u.fileCache,visited:u.visited});return N?hl(N.kind==="external"?N:{...N,displayExpression:C.expression},{componentName:g.componentName,propName:g.propName,file:S.sourceFile}):null}async function l(u){let g=await jt(u.caller.sourceFile,u.readFile,u.fileCache);if(!g.ast)return null;let h=pl(g.ast,u.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===u.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=ps(y.node);return v?{kind:"value",file:u.caller.sourceFile,root:{kind:"expression",sourceRange:v},path:u.remainingPath,sourceKind:"binding",semanticKind:"component-prop",displayExpression:u.propName,editMode:"upstream",diagnostics:[]}:null}async function d(u){let g=await jt(u.caller.sourceFile,u.readFile,u.fileCache);if(!g.ast)return null;let h=pl(g.ast,u.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:u.caller.sourceFile,readFile:u.readFile,exists:u.exists,fileCache:u.fileCache,visited:u.visited});if(!v)continue;let C=[{kind:"property",name:u.propName},...u.remainingPath],N={...v,expression:yr(v.expression,C),path:[...v.path,...C]},A=await o({currentFile:u.caller.sourceFile,expressionPath:y,sourceInfo:N,readFile:u.readFile,exists:u.exists,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:u.fileCache,visited:u.visited});if(A)return A.kind==="external"?A:{...A,displayExpression:N.expression}}return null}async function f(u){let{currentFile:g,binding:h,readFile:S,exists:E,fileCache:y,visited:v}=u,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 yn(g,N,E);if(!A)return null;if(h.path.isImportDefaultSpecifier()){let ee=await jt(A,S,y),Re=ee.ast?yl(ee.ast,"default"):null,Q=await m({file:A,exportName:"default",readFile:S,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:y,visited:v});return!Q||Q.kind!=="static"?null:{kind:"static",file:Re?.kind==="default-expression"?Q.file:A,root:Re?.kind==="default-expression"?Q.root:{kind:"default-export"},value:Q.value,sourceKind:"imported-binding"}}if(!h.path.isImportSpecifier())return null;let R=h.path.node.imported,T=$.isIdentifier(R)?R.name:R.value,O=await jt(A,S,y),M=O.ast?yl(O.ast,T):null,U=await m({file:A,exportName:T,readFile:S,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:y,visited:v});return U?U.kind==="external"?U:{kind:"static",file:M?.kind==="re-export"?U.file:A,root:M?.kind==="re-export"||U.root.kind==="binding"&&U.root.name!==M?.name?U.root:{kind:"named-export",name:T},value:U.value,sourceKind:"imported-binding"}:null}async function m(u){let{file:g,exportName:h,readFile:S,exists:E,fileCache:y,visited:v}=u,C=`export::${g}::${h}`;if(!v.has(C)){v.add(C);try{let N=await jt(g,S,y);if(!N.ast)return;let A=yl(N.ast,h);if(!A)return;if(A.kind==="default-expression"){let M=A.expression;if(!M||!$.isIdentifier(M))return;let U=ko(N.ast).getBinding(M.name);return U?await s({currentFile:g,binding:U,readFile:S,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:y,visited:v})??void 0:void 0}if(A.kind==="re-export"){if(!A.source||!A.name)return;let M=await yn(g,A.source,E);return M?m({...u,file:M,exportName:A.name}):void 0}let R=A.name;if(!R)return;let T=ko(N.ast).getBinding(R);return T?await s({currentFile:g,binding:T,readFile:S,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.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 bl(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=kt(o,t);if(!i)return null;let s=r.parentPath;return!s||!s.isCallExpression()||!aR(s,r)?null:{callPath:s,basePath:i}}function aR(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 ug(e,t){let n=e.get("callee");if(!n.isMemberExpression())return null;let r=n.get("object");return Array.isArray(r)||!r.isExpression()?null:Ui(r,t)}function cg(e,t){return e?H.isNumericLiteral(e)&&Number.isInteger(e.value)?e.value:null:t}function lg(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=xl(i,t,n,r,o);return typeof s=="number"?s:void 0}function xl(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=us(e,t);if(i)return Qe(r,i);let s=us(e,n);return s?Qe(o,s):void 0}if(H.isBinaryExpression(e)&&e.operator==="-"){let i=H.isExpression(e.left)?xl(e.left,t,n,r,o):void 0,s=H.isExpression(e.right)?xl(e.right,t,n,r,o):void 0;return typeof i=="number"&&typeof s=="number"?i-s:void 0}}function cR(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 lR(e,t,n){let r=Ln(e,t,n);return typeof r=="boolean"?r:void 0}function Ln(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=us(e,t);return r?Qe(n,r):void 0}if(H.isUnaryExpression(e)&&e.operator==="!"){let r=Ln(e.argument,t,n);return r===void 0?void 0:!r}if(H.isLogicalExpression(e)){let r=Ln(e.left,t,n);if(r===void 0)return;if(e.operator==="&&")return r&&Ln(e.right,t,n);if(e.operator==="||")return r||Ln(e.right,t,n)}if(H.isBinaryExpression(e)){let r=H.isExpression(e.left)?Ln(e.left,t,n):void 0,o=H.isExpression(e.right)?Ln(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 dg(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 fg(e){return e.some(t=>t.kind==="dynamic")}function uR(e){return typeof e=="string"?{kind:"property",name:e}:Number.isInteger(e)?{kind:"index",index:e}:null}function pg(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 dR(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 mg(e){let{resolveBindingTarget:t,evaluateStaticExpression:n,buildExpressionSourceInfo:r,resolveSourceInfoProvenance:o}=e;async function i(u){let{currentFile:g,callPath:h,readFile:S,exists:E,fileCache:y,visited:v}=u,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:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:y,visited:v});return!R||!Array.isArray(R.value)||R.value.length===0?null:R}async function s(u){let{currentFile:g,expressionPath:h,readFile:S,exists:E,fileCache:y,visited:v}=u;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:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.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:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.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({...u,expressionPath:C})}if(h.isArrayExpression()){let C=ps(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:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.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:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:y,visited:v});if(!A||A.kind!=="static")return null;if(N.collectionPathMap?.length){let T=dR(A.value,N.collectionPathMap);if(T)return{kind:"static",file:N.file,root:N.root,value:T.value,sourceKind:N.sourceKind,collectionPathMap:T.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(u){let{provenance:g}=u;if(g.root.kind==="binding"){let y=u.expressionPath.scope.getBinding(g.root.name);if(!y&&g.file!==u.currentFile){let v=await jt(g.file,u.readFile,u.fileCache);y=v.ast?ko(v.ast).getBinding(g.root.name):void 0}return y?await t({currentFile:g.file,binding:y,readFile:u.readFile,exists:u.exists,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:u.fileCache,visited:u.visited}):null}if(g.root.kind!=="expression")return null;let h=await jt(g.file,u.readFile,u.fileCache);if(!h.ast)return null;let S=ig(h.ast,g.root.sourceRange);if(!S)return null;let E=await n(S.node,S.scope,g.file,u.readFile,u.exists,u.fileCache,u.visited);return E===void 0?null:{kind:"static",file:g.file,root:g.root,value:E,sourceKind:g.sourceKind}}async function c(u){return await l(u)??await d(u)??await f(u)}async function l(u){let{callPath:g}=u,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:u.currentFile,expressionPath:E,readFile:u.readFile,exists:u.exists,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:u.fileCache,visited:u.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=cR(v);if(!N)return null;let A=[],R=[],T=[];for(let[O,M]of y.value.entries()){let U=lR(N,C.name,M);if(typeof U!="boolean")return null;if(U){A.push(M),R.push(y.collectionIndexMap?.[O]??O);let ee=y.collectionPathMap?.[O];ee&&T.push(ee)}}return{...y,value:A,pathPrefix:y.pathPrefix,collectionIndexMap:R,...T.length>0?{collectionPathMap:T}:{}}}async function d(u){let{callPath:g}=u,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:u.currentFile,expressionPath:E,readFile:u.readFile,exists:u.exists,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:u.fileCache,visited:u.visited});if(!y||!Array.isArray(y.value))return null;let[v,C]=g.node.arguments,N=cg(v,0),A=cg(C,y.value.length);if(N===null||A===null)return null;let R=Math.max(0,N<0?y.value.length+N:N),T=Math.max(0,A<0?y.value.length+A:A),O=y.value.map((U,ee)=>y.collectionIndexMap?.[ee]??ee).slice(R,T),M=y.collectionPathMap?.slice(R,T);return{...y,value:y.value.slice(R,T),pathPrefix:y.pathPrefix,collectionIndexMap:O,...M?{collectionPathMap:M}:{}}}async function f(u){let{callPath:g}=u,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:u.currentFile,expressionPath:E,readFile:u.readFile,exists:u.exists,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:u.fileCache,visited:u.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((T,O)=>({value:T,sourceIndex:y.collectionIndexMap?.[O]??O,originalIndex:O})),R=[...A];for(let T of A)for(let O of A)if(lg(v,C.name,N.name,T.value,O.value)===void 0)return null;return R.sort((T,O)=>{let M=lg(v,C.name,N.name,T.value,O.value)??0;return M===0?T.originalIndex-O.originalIndex:M}),{...y,value:R.map(T=>T.value),pathPrefix:y.pathPrefix,collectionIndexMap:R.map(T=>T.sourceIndex),...y.collectionPathMap?{collectionPathMap:R.map(T=>y.collectionPathMap?.[T.originalIndex]).filter(T=>!!T)}:{}}}async function m(u){let g=null,h,S=[];for(let y of u.segments){if(y.kind!=="dynamic")continue;let v=await r({expression:y.expression,scope:u.expressionPath.scope,source:u.fileCache.get(u.currentFile)?.source,currentFile:u.currentFile,readFile:u.readFile,exists:u.exists,fileCache:u.fileCache,visited:u.visited});if(!v)return null;let C=bl(u.expressionPath,v.base);if(!C)return null;let N=await i({currentFile:u.currentFile,callPath:C.callPath,readFile:u.readFile,exists:u.exists,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:u.fileCache,visited:u.visited});if(!N||!Array.isArray(N.value))return null;let A=N.value.map((R,T)=>{let O=Qe(N.value,[{kind:"index",index:T},...C.basePath,...v.path]);return uR(O)});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=[...u.rootPath],C=0;for(let N of u.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:fR,evaluateStaticExpression:ms}=qm({resolveBindingTarget:e=>gs(e)}),{resolveRepeatCollectionTarget:pR,resolveCollectionCallTarget:mR,resolveDynamicMemberPathMap:gR}=mg({resolveBindingTarget:e=>gs(e),evaluateStaticExpression:ms,buildExpressionSourceInfo:$t,resolveSourceInfoProvenance:bt}),{resolveExportValue:hR,resolveComponentPropBinding:yR,resolveBindingTarget:gs}=ag({resolveExternalExpression:Rl,resolveCollectionCallTarget:mR,evaluateStaticExpression:ms,resolveSourceInfoProvenance:bt,buildExpressionSourceInfo:$t});function vg(e){return new Map([...e].map(t=>[t.file,{source:t.source,ast:t.ast}]))}function gg(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 kg(e){let{file:t,source:n,segment:r,readFile:o,exists:i}=e,s=e.fileCache??new Map,a=ds(s,t,n);if(!a)return null;let c=fs(a,r.sourceRange);if(!c)return null;let l=await $t({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:o,exists:i,fileCache:s,visited:new Set});if(!l){let m=await Al({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?vl(m,hr(c.node,n)):null}let d=new Set,f=await jR({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:d});return f?vl(f,l.expression):null}async function xr(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=ds(i,t,n);if(!s)return null;let a=e.sourceRange?fs(s,e.sourceRange):e.expression!==void 0?vo(s,n,e.expression):null;if(!a)return null;let c=hs(a);if(!c.isIdentifier()&&!c.isMemberExpression())return null;let l=new Set,d=await $t({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:r,exists:o,fileCache:i,visited:l}),f=d?await bt({currentFile:t,expressionPath:c,sourceInfo:d,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:l}):await Tg({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 vl(f,e.expression??hr(c.node,n))}async function Cl(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=ds(i,t,n);if(!s)return ut("unsupported-expression","Unable to parse source for provenance resolution");let a=new Set;return e.target.kind==="text-segment"?xR({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}):bR({file:t,source:n,ast:s,candidate:e.target.candidate,readFile:r,exists:o,graph:e.graph,fileCache:i,visited:a})}async function $t(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 fR(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:hr(e.expression,e.source),base:t.base,path:t.path}:null}function vl(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 xR(e){let{file:t,source:n,ast:r,segment:o,readFile:i,exists:s,fileCache:a,visited:c}=e,l=fs(r,o.sourceRange),d=l?await $t({expression:l.node,scope:l.scope,source:n,currentFile:t,readFile:i,exists:s,fileCache:a,visited:c}):null;if(!d){if(!l||l.isStringLiteral()||l.isTemplateLiteral()&&l.node.expressions.length===0)return hg(t,o.value);let m=await Al({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"?Eg(t,m):Il(t,hr(l.node,n),m):SR({expression:l.node,scope:l.scope,currentFile:t,source:n,readFile:i,exists:s,fileCache:a,visited:c,functionCallContracts:e.functionCallContracts})}if(!l)return ut("unsupported-expression","Unable to locate text expression for provenance resolution");let f=await bt({currentFile:t,expressionPath:l,sourceInfo:d,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:c});if(!f){let m=kl(l.node);if(m)return ut(m.code,m.message);let u=l.scope.getBinding(d.base);if(u?.path.isVariableDeclarator()){let g=kl(u.path.node.init);if(g)return ut(g.code,g.message)}return u?.path.isVariableDeclarator()&&Z.isCallExpression(u.path.node.init)?ER("unsupported-expression",Ng(u.path.node.init,e.functionCallContracts)):ut("unsupported-expression",`Unable to resolve provenance for expression "${d.expression}"`)}return f.kind==="external"?Eg(t,f):Il(t,d.expression,f)}async function bR(e){let{file:t,source:n,ast:r,candidate:o,readFile:i,exists:s,fileCache:a,visited:c}=e;if(!o.conditionSource)return ut("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let l=vo(r,n,o.conditionExpression);if(!l)return ut("conditional-branch-unresolved",`Unable to locate conditional expression "${o.conditionExpression}"`);let d=await bt({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(!d)return ut("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);if(d.kind==="external")return ut("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let f=Il(t,o.conditionExpression,d);return f.finalSource?{...f,finalSource:{...f.finalSource,kind:"conditional-branch",displayPath:o.conditionExpression},chain:[...f.chain,{kind:"conditional-branch",file:d.file,displayName:o.conditionExpression,canEditHere:!0}]}:f}function hg(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 SR(e){let t=await Cg(e);if(t.length===0)return ut("unsupported-expression",`Unsupported expression type: ${e.expression.type}`);if(vR(e.expression))return Ig(t);if(wg(e.expression))return ut("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 ut("dynamic-key","Computed member expressions are not supported for provenance resolution");let[n]=t;return ut(n.code,n.message)}function ut(e,t){return{finalSource:null,chain:[],confidence:"unknown",editMode:"unsupported",diagnostics:[{code:e,message:t}]}}function ER(e,t){return Ig([{code:e,message:t}])}function Ig(e){return{finalSource:null,chain:[],confidence:"partial",editMode:"readonly",diagnostics:e}}function vR(e){return Z.isCallExpression(e)||Z.isConditionalExpression(e)||Z.isLogicalExpression(e)||Z.isBinaryExpression(e)}function Co(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 Cg(e){let{expression:t,scope:n,currentFile:r,readFile:o,exists:i,fileCache:s,visited:a,functionCallContracts:c}=e,l=kl(t);if(l)return[l];if(Z.isCallExpression(t))return[{code:"unsupported-expression",message:Ng(t,c)}];if(Z.isMemberExpression(t)&&t.computed){let d=t.property;if(!Z.isNumericLiteral(d)&&!Z.isStringLiteral(d)){if(!Z.isExpression(d))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}];let m=await ms(d,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)?Co([...await Sl(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)?Co([...await Sl(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)?Co([...await Sl(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 kl(e){return wg(e)?yg("i18n helpers require a static message id string"):wR(e)?yg("CMS helpers require static entry id and field path string arguments"):null}async function Sl(...e){let t=e[e.length-1],n=e.slice(0,-1),r=[];for(let o of n)r.push(...await Cg({...t,expression:o}));return r}function kR(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:[IR(e.sourceType)]}}async function Rl(e){for(let n of TR){if(!xg(e.expressionPath,n.helperNames))continue;let r=await n.resolve(e);if(r)return Sg(bg(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(!xg(e.expressionPath,n.helperNames))continue;let r=await n.resolve(t);if(r)return Sg(bg(r),e.externalAdapters)}return null}function IR(e){return{code:"missing-adapter",message:`No external adapter is registered for ${e}`}}function CR(e){return{code:"external-source-readonly",message:e}}function yg(e){return{code:"unsupported-expression",message:e}}function wl(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 xg(e,t){if(!t||t.length===0)return!0;let n=wl(e.node);return n?t.includes(n):!1}function bg(e){return"match"in e?{match:e.match,editMode:e.editMode,diagnostics:Co(e.diagnostics??[])}:{match:e,diagnostics:[]}}function Sg(e,t){let n=kR(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:Co([...e.diagnostics,...e.editMode==="readonly"||n.editMode==="readonly"?n.diagnostics:[]])}}function RR(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 wR(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 Rg(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 wg(e){return Rg(e)===null}async function NR(e,t,n){let r=new Set,o=Io.posix.dirname(e);for(;r.add(o),!(o==="."||o==="/");){let i=Io.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"]:[Io.posix.join(i,"locales"),Io.posix.join(i,"messages")];for(let a of s){let c=Io.posix.join(a,`${t}.json`);if(await n(c))return c}}return null}async function PR(e){let t=Rg(e.expressionPath.node);if(typeof t!="string"||t.length===0)return null;let n="en",r=await NR(e.currentFile,n,e.exists);return r?{sourceType:"i18n-message",sourceId:`${n}:${t}`,file:r,displayPath:t}:null}async function AR(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 ms(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:[CR("API mapping transforms must stay readonly until a reversible mapping strategy is registered")]}:i}var TR=[{helperNames:["getCmsField"],resolve:({expressionPath:e})=>RR(e)},{helperNames:["apiField"],resolve:e=>AR(e)},{helperNames:["t","intl.formatMessage"],resolve:({currentFile:e,expressionPath:t,exists:n})=>PR({currentFile:e,expressionPath:t,exists:n})}];function Nl(e){return{...e,editMode:"readonly",diagnostics:[{code:"unsupported-expression",message:"Derived display values are readonly because no identity-preserving write target exists"}]}}function Eg(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 Il(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=BR(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 FR=[{helperName:"formatPrice",purity:"pure",sourceArgIndex:0},{helperName:"formatDate",purity:"pure",sourceArgIndex:0},{helperName:"pickLabel",purity:"pure",sourceArgIndex:0}];function Pl(e,t){let n=[...FR,...t??[]];for(let r=n.length-1;r>=0;r-=1){let o=n[r];if(o?.helperName===e)return o}return null}function Ng(e,t){let n=e.callee;return Z.isIdentifier(n)&&Pl(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 Al(e){let t=await Rl(e);if(t)return t;let n=await Pg({...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 $t({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 bt({...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 DR(e)}async function Pg(e){let t=await Ct({...e,allowComposed:!1});if(t?.kind!=="source")return null;let n=hs(e.expressionPath);return n.isIdentifier()||n.isMemberExpression()?t.provenance:Nl(t.provenance)}async function Ct(e){let t=hs(e.expressionPath),n=MR(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 $t({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 bt({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 $t({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 bt({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 Ct({...e,expressionPath:r,allowComposed:!0}),a=await Ct({...e,expressionPath:o,allowComposed:!1}),c=await Ct({...e,expressionPath:i,allowComposed:!1});return El(s,a,c)}if(t.isCallExpression())return _R({...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 Ct({...e,expressionPath:r,allowComposed:!0}),s=await Ct({...e,expressionPath:o,allowComposed:!0});return El(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 Ct({...e,expressionPath:r,allowComposed:!0}),s=await Ct({...e,expressionPath:o,allowComposed:!0});return El(i,s)}if(t.isUnaryExpression()){let r=t.get("argument");return Array.isArray(r)||!r.isExpression()?null:Ct({...e,expressionPath:r,allowComposed:!0})}return null}finally{n&&e.visited.delete(n)}}function hs(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 _R(e){let t=wl(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:Ct({...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:Ct({...e,expressionPath:o,allowComposed:!1})}}return null}function El(...e){let t=null;for(let n of e){if(!n)return null;if(n.kind!=="none"){if(!t){t=n.provenance;continue}if(!OR(t,n.provenance))return null}}return t?{kind:"source",provenance:t}:{kind:"none"}}function OR(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 MR(e,t){return t.start==null||t.end==null?null:`safe-derived:${e}:${t.start}:${t.end}`}async function DR(e){if(!e.expressionPath.isCallExpression())return null;let t=wl(e.expressionPath.node);if(!t)return null;let n=Pl(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 Ag({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?Nl(i):null}async function Ag(e){let t=await Rl({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 $t({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 bt({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 Al({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 LR(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=Pl(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 Ag({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?Nl(a):null}function BR(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=yr(t,e.path);return{sourceId:o,displayPath:o}}async function jR(e){let t=e.segment.source;return t?bt({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 bt(e){let t=e.sourceInfo,n=bl(e.expressionPath,t.base);if(n){let l=await pR({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=ug(n.callPath,[...n.basePath,...t.path]);return io(h)?gg(e.currentFile,h.sourceId,h.displayPath):null}let d=pg(l,[...n.basePath,...t.path]),f=l.collectionIndexMap?.[0]??0,m=[...l.pathPrefix??[],{kind:"index",index:f},...n.basePath,...t.path],u=[{kind:"index",index:0},...n.basePath,...t.path];return Qe(l.value,u)===void 0?null:{kind:"value",file:l.file,root:l.root,path:d?.[0]??m,sourceKind:"repeat-template",collectionIndexMap:l.collectionIndexMap,...d?{collectionPathMap:d}:{}}}let r=e.expressionPath.scope.getBinding(t.base);if(!r)return null;if(r.path.isImportNamespaceSpecifier()){let l=t.path[0],d=r.path.parentPath;if(!l||l.kind!=="property"||!d?.isImportDeclaration())return null;let f=await yn(e.currentFile,d.node.source.value,e.exists);if(!f)return null;let m=await hR({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 u=t.path.slice(1);return Qe(m.value,u)===void 0?null:{kind:"value",file:m.file,root:m.root,path:u,sourceKind:"imported-binding",collectionIndexMap:m.collectionIndexMap}}let o=pp(r);if(o){let l=o.expressionPath,d=await $t({expression:l.node,scope:l.scope,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(d){let f=await bt({...e,expressionPath:l,sourceInfo:{...d,expression:yr(d.expression,t.path),path:[...d.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 Tg({...e,expressionPath:hs(l),memberSuffix:t.path});if(m?.kind==="value")return m}finally{e.visited.delete(f)}}if(t.path.length===0){let f=await Pg({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 yR({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 LR({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=Vi(r,t.path);if(io(s))return gg(e.currentFile,s.sourceId,s.displayPath);let a=await gs({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 Tg(e){let t=dg(e.expressionPath.node);if(!t||!fg(t.segments))return null;let n=await bt({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 gR({...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 gs({...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:hr(e.expressionPath.node,e.fileCache.get(e.currentFile)?.source),...r.collectionIndexMap?{collectionIndexMap:r.collectionIndexMap}:{},collectionPathMap:o}}async function Fg(e){let t=$R(e.propertyName);if(t.owner==="blocked")return pn(t.owner,t.diagnostic);if(t.owner==="class-name-source"||t.owner==="style")return pn(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 pn("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 KR(e,l)});o.sort((l,d)=>l.order-d.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 pn("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}:pn("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?pn("generic",{code:"remove-exposes-spread",message:`Removing '${e.propertyName}' would expose an earlier spread source`}):VR(e,s.attribute)}async function VR(e,t){if(t.resolution&&t.resolution.status!=="resolved"&&!t.source){let r=await xr({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}}:pn("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 xr({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"?pn("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 KR(e,t){let n=t.source?.expression;if(!n)return;let r=await xr({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:UR(r,e.propertyName)}}function UR(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 pn(e,t){return{status:"blocked",owner:e,...t?{diagnostic:t}:{}}}function _g(e){let{key:t,element:n,graph:r,provenances:o}=e,i=XR(t,n,r),s=i?.tag??(Bn(n.tag)?n.tag:n.componentName),a=i?.identity.key??Og(n,r)??t,c=WR(i),l=GR(t,n,r,o,i),d=JR(t,n,r,o,a);return{componentName:s,instanceKey:a,templateOwner:HR(i??n,s),...c.length>0?{variantKeys:c}:{},...l.length>0?{slotKeys:l}:{},editableStrategy:d,impactScope:YR(d),alternativeStrategies:ZR(d)}}function JR(e,t,n,r,o){for(let i of r.values())if(i?.editMode==="upstream")return"upstream";return Tl(e,n)?"instance":!Bn(t.tag)&&t.sourceFile!==n.routeId&&o!==e?"template":"instance"}function Og(e,t){if(Bn(e.tag))return e.identity.key;let n=[...t.elements.values()].filter(r=>r.importedFrom===e.sourceFile&&zR(r,e.componentName));return n.length!==1?null:n[0].identity.key}function XR(e,t,n){if(Bn(t.tag))return t;let r=Tl(e,n);if(r)return r;let o=Og(t,n);return o?n.elements.get(o)??null:null}function zR(e,t){return e.exportName===t||e.tag===t||e.exportName==="default"}function HR(e,t){return Bn(e.tag)&&e.importedFrom?`${e.importedFrom}#${t}`:`${e.sourceFile}#${t}`}function WR(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 GR(e,t,n,r,o){let i=new Set,s=Tl(e,n);s&&o?.identity.key===s.identity.key&&i.add("children");for(let a of r.values()){let c=a?.chain.find(d=>d.kind==="component-prop");if(!c)continue;let l=c.displayName.split(".").pop();l&&i.add(l)}return i.size===0&&Bn(t.tag)&&t.childKeys.length>0&&i.add("children"),[...i]}function Tl(e,t){let n=t.elements.get(e)?.parentKey??null;for(;n;){let r=t.elements.get(n);if(!r)break;if(Bn(r.tag))return r;n=r.parentKey}return null}function Bn(e){return/^[A-Z]/.test(e)}function YR(e){switch(e){case"template":return"component-template";case"upstream":return"upstream-source";default:return"current-instance"}}function ZR(e){switch(e){case"template":return["instance"];case"upstream":return["template"];default:return["template"]}}function Lg(e){let t=e.isRepeat??(e.graph?sw(e.element,e.graph):!1),n=e.propertyProvenance??new Map,r=e.repeatTargets??new Map,o=iw(e.element.attributes??[]),i=[...r.values()].some(d=>d.ok),s=o.map(d=>QR({attribute:d,element:e.element,isRepeat:t,selectionRef:e.selectionRef,provenance:n.get(d.name),repeatTarget:r.get(d.name)})),a=(e.element.attributeSpreads?.length??0)>0,c=(e.element.attributeSpreads??[]).slice().sort((d,f)=>d.order-f.order).map(d=>({raw:d.raw,sourceRange:aw(d.sourceRange,e.source),order:d.order,diagnostics:d.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 QR(e){let{attribute:t,provenance:n,repeatTarget:r}=e,o=e.selectionRef?.instanceIndex!==void 0&&r?.ok===!0?r:null,i=qR(t,n,e.isRepeat),s=["selection","template"].map(S=>({scope:S,result:Yi({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,d=ew(t,n,l,e.isRepeat),f=c?rw(c,e.element,t.name):void 0,m=s.filter(({result:S})=>S.ok).map(({scope:S})=>S),u=m.length>0?nw(n,o,e.element):"unsupported",g=o?"repeat-item":e.isRepeat?"repeat-template":"node",h=ow(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:d,editMode:u,sourceScope:g,allowedWriteScopes:m,...f?{effectiveWriteTarget:f}:{},diagnostics:h}}function qR(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 ew(e,t,n,r){return n?Mg(n.selectedResolution):t?.status==="blocked"?{status:"unresolved"}:r&&t?.status==="binding"?{status:"unresolved"}:Mg(tw(e))}function tw(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 Mg(e){return!e||e.status==="unresolved"?{status:"unresolved"}:e.status==="undefined"?{status:"undefined"}:{status:"resolved",value:e.value}}function nw(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 rw(e,t,n){return e.kind==="repeat-property"?{kind:"value-path",file:e.target.sourceFile,isProxy:e.target.sourceFile!==t.sourceFile,displayPath:Dg({...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:Dg(e.locator)}:{kind:"jsx-node",file:t.sourceFile,isProxy:!1,displayPath:t.componentName+" > "+n}}function ow(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 iw(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 Dg(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 aw(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 cw(e){return e==="api-field"||e==="cms-field"||e==="i18n-message"||e==="config-entry"}var lw=160;function Bg(e,t,n,r={}){let o=qn(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 jg(e,t,n,r,o,i,s,a,c,l,d){let f=qn(t),m=t.elements.get(e),u=n.nodes.get(e),g=r.get(e);if(!m||!u||!g)throw new Error(`Node not found: ${e}`);let h=Jg(m.textSegments,s),S=Xg(e,t,m,g,h),E=h?pw(h):void 0,y=mw(i,h),v=m.textSegments.map(R=>({index:R.index,value:R.value,editable:zg(R,g,s?.get(R.index)??null),source:o.get(R.index)??null})),C=Kg(m,t),N=m.childKeys.map(R=>{let T=t.elements.get(R);return T?{key:R,tag:T.tag,label:T.tag}:null}).filter(R=>R!==null),A=[];if(m.parentKey){let R=t.elements.get(m.parentKey);if(R)for(let T of R.childKeys){if(T===e)continue;let O=t.elements.get(T);O&&A.push({key:T,tag:O.tag,label:O.tag})}}return{composition:f,key:e,tag:m.tag,componentName:m.componentName,sourceFile:m.sourceFile,sourceLocator:Vg(m),label:m.tag,capabilities:S,writeTarget:i,effectiveWriteTarget:y,provenanceChain:E,componentSemantic:c,styleSource:l,conditional:a,...d?{dynamicData:d}:{},textSegments:v,boundaryKind:m.boundaryKind,isOpaque:m.isOpaque,ancestors:C,children:N,siblings:A}}function $g(e,t,n,r,o,i,s,a){let c=qn(t),l=t.elements.get(e),d=n.nodes.get(e),f=r.get(e);if(!l||!d||!f)throw new Error(`Node not found: ${e}`);let m=Jg(l.textSegments,i),u=uw(l);return{composition:c,key:e,tag:l.tag,...u?{linkSourceKind:u}:{},componentName:l.componentName,sourceFile:l.sourceFile,sourceLocator:Vg(l),label:l.tag,capabilities:Xg(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:zg(g,f,i?.get(g.index)??null),source:h?{kind:h.kind}:null}}),boundaryKind:l.boundaryKind,isOpaque:l.isOpaque,ancestors:Kg(l,t)}}function uw(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 Vg(e){return{sourceFile:e.sourceFile,componentName:e.componentName,openingElementRange:dw(e.sourceRange),structuralPath:e.identity.structuralPath,...fw(e.textSegments)}}function Kg(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 dw(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function fw(e){let t=e.map(n=>n.value.trim()).filter(Boolean).join(" ").replace(/\s+/g," ").trim();return t?{textPreview:t.slice(0,lw)}:{}}function Ug(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 Jg(e,t){if(!t)return null;for(let n of e){let r=t.get(n.index);if(r)return r}return null}function Xg(e,t,n,r,o){let i=n.identity.structuralPath.includes("#repeat:"),s=t.regions.some(d=>d.kind==="repeat-region"&&d.childKeys.includes(e)),a=o?.diagnostics.find(d=>d.code==="missing-adapter"||d.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&&Hg(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 zg(e,t,n){return!e.editable||!t.canUpdateText?!1:n?Hg(n.editMode):!0}function Hg(e){return e==="direct"||e==="proxy"||e==="upstream"}function pw(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 mw(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}:cw(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 Fl=["set-class-name-source","apply-style-draft"];function Wg(e){let t=e.attributes?.find(n=>n.name==="className");if(!t)return{kind:"class-name-source",className:"",sourceKind:"missing",editable:!0,operationBoundary:Fl,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:Fl,sourcePath:n}}return{kind:"class-name-source",className:t.value,sourceKind:t.resolvedValue===void 0?"static-attribute":"static-expression",editable:!0,operationBoundary:Fl}}function Gg(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}),Yg(i,r,o,t,e)}}return{nodes:t,rootKeys:[...e.rootKeys]}}function Yg(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}),Yg(s,t,n,r,o))}}import Zg 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 qg(e,t,n){let r=[],o=new Set;for(let i of e.intents){let s=xw(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 ys(e){let t=()=>gw(e);return e.mutex?e.mutex.runExclusive(t):t()}async function gw(e){let t=await qg(e.plan,e.overlay,e.exists);if(!t.ok)return{ok:!1,stage:"precheck",reason:t.reason,error:t,recoveryRequired:!1};let n=hw(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 _l({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 _l({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 _l({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 Qg("swap",l,"Live state swap failed after durable publish.")}try{await e.finalizeCandidate?.(c)}catch(l){return Qg("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 hw(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 _l(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:yw(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 Qg(e,t,n){return{ok:!1,stage:e,reason:n,error:t,recoveryRequired:!0}}function yw(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 xw(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)||Zg.isAbsolute(e))return{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`};let t=Zg.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 bw=50,Sw=8*1024*1024;function rh(e,t={}){let n=[],r=[],o=t.externalAdapters??[],i=Math.max(0,t.maxUndoEntries??bw),s=Math.max(0,t.maxUndoBytes??Sw);return{prepareRewritePlan:a,execute:c,executeFilePlan:l,undo:d,redo:f};async function a(R){let T=[...R.steps].sort((Q,de)=>Q.order-de.order),O=T.filter(Q=>Q.type!=="invoke-external-adapter");if(O.length!==T.length)return{ok:!1,errorCode:"unsupported-operation",reason:"External adapter writes require a transactional prepare/commit/rollback contract."};let M=new Set(O.map(Q=>Q.file)),U=await y(M),ee=new Map(U.map(Q=>[Q.file,Q.exists===!1?"":Q.content])),Re;for(let Q of O){let de=nh(Q,ee.get(Q.file)??"");if(!de.ok)return{ok:!1,errorCode:de.errorCode,reason:de.reason};ee.set(Q.file,de.source),Re=de.selectionRef??Re}return{ok:!0,filePlan:{operationId:R.operationId,kind:"source-edit",target:R.target,documentVersion:R.documentVersion,conflictPolicy:"compare-and-swap",edits:[...ee].map(([Q,de])=>({operation:"upsert",file:Q,content:de,baseContentHash:U.find(Te=>Te.file===Q)?.sha256??null}))},...Re?{selectionRef:Re}:{}}}async function c(R){let T=[...R.steps].sort((Te,Gt)=>Te.order-Gt.order),O=T.filter(Te=>Te.type!=="invoke-external-adapter"),M=T.filter(Te=>Te.type==="invoke-external-adapter"),U=new Set(O.map(Te=>Te.file));if(O.length>0&&M.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(O.length===0)return S(R,M);let ee=await y(U),Re=new Map;for(let Te of ee)Re.set(Te.file,Te.exists===!1?"":Te.content);let Q;for(let Te of O){let Gt=Re.get(Te.file)??"",Yt=nh(Te,Gt);if(!Yt.ok)return{ok:!1,operationId:R.operationId,errorCode:Yt.errorCode,reason:Yt.reason,rolledBack:!1};Re.set(Te.file,Yt.source),Yt.selectionRef&&(Q=Yt.selectionRef)}let de=await C([...Re].map(([Te,Gt])=>({file:Te,content:Gt,exists:!0,version:0,sha256:Se(Gt)})),ee);return de.ok===!1?{ok:!1,operationId:R.operationId,errorCode:de.rolledBack?"writeback-failed":"rollback-failed",reason:de.reason,rolledBack:de.rolledBack}:(n.push({operationId:R.operationId,preSnapshots:ee,postSnapshots:de.snapshots,plan:R}),m(),r.length=0,{ok:!0,operationId:R.operationId,kind:R.kind,target:R.target,resultVersion:Math.max(...de.snapshots.map(Te=>Te.version)),affectedFiles:[...U],...Q?{selectionRef:Q}:{}})}async function l(R){let T=new Set(R.edits.map(de=>de.file)),O=await y(T),M=E(R,O);if(M)return{ok:!1,operationId:R.operationId,errorCode:"stale-version",reason:M.reason,affectedFiles:[M.file],rolledBack:!1};let U=new Map(O.map(de=>[de.file,de])),ee=R.edits.find(de=>de.operation==="create-only"&&U.get(de.file)?.exists!==!1);if(ee)return{ok:!1,operationId:R.operationId,errorCode:"stale-version",reason:`MATERIALIZATION_INSTANCE_CONFLICT: create-only target already exists: ${ee.file}`,affectedFiles:[ee.file],rolledBack:!1};let Re=R.edits.map(de=>de.operation==="delete"?{file:de.file,content:"",exists:!1,version:0}:{file:de.file,content:de.content,exists:!0,version:0,sha256:Se(de.content)}),Q=await C(Re,O,new Set(R.edits.filter(de=>de.operation==="create-only").map(de=>de.file)));return Q.ok===!1?{ok:!1,operationId:R.operationId,errorCode:Q.rolledBack?"writeback-failed":"rollback-failed",reason:Q.reason,rolledBack:Q.rolledBack}:(n.push({operationId:R.operationId,preSnapshots:O,postSnapshots:Q.snapshots,plan:{operationId:R.operationId,kind:R.kind,target:R.target,documentVersion:R.documentVersion,steps:[],preSnapshots:O}}),m(),r.length=0,{ok:!0,operationId:R.operationId,kind:R.kind,target:R.target,resultVersion:Math.max(...Q.snapshots.map(de=>de.version)),affectedFiles:[...T]})}async function d(){let R=n.at(-1);if(!R)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to undo"};let T=await C(R.preSnapshots,R.postSnapshots);return T.ok===!1?{ok:!1,operationId:R.operationId,errorCode:T.rolledBack?"writeback-failed":"rollback-failed",reason:T.reason,rolledBack:T.rolledBack}:(n.pop(),r.push(R),{ok:!0,operationId:R.operationId,kind:R.plan.kind,target:R.plan.target,resultVersion:Math.max(...T.snapshots.map(O=>O.version)),affectedFiles:R.preSnapshots.map(O=>O.file)})}async function f(){let R=r.at(-1);if(!R)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to redo"};let T=await C(R.postSnapshots,R.preSnapshots);return T.ok===!1?{ok:!1,operationId:R.operationId,errorCode:T.rolledBack?"writeback-failed":"rollback-failed",reason:T.reason,rolledBack:T.rolledBack}:(r.pop(),n.push(R),m(),{ok:!0,operationId:R.operationId,kind:R.plan.kind,target:R.plan.target,resultVersion:Math.max(...T.snapshots.map(O=>O.version)),affectedFiles:R.postSnapshots.map(O=>O.file)})}function m(){for(;n.length>i;)n.shift();for(;n.length>0&&u()>s;)n.shift()}function u(){return n.reduce((R,T)=>R+g(T),0)}function g(R){return h(R.preSnapshots)+h(R.postSnapshots)}function h(R){return R.reduce((T,O)=>T+O.file.length+O.content.length,0)}async function S(R,T){let O=[];for(let M of T){let U=M.capability??"write-text",ee=o.find(Q=>Q.sourceType===M.sourceType&&(M.adapterId===void 0||Q.adapterId===M.adapterId)&&(Q.capabilities===void 0||Q.capabilities.includes(U)));if(!ee)return{ok:!1,operationId:R.operationId,errorCode:"unsupported-operation",reason:`No external adapter registered for ${M.sourceType}`,rolledBack:!1};let Re=await ee.execute(M);if(!Re.ok)return{ok:!1,operationId:R.operationId,errorCode:"writeback-failed",reason:Re.reason??`External adapter failed for ${M.sourceType}`,rolledBack:!1};O.push(M.file)}return{ok:!0,operationId:R.operationId,kind:R.kind,target:R.target,resultVersion:0,affectedFiles:O}}function E(R,T){if(R.conflictPolicy!=="compare-and-swap")return null;let O=new Map(T.map(M=>[M.file,M]));for(let M of R.edits){if(M.operation==="create-only")continue;if(M.baseContentHash===void 0)return{file:M.file,reason:`Source file ${M.file} is missing baseContentHash. Reopen the file before saving.`};let U=O.get(M.file),ee=M.baseContentHash;if(ee===null){if(U?.exists!==!1)return{file:M.file,reason:`Source file ${M.file} was created or changed before save.`};continue}if(!ee)return{file:M.file,reason:`Source file ${M.file} is missing baseContentHash. Reopen the file before saving.`};if(U?.exists===!1||U?.sha256!==ee)return{file:M.file,reason:`Source file ${M.file} changed before save. Reload or explicitly overwrite the newer version.`}}return null}async function y(R){let T=[];for(let O of R)T.push(await v(O));return T}async function v(R){if(!await e.exists(R))return{file:R,content:"",version:0,exists:!1};let O=Math.max(1,e.getVersion(R)),M=await e.readFile(R);return{file:R,content:M,version:O,exists:!0,sha256:Se(M)}}async function C(R,T,O=new Set){let M=[];try{for(let U of R){if(O.has(U.file)){if(!e.createExclusive)throw new Error("Create-only write requires atomic exclusive-create support.");await e.createExclusive(U.file,U.content)}else await N(U);let ee=e.bumpVersion(U.file);M.push(U.file),U.version=ee}}catch(U){let ee=await A(T.filter(Q=>M.includes(Q.file)));if(ee.ok===!1)return{ok:!1,reason:`Writeback failed, then rollback failed for ${ee.failedFiles.join(", ")}: ${th(U)}`,rolledBack:!1,instanceConflict:eh(U)};let Re=eh(U);return{ok:!1,reason:`${Re?"MATERIALIZATION_INSTANCE_CONFLICT: ":""}Writeback failed and committed files were restored: ${th(U)}`,rolledBack:!0,instanceConflict:Re}}return{ok:!0,snapshots:R.map(Ew)}}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 T=[];for(let O of R)try{await N(O),e.bumpVersion(O.file)}catch{T.push(O.file)}return T.length===0?{ok:!0}:{ok:!1,failedFiles:T}}}function eh(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="EEXIST"}function Ew(e){let t=e.exists!==!1;return{file:e.file,content:t?e.content:"",version:e.version,exists:t,...t?{sha256:Se(e.content)}:{}}}function th(e){return e instanceof Error?e.message:String(e)}function nh(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(Zn({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(Wn({source:t,locator:e.parentLocator,node:e.node,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"update-text":return We(Zo({source:t,locator:e.locator,segmentIndex:e.segmentIndex,newText:e.newText}));case"update-value":return We(Fr({source:t,locator:e.locator,next:e.value}));case"update-array-item":return We(Fr({source:t,locator:e.locator,next:e.value}));case"insert-bound-array-item":return We(oi({source:t,locator:e.locator,index:e.index,value:e.value}));case"insert-jsx-expression-child":return We(qo({source:t,locator:e.parentLocator,expression:e.expression,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"remove-bound-array-item":return We(ii({source:t,locator:e.locator,index:e.index}));case"move-array-item":return We(si({source:t,locator:e.locator,fromIndex:e.fromIndex,toIndex:e.toIndex}));case"move-node":return We(Gn({source:t,locator:e.locator,targetParentLocator:e.targetParentLocator,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"move-repeat-template-child":return We(ei({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 vw(e,t);case"set-property-changes":return We(ti({source:t,locator:e.locator,changes:e.changes}));case"set-link-target":return We(ni({source:t,locator:e.locator,link:e.link,changes:e.changes}));case"set-property-binding":return We(ri({source:t,locator:e.locator,name:e.name,object:e.object,property:e.property}));case"upsert-object-property":return We(ci({source:t,objectLocator:e.locator,name:e.name,value:e.value}));default:return{ok:!1,reason:`Unknown step type: ${e.type}`,errorCode:"unknown"}}}function vw(e,t){let{request:n}=e;if(n.newAttrRaw!==null&&!gd(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!==Se(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:md({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 xs,SiteEditCompositionContextSchema as kw,SiteEditCompositionSelectorSchema as Iw}from"@vcp-dev/contracts";var Ye=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="SiteEditCompositionError"}};function oh(e,t){throw new Ye("INVALID_COMPOSITION",e,{value:t})}function bs(e){let t=kw.safeParse(e);return t.success?t.data:oh("Invalid SiteEditCompositionContext.",e)}function ih(e){let t=[],n=new Map,r=new Map;for(let l of e.compositions){let d=bs(l?.context);if(typeof l.entryFile!="string"||!l.entryFile)throw new Ye("INVALID_COMPOSITION","A registered composition must have a non-empty entryFile.");let f=xs(d);if(n.has(f))throw new Ye("DUPLICATE_COMPOSITION",`Composition key ${f} is registered more than once.`,{key:f,context:d});let m=r.get(l.entryFile);if(m)throw new Ye("DUPLICATE_COMPOSITION",`Entry file ${l.entryFile} is registered more than once.`,{entryFile:l.entryFile,context:m});let u={context:d,entryFile:l.entryFile,key:f};t.push(u),n.set(f,u),r.set(l.entryFile,f)}if(t.length===0)throw new Ye("INVALID_COMPOSITION","At least one composition must be registered.");let o=new Map;for(let l of e.initialDocumentVersions??[]){let d=bs(l?.composition);if(!Number.isInteger(l?.version)||(l?.version??-1)<0)throw new Ye("INVALID_INITIAL_DOCUMENT_VERSION","Initial document version must be a non-negative integer.",{context:d,version:l?.version});let f=xs(d);if(!n.has(f))throw new Ye("UNKNOWN_COMPOSITION","Initial document version references an unregistered composition.",{context:d,key:f});if(o.has(f))throw new Ye("DUPLICATE_COMPOSITION","Initial document versions must contain each composition at most once.",{context:d,key:f});o.set(f,l.version)}function i(l){let d=Iw.safeParse(l);if(!d.success)return oh("Invalid SiteEditCompositionSelector.",l);let f=t.filter(({context:m})=>m.routeId===d.data.routeId&&(d.data.templateId===void 0?m.effectiveTemplateId===void 0:m.effectiveTemplateId===d.data.templateId));if(f.length===1)return f[0];throw f.length>1?new Ye("AMBIGUOUS_COMPOSITION","The composition selector matches multiple registered contexts.",{selector:d.data}):new Ye("UNKNOWN_COMPOSITION","The composition selector is not registered.",{selector:d.data})}function s(l){let d=bs(l),f=xs(d),m=n.get(f);if(!m)throw new Ye("UNKNOWN_COMPOSITION","The composition context is not registered.",{context:d,key:f});return m}function a(l){let d=bs(l?.context);if(typeof l.entryFile!="string"||!l.entryFile)throw new Ye("INVALID_COMPOSITION","A registered composition must have a non-empty entryFile.");let f=xs(d),m=n.get(f);if(m){if(m.entryFile===l.entryFile)return m;throw new Ye("DUPLICATE_COMPOSITION",`Composition key ${f} is registered more than once.`,{key:f,context:d})}let u=[...n.values()].find(h=>h.entryFile===l.entryFile);if(u)throw new Ye("DUPLICATE_COMPOSITION",`Entry file ${l.entryFile} is registered more than once.`,{entryFile:l.entryFile,context:u.context});let g={context:d,entryFile:l.entryFile,key:f};return t.push(g),n.set(f,g),g}function c(l){let d=n.get(l);if(!d)return;n.delete(l);let f=t.findIndex(m=>m.key===l);return f>=0&&t.splice(f,1),o.delete(l),d}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))]}}import{composeSiteEditRepeatInstanceKey as Cw,stripSiteEditRepeatInstanceKeys as sh}from"@vcp-dev/contracts";function ah(e){let t=new Map,n=new Map,r=new Map;for(let o of e.entries){t.set(o.key,o);let i=sh(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 Rw(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 Ss(e){return e?.map(t=>({...t}))}function Ml(e,t){if(t===null||e?.kind!=="value-binding"||e.sourceKind!=="repeat-template")return e;let n=e.collectionIndexMap?.[t]??t,r=Ss(e.collectionPathMap?.[t])??Ss(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:Ss(e.path),locator:e.locator?{...e.locator,path:r}:e.locator,collectionIndexMap:e.collectionIndexMap?[...e.collectionIndexMap]:void 0,collectionPathMap:e.collectionPathMap?.map(o=>Ss(o)??[])}}function ch(e,t,n){let r=new Set;for(let u of t.regions)if(u.kind==="repeat-region")for(let g of u.childKeys)r.add(g);if(r.size===0)return e;let o=new Map(e.entries.map(u=>[u.key,u])),i=[],s=new Map,a=(u,g)=>Cw(u,g),c=(u,g,h)=>{let S=o.get(u);if(!S)return a(u,h);let E=a(u,h),y={...S,key:E,parentKey:g,childKeys:[]};return i.push(y),y.childKeys=S.childKeys.flatMap(v=>l(v,h,E)),E},l=(u,g,h)=>{if(!r.has(u))return[c(u,h,g)];let S=f(u,g),E=[];for(let y=0;y<S;y+=1)E.push(c(u,h,[...g,y]));return E},d=Array.from(new Set([...e.rootKeys,...e.entries.filter(u=>u.parentKey===null).map(u=>u.key)]));for(let u of d){if(!r.has(u)){c(u,null,[]);continue}let g=f(u,[]);for(let h=0;h<g;h+=1)c(u,null,[h])}return{...e,rootKeys:[...e.rootKeys],entries:i};function f(u,g){let h=new Set;for(let S of m(u)){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 ww(y))v.length<=g.length||Nw(v,g)&&h.add(v[g.length])}}return h.size>0?h.size:Rw(n.get(u))}function m(u){let g=s.get(u);if(g)return g;let h=[u],S=o.get(u);for(let E of S?.childKeys??[])h.push(...m(E));return s.set(u,h),h}}function lh(e){let t=e.parts.at(-1);return typeof t?.repeatIndex=="number"?t.repeatIndex:null}function uh(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((sh(s.key)??s.key)===n){if(s.key===t)return i;i+=1}return null}function ww(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 Nw(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 dh(e,t,n,r){if(!n)return{...e,key:t};let o=r??new Map(n.entries.map(d=>[d.key,d])),i=o.get(t);if(!i)return{...e,key:t};let s=[],a=i.parentKey;for(;a;){let d=o.get(a);if(!d)break;s.push({key:d.key,tag:d.tag,label:d.label}),a=d.parentKey}s.reverse();let c=i.childKeys.map(d=>o.get(d)).filter(d=>d!==void 0).map(d=>({key:d.key,tag:d.tag,label:d.label})),l=i.parentKey===null?[]:(o.get(i.parentKey)?.childKeys??[]).filter(d=>d!==i.key).map(d=>o.get(d)).filter(d=>d!==void 0).map(d=>({key:d.key,tag:d.tag,label:d.label}));return{...e,key:i.key,ancestors:s,children:c,siblings:l}}function fh(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 ph(e){return{path:e.path,code:e.code,message:e.message,...e.details?{details:JSON.parse(JSON.stringify(e.details))}:{}}}function Pw(e){return e.map(t=>`${t.code} (${t.path}): ${t.message}`).join("; ")}var Ro=class extends Error{constructor(t){let n=t.map(ph);super(Pw(n)),this.name="RouteBuildDiagnosticsError",this.diagnostics=n}};function mh(e,t){let n=t instanceof Error&&t.message?t.message:String(t);return t instanceof Ro?{routeId:e,message:n,diagnostics:t.diagnostics.map(ph)}:{routeId:e,message:n}}function Dl(e){return e.map(({routeId:t,message:n})=>`${t}: ${n}`).join("; ")}function Ll(e,t){let n=new Map(e);for(let r of t)n.delete(r);return n}function br(e,t){e.clear();for(let[n,r]of t)e.set(n,r)}function gh(e,t){for(let n of t){if(n.exists===!1){e.delete(n.file);continue}e.set(n.file,n.content)}}function Bl(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 hh(e){let{journal:t,index:n,observedFileDigests:r}=e;if(r.length!==t.files.length)return"ambiguous";let o=t.files.every((l,d)=>l.preDigest===r[d]),i=t.files.every((l,d)=>l.postDigest===r[d]),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 Lw=/^(?:src\/)?app\/.*\/?page\.[cm]?[jt]sx?$/,Bw=["layout.tsx","layout.ts","layout.jsx","layout.js","layout.mjs","layout.cjs"],yh=32,xh=256;function jw(e){return{expectedIndexDigest:e.digest,publishedIndexDigest:e.digest,publishedCursor:e.cursor,publishedCurrentId:e.currentId}}var bh={maxEntries:50,maxBytes:8*1024*1024};function $w(){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 ui(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 Vw(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 Kw(){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>bh.maxEntries||Uw(e)>bh.maxBytes;)e.shift()}}function Uw(e){return e.reduce((t,n)=>t+Jw(n),0)}function Jw(e){return Sh(e.preSnapshots)+Sh(e.postSnapshots)+Xw(e.provenance)}function Xw(e){return e?new TextEncoder().encode(JSON.stringify(e)).byteLength:0}function Sh(e){return e.reduce((t,n)=>t+n.file.length+n.content.length,0)}function Eh(e,t){return{key:Tw(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 vs=class extends Error{constructor(t){super(t.reason),this.result=t}},jn=class extends Error{constructor(t){super(Dl(t)),this.failedRoutes=t}};function vh(e,t){if(!e)return;let n=[...t];if(n.some(o=>o?.entries.some(i=>i.key===e.key)))return e;let r=ot(e.key)??e.key;for(let o of n){let i=o?.entries.find(s=>(ot(s.key)??s.key)===r);if(i)return{...e,key:i.key}}return e}function zw(e,t,n){if(!n)return;let r=ot(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 Hw=/\.(?:[cm]?[jt]sx?)$/i,Ww=/\.json$/i,Gw=/\.(?:css|scss|sass)$/i,Yw=/\.mdx$/i,Zw=/\.ya?ml$/i;function Qw(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 qw(e){return{kind:e.isProxy?"component-proxy":"jsx-node",file:e.file,componentName:e.componentName,isProxy:e.isProxy}}function eN(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=Nh(await e.listFiles(i)),a=new Map(s.files.map(l=>[l.path,l]));for(let[l,d]of n)if(tN(l,i.roots??[])){if(!d.exists){a.delete(l);continue}a.set(l,{path:l,sizeBytes:Buffer.byteLength(d.content,"utf8")})}let c=[...a.values()].sort((l,d)=>l.path.localeCompare(d.path));return s.truncated?{files:c,truncated:s.truncated}:c},getVersion(i){return e.getVersion(i)},bumpVersion(i){return e.getVersion(i)}}}function tN(e,t){return t.length===0?!0:t.some(n=>e===n||e.startsWith(`${n}/`))}function Nh(e){return Array.isArray(e)?{files:e}:e}function nN(e){if(!_w(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!==Mw||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=Fw(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(Hw.test(e.path)){let t=Nt({source:e.content,profile:bn({filePath:e.path,source:e.content})});if(!t.ok)return{ok:!1,errorCode:"ast-error",message:t.diagnostic.message,details:{path:e.path}}}if(Ww.test(e.path))try{JSON.parse(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`JSON parse failed: ${qe(t)}`,details:{path:e.path}}}if(Gw.test(e.path)){let t=kh({content:e.content,path:e.path,profile:"css"});if(!t.ok)return t}if(Yw.test(e.path)){let t=kh({content:e.content,path:e.path,profile:"mdx"});if(!t.ok)return t}if(Zw.test(e.path))try{Dw(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`YAML parse failed: ${qe(t)}`,details:{path:e.path}}}return{ok:!0}}function kh({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]??"",u=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==="*"&&u==="/"&&(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
|
-
`||m==="\r"))return
|
|
13
|
-
`||m==="\r";continue}if(m==="/"&&u==="*"){s=!0,f+=1,l=!1;continue}if(n==="mdx"&&m==="/"&&u==="/"){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
|
|
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 d=r.at(-1);return d?Er(t,`Unclosed token "${d.char}" in ${t}.`):{ok:!0}}function Er(e,t){return{ok:!1,errorCode:"ast-error",message:t,details:{path:e}}}function Ao(e){let t="idle",n=e.fileSystem??jw(),r=hd(),o=ih({compositions:e.compositions,initialDocumentVersions:e.initialDocumentVersions}),i=new Map,s=new Map,a=new Set,c=null,l=e.history??(e.historyStore?of(e.historyStore):Vw()),d=rh(n,{externalAdapters:e.externalAdapters}),f=new Map,m=new Set,u=0,g=e.historyStore?.recoveryRequired??!1,h=Ol(),S=I();function E(p){return(ks.isAbsolute(p)?ks.relative(e.projectRoot,p):p).replace(/\\/g,"/").replace(/^\.\//,"")}function y(p,x){let b=ks.posix.dirname(p),C=x.replace(/\.(?:tsx?|jsx?)$/i,""),N=ks.posix.relative(b,C);return N.startsWith(".")?N:`./${N}`}function v(p,x){return p.startLine===x.startLine&&p.startColumn===x.startColumn&&p.endLine===x.endLine&&p.endColumn===x.endColumn}async function I(){let p=e.historyStore;if(p)try{let x=await p.readTransactionJournal();if(!x)return;let b=await p.readIndex(),C=await Promise.all(x.files.map(async O=>await n.exists(O.path)?Ee(await n.readFile(O.path)):null));if(hh({journal:x,index:b,observedFileDigests:C})!=="ambiguous"){await p.clearTransactionJournal(x.transactionId);let O=await p.readStatus();O.recoveryRequired||(await p.cleanupTmp(),O=await p.readStatus()),g=O.recoveryRequired;return}await p.markRecoveryRequired(`Ambiguous transaction journal ${x.transactionId} at phase ${x.phase}`),g=!0}catch(x){g=!0,await p.markRecoveryRequired(`Transaction journal recovery failed: ${qe(x)}`).catch(()=>{})}}function P(){return t==="disposed"}e.onEvent&&r.subscribe(e.onEvent);for(let p of o.entries){let x=Eh(p.context,p.entryFile);i.set(p.key,x),A(x,x.dependencyFiles)}function A(p,x){let b=new Set(x);R(p),p.dependencyFiles=b;for(let C of p.dependencyFiles){let N=s.get(C);N||(N=new Set,s.set(C,N)),N.add(p.key)}}function R(p){for(let x of p.dependencyFiles){let b=s.get(x);b&&(b.delete(p.key),b.size===0&&s.delete(x))}p.dependencyFiles.clear()}function T(p){let x=new Set;for(let b of p)for(let C of s.get(b)??[])x.add(C);return x}function F(p){for(let x of p)if(!s.has(x))return!1;return!0}async function D(p,x,b,C,N){let O=new Map,M=vg(N.values()),H=new Map,X=typeof n.exists=="function"?L=>n.exists(L):async()=>!1;for(let[L,B]of p.elements){let se=x.nodes.get(L);if(!se)continue;let te=b.get(B.sourceFile)??C.get(B.sourceFile),Ne=new Map,ye=new Map,ke=new Map,Ie=[];for(let Se of B.textSegments){if(!te){Ne.set(Se.index,null);continue}let vr=await kg({file:B.sourceFile,source:te,segment:Se,readFile:st=>n.readFile(st),exists:X,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:st,adapterId:hn,capabilities:Os})=>({sourceType:st,adapterId:hn,capabilities:Os})),functionCallContracts:e.functionCallContracts,fileCache:M}),Ze=await Cl({file:B.sourceFile,source:te,target:{kind:"text-segment",segment:Se},readFile:st=>n.readFile(st),exists:X,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:st,adapterId:hn,capabilities:Os})=>({sourceType:st,adapterId:hn,capabilities:Os})),functionCallContracts:e.functionCallContracts,fileCache:M}),ft=Zw(vr);Ne.set(Se.index,ft),ye.set(Se.index,vr),ke.set(Se.index,Ze),Ie.push({editable:Se.editable,source:ft})}let _=new Map,V=new Map;if(te)for(let Se of B.attributes??[]){let vr=await br({file:B.sourceFile,source:te,sourceRange:Se.sourceRange,expression:Se.source?.expression??Se.value,sourceInfo:Se.source,readFile:ft=>n.readFile(ft),exists:X,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:ft,adapterId:st,capabilities:hn})=>({sourceType:ft,adapterId:st,capabilities:hn})),functionCallContracts:e.functionCallContracts,fileCache:M}),Ze=await Fg({element:B,file:B.sourceFile,source:te,propertyName:Se.name,readFile:ft=>n.readFile(ft),exists:X,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:ft,adapterId:st,capabilities:hn})=>({sourceType:ft,adapterId:st,capabilities:hn})),functionCallContracts:e.functionCallContracts,fileCache:M});V.set(Se.name,Ze),_.set(Se.name,vr)}let pe=Ug(Qw(se.writeTarget),Ie),ie=_g({key:L,element:B,graph:p,provenances:ke}),Pe=Wg(B),De=te?await Rm({element:B,graph:p,file:B.sourceFile,source:te,readFile:Se=>n.readFile(Se),exists:X,fileCache:H}):void 0,it=p.regions.find(Se=>Se.kind==="conditional-region"&&Se.childKeys.includes(L)),Qt,We=it?.sourceCandidates?.[0];if(te&&it&&We?.kind==="conditional-branch"){let Se=await Cl({file:B.sourceFile,source:te,target:{kind:"conditional-branch",candidate:We},readFile:Ze=>n.readFile(Ze),exists:X,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Ze,adapterId:ft,capabilities:st})=>({sourceType:Ze,adapterId:ft,capabilities:st})),functionCallContracts:e.functionCallContracts,fileCache:M});Qt={currentBranch:it.childKeys.indexOf(L)<=0?"then":"else",availableBranches:it.childKeys.length>1?["then","else"]:["then"],conditionExpression:We.conditionExpression,provenance:{finalSource:Se.finalSource?{kind:Se.finalSource.kind,file:Se.finalSource.file,displayPath:Se.finalSource.displayPath}:null,chain:Se.chain.map(Ze=>({kind:Ze.kind,file:Ze.file,displayName:Ze.displayName,canEditHere:Ze.canEditHere})),confidence:Se.confidence,editMode:Se.editMode,diagnostics:Se.diagnostics.map(Ze=>({code:Ze.code,message:Ze.message}))}}}O.set(L,{textSources:Ne,textTargets:ye,elementPropertyTargets:_,propertyProvenances:V,isRepeat:yN(L,p),provenances:ke,writeTarget:pe,componentSemantic:ie,styleSource:Pe,conditional:Qt,dynamicData:De})}return O}function U(p){return typeof n.getVersion=="function"?n.getVersion(p):0}function ee(p,x){let b=o.initialVersions.get(p.key)??0;for(let C of x.values())b=Math.max(b,C);return Math.max(b,p.graph?.version??0)}function we(p){return i.get(p)?.graph?.version??o.initialVersions.get(p)??0}function Q(p){try{return we(o.resolveSelector(p.composition).key)}catch{return 0}}async function fe(p,x,b={}){let C=i.get(p);if(!C)return null;let N=b.sourceCache??Ll(f,[]),O=await Oe(C.entryFile),{graph:M,allSources:H,diagnostics:X,parsedModules:L,entryModule:B}=await Cd(C.entryFile,x,We=>n.readFile(We),typeof n.exists=="function"?We=>n.exists(We):async()=>!1,{additionalEntries:O,version:C.graph?.version??1});if(X.length>0)throw new wo(X);let se=new Map;for(let We of H.keys())se.set(We,U(We));let te=Math.max(ee(C,se),b.minimumVersion??0);b.changed&&te<=(C.graph?.version??0)&&(te=(C.graph?.version??0)+1),M.version=te;for(let[We,Se]of H)Bl(N,We,Se,xh);let Ne=await Yt(C.composition,C.entryFile,H,N);M.routeId=C.routeId,M.composition=C.composition;let ye=Gg(M),ke=dd(ye,M),Ie=await D(M,ye,H,N,L),_=Fh(M,ke,Ie),V=Th(Ie),pe=ch(Bg(M,ye,ke,{canUpdateTextByKey:_,dynamicDataSummaryByKey:V}),M,Ie),ie=Kf({route:C.routeId,composition:C.composition,entryFile:C.entryFile,version:te,source:x,ast:B?.ast}),Pe=Uf(ie);ie.ok&&rN(pe,M,ie.projection,L);let De={...pe,composition:C.composition,...Ne?{styleContext:Ne}:{},pageComposition:Pe},it=new Set([C.entryFile,...H.keys()]);if(Ne){it.add(Ne.entryCss.path);for(let We of Ne.stylesheets)it.add(We.path)}let Qt={...C,dependencyFiles:it,graph:M,topology:ye,capabilities:ke,document:De,pageComposition:Pe,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:ah(De),detailProjections:Ie,fileVersions:se,styleContext:Ne};if(b.publish===!1)return Qt;Sr(f,N);for(let We of N.keys())m.delete(We);return A(C,it),Object.assign(C,Qt),C}async function Oe(p){let x=[];for(let b of dN(p))typeof n.exists=="function"&&await n.exists(b)&&x.push({file:b,source:await n.readFile(b)});return x}async function Yt(p,x,b,C){let N=[];for(let[L,B]of b){if(jl(L)){N.push(L);continue}for(let se of pN(B)){let te=wh(L,se);te&&N.push(te)}}if(!N.length){for(let L of fN(x))if(await Vl(L)){N.push(L);break}}let O=new Map,M=hN(N).slice(0,yh);for(;M.length>0&&O.size<yh;){let L=M.shift();if(O.has(L)||!jl(L))continue;let B=await Zt(L,C);if(B!==null){O.set(L,{path:L,content:B});for(let se of mN(B)){let te=wh(L,se);te&&!O.has(te)&&!M.includes(te)&&M.push(te)}}}let H=[...O.values()].map(L=>({...L,hash:Ee(L.content)})),X=H[0];return X?{composition:p,revision:Ee(JSON.stringify(H.map(({path:L,hash:B})=>({path:L,hash:B})))),entryCss:X,stylesheets:H.slice(1)}:null}async function Zt(p,x){let b=x.get(p);if(b!==void 0)return b;if(!await Vl(p))return null;let C=await n.readFile(p);return Bl(x,p,C,xh),C}async function Vl(p){return typeof n.exists=="function"?n.exists(p):!1}function Th(p){let x=new Map;for(let[b,C]of p)C.dynamicData?.bindings.length&&x.set(b,Lm(C.dynamicData.bindings));return x}function Fh(p,x,b){let C=new Map;for(let[N,O]of p.elements){if(!x.get(N)?.canUpdateText){C.set(N,!1);continue}let H=b.get(N),X=O.textSegments.some(L=>{if(!L.editable)return!1;let B=H?.provenances.get(L.index)??null;return!B||_h(B)});C.set(N,X)}return C}function _h(p){return p.editMode==="direct"||p.editMode==="proxy"||p.editMode==="upstream"}async function To(p,x={}){let b=[...new Set(p)],C=x.affectedCompositionKeys!==void 0,N=C?new Set(x.affectedCompositionKeys):T(b);if(!C&&(N.size===0||!F(b)))for(let X of i.values())Kl(X,b)&&N.add(X.key);let O=!C&&N.size===0&&b.some(Rh),M=x.publish===!1?Ll(f,b):void 0,H={rebuiltRoutes:[],failedRoutes:[],...x.publish===!1?{candidateRouteStates:[],candidateSourceCache:M}:{}};for(let X of i.values())if(!(x.excludedCompositionKeys?.has(X.key)||!(N.has(X.key)||O)))try{let B=!!X.graph,se=await n.readFile(X.entryFile),te=await fe(X.key,se,{...x,...M?{sourceCache:M}:{}});te?.graph&&(H.rebuiltRoutes.push({documentChanged:B,composition:X.composition,routeId:X.routeId,version:te.graph.version}),H.candidateRouteStates?.push({composition:X.composition,key:X.key,routeId:X.routeId,state:te}))}catch(B){H.failedRoutes.push({...mh(X.routeId,B),composition:X.composition})}return H}function Kn(p){let x=[...new Set(p)],b=T(x);if(b.size>0&&F(x))return[...b];for(let C of i.values())Kl(C,x)&&b.add(C.key);return[...b]}function Oh(p){let x=new Set(Kn(p));return o.entries.filter(b=>x.has(b.key)).map(b=>b.context)}function Mh(p){return[...new Set(Kn(p))].sort((b,C)=>b<C?-1:b>C?1:0).map(b=>o.getByKey(b)?.context).filter(b=>b!==void 0)}function Dh(p,x){let b=new Set(Kn(x)),C=p.provenance?.affectedCompositions??[];if(C.length===0)return b;if([...new Set(C.map(O=>o.resolveContext(O).key))].some(O=>!b.has(O)))throw new Error("History provenance does not match the affected composition index.");return b}function Lh(p,x){let b=p.composition??p.provenance?.initiatingComposition;if(b){let O=o.resolveContext(b);return{context:O.context,key:O.key}}let C=[...new Set(Kn(x))];if(C.length!==1)throw new Error(`Legacy history entry cannot be attributed to a unique composition (affected composition count: ${C.length}).`);let N=o.getByKey(C[0]);if(!N)throw new Error("Legacy history entry references an unknown affected composition.");return{context:N.context,key:N.key}}function Ns(p,x){r.emit({type:"operation-completed",composition:p.composition,result:p});for(let{composition:b,version:C}of x.rebuiltRoutes)r.emit({type:"document-changed",composition:b,version:C});for(let{composition:b,message:C}of x.failedRoutes)r.emit({type:"graph-error",composition:b,message:C})}function Kl(p,x){return x.some(b=>p.dependencyFiles.has(b)||p.entryFile===b||p.graph?.fileIndex.has(b))}function Ul(p){for(let x of p)a.add(x);c||P()||(c=(async()=>{t="building";let x=!1;try{for(;a.size>0;){if(P())return;await Bh();let b=[...a];a.clear();let C=await Jl(b);if(C.length===0)continue;let N=Kn(C);for(let H of N){let X=i.get(H)?.composition;X&&r.emit({type:"graph-invalidated",composition:X})}let{rebuiltRoutes:O,failedRoutes:M}=await To(C,{changed:!0});for(let{documentChanged:H,composition:X,version:L}of O)r.emit({type:"graph-ready",composition:X,version:L}),H&&r.emit({type:"document-changed",composition:X,version:L});for(let{composition:H,message:X}of M)x=!0,r.emit({type:"graph-error",composition:H,message:X})}}finally{c=null,t!=="disposed"&&(t=!x&&[...i.values()].some(b=>b.graph)?"ready":"idle"),a.size>0&&Ul([])}})())}async function Bh(){for(;u>0;)await new Promise(p=>setTimeout(p,0))}async function Jl(p){let x=[];for(let b of new Set(p)){let C=f.get(b);if(C===void 0){if(m.has(b)&&!await n.exists(b))continue;m.delete(b),x.push(b);continue}try{await n.readFile(b)!==C&&(m.delete(b),x.push(b))}catch(N){if(!nN(N))try{if(await n.exists(b))continue}catch{continue}m.add(b),x.push(b)}}return x}function Xl(p){gh(f,p);for(let x of p)x.exists===!1?m.add(x.file):m.delete(x.file)}function zl(p){m.clear();for(let x of p)m.add(x)}async function Hl(p){let x=await Jl(p);if(x.length===0)return;let b=Kn(x);for(let O of b){let M=i.get(O)?.composition;M&&r.emit({type:"graph-invalidated",composition:M})}let{rebuiltRoutes:C,failedRoutes:N}=await To(x,{changed:!0});for(let{documentChanged:O,composition:M,version:H}of C)r.emit({type:"graph-ready",composition:M,version:H}),O&&r.emit({type:"document-changed",composition:M,version:H});for(let{composition:O,message:M}of N)r.emit({type:"graph-error",composition:O,message:M})}async function jh(p,x){let b=Xn(p,x);if(!b?.graph)return;let C=ot(p)??p,N=b.graph.elements.get(C);N&&await Hl([N.sourceFile])}async function Wl(p){let x=new Set;if(p.target.kind==="node"){let b=Xn(p.target.key,p.composition),C=ot(p.target.key)??p.target.key,N=b?.graph?.elements.get(C);N&&x.add(N.sourceFile)}else if(p.target.kind==="route"){let b=i.get(o.resolveSelector(p.target.composition).key);b&&x.add(b.entryFile)}else if(p.target.kind==="page-unit"){let b=i.get(o.resolveSelector(p.target.composition).key);b&&x.add(b.entryFile)}else if(p.target.kind==="source-file")x.add(p.target.path);else if(p.target.kind==="source-batch")for(let b of p.target.paths)x.add(b);if(p.params.kind==="move-node"&&!("kind"in p.params.target)){let b=[p.params.target.parentKey,...p.params.target.relation==="before"||p.params.target.relation==="after"?[p.params.target.anchorKey]:[]];for(let C of b){let N=Xn(C,p.composition),O=ot(C)??C,M=N?.graph?.elements.get(O);M&&x.add(M.sourceFile)}}await Hl(x)}async function $h(p){if(p.params.kind!=="source-edit")return Ps(p,"invalid-params","source-edit requires source-edit params");for(let x of p.params.edits){let b=tN(x);if(!b.ok)return Ps(p,b.errorCode,b.message,b.details)}u+=1;try{let x=await Xh(p.params.edits);if(!x.ok)return Ps(p,x.errorCode,x.message,x.details);await Wl(p);let b={operationId:p.id,kind:"source-edit",target:p.target,documentVersion:p.documentVersion,conflictPolicy:p.params.conflictPolicy,edits:p.params.edits.map(C=>C.operation==="delete"?{operation:"delete",file:C.path,baseContentHash:C.baseContentHash??null}:{operation:"upsert",file:C.path,baseContentHash:C.baseContentHash??null,content:C.content})};return await Jn({request:p,filePlan:b})}catch(x){return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Q(p),error:{code:$.INTERNAL_ERROR,message:qe(x)}}}finally{u-=1}}async function Vh(p){if(p.target.kind!=="project"||p.params.kind!=="insert-page-resource")return le(p,$.INVALID_PARAMS,"insert-page-resource requires project target and matching params.");u+=1;try{let x=await Mo({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:[...p.params.artifact.components.flatMap(C=>C.materialization.files.map(N=>({path:N.pathTemplate,content:N.content}))),...p.params.artifact.pages.flatMap(C=>C.materialization.files.map(N=>({path:N.pathTemplate,content:N.content})))],exists:C=>n.exists(C),readFile:C=>n.readFile(C)});if(!x.ok)return le(p,$.MATERIALIZATION_REJECTED,x.message);let b=await Wa({artifact:p.params.artifact,exists:C=>n.exists(C)});return b.ok?await Jn({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:p.target,documentVersion:p.documentVersion,conflictPolicy:"overwrite",edits:b.files},output:{kind:"insert-page-resource",package_instance_id:b.packageInstanceId,pages:b.pages},historyPolicy:"none"}):le(p,b.code==="MATERIALIZATION_CONFLICT"?$.MATERIALIZATION_CONFLICT:$.MATERIALIZATION_REJECTED,b.message,b.path?{path:b.path}:void 0)}catch(x){return le(p,$.INTERNAL_ERROR,qe(x))}finally{u-=1}}async function Kh(p){if(p.target.kind!=="project"||p.params.kind!=="delete-page-source")return le(p,$.INVALID_PARAMS,"delete-page-source requires project target and matching params.");if(!n.listFiles)return le(p,$.PLAN_FAILED,"Complete project file listing is required for page deletion.");u+=1;try{let x=Nh(await n.listFiles({maxFiles:5e4,maxDepth:64}));if(x.truncated)return le(p,$.PLAN_FAILED,"Project file listing is incomplete; page deletion was refused.",{truncationReasons:x.truncated.reasons});let b=x.files.filter(({path:M})=>/\.(?:tsx?|jsx?)$/.test(M)),C=Object.fromEntries(await Promise.all(b.map(async({path:M})=>[M,await n.readFile(M)]))),N=fp({expectedUrlPath:p.params.expectedUrlPath,files:C});if(!N.ok)return le(p,N.code==="HOME_PAGE_LOCKED"?$.HOME_PAGE_LOCKED:N.code==="ROUTE_NOT_FOUND"?$.ROUTE_NOT_FOUND:$.PLAN_FAILED,N.message);let O=await Promise.all(N.edits.map(async M=>({...M,baseContentHash:Ee(await n.readFile(M.file))})));return Jn({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:p.target,documentVersion:p.documentVersion,conflictPolicy:"compare-and-swap",edits:O},output:{kind:"delete-page-source",deleted_files:N.deletedFiles,updated_files:N.updatedFiles,preserved_shared_files:N.preservedSharedFiles,warnings:N.warnings},historyPolicy:"none"})}catch(x){return le(p,$.INTERNAL_ERROR,qe(x))}finally{u-=1}}async function Uh(p,x){if(p.kind!=="insert-child"&&p.kind!=="replace-node")return le(p,$.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,$.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,$.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.");if(p.params.position.documentVersion!==p.documentVersion)return le(p,$.VERSION_STALE,"Page-unit insert-child placement belongs to a different document version.")}let b=x.document,C=x.pageCompositionProjection;if(!b||b.pageComposition?.status!=="supported"||!C||C.status!=="supported")return le(p,$.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(p.documentVersion!==b.version||C.documentVersion!==b.version)return le(p,$.VERSION_STALE,`Document version ${p.documentVersion} is stale (current: ${b.version}).`);let N=p.params.node.kind==="component-call"?p.params.node.materialization:void 0;if(!N)return le(p,$.UNSUPPORTED_OPERATION,"Page-unit insertion currently requires a static materialization manifest.");let O=p.params.kind==="insert-child"?p.params.position:null,M=await Mo({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:N.files.map(L=>({path:L.pathTemplate,content:L.content})),exists:L=>n.exists(L),readFile:L=>n.readFile(L)});if(!M.ok)return le(p,$.MATERIALIZATION_REJECTED,M.message);let H=await $w(n,Object.keys(N.projectDependencies??{})),X=await Rf({manifest:N,generatedRoot:"components/site/generated",controlledFiles:N.files.map(L=>({pathTemplate:L.pathTemplate})),exists:L=>n.exists(L),availableHostDependencies:H,commit:async L=>{let B=await n.readFile(x.entryFile),se=x.document,te=x.pageCompositionProjection;if(!se||se.pageComposition?.status!=="supported"||se.version!==p.documentVersion||!te||te.status!=="supported"||te.documentVersion!==se.version)return{ok:!0,data:le(p,$.VERSION_STALE,"The route changed before the page-unit insertion could commit.")};let Ne=L.entry.path,ye=Qh(L.instanceName),ke,Ie=[];if(p.params.kind==="insert-child"){if(!O||!("kind"in O)||O.kind!=="page-composition")return{ok:!0,data:le(p,$.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.")};let ie=tc({routeId:x.routeId,entryFile:x.entryFile,currentDocumentVersion:se.version,expectedDocumentVersion:p.documentVersion,source:B,projection:te,placementKey:O.placementKey,component:{source:Ne,exportName:L.entry.export.kind==="default"?"default":L.entry.export.name,localName:ye}});if(!ie.ok)return{ok:!0,data:le(p,_s(ie.error.code),ie.error.message,{diagnostics:ie.error.diagnostics})};let Pe=ie.plan.rewriteStep,De;switch(Pe.kind){case"insert-root-expression":De=Di({source:B,locator:Pe.locator,expectedSourceHash:Pe.sourceHash,action:{kind:"insert",jsx:Pe.node.jsx,placement:Pe.placement,replaceOriginal:Pe.replaceOriginal}});break;case"insert-child":De=Gn({source:B,locator:Pe.parentLocator,node:Pe.node,placement:Pe.placement,...Pe.anchorLocator?{anchorLocator:Pe.anchorLocator}:{}});break;default:De={ok:!1,source:B,diagnostic:{code:"unsupported-syntax",message:`Unsupported route composition rewrite: ${String(Pe)}`}}}if(!De.ok)return{ok:!0,data:le(p,$.AST_PARSE_ERROR,De.diagnostic.message)};ke=De.source}else{let ie=nc({routeId:x.routeId,composition:x.composition,entryFile:x.entryFile,currentDocumentVersion:se.version,expectedDocumentVersion:p.documentVersion,source:B,projection:te,placementUnitKey:p.target.placementUnitKey,operation:"replace-node"});if(!ie.ok)return{ok:!0,data:le(p,_s(ie.error.code),ie.error.message,{diagnostics:ie.error.diagnostics})};let Pe=ie.plan.rewriteStep,De;switch(Pe.kind){case"replace-root-expression":De=Di({source:B,locator:Pe.locator,expectedSourceHash:Pe.sourceHash,action:{kind:"replace",jsx:`<${ye} />`}});break;case"replace-node":De=ei({source:B,locator:Pe.locator,node:{jsx:`<${ye} />`}});break;default:De={ok:!1,source:B,diagnostic:{message:`Unsupported page-unit replacement rewrite: ${Pe.kind}`}}}if(!De.ok)return{ok:!0,data:le(p,$.AST_PARSE_ERROR,De.diagnostic.message)};let it=await Gl({routeState:x,placementUnitKey:p.target.placementUnitKey,source:B,mutatedSource:De.source});ke=it.source,Ie=await Promise.all(it.files.map(async Qt=>({operation:"delete",file:Qt,baseContentHash:Ee(await n.readFile(Qt))})))}let _=Qn({source:ke,moduleSpecifier:y(x.entryFile,Ne),imports:L.entry.export.kind==="default"?[{kind:"default",local:ye}]:[{kind:"named",imported:L.entry.export.name,local:ye}]});if(!_.ok)return{ok:!0,data:le(p,$.AST_PARSE_ERROR,_.diagnostic.message)};let V=L.files.map(ie=>({operation:"create-only",file:ie.path,content:ie.content})),pe=[{operation:"upsert",file:x.entryFile,content:_.source,baseContentHash:Ee(B)},...V,...Ie];u+=1;try{let ie=await Jn({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:{kind:"source-file",path:x.entryFile},documentVersion:p.documentVersion,conflictPolicy:"compare-and-swap",edits:pe}});return!ie.ok&&ie.error?.message.includes("MATERIALIZATION_INSTANCE_CONFLICT")?{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:ie.error?.message??"Static prefab instance conflicted during commit."}}:{ok:!0,data:ie}}finally{u-=1}}});return X.ok?X.data:le(p,X.error.code==="MATERIALIZATION_INSTANCE_CONFLICT"?$.MATERIALIZATION_CONFLICT:$.MATERIALIZATION_REJECTED,X.error.message,{materializationCode:X.error.code})}async function Jh(p,x){if(p.kind!=="move-node"&&p.kind!=="remove-node")return le(p,$.UNSUPPORTED_OPERATION,"Only page-unit move-node and remove-node are currently supported by the page composition transaction.");let b=x.document,C=x.pageCompositionProjection;if(!b||b.pageComposition?.status!=="supported"||!C||C.status!=="supported")return le(p,$.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(p.documentVersion!==b.version||C.documentVersion!==b.version)return le(p,$.VERSION_STALE,`Document version ${p.documentVersion} is stale (current: ${b.version}).`);let N=await n.readFile(x.entryFile),O=nc({routeId:x.routeId,composition:x.composition,entryFile:x.entryFile,currentDocumentVersion:b.version,expectedDocumentVersion:p.documentVersion,source:N,projection:C,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(!O.ok)return le(p,_s(O.error.code),O.error.message,{diagnostics:O.error.diagnostics});let M=O.plan.rewriteStep,H;switch(M.kind){case"move-node":H=Yn({source:N,locator:M.locator,targetParentLocator:M.targetParentLocator,placement:M.placement,...M.anchorLocator?{anchorLocator:M.anchorLocator}:{}});break;case"remove-node":H=Wn({source:N,locator:M.locator});break;case"remove-root-expression":H=Di({source:N,locator:M.locator,expectedSourceHash:M.sourceHash,action:{kind:"remove"}});break;default:H={ok:!1,source:N,diagnostic:{message:`Unsupported page-unit mutation rewrite: ${M.kind}`}}}if(!H.ok)return le(p,$.AST_PARSE_ERROR,H.diagnostic.message);let X=H.source,L=[];if(p.kind==="remove-node"){let se=await Gl({routeState:x,placementUnitKey:p.target.placementUnitKey,source:N,mutatedSource:X});X=se.source,L=await Promise.all(se.files.map(async te=>({operation:"delete",file:te,baseContentHash:Ee(await n.readFile(te))})))}let B=[{operation:"upsert",file:x.entryFile,content:X,baseContentHash:Ee(N)},...L];u+=1;try{return await Jn({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:{kind:"source-file",path:x.entryFile},documentVersion:p.documentVersion,conflictPolicy:"compare-and-swap",edits:B}})}finally{u-=1}}async function Gl(p){let x={source:p.mutatedSource,files:[]},b=p.routeState.graph,C=p.routeState.pageCompositionProjection;if(!b||!C||C.status!=="supported"||!n.listFiles)return x;let O=C.placementUnitByKey.get(p.placementUnitKey)?.sourceRange;if(!O)return x;let M=[...b.elements.values()].find(_=>_.sourceFile===p.routeState.entryFile&&_.importedFrom&&v(_.sourceRange,O));if(!M?.importedFrom||!M.exportName)return x;let H=E(M.importedFrom),X="components/site/generated/";if(!H.startsWith(X))return x;let L=H.slice(X.length).split("/")[0];if(!L||!/-[0-9a-f]{8}$/i.test(L))return x;let B=`${X}${L}`;if([...b.elements.values()].filter(_=>_.sourceFile===p.routeState.entryFile&&E(_.importedFrom??"")===H).length!==1)return x;let te=await n.listFiles({maxFiles:5e3,maxDepth:32}),Ne=Array.isArray(te)?te:te.files;if(!Array.isArray(te)&&te.truncated)return x;let ye=Ne.map(({path:_})=>_).filter(_=>_===B||_.startsWith(`${B}/`));if(ye.length===0||!ye.includes(H))return x;for(let{path:_}of Ne)if(!(_===p.routeState.entryFile||_===B||_.startsWith(`${B}/`)))try{if((await n.readFile(_)).includes(L))return x}catch{return x}let ke=y(p.routeState.entryFile,H),Ie=qn({source:p.mutatedSource,moduleSpecifier:ke,imports:M.exportName==="default"?[{kind:"default"}]:[{kind:"named",imported:M.exportName}]});return Ie.ok?Ie.source.includes(L)?{source:Ie.source,files:[]}:{source:Ie.source,files:ye.sort((_,V)=>_.localeCompare(V))}:x}async function Xh(p){if(n.getFileInfo){for(let N of p)if(await n.exists(N.path)&&await n.getFileInfo(N.path)===null)return{ok:!1,errorCode:"invalid-params",message:`Source edit path must resolve to a regular non-symbolic-link file: ${N.path}`,details:{path:N.path}}}for(let N of p){if(N.operation!=="upsert"||!/^(?:src\/)?app\/globals\.css$/i.test(N.path))continue;let O=await n.exists(N.path)?await Ys(n,N.path):null;if(O?.ok){let M=Pw(O.content,N.content);if(!M.ok)return{ok:!1,errorCode:"invalid-params",message:M.message,details:{path:N.path,code:M.code}}}}let x=zh(p);if(x.length===0)return{ok:!0};let b=qw(n,p),C=Ao({projectRoot:e.projectRoot,fileSystem:b,compositions:[...i.values()].map(N=>({context:N.composition,entryFile:N.entryFile})),externalAdapters:e.externalAdapters,externalSourceResolvers:e.externalSourceResolvers,functionCallContracts:e.functionCallContracts,dev:e.dev});try{for(let N of x){let O=i.get(N)?.composition;if(!O)continue;let M={routeId:O.routeId,...O.effectiveTemplateId!==void 0?{templateId:O.effectiveTemplateId}:{}};await C.initializeComposition(M),C.getDocument(M)}}catch(N){return{ok:!1,errorCode:"ast-error",message:`Source edit preflight failed: ${qe(N)}`,details:{compositionKeys:x}}}finally{C.dispose()}return{ok:!0}}function zh(p){return p.map(b=>b.path).some(Rh)?[...i.keys()]:[]}function Ps(p,x,b,C){let N=No(x);return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Q(p),error:{code:N,message:b,...C?{details:C}:{}}}}async function As(p){let x=[];for(let b of new Set(p))x.push(await Hh(b));return x}async function Hh(p){if(!(typeof n.exists=="function"?await n.exists(p):!0))return{file:p,content:"",version:Math.max(0,U(p)),exists:!1};let b=await n.readFile(p);return{file:p,content:b,version:Math.max(1,U(p)),exists:!0,sha256:Ee(b)}}async function Yl(p,x,b,C){if(!e.historyStore)return null;let N=new Map(x.map(H=>[H.file,H])),O=new Map(b.map(H=>[H.file,H])),M=[...new Set([...N.keys(),...O.keys()])].sort().map(H=>{let X=N.get(H),L=O.get(H);return{path:H,preDigest:X?.exists===!1||!X?null:Ee(X.content),postDigest:L?.exists===!1||!L?null:Ee(L.content)}});return{schemaVersion:2,transactionId:`${p}:${C.expectedIndexDigest}`,operationId:p,phase:"prepared",historyTransition:C,files:M}}async function Zl(p){return!p||!e.historyStore||await e.historyStore.writeTransactionJournal(p),p}async function Un(p){p&&e.historyStore&&await e.historyStore.clearTransactionJournal(p.transactionId)}async function Ts(p,x){let b=[];try{for(let C of p)await Ql(C),typeof n.bumpVersion=="function"&&n.bumpVersion(C.file),b.push(C.file)}catch(C){let N=await Wh(x.filter(O=>b.includes(O.file)));return N.ok?{ok:!1,reason:`Writeback failed and committed files were restored: ${qe(C)}`,rolledBack:!0}:{ok:!1,reason:`Writeback failed, then rollback failed for ${N.failedFiles.join(", ")}: ${qe(C)}`,rolledBack:!1}}return{ok:!0,snapshots:p.map(Gh)}}async function Ql(p){if(p.exists===!1){await n.deleteFile(p.file);return}await n.writeFile(p.file,p.content)}async function Wh(p){let x=[];for(let b of p)try{await Ql(b),typeof n.bumpVersion=="function"&&n.bumpVersion(b.file)}catch{x.push(b.file)}return x.length===0?{ok:!0}:{ok:!1,failedFiles:x}}function Gh(p){let x=p.exists!==!1;return{file:p.file,content:x?p.content:"",version:p.version,exists:x,...x?{sha256:Ee(p.content)}:{}}}async function Jn(p){return h.runExclusive(()=>Yh(p))}async function Yh(p){let x=p.filePlan.edits.map(_=>_.file),b=o.resolveSelector(p.request.composition),C=b.context,N=p.historyPolicy==="none"?void 0:{initiatingComposition:C,affectedCompositions:Mh(x)},O=await As(x),M=new Map(O.filter(_=>_.exists!==!1).map(_=>[_.file,_.content])),H=eu(),X=new Map(f),L=new Set(m),B=new Set([...i.values()].filter(_=>p.filePlan.edits.some(V=>V.operation==="delete"&&V.file===_.entryFile)).map(_=>_.key)),se=p.filePlan.edits.map(_=>_.operation==="delete"?{file:_.file,content:"",version:0,exists:!1}:{file:_.file,content:_.content,version:0,exists:!0,sha256:Ee(_.content)}),te={operationId:p.filePlan.operationId,intents:p.filePlan.edits.map(_=>_.operation==="delete"?{kind:"delete",path:_.file}:{kind:_.operation==="create-only"?"create-only":"upsert",path:_.file,content:_.content})},Ne=null,ye=!1,ke=await bs({overlay:M,exists:_=>n.exists(_),plan:te,buildCandidate:async({plan:_})=>({plan:_}),prepareHistory:async()=>{let _=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:O,postSnapshots:se,...p.selectionRef?{selectionRef:p.selectionRef}:{},...p.output?{output:p.output}:{},...N?{provenance:N}:{}}),V=_?.historyTransition?_.historyTransition:e.historyStore?Bw(await e.historyStore.readIndex()):null;if(e.historyStore&&!V)throw new Error("Durable history did not provide an exact index transition.");return Ne=await Yl(p.request.id,O,se,V),Ne=await Zl(Ne),{history:_,historyTransition:V}},reverify:async()=>{},writeCandidate:async()=>{let _=await d.executeFilePlan(p.filePlan);if(!_.ok)throw new Is(_);return{postSnapshots:await As(_.affectedFiles),affectedFiles:_.affectedFiles,internalResultVersion:_.resultVersion}},validateCandidate:async({candidate:_,receipt:V})=>{let pe=await To(V.affectedFiles,{changed:!0,minimumVersion:V.internalResultVersion,publish:!1,excludedCompositionKeys:B});if(pe.failedRoutes.length>0)throw new $n(pe.failedRoutes);let ie=nu(H,pe.candidateRouteStates??[]),Pe=tu(ie,b.key);return{..._,rebuild:pe,routeSnapshots:ie,resultVersion:Pe,...vh(p.selectionRef,ie.map(De=>De.state.document))?{selectionRef:vh(p.selectionRef,ie.map(De=>De.state.document))}:{}}},publishCandidate:async({candidate:_,history:V,receipt:pe})=>{V?.history&&(await l.publishPrepared(V.history),ye=!0);let ie=_.resultVersion??pe.internalResultVersion;return{composition:C,requestId:p.request.id,kind:p.request.kind,target:p.request.target,ok:!0,resultVersion:ie,affectedFiles:pe.affectedFiles,...p.output?{output:p.output}:{},..._.selectionRef?{selectionRef:_.selectionRef}:{}}},swapCandidate:({candidate:_,receipt:V})=>{_.routeSnapshots&&Fo(_.routeSnapshots),_.rebuild?.candidateSourceCache&&Sr(f,_.rebuild.candidateSourceCache),Xl(V.postSnapshots)},finalizeCandidate:async()=>{await Un(Ne);for(let _ of B)i.delete(_)},emitCommitted:({candidate:_,published:V})=>{Ns(V,_.rebuild??{rebuiltRoutes:[],failedRoutes:[]})},rollbackCandidate:async({history:_,receipt:V})=>{if(ye)throw new Error("history was published before transaction finalization failed");if(V){let pe=await Ts(O,V.postSnapshots);if(!pe.ok)throw new Error(pe.reason)}Fo(H),Sr(f,X),zl(L),_?.history&&await l.discardPrepared?.(_.history),await Un(Ne)}});if(ke.ok)return ke.published;if(ke.stage==="precheck"||ke.stage==="build")try{await Un(Ne)}catch(_){let V=await _o(qe(_));return le(p.request,V,"Unable to clear an uncommitted transaction journal.")}if(ke.recoveryRequired){let _=await _o(ke.reason);return le(p.request,_===$.RECOVERY_PERSIST_FAILED?_:$.ROLLBACK_FAILED,ke.reason)}let Ie=ke.error;return Ie instanceof Is?{...le(p.request,No(Ie.result.errorCode),Ie.result.reason),...Ie.result.affectedFiles?{affectedFiles:Ie.result.affectedFiles}:{}}:Ie instanceof $n?le(p.request,$.ROUTE_REBUILD_FAILED,`Route rebuild failed and source was rolled back: ${Dl(Ie.failedRoutes)}`,{failedRoutes:Ie.failedRoutes}):le(p.request,ou(ke.stage),qe(Ie))}async function ql(p){return h.runExclusive(async()=>{let x=p==="undo"?await l.prepareUndo():await l.prepareRedo();return x?Zh(p,x):{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:$.INTERNAL_ERROR,message:p==="undo"?"Nothing to undo":"Nothing to redo"}}})}async function Zh(p,x){let b=x.entry,C=p==="undo"?b.preSnapshots:b.postSnapshots,N=p==="undo"?b.postSnapshots:b.preSnapshots,O=C.map(V=>V.file),{context:M,key:H}=Lh(b,O),X=await As(O),L=new Map(X.filter(V=>V.exists!==!1).map(V=>[V.file,V.content])),B=we(H),se=eu(),te=new Map(f),Ne=new Set(m),ye=null,ke=!1,Ie,_=await bs({overlay:L,plan:{operationId:`${p}:${b.operationId}`,intents:C.map(V=>V.exists===!1?{kind:"delete",path:V.file}:{kind:"upsert",path:V.file,content:V.content})},buildCandidate:async()=>({}),prepareHistory:async()=>(ye=await Yl(`${p}:${b.operationId}`,X,C,x.historyTransition),ye=await Zl(ye),x),reverify:async()=>{},writeCandidate:async()=>{let V=await Ts(C,N);if(!V.ok)throw new Error(V.reason);return{snapshots:V.snapshots}},validateCandidate:async({candidate:V})=>{Ie=Dh(b,O);let pe=await To(O,{changed:!0,minimumVersion:B+1,publish:!1,affectedCompositionKeys:Ie});if(pe.failedRoutes.length>0)throw new $n(pe.failedRoutes);let ie=nu(se,pe.candidateRouteStates??[]),Pe=tu(ie,H);return{...V,rebuild:pe,routeSnapshots:ie,resultVersion:Pe}},publishCandidate:async({candidate:V,history:pe})=>{if(!pe)throw new Error("history cursor intent is missing");await l.publishPrepared(pe),ke=!0;let ie=V.resultVersion??B+1;return{composition:M,requestId:p,kind:b.kind,target:b.target,ok:!0,resultVersion:ie,affectedFiles:O,...b.output?{output:b.output}:{}}},swapCandidate:({candidate:V,receipt:pe})=>{V.routeSnapshots&&Fo(V.routeSnapshots),V.rebuild?.candidateSourceCache&&Sr(f,V.rebuild.candidateSourceCache),Xl(pe.snapshots)},finalizeCandidate:async()=>{await Un(ye)},emitCommitted:({candidate:V,published:pe})=>Ns(pe,V.rebuild??{rebuiltRoutes:[],failedRoutes:[]}),rollbackCandidate:async({history:V,receipt:pe})=>{if(ke)throw new Error("history cursor was published before transaction finalization failed");if(pe){let ie=await Ts(N,pe.snapshots);if(!ie.ok)throw new Error(ie.reason)}Fo(se),Sr(f,te),zl(Ne),V&&await l.discardPrepared?.(V),await Un(ye)}});if(_.ok)return _.published;if(_.stage==="precheck"||_.stage==="build")try{await Un(ye)}catch(V){let pe=await _o(qe(V));return{composition:M,requestId:p,kind:b.kind,target:b.target,ok:!1,resultVersion:B,error:{code:pe,message:"Unable to clear an uncommitted transaction journal."}}}if(_.recoveryRequired){let V=await _o(_.reason);return{composition:M,requestId:p,kind:b.kind,target:b.target,ok:!1,resultVersion:B,affectedFiles:O,error:{code:V===$.RECOVERY_PERSIST_FAILED?V:$.ROLLBACK_FAILED,message:_.reason}}}return{composition:M,requestId:p,kind:b.kind,target:b.target,ok:!1,resultVersion:B,affectedFiles:O,error:{code:_.error instanceof $n?$.ROUTE_REBUILD_FAILED:ou(_.stage),message:qe(_.error),..._.error instanceof $n?{details:{failedRoutes:_.error.failedRoutes}}:{}}}}function eu(){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 tu(p,x){return p.find(C=>C.key===x)?.state.graph?.version??o.initialVersions.get(x)??0}function nu(p,x){let b=new Map(p.map(C=>[C.key,C]));for(let C of x)b.set(C.key,C);return[...b.values()]}function Fo(p){for(let x of i.values())R(x);for(let x of p){let b={...x.state,dependencyFiles:new Set(x.state.dependencyFiles),fileVersions:new Map(x.state.fileVersions)};i.set(x.key,b),A(b,b.dependencyFiles)}}async function Fs(p){let x=i.get(p);if(!x)throw new Error(`Composition not found: ${p}`);if(x.graph)return;let b=await n.readFile(x.entryFile);await fe(p,b)}function Xn(p,x){let b=i.get(o.resolveSelector(x).key)??null;return!b||!ru(b,p)?null:b}function ru(p,x){if(p.documentIndex?.entriesByKey.has(x)||p.graph?.elements.has(x))return!0;let b=ot(x);return b&&b!==x?p.graph?.elements.has(b)===!0:!1}function le(p,x,b,C){return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Q(p),error:{code:x,message:b,...C?{details:C}:{}}}}function ou(p){return p==="validate"?$.ROUTE_REBUILD_FAILED:p==="publish"?$.HISTORY_COMMIT_FAILED:$.WRITE_IO_ERROR}async function _o(p){if(g=!0,!l.markRecoveryRequired)return $.RECOVERY_REQUIRED;try{return await l.markRecoveryRequired(p),$.RECOVERY_REQUIRED}catch{return $.RECOVERY_PERSIST_FAILED}}function Qh(p){let b=p.split(/[^a-zA-Z0-9]+/).filter(Boolean).map(C=>C.charAt(0).toUpperCase()+C.slice(1)).join("").replace(/^[^a-zA-Z_$]+/,"");return b?`Prefab${b}`:"GeneratedPrefab"}function _s(p){return p==="VERSION_STALE"?$.VERSION_STALE:p==="CROSS_PAGE_MOVE_UNSUPPORTED"?$.CROSS_PAGE_MOVE_UNSUPPORTED:$.UNSUPPORTED_OPERATION}async function iu(p){if(p.target.kind==="route"){let b=i.get(o.resolveSelector(p.target.composition).key)??null;return b?(b.graph||await Fs(b.key),b):le(p,$.ROUTE_NOT_FOUND,"Composition not found for route target.")}if(p.target.kind==="page-unit"){let b=i.get(o.resolveSelector(p.target.composition).key)??null;return b?(b.graph||await Fs(b.key),b):le(p,$.ROUTE_NOT_FOUND,"Composition not found for page-unit target.")}if(p.target.kind!=="node")return le(p,$.UNSUPPORTED_OPERATION,`${p.kind} source target execution is not implemented yet.`);let x=i.get(o.resolveSelector(p.composition).key)??null;return x?(x.graph||await Fs(x.key),ru(x,p.target.key)?x:le(p,$.NODE_NOT_FOUND,`Target key not found: ${p.target.key}`)):le(p,$.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,x){let b=o.register({context:p,entryFile:x}),C=i.get(b.key);if(C?.entryFile===x)return;C&&R(C);let N=Eh(b.context,x);i.set(b.key,N),A(N,N.dependencyFiles),r.emit({type:"graph-invalidated",composition:b.context})},unregisterComposition(p){let x=o.resolveSelector(p),b=i.get(x.key);b&&(R(b),i.delete(x.key),o.unregister(x.key),i.size===0&&(t="idle"),r.emit({type:"graph-invalidated",composition:x.context}))},getCompositionEntryFiles(){return[...i.values()].map(p=>p.entryFile)},getCompositionContext(p){return o.resolveSelector(p).context},async initializeComposition(p){let x=o.resolveSelector(p),b=i.get(x.key);if(!b)throw new Error(`Composition not registered: ${x.key}`);if(b.graph)t="ready";else{t="building";try{let C=await n.readFile(b.entryFile);await fe(x.key,C),t="ready",r.emit({type:"graph-ready",composition:x.context,version:i.get(x.key)?.graph?.version??0})}catch(C){throw t="idle",r.emit({type:"graph-error",composition:x.context,message:qe(C)}),C}}},getDocument(p){let x=o.resolveSelector(p),b=i.get(x.key);if(!b)throw new Error(`Composition not registered: ${x.key}`);if(!b.document)throw new Error(`Composition not built: ${x.key}`);return b.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,x,b){let C=Xn(p,x),N=ot(p)??p;if(C?.graph&&C.topology&&C.capabilities&&C.detailProjections){let O=C.detailProjections.get(N);if(O){let M=C.graph.elements.get(N);if(!M)throw new Error(`Key not found: ${p}`);let H=Xw(p,N,b),X=new Map;if(O.isRepeat&&H?.instanceIndex!==void 0)for(let se of M.attributes??[])X.set(se.name,dl({file:M.sourceFile,source:f.get(M.sourceFile)??"",element:M,propertyName:se.name,selectionRef:H,graph:C.graph,sources:f}));let L=Lg({element:M,graph:C.graph,source:f.get(M.sourceFile),documentVersion:C.graph.version,selectionRef:b,isRepeat:O.isRepeat,propertyProvenance:O.propertyProvenances,repeatTargets:X}),B=$g(N,C.graph,C.topology,C.capabilities,O.textSources,O.provenances,O.dynamicData,L);return p===N?B:fh(B,p,C.document??null,C.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${p}`)},getRenderDetail(p,x){let b=Xn(p,x),C=ot(p)??p;if(b?.graph&&b.topology&&b.capabilities&&b.detailProjections){let N=b.detailProjections.get(C);if(N){let O=jg(C,b.graph,b.topology,b.capabilities,N.textSources,N.writeTarget,N.provenances,N.conditional,N.componentSemantic,N.styleSource,N.dynamicData);return p===C?O:dh(O,p,b.document??null,b.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${p}`)},getClassNameSource(p,x){let b=Xn(p,x),C=ot(p)??p;if(!b?.graph)throw new Error(`Key not found: ${p}`);let N=b.graph.elements.get(C);if(!N)throw new Error(`Key not found: ${p}`);let O=f.get(N.sourceFile);if(O===void 0)throw new Error(`Source not loaded: ${N.sourceFile}`);return ga({key:C,route:{composition:b.composition,routeId:b.routeId,graph:b.graph,source:O}})},refreshSourceForKey:jh,async execute(p){if(await S,g)return le(p,$.RECOVERY_REQUIRED,"The edit engine requires explicit recovery before accepting mutations.");if(p.kind==="source-edit")return $h(p);if(p.kind==="insert-page-resource")return Vh(p);if(p.kind==="delete-page-source")return Kh(p);let x=await iu(p);if("ok"in x)return x;await Wl(p);let b=await iu(p);if("ok"in b)return b;let C=b;if(p.target.kind==="page-unit"){let B=p;return p.kind==="insert-child"||p.kind==="replace-node"?Uh(B,C):p.kind==="move-node"||p.kind==="remove-node"?Jh(B,C):le(p,$.UNSUPPORTED_OPERATION,"Only page-unit insert-child, replace-node, move-node, and remove-node are currently supported by the page composition transaction.")}let O=p.params,M=p.target.kind==="node"?p.target.key:null;if(O.kind==="move-node"&&"kind"in O.target&&O.target.kind==="source-sibling"){let B=O.target,se=M?C.document?.entries.find(V=>V.key===M):null,te=C.document?.entries.find(V=>V.key===B.anchorKey),Ne=se?.pageCompositionActionScope,ye=Ne?.kind==="source-siblings"?Ne.siblingKeys:null,ke=ye?.indexOf(se?.key??"")??-1,Ie=ye?.indexOf(B.anchorKey)??-1,_=B.relation==="before"?ke-1:ke+1;if(!se||!te||!ye||ke<0||Ie!==_||te.pageCompositionActionScope?.kind!=="source-siblings"||te.pageCompositionActionScope.siblingKeys.length!==ye.length||te.pageCompositionActionScope.siblingKeys.some((V,pe)=>V!==ye[pe])||!se.operationSummary.canMove)return le(p,$.INVALID_TARGET,"Source sibling move is unavailable because the current source sibling scope or adjacent anchor no longer matches.")}if(!C.graph||!C.topology||!C.capabilities)return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Q(p),error:{code:p.target.kind==="route"?$.ROUTE_NOT_FOUND:$.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 H=lN(C,C.graph,C.capabilities,f,i),X=await new rs(H).plan(p);if(!X.ok)return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Q(p),error:{code:No(X.errorCode),message:X.reason}};let L=X.plan;if(L.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:Q(p),affectedFiles:[]}:{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Q(p),error:{code:$.PLAN_FAILED,message:"Planner could not generate a valid execution plan"}};u+=1;try{if(L.steps.some(se=>se.type==="invoke-external-adapter")){let se=await d.execute(L);if(!se.ok)return le(p,No(se.errorCode),se.reason);let te={composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!0,resultVersion:Math.max(Q(p),se.resultVersion),affectedFiles:se.affectedFiles,...se.selectionRef?{selectionRef:se.selectionRef}:{}};return Ns(te,{rebuiltRoutes:[],failedRoutes:[]}),te}let B=await d.prepareRewritePlan(L);return B.ok?await Jn({request:p,filePlan:B.filePlan,...B.selectionRef?{selectionRef:B.selectionRef}:{}}):le(p,No(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:Q(p),error:{code:$.INTERNAL_ERROR,message:qe(B)}}}finally{u-=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:we(o.entries[0].key),error:{code:$.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting undo."}};u+=1;try{return await ql("undo")}finally{u-=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:we(o.entries[0].key),error:{code:$.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting redo."}};u+=1;try{return await ql("redo")}finally{u-=1}},notifyFileChanged(p){Ul([p])},getAffectedCompositions(p){return Oh(p)},subscribe(p){return r.subscribe(p)}}}function nN(e){return e instanceof Error&&"code"in e&&(e.code==="ENOENT"||e.code==="ENOTDIR")}function rN(e,t,n,r){let o=new Map,i=new Map,s=(f,m,u)=>{let g=f.get(m)??new Set,h=g.size;return g.add(u),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 u=s(o,`${f.importedFrom}#${f.tag}`,m);return f.exportName&&f.exportName!==f.tag&&(u=s(o,`${f.importedFrom}#${f.exportName}`,m)||u),u},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&&Po(f.sourceRange,h.sourceRange)));if(!m)continue;let u=m.placementUnitKey;a(f,u)}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 u of m)l=a(f,u)||l}}let d=n.placements.find(f=>f.placementKey===n.container.placementKey&&f.relation==="append");for(let f of e.entries){let m=ot(f.key)??f.key,u=t.elements.get(f.key)??t.elements.get(m);if(!u)continue;if(u.sourceFile===n.entryFile){if(n.container.sourceRange&&Po(u.sourceRange,n.container.sourceRange)&&d){f.pageCompositionUnitKey=d.placementUnitKey;continue}let S=n.placements.find(E=>E.members.some(y=>y.sourceRange!==null&&(Po(u.sourceRange,y.sourceRange)||cN(y.sourceRange,u.sourceRange))));if(S){f.pageCompositionUnitKey=S.placementUnitKey;continue}}let g=o.get(`${u.sourceFile}#${u.componentName}`);if(g){g.size===1&&(f.pageCompositionUnitKey=g.values().next().value);continue}let h=i.get(u.sourceFile);h?.size===1&&(f.pageCompositionUnitKey=h.values().next().value)}oN(e,t,n,r)}function oN(e,t,n,r){let o=new Map(e.entries.map(m=>[m.key,m])),i=e.entries.filter(m=>{let u=m.pageCompositionUnitKey;return u?m.parentKey?o.get(m.parentKey)?.pageCompositionUnitKey!==u:!0:!1}),s=new Map,a=(m,u)=>{s.set(m,Math.min(2,(s.get(m)??0)+u))},c=m=>n.placements.some(u=>u.members.some(g=>g.sourceRange!==null&&Po(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 u=!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),u=!0)}if(!u)break}let d=m=>s.get(`${m.sourceFile}#${m.componentName}`)??s.get(`${m.sourceFile}#default`)??0;for(let m of i){m.pageCompositionActionScope={kind:"unavailable"};let u=t.elements.get(m.key);m.pageCompositionUnitKey&&u?.sourceFile===n.entryFile&&(m.pageCompositionActionScope={kind:"route-unit"})}let f=new Map;for(let m of i){let u=t.elements.get(m.key);if(!u||u.sourceFile===n.entryFile||m.key!==(ot(m.key)??m.key))continue;let g=r.get(u.sourceFile);if(!g)continue;let h=ae(g.ast,{kind:"jsx-node",strategy:"source-range",sourceRange:u.sourceRange});if(!h.ok||!h.match.path.isJSXElement())continue;let S=h.match.path,E=S.parentPath;if(!E||!E.isJSXFragment()&&!(E.isJSXElement()&&Fe(E))){d(u)===1&&Ih(S)&&(m.pageCompositionActionScope={kind:"route-unit"});continue}if(!Ih(E))continue;let y=f.get(E.node)??[];y.push({entry:m,element:u,parentPath:E}),f.set(E.node,y)}for(let m of f.values()){let u=m[0];if(!u)continue;let g=u.entry.pageCompositionUnitKey,h=[],S=!!(g&&d(u.element)===1);for(let y of u.parentPath.node.children){if(iN(y))continue;if(!sN(y)){S=!1;break}let v=[...t.elements.values()].find(P=>P.sourceFile===u.element.sourceFile&&P.componentName===u.element.componentName&&Po(P.sourceRange,aN(y))),I=v?o.get(v.identity.key):null;if(!v||!I||I.parentKey||I.pageCompositionUnitKey!==g||d(v)!==1){S=!1;break}h.push(I)}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 Ih(e){let t=e.parentPath;return!!(t?.isReturnStatement?.()||t?.isArrowFunctionExpression?.()&&t.node.body===e.node)}function iN(e){return!!(e&&typeof e=="object"&&e.type==="JSXText"&&!(e.value??"").trim())}function sN(e){return!!(e&&typeof e=="object"&&e.type==="JSXElement")}function aN(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 Po(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function cN(e,t){return Ch(e.startLine,e.startColumn,t.startLine,t.startColumn)<=0&&Ch(e.endLine,e.endColumn,t.endLine,t.endColumn)>=0}function Ch(e,t,n,r){return e!==n?e-n:t-r}function lN(e,t,n,r,o){let i=new Map,s=new Map,a=(d,f)=>{if(s.has(d))return;s.set(d,f);let m=t.elements.get(d);for(let u of m?.childKeys??[])a(u,f)};for(let d of t.regions)if(d.kind==="repeat-region")for(let f of d.childKeys)i.set(f,d.ownerKey),a(f,d.ownerKey);return{getNode(d){let f=c(d),m=t.elements.get(f.baseKey);return m?l(d,m):null},getChildNodes(d){let f=c(d),u=e.documentIndex?.entriesByKey.get(d)?.childKeys;if(u)return u.map(h=>{let S=ot(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(([d,f])=>({file:d,content:f}))},getRouteEntryFiles(){return[...o.values()].map(d=>d.entryFile)},getCapability(d){let f=c(d),m=n.get(f.baseKey);return m?{...m,key:d,constraints:m.constraints.map(u=>({...u})),...m.editModes?{editModes:{...m.editModes}}:{}}:{composition:e.composition,key:d,canUpdateText:!1,canRemove:!1,canInsertChild:!1,canMove:!1,constraints:[]}},getFileContent(d){return r.get(d)??""},getFileVersion(d){return Math.max(e.fileVersions.get(d)??0,t.version)},getRouteEntryFile(d){return e.routeId===d?e.entryFile:null},getComponentSemantic(d){let f=c(d);return e.detailProjections?.get(f.baseKey)?.componentSemantic??null},getClassNameSource(d){let f=c(d),m=t.elements.get(f.baseKey),u=m?r.get(m.sourceFile):void 0;return!m||u===void 0?null:ga({key:f.baseKey,route:{composition:e.composition,routeId:e.routeId,graph:t,source:u}})},getEditableTextSegmentIndex(d){let f=c(d),u=e.detailProjections?.get(f.baseKey)?.textTargets.keys()?.next();return u&&!u.done?u.value:null},async getTextWriteTarget(d,f){let m=c(d);return Ml(e.detailProjections?.get(m.baseKey)?.textTargets.get(f)??null,m.repeatIndex)},async getElementPropertyWriteTarget(d,f){let m=c(d);return Ml(e.detailProjections?.get(m.baseKey)?.elementPropertyTargets.get(f)??null,m.repeatIndex)},getPropertyState(d,f,m){let u=c(d),g=t.elements.get(u.baseKey);if(!g)return null;let S=e.detailProjections?.get(u.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(d,f,m){let u=c(d),g=t.elements.get(u.baseKey);if(!g)return{ok:!1,errorCode:"repeat-not-found",reason:`Node not found: ${d}`};let h=m?{...m,key:u.baseKey}:u.repeatIndex!==null?{key:u.baseKey,instanceIndex:u.repeatIndex}:void 0;return dl({file:g.sourceFile,source:r.get(g.sourceFile)??"",element:g,propertyName:f,selectionRef:h,graph:t,sources:r})},getTextProvenance(d,f){let m=c(d);return e.detailProjections?.get(m.baseKey)?.provenances.get(f)??null}};function c(d){let f=_w(d);return f?{baseKey:f.baseKey,repeatIndex:uh(e.document??null,d,f.baseKey,e.documentIndex)??lh(f)}:{baseKey:d,repeatIndex:null}}function l(d,f){let m=ot(d)??d,u=e.documentIndex?.entriesByKey.get(d);return{key:d,file:f.sourceFile,component:f.componentName,tag:f.tag,structuralPath:f.identity.structuralPath,sourceRange:f.sourceRange,parentKey:u?.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 uN={"stale-version":$.VERSION_STALE,"capability-denied":$.CAPABILITY_REJECTED,"invalid-params":$.INVALID_PARAMS,"locator-miss":$.LOCATOR_FAILED,"route-not-found":$.ROUTE_NOT_FOUND,"unsupported-operation":$.UNSUPPORTED_OPERATION,"invalid-target":$.INVALID_TARGET,"ast-error":$.AST_PARSE_ERROR,"writeback-failed":$.WRITE_IO_ERROR,"rollback-failed":$.RECOVERY_REQUIRED,unknown:$.INTERNAL_ERROR};function No(e){return uN[e]}function qe(e){return e instanceof Error&&e.message?e.message:String(e)}function Rh(e){return/\.(?:[cm]?[jt]sx?|css|scss|sass|mdx|json)$/i.test(e)}function dN(e){let t=Vn(e);if(!Dw.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=>Lw.map(a=>`${s}/${a}`))}function fN(e){let n=Vn(e).startsWith("src/app/")?"src/app":"app";return[`${n}/globals.css`,`${n}/global.css`]}function pN(e){return Ph(e,/\bimport\s+(?:[^'";]+?\s+from\s+)?["']([^"']+\.css(?:\?[^"']*)?)["']/g)}function mN(e){return Ph(e,/@import\s+(?:url\(\s*)?["']([^"']+)["']/g)}function Ph(e,t){let n=[];for(let r of e.matchAll(t)){let o=Ah(r[1]??"");o&&n.push(o)}return n}function wh(e,t){let n=Ah(t);return!n||n.startsWith("tailwindcss")||n.startsWith("http:")||n.startsWith("https:")?null:n.startsWith("@/")?Vn(`src/${n.slice(2)}`):n.startsWith("./")||n.startsWith("../")?Vn(`${gN(e)}/${n}`):n.startsWith("/")?Vn(n.slice(1)):jl(n)?Vn(n):null}function Ah(e){return e.split(/[?#]/,1)[0]?.trim()??""}function jl(e){return/\.css$/i.test(e)}function gN(e){let t=Vn(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function hN(e){return Array.from(new Set(e))}function Vn(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 yN(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 Cs=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 Vo(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 Ko(r?this.engine.getObjectEditContext(t,n,r):this.engine.getObjectEditContext(t,n))}getClassNameSource(t,n){return this.engine.getClassNameSource(t,n)}getSourceTree(t){return Xo(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}getSourceFile(t){return zo(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=bN.safeParse(t);if(!n.success)return{result:$o(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:In(i)},a=r.getChangedFiles();if(a.length===0)return{result:s};let c=SN.parse({siteId:t.siteId,baseSnapshotId:t.baseSnapshotId,operationId:t.id,reason:`site-edit:${t.kind}`,patches:a.map(l=>EN(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 Ao({projectRoot:"/snapshot",fileSystem:t,compositions:this.options.compositions,onEvent:r&&this.options.onEvent?o=>{let i=Uo(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 EN(e,t){return e.after===void 0?{path:e.path,operation:"delete",...t||e.before===void 0?{}:{expectedHash:Ee(e.before)}}:{path:e.path,operation:e.before===void 0?"create":"update",...t||e.before===void 0?{}:{expectedHash:Ee(e.before)},fullContent:e.after}}function vN(e){return new Cs(e)}import{SiteEditOperationRequestSchema as CN}from"@vcp-dev/contracts";import wt from"node:fs/promises";import et from"node:path";import{SITE_EDIT_SOURCE_ALLOWED_DIRS as kN,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as IN}from"@vcp-dev/contracts";var Rs=class{constructor(t){this.options=t,this.fileSystem=this.createFileSystem(),this.engine=Ao({...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 Xo(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.engine.getCompositionEntryFiles()})}getSourceFile(t){return zo(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(et.join(n,r),"utf8")},async readFileBytes(r){return wt.readFile(et.join(n,r))},async getFileInfo(r){let o=et.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 fi(et.join(n,r),o)},async createExclusive(r,o){let i=et.join(n,r);await wt.mkdir(et.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(et.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=et.join(n,i),a=et.dirname(et.join(n,o));for(;a!==s&&a.startsWith(`${s}${et.sep}`);){try{await wt.rmdir(a)}catch(c){if(c instanceof Error&&"code"in c&&c.code==="ENOENT"){a=et.dirname(a);continue}break}a=et.dirname(a)}},async exists(r){try{return await wt.access(et.join(n,r)),!0}catch{return!1}},async listFiles(r={}){let o=r.roots??[...IN,...kN],i=[],s=new Set,a=new Set,c=0;for(let f of o)await d(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 d(f,m,u){if(r.maxDepth!==void 0&&u>r.maxDepth){a.add("max-depth");return}let g=et.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 d(`${f}/${E.name}`,m,u+1)}},getVersion(r){return t.get(r)??1},bumpVersion(r){let o=(t.get(r)??1)+1;return t.set(r,o),o}}}};function $l(e){return new Rs(e)}var ws=class{constructor(t){this.options=t,this.listeners=new Set,this.engine=$l({projectRoot:t.projectRoot,fileSystem:t.fileSystem,compositions:t.compositions,onEvent:n=>{let r=Uo(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:Vo(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:Ko(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=CN.safeParse(r);if(!o.success)return $o(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:In(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:In(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:In(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 RN(e){return new ws(e)}export{oe as FileHistoryStoreError,Qr as PageTemplateManagedSourceError,ws as PreviewFileSystemSiteEditEngineRuntime,lf as SITE_EDIT_RAW_COLOR_LITERAL_RE,Cs as SnapshotSiteEditEngineRuntime,Mo as checkComponentI18nHostCompatibility,ep as computeManagedPageTemplatePaths,RN as createPreviewSiteEditEngineRuntime,vN as createSiteEditEngineRuntime,Zf as decodePageTemplateKey,gc as encodePageTemplateId,vy as instrumentSiteEditRuntimeAttributes,tp as isManagedPageTemplateSourcePath,Bd as openFileHistoryStore,sy as parseSourceModule,ay as resolveImportBase,bk as resolveManagedPageTemplateComposition,ji as scanManagedPageTemplateCandidates,rp as scanSiteEditCompositionsFromFiles,Xr as scanSiteEditThemeStyleViolations};
|
|
12
|
+
`||m==="\r"))return Sr(t,`Unterminated string literal in ${t}.`);l=m===`
|
|
13
|
+
`||m==="\r";continue}if(m==="/"&&u==="*"){s=!0,f+=1,l=!1;continue}if(n==="mdx"&&m==="/"&&u==="/"){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 Sr(t,`Unexpected closing token "${m}" in ${t}.`);l=!1;continue}l=m===`
|
|
14
|
+
`||m==="\r"}if(s)return Sr(t,`Unterminated block comment in ${t}.`);if(o)return Sr(t,`Unterminated string literal in ${t}.`);if(c)return Sr(t,`Unterminated MDX code fence in ${t}.`);let d=r.at(-1);return d?Sr(t,`Unclosed token "${d.char}" in ${t}.`):{ok:!0}}function Sr(e,t){return{ok:!1,errorCode:"ast-error",message:t,details:{path:e}}}function ks(e){let t="idle",n=e.fileSystem??$w(),r=hd(),o=ih({compositions:e.compositions,initialDocumentVersions:e.initialDocumentVersions}),i=new Map,s=new Map,a=new Set,c=null,l=e.history??(e.historyStore?of(e.historyStore):Kw()),d=rh(n,{externalAdapters:e.externalAdapters}),f=new Map,m=new Set,u=0,g=e.historyStore?.recoveryRequired??!1,h=Ol(),S=C();function E(p){return(Es.isAbsolute(p)?Es.relative(e.projectRoot,p):p).replace(/\\/g,"/").replace(/^\.\//,"")}function y(p,b){let x=Es.posix.dirname(p),I=b.replace(/\.(?:tsx?|jsx?)$/i,""),P=Es.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 F=>await n.exists(F.path)?Se(await n.readFile(F.path)):null));if(hh({journal:b,index:x,observedFileDigests:I})!=="ambiguous"){await p.clearTransactionJournal(b.transactionId);let F=await p.readStatus();F.recoveryRequired||(await p.cleanupTmp(),F=await p.readStatus()),g=F.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: ${qe(b)}`).catch(()=>{})}}function N(){return t==="disposed"}e.onEvent&&r.subscribe(e.onEvent);for(let p of o.entries){let b=Eh(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 T(p){let b=new Set;for(let x of p)for(let I of s.get(x)??[])b.add(I);return b}function O(p){for(let b of p)if(!s.has(b))return!1;return!0}async function M(p,b,x,I,P){let F=new Map,L=vg(P.values()),G=new Map,X=typeof n.exists=="function"?B=>n.exists(B):async()=>!1;for(let[B,j]of p.elements){let ie=b.nodes.get(B);if(!ie)continue;let te=x.get(j.sourceFile)??I.get(j.sourceFile),Fe=new Map,ye=new Map,we=new Map,Ne=[];for(let Ce of j.textSegments){if(!te){Fe.set(Ce.index,null);continue}let Er=await kg({file:j.sourceFile,source:te,segment:Ce,readFile:it=>n.readFile(it),exists:X,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:it,adapterId:gn,capabilities:Os})=>({sourceType:it,adapterId:gn,capabilities:Os})),functionCallContracts:e.functionCallContracts,fileCache:L}),Ze=await Cl({file:j.sourceFile,source:te,target:{kind:"text-segment",segment:Ce},readFile:it=>n.readFile(it),exists:X,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:it,adapterId:gn,capabilities:Os})=>({sourceType:it,adapterId:gn,capabilities:Os})),functionCallContracts:e.functionCallContracts,fileCache:L}),dt=Qw(Er);Fe.set(Ce.index,dt),ye.set(Ce.index,Er),we.set(Ce.index,Ze),Ne.push({editable:Ce.editable,source:dt})}let _=new Map,D=new Map;if(te)for(let Ce of j.attributes??[]){let Er=await xr({file:j.sourceFile,source:te,sourceRange:Ce.sourceRange,expression:Ce.source?.expression??Ce.value,sourceInfo:Ce.source,readFile:dt=>n.readFile(dt),exists:X,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:dt,adapterId:it,capabilities:gn})=>({sourceType:dt,adapterId:it,capabilities:gn})),functionCallContracts:e.functionCallContracts,fileCache:L}),Ze=await Fg({element:j,file:j.sourceFile,source:te,propertyName:Ce.name,readFile:dt=>n.readFile(dt),exists:X,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:dt,adapterId:it,capabilities:gn})=>({sourceType:dt,adapterId:it,capabilities:gn})),functionCallContracts:e.functionCallContracts,fileCache:L});D.set(Ce.name,Ze),_.set(Ce.name,Er)}let pe=Ug(qw(ie.writeTarget),Ne),fe=_g({key:B,element:j,graph:p,provenances:we}),Ie=Wg(j),De=te?await Rm({element:j,graph:p,file:j.sourceFile,source:te,readFile:Ce=>n.readFile(Ce),exists:X,fileCache:G}):void 0,Xe=p.regions.find(Ce=>Ce.kind==="conditional-region"&&Ce.childKeys.includes(B)),mn,_s=Xe?.sourceCandidates?.[0];if(te&&Xe&&_s?.kind==="conditional-branch"){let Ce=await Cl({file:j.sourceFile,source:te,target:{kind:"conditional-branch",candidate:_s},readFile:Ze=>n.readFile(Ze),exists:X,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Ze,adapterId:dt,capabilities:it})=>({sourceType:Ze,adapterId:dt,capabilities:it})),functionCallContracts:e.functionCallContracts,fileCache:L});mn={currentBranch:Xe.childKeys.indexOf(B)<=0?"then":"else",availableBranches:Xe.childKeys.length>1?["then","else"]:["then"],conditionExpression:_s.conditionExpression,provenance:{finalSource:Ce.finalSource?{kind:Ce.finalSource.kind,file:Ce.finalSource.file,displayPath:Ce.finalSource.displayPath}:null,chain:Ce.chain.map(Ze=>({kind:Ze.kind,file:Ze.file,displayName:Ze.displayName,canEditHere:Ze.canEditHere})),confidence:Ce.confidence,editMode:Ce.editMode,diagnostics:Ce.diagnostics.map(Ze=>({code:Ze.code,message:Ze.message}))}}}F.set(B,{textSources:Fe,textTargets:ye,elementPropertyTargets:_,propertyProvenances:D,isRepeat:xN(B,p),provenances:we,writeTarget:pe,componentSemantic:fe,styleSource:Ie,conditional:mn,dynamicData:De})}return F}function U(p){return typeof n.getVersion=="function"?n.getVersion(p):0}function ee(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 Re(p){return i.get(p)?.graph?.version??o.initialVersions.get(p)??0}function Q(p){try{return Re(o.resolveSelector(p.composition).key)}catch{return 0}}async function de(p,b,x=n,I=1){let P=await Cd(p,b,F=>x.readFile(F),F=>x.exists(F),{additionalEntries:await Gt(p,x),version:I});if(P.diagnostics.length>0)throw new Ro(P.diagnostics);return P}async function Te(p,b,x={}){let I=i.get(p);if(!I)return null;let P=x.sourceCache??Ll(f,[]),{graph:F,allSources:L,parsedModules:G,entryModule:X}=await de(I.entryFile,b,n,I.graph?.version??1),B=new Map;for(let Xe of L.keys())B.set(Xe,U(Xe));let j=Math.max(ee(I,B),x.minimumVersion??0);x.changed&&j<=(I.graph?.version??0)&&(j=(I.graph?.version??0)+1),F.version=j;for(let[Xe,mn]of L)Bl(P,Xe,mn,xh);let ie=await Yt(I.composition,I.entryFile,L,P);F.routeId=I.routeId,F.composition=I.composition;let te=Gg(F),Fe=dd(te,F),ye=await M(F,te,L,P,G),we=_h(F,Fe,ye),Ne=Fh(ye),_=ch(Bg(F,te,Fe,{canUpdateTextByKey:we,dynamicDataSummaryByKey:Ne}),F,ye),D=Kf({route:I.routeId,composition:I.composition,entryFile:I.entryFile,version:j,source:b,ast:X?.ast}),pe=Uf(D);D.ok&&oN(_,F,D.projection,G);let fe={..._,composition:I.composition,...ie?{styleContext:ie}:{},pageComposition:pe},Ie=new Set([I.entryFile,...L.keys()]);if(ie){Ie.add(ie.entryCss.path);for(let Xe of ie.stylesheets)Ie.add(Xe.path)}let De={...I,dependencyFiles:Ie,graph:F,topology:te,capabilities:Fe,document:fe,pageComposition:pe,pageCompositionProjection:D.projection,pagePlacementByKey:D.ok?D.projection.placementByKey:null,pagePlacementUnitByKey:D.ok?D.projection.placementUnitByKey:null,pageUnitByKey:D.ok?D.projection.unitByKey:null,pagePlacementsByUnitKey:D.ok?D.projection.placementsByUnitKey:null,documentIndex:ah(fe),detailProjections:ye,fileVersions:B,styleContext:ie};if(x.publish===!1)return De;br(f,P);for(let Xe of P.keys())m.delete(Xe);return A(I,Ie),Object.assign(I,De),I}async function Gt(p,b=n){let x=[];for(let I of fN(p))typeof b.exists=="function"&&await b.exists(I)&&x.push({file:I,source:await b.readFile(I)});return x}async function Yt(p,b,x,I){let P=[];for(let[B,j]of x){if(jl(B)){P.push(B);continue}for(let ie of mN(j)){let te=wh(B,ie);te&&P.push(te)}}if(!P.length){for(let B of pN(b))if(await Vl(B)){P.push(B);break}}let F=new Map,L=yN(P).slice(0,yh);for(;L.length>0&&F.size<yh;){let B=L.shift();if(F.has(B)||!jl(B))continue;let j=await Th(B,I);if(j!==null){F.set(B,{path:B,content:j});for(let ie of gN(j)){let te=wh(B,ie);te&&!F.has(te)&&!L.includes(te)&&L.push(te)}}}let G=[...F.values()].map(B=>({...B,hash:Se(B.content)})),X=G[0];return X?{composition:p,revision:Se(JSON.stringify(G.map(({path:B,hash:j})=>({path:B,hash:j})))),entryCss:X,stylesheets:G.slice(1)}:null}async function Th(p,b){let x=b.get(p);if(x!==void 0)return x;if(!await Vl(p))return null;let I=await n.readFile(p);return Bl(b,p,I,xh),I}async function Vl(p){return typeof n.exists=="function"?n.exists(p):!1}function Fh(p){let b=new Map;for(let[x,I]of p)I.dynamicData?.bindings.length&&b.set(x,Lm(I.dynamicData.bindings));return b}function _h(p,b,x){let I=new Map;for(let[P,F]of p.elements){if(!b.get(P)?.canUpdateText){I.set(P,!1);continue}let G=x.get(P),X=F.textSegments.some(B=>{if(!B.editable)return!1;let j=G?.provenances.get(B.index)??null;return!j||Oh(j)});I.set(P,X)}return I}function Oh(p){return p.editMode==="direct"||p.editMode==="proxy"||p.editMode==="upstream"}async function Po(p,b={}){let x=[...new Set(p)],I=b.affectedCompositionKeys!==void 0,P=I?new Set(b.affectedCompositionKeys):T(x);if(!I&&(P.size===0||!O(x)))for(let X of i.values())Kl(X,x)&&P.add(X.key);let F=!I&&P.size===0&&x.some(Rh),L=b.publish===!1?Ll(f,x):void 0,G={rebuiltRoutes:[],failedRoutes:[],...b.publish===!1?{candidateRouteStates:[],candidateSourceCache:L}:{}};for(let X of i.values())if(!(b.excludedCompositionKeys?.has(X.key)||!(P.has(X.key)||F)))try{let j=!!X.graph,ie=await n.readFile(X.entryFile),te=await Te(X.key,ie,{...b,...L?{sourceCache:L}:{}});te?.graph&&(G.rebuiltRoutes.push({documentChanged:j,composition:X.composition,routeId:X.routeId,version:te.graph.version}),G.candidateRouteStates?.push({composition:X.composition,key:X.key,routeId:X.routeId,state:te}))}catch(j){G.failedRoutes.push({...mh(X.routeId,j),composition:X.composition})}return G}function Vn(p){let b=[...new Set(p)],x=T(b);if(x.size>0&&O(b))return[...x];for(let I of i.values())Kl(I,b)&&x.add(I.key);return[...x]}function Mh(p){let b=new Set(Vn(p));return o.entries.filter(x=>b.has(x.key)).map(x=>x.context)}function Dh(p){return[...new Set(Vn(p))].sort((x,I)=>x<I?-1:x>I?1:0).map(x=>o.getByKey(x)?.context).filter(x=>x!==void 0)}function Lh(p,b){let x=new Set(Vn(b)),I=p.provenance?.affectedCompositions??[];if(I.length===0)return x;if([...new Set(I.map(F=>o.resolveContext(F).key))].some(F=>!x.has(F)))throw new Error("History provenance does not match the affected composition index.");return x}function Bh(p,b){let x=p.composition??p.provenance?.initiatingComposition;if(x){let F=o.resolveContext(x);return{context:F.context,key:F.key}}let I=[...new Set(Vn(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 ws(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 Kl(p,b){return b.some(x=>p.dependencyFiles.has(x)||p.entryFile===x||p.graph?.fileIndex.has(x))}function Ul(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 jh(),await h.runExclusive(async()=>{if(u>0||N())return;let x=[...a];a.clear();let I=await Jl(x);if(I.length===0)return;let P=Vn(I);for(let G of P){let X=i.get(G)?.composition;X&&r.emit({type:"graph-invalidated",composition:X})}let{rebuiltRoutes:F,failedRoutes:L}=await Po(I,{changed:!0});for(let{documentChanged:G,composition:X,version:B}of F)r.emit({type:"graph-ready",composition:X,version:B}),G&&r.emit({type:"document-changed",composition:X,version:B});for(let{composition:G,message:X}of L)b=!0,r.emit({type:"graph-error",composition:G,message:X})})}}finally{c=null,t!=="disposed"&&(t=!b&&[...i.values()].some(x=>x.graph)?"ready":"idle"),a.size>0&&Ul([])}})())}async function jh(){for(;u>0;)await new Promise(p=>setTimeout(p,0))}async function Jl(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(!rN(P))try{if(await n.exists(x))continue}catch{continue}m.add(x),b.push(x)}}return b}function Xl(p){gh(f,p);for(let b of p)b.exists===!1?m.add(b.file):m.delete(b.file)}function zl(p){m.clear();for(let b of p)m.add(b)}async function Hl(p){let b=await Jl(p);if(b.length===0)return;let x=Vn(b);for(let F of x){let L=i.get(F)?.composition;L&&r.emit({type:"graph-invalidated",composition:L})}let{rebuiltRoutes:I,failedRoutes:P}=await Po(b,{changed:!0});for(let{documentChanged:F,composition:L,version:G}of I)r.emit({type:"graph-ready",composition:L,version:G}),F&&r.emit({type:"document-changed",composition:L,version:G});for(let{composition:F,message:L}of P)r.emit({type:"graph-error",composition:F,message:L})}async function $h(p,b){let x=Jn(p,b);if(!x?.graph)return;let I=ot(p)??p,P=x.graph.elements.get(I);P&&await Hl([P.sourceFile])}async function Wl(p){let b=new Set;if(p.target.kind==="node"){let x=Jn(p.target.key,p.composition),I=ot(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=Jn(I,p.composition),F=ot(I)??I,L=P?.graph?.elements.get(F);L&&b.add(L.sourceFile)}}await Hl(b)}async function Vh(p){if(p.params.kind!=="source-edit")return Ns(p,"invalid-params","source-edit requires source-edit params");for(let b of p.params.edits){let x=nN(b);if(!x.ok)return Ns(p,x.errorCode,x.message,x.details)}u+=1;try{let b=await zh(p.params.edits);if(!b.ok)return Ns(p,b.errorCode,b.message,b.details);await Wl(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 Un({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:Q(p),error:{code:V.INTERNAL_ERROR,message:qe(b)}}}finally{u-=1}}async function Kh(p){if(p.target.kind!=="project"||p.params.kind!=="insert-page-resource")return ce(p,V.INVALID_PARAMS,"insert-page-resource requires project target and matching params.");u+=1;try{let b=await _o({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 ce(p,V.MATERIALIZATION_REJECTED,b.message);let x=await Wa({artifact:p.params.artifact,exists:I=>n.exists(I)});return x.ok?await Un({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"}):ce(p,x.code==="MATERIALIZATION_CONFLICT"?V.MATERIALIZATION_CONFLICT:V.MATERIALIZATION_REJECTED,x.message,x.path?{path:x.path}:void 0)}catch(b){return ce(p,V.INTERNAL_ERROR,qe(b))}finally{u-=1}}async function Uh(p){if(p.target.kind!=="project"||p.params.kind!=="delete-page-source")return ce(p,V.INVALID_PARAMS,"delete-page-source requires project target and matching params.");if(!n.listFiles)return ce(p,V.PLAN_FAILED,"Complete project file listing is required for page deletion.");u+=1;try{let b=Nh(await n.listFiles({maxFiles:5e4,maxDepth:64}));if(b.truncated)return ce(p,V.PLAN_FAILED,"Project file listing is incomplete; page deletion was refused.",{truncationReasons:b.truncated.reasons});let x=b.files.filter(({path:L})=>/\.(?:tsx?|jsx?)$/.test(L)),I=Object.fromEntries(await Promise.all(x.map(async({path:L})=>[L,await n.readFile(L)]))),P=fp({expectedUrlPath:p.params.expectedUrlPath,files:I});if(!P.ok)return ce(p,P.code==="HOME_PAGE_LOCKED"?V.HOME_PAGE_LOCKED:P.code==="ROUTE_NOT_FOUND"?V.ROUTE_NOT_FOUND:V.PLAN_FAILED,P.message);let F=await Promise.all(P.edits.map(async L=>({...L,baseContentHash:Se(await n.readFile(L.file))})));return Un({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:p.target,documentVersion:p.documentVersion,conflictPolicy:"compare-and-swap",edits:F},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 ce(p,V.INTERNAL_ERROR,qe(b))}finally{u-=1}}async function Jh(p,b){if(p.kind!=="insert-child"&&p.kind!=="replace-node")return ce(p,V.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 ce(p,V.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 ce(p,V.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.");if(p.params.position.documentVersion!==p.documentVersion)return ce(p,V.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 ce(p,V.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(p.documentVersion!==x.version||I.documentVersion!==x.version)return ce(p,V.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 ce(p,V.UNSUPPORTED_OPERATION,"Page-unit insertion currently requires a static materialization manifest.");let F=p.params.kind==="insert-child"?p.params.position:null,L=await _o({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:P.files.map(B=>({path:B.pathTemplate,content:B.content})),exists:B=>n.exists(B),readFile:B=>n.readFile(B)});if(!L.ok)return ce(p,V.MATERIALIZATION_REJECTED,L.message);let G=await Vw(n,Object.keys(P.projectDependencies??{})),X=await Rf({manifest:P,generatedRoot:"components/site/generated",controlledFiles:P.files.map(B=>({pathTemplate:B.pathTemplate})),exists:B=>n.exists(B),availableHostDependencies:G,commit:async B=>{let j=await n.readFile(b.entryFile),ie=b.document,te=b.pageCompositionProjection;if(!ie||ie.pageComposition?.status!=="supported"||ie.version!==p.documentVersion||!te||te.status!=="supported"||te.documentVersion!==ie.version)return{ok:!0,data:ce(p,V.VERSION_STALE,"The route changed before the page-unit insertion could commit.")};let Fe=B.entry.path,ye=qh(B.instanceName),we,Ne=[];if(p.params.kind==="insert-child"){if(!F||!("kind"in F)||F.kind!=="page-composition")return{ok:!0,data:ce(p,V.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.")};let fe=tc({routeId:b.routeId,entryFile:b.entryFile,currentDocumentVersion:ie.version,expectedDocumentVersion:p.documentVersion,source:j,projection:te,placementKey:F.placementKey,component:{source:Fe,exportName:B.entry.export.kind==="default"?"default":B.entry.export.name,localName:ye}});if(!fe.ok)return{ok:!0,data:ce(p,Fs(fe.error.code),fe.error.message,{diagnostics:fe.error.diagnostics})};let Ie=fe.plan.rewriteStep,De;switch(Ie.kind){case"insert-root-expression":De=Oi({source:j,locator:Ie.locator,expectedSourceHash:Ie.sourceHash,action:{kind:"insert",jsx:Ie.node.jsx,placement:Ie.placement,replaceOriginal:Ie.replaceOriginal}});break;case"insert-child":De=Wn({source:j,locator:Ie.parentLocator,node:Ie.node,placement:Ie.placement,...Ie.anchorLocator?{anchorLocator:Ie.anchorLocator}:{}});break;default:De={ok:!1,source:j,diagnostic:{code:"unsupported-syntax",message:`Unsupported route composition rewrite: ${String(Ie)}`}}}if(!De.ok)return{ok:!0,data:ce(p,V.AST_PARSE_ERROR,De.diagnostic.message)};we=De.source}else{let fe=nc({routeId:b.routeId,composition:b.composition,entryFile:b.entryFile,currentDocumentVersion:ie.version,expectedDocumentVersion:p.documentVersion,source:j,projection:te,placementUnitKey:p.target.placementUnitKey,operation:"replace-node"});if(!fe.ok)return{ok:!0,data:ce(p,Fs(fe.error.code),fe.error.message,{diagnostics:fe.error.diagnostics})};let Ie=fe.plan.rewriteStep,De;switch(Ie.kind){case"replace-root-expression":De=Oi({source:j,locator:Ie.locator,expectedSourceHash:Ie.sourceHash,action:{kind:"replace",jsx:`<${ye} />`}});break;case"replace-node":De=Qo({source:j,locator:Ie.locator,node:{jsx:`<${ye} />`}});break;default:De={ok:!1,source:j,diagnostic:{message:`Unsupported page-unit replacement rewrite: ${Ie.kind}`}}}if(!De.ok)return{ok:!0,data:ce(p,V.AST_PARSE_ERROR,De.diagnostic.message)};let Xe=await Gl({routeState:b,placementUnitKey:p.target.placementUnitKey,source:j,mutatedSource:De.source});we=Xe.source,Ne=await Promise.all(Xe.files.map(async mn=>({operation:"delete",file:mn,baseContentHash:Se(await n.readFile(mn))})))}let _=Zn({source:we,moduleSpecifier:y(b.entryFile,Fe),imports:B.entry.export.kind==="default"?[{kind:"default",local:ye}]:[{kind:"named",imported:B.entry.export.name,local:ye}]});if(!_.ok)return{ok:!0,data:ce(p,V.AST_PARSE_ERROR,_.diagnostic.message)};let D=B.files.map(fe=>({operation:"create-only",file:fe.path,content:fe.content})),pe=[{operation:"upsert",file:b.entryFile,content:_.source,baseContentHash:Se(j)},...D,...Ne];u+=1;try{let fe=await Un({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:{kind:"source-file",path:b.entryFile},documentVersion:p.documentVersion,conflictPolicy:"compare-and-swap",edits:pe}});return!fe.ok&&fe.error?.message.includes("MATERIALIZATION_INSTANCE_CONFLICT")?{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:fe.error?.message??"Static prefab instance conflicted during commit."}}:{ok:!0,data:fe}}finally{u-=1}}});return X.ok?X.data:ce(p,X.error.code==="MATERIALIZATION_INSTANCE_CONFLICT"?V.MATERIALIZATION_CONFLICT:V.MATERIALIZATION_REJECTED,X.error.message,{materializationCode:X.error.code})}async function Xh(p,b){if(p.kind!=="move-node"&&p.kind!=="remove-node")return ce(p,V.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 ce(p,V.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(p.documentVersion!==x.version||I.documentVersion!==x.version)return ce(p,V.VERSION_STALE,`Document version ${p.documentVersion} is stale (current: ${x.version}).`);let P=await n.readFile(b.entryFile),F=nc({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(!F.ok)return ce(p,Fs(F.error.code),F.error.message,{diagnostics:F.error.diagnostics});let L=F.plan.rewriteStep,G;switch(L.kind){case"move-node":G=Gn({source:P,locator:L.locator,targetParentLocator:L.targetParentLocator,placement:L.placement,...L.anchorLocator?{anchorLocator:L.anchorLocator}:{}});break;case"remove-node":G=Hn({source:P,locator:L.locator});break;case"remove-root-expression":G=Oi({source:P,locator:L.locator,expectedSourceHash:L.sourceHash,action:{kind:"remove"}});break;default:G={ok:!1,source:P,diagnostic:{message:`Unsupported page-unit mutation rewrite: ${L.kind}`}}}if(!G.ok)return ce(p,V.AST_PARSE_ERROR,G.diagnostic.message);let X=G.source,B=[];if(p.kind==="remove-node"){let ie=await Gl({routeState:b,placementUnitKey:p.target.placementUnitKey,source:P,mutatedSource:X});X=ie.source,B=await Promise.all(ie.files.map(async te=>({operation:"delete",file:te,baseContentHash:Se(await n.readFile(te))})))}let j=[{operation:"upsert",file:b.entryFile,content:X,baseContentHash:Se(P)},...B];u+=1;try{return await Un({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:{kind:"source-file",path:b.entryFile},documentVersion:p.documentVersion,conflictPolicy:"compare-and-swap",edits:j}})}finally{u-=1}}async function Gl(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 F=I.placementUnitByKey.get(p.placementUnitKey)?.sourceRange;if(!F)return b;let L=[...x.elements.values()].find(_=>_.sourceFile===p.routeState.entryFile&&_.importedFrom&&v(_.sourceRange,F));if(!L?.importedFrom||!L.exportName)return b;let G=E(L.importedFrom),X="components/site/generated/";if(!G.startsWith(X))return b;let B=G.slice(X.length).split("/")[0];if(!B||!/-[0-9a-f]{8}$/i.test(B))return b;let j=`${X}${B}`;if([...x.elements.values()].filter(_=>_.sourceFile===p.routeState.entryFile&&E(_.importedFrom??"")===G).length!==1)return b;let te=await n.listFiles({maxFiles:5e3,maxDepth:32}),Fe=Array.isArray(te)?te:te.files;if(!Array.isArray(te)&&te.truncated)return b;let ye=Fe.map(({path:_})=>_).filter(_=>_===j||_.startsWith(`${j}/`));if(ye.length===0||!ye.includes(G))return b;for(let{path:_}of Fe)if(!(_===p.routeState.entryFile||_===j||_.startsWith(`${j}/`)))try{if((await n.readFile(_)).includes(B))return b}catch{return b}let we=y(p.routeState.entryFile,G),Ne=Qn({source:p.mutatedSource,moduleSpecifier:we,imports:L.exportName==="default"?[{kind:"default"}]:[{kind:"named",imported:L.exportName}]});return Ne.ok?Ne.source.includes(B)?{source:Ne.source,files:[]}:{source:Ne.source,files:ye.sort((_,D)=>_.localeCompare(D))}:b}async function zh(p){if(n.getFileInfo){for(let I of p)if(await n.exists(I.path)&&await n.getFileInfo(I.path)===null)return{ok:!1,errorCode:"invalid-params",message:`Source edit path must resolve to a regular non-symbolic-link file: ${I.path}`,details:{path:I.path}}}for(let I of p){if(I.operation!=="upsert"||!/^(?:src\/)?app\/globals\.css$/i.test(I.path))continue;let P=await n.exists(I.path)?await Ys(n,I.path):null;if(P?.ok){let F=Aw(P.content,I.content);if(!F.ok)return{ok:!1,errorCode:"invalid-params",message:F.message,details:{path:I.path,code:F.code}}}}let b=Hh(p);if(b.length===0)return{ok:!0};let x=eN(n,p);try{for(let I of b){let P=i.get(I);P&&await de(P.entryFile,await x.readFile(P.entryFile),x)}}catch(I){return{ok:!1,errorCode:"ast-error",message:`Source edit preflight failed: ${qe(I)}`,details:{compositionKeys:b}}}return{ok:!0}}function Hh(p){return p.map(x=>x.path).some(Rh)?[...i.keys()]:[]}function Ns(p,b,x,I){let P=wo(b);return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Q(p),error:{code:P,message:x,...I?{details:I}:{}}}}async function Ps(p){let b=[];for(let x of new Set(p))b.push(await Wh(x));return b}async function Wh(p){if(!(typeof n.exists=="function"?await n.exists(p):!0))return{file:p,content:"",version:Math.max(0,U(p)),exists:!1};let x=await n.readFile(p);return{file:p,content:x,version:Math.max(1,U(p)),exists:!0,sha256:Se(x)}}async function Yl(p,b,x,I){if(!e.historyStore)return null;let P=new Map(b.map(G=>[G.file,G])),F=new Map(x.map(G=>[G.file,G])),L=[...new Set([...P.keys(),...F.keys()])].sort().map(G=>{let X=P.get(G),B=F.get(G);return{path:G,preDigest:X?.exists===!1||!X?null:Se(X.content),postDigest:B?.exists===!1||!B?null:Se(B.content)}});return{schemaVersion:2,transactionId:`${p}:${I.expectedIndexDigest}`,operationId:p,phase:"prepared",historyTransition:I,files:L}}async function Zl(p){return!p||!e.historyStore||await e.historyStore.writeTransactionJournal(p),p}async function Kn(p){p&&e.historyStore&&await e.historyStore.clearTransactionJournal(p.transactionId)}async function As(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 Gh(b.filter(F=>x.includes(F.file)));return P.ok?{ok:!1,reason:`Writeback failed and committed files were restored: ${qe(I)}`,rolledBack:!0}:{ok:!1,reason:`Writeback failed, then rollback failed for ${P.failedFiles.join(", ")}: ${qe(I)}`,rolledBack:!1}}return{ok:!0,snapshots:p.map(Yh)}}async function Ql(p){if(p.exists===!1){await n.deleteFile(p.file);return}await n.writeFile(p.file,p.content)}async function Gh(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 Yh(p){let b=p.exists!==!1;return{file:p.file,content:b?p.content:"",version:p.version,exists:b,...b?{sha256:Se(p.content)}:{}}}async function Un(p){return h.runExclusive(()=>Zh(p))}async function Zh(p){let b=p.filePlan.edits.map(_=>_.file),x=o.resolveSelector(p.request.composition),I=x.context,P=p.historyPolicy==="none"?void 0:{initiatingComposition:I,affectedCompositions:Dh(b)},F=await Ps(b),L=new Map(F.filter(_=>_.exists!==!1).map(_=>[_.file,_.content])),G=eu(),X=new Map(f),B=new Set(m),j=new Set([...i.values()].filter(_=>p.filePlan.edits.some(D=>D.operation==="delete"&&D.file===_.entryFile)).map(_=>_.key)),ie=p.filePlan.edits.map(_=>_.operation==="delete"?{file:_.file,content:"",version:0,exists:!1}:{file:_.file,content:_.content,version:0,exists:!0,sha256:Se(_.content)}),te={operationId:p.filePlan.operationId,intents:p.filePlan.edits.map(_=>_.operation==="delete"?{kind:"delete",path:_.file}:{kind:_.operation==="create-only"?"create-only":"upsert",path:_.file,content:_.content})},Fe=null,ye=!1,we=await ys({overlay:L,exists:_=>n.exists(_),plan:te,buildCandidate:async({plan:_})=>({plan:_}),prepareHistory:async()=>{let _=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:F,postSnapshots:ie,...p.selectionRef?{selectionRef:p.selectionRef}:{},...p.output?{output:p.output}:{},...P?{provenance:P}:{}}),D=_?.historyTransition?_.historyTransition:e.historyStore?jw(await e.historyStore.readIndex()):null;if(e.historyStore&&!D)throw new Error("Durable history did not provide an exact index transition.");return Fe=await Yl(p.request.id,F,ie,D),Fe=await Zl(Fe),{history:_,historyTransition:D}},reverify:async()=>{},writeCandidate:async()=>{let _=await d.executeFilePlan(p.filePlan);if(!_.ok)throw new vs(_);return{postSnapshots:await Ps(_.affectedFiles),affectedFiles:_.affectedFiles,internalResultVersion:_.resultVersion}},validateCandidate:async({candidate:_,receipt:D})=>{let pe=await Po(D.affectedFiles,{changed:!0,minimumVersion:D.internalResultVersion,publish:!1,excludedCompositionKeys:j});if(pe.failedRoutes.length>0)throw new jn(pe.failedRoutes);let fe=nu(G,pe.candidateRouteStates??[]),Ie=tu(fe,x.key);return{..._,rebuild:pe,routeSnapshots:fe,resultVersion:Ie,...vh(p.selectionRef,fe.map(De=>De.state.document))?{selectionRef:vh(p.selectionRef,fe.map(De=>De.state.document))}:{}}},publishCandidate:async({candidate:_,history:D,receipt:pe})=>{D?.history&&(await l.publishPrepared(D.history),ye=!0);let fe=_.resultVersion??pe.internalResultVersion;return{composition:I,requestId:p.request.id,kind:p.request.kind,target:p.request.target,ok:!0,resultVersion:fe,affectedFiles:pe.affectedFiles,...p.output?{output:p.output}:{},..._.selectionRef?{selectionRef:_.selectionRef}:{}}},swapCandidate:({candidate:_,receipt:D})=>{_.routeSnapshots&&Ao(_.routeSnapshots),_.rebuild?.candidateSourceCache&&br(f,_.rebuild.candidateSourceCache),Xl(D.postSnapshots)},finalizeCandidate:async()=>{await Kn(Fe);for(let _ of j)i.delete(_)},emitCommitted:({candidate:_,published:D})=>{ws(D,_.rebuild??{rebuiltRoutes:[],failedRoutes:[]})},rollbackCandidate:async({history:_,receipt:D})=>{if(ye)throw new Error("history was published before transaction finalization failed");if(D){let pe=await As(F,D.postSnapshots);if(!pe.ok)throw new Error(pe.reason)}Ao(G),br(f,X),zl(B),_?.history&&await l.discardPrepared?.(_.history),await Kn(Fe)}});if(we.ok)return we.published;if(we.stage==="precheck"||we.stage==="build")try{await Kn(Fe)}catch(_){let D=await To(qe(_));return ce(p.request,D,"Unable to clear an uncommitted transaction journal.")}if(we.recoveryRequired){let _=await To(we.reason);return ce(p.request,_===V.RECOVERY_PERSIST_FAILED?_:V.ROLLBACK_FAILED,we.reason)}let Ne=we.error;return Ne instanceof vs?{...ce(p.request,wo(Ne.result.errorCode),Ne.result.reason),...Ne.result.affectedFiles?{affectedFiles:Ne.result.affectedFiles}:{}}:Ne instanceof jn?ce(p.request,V.ROUTE_REBUILD_FAILED,`Route rebuild failed and source was rolled back: ${Dl(Ne.failedRoutes)}`,{failedRoutes:Ne.failedRoutes}):ce(p.request,ou(we.stage),qe(Ne))}async function ql(p){return h.runExclusive(async()=>{let b=p==="undo"?await l.prepareUndo():await l.prepareRedo();return b?Qh(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:V.INTERNAL_ERROR,message:p==="undo"?"Nothing to undo":"Nothing to redo"}}})}async function Qh(p,b){let x=b.entry,I=p==="undo"?x.preSnapshots:x.postSnapshots,P=p==="undo"?x.postSnapshots:x.preSnapshots,F=I.map(D=>D.file),{context:L,key:G}=Bh(x,F),X=await Ps(F),B=new Map(X.filter(D=>D.exists!==!1).map(D=>[D.file,D.content])),j=Re(G),ie=eu(),te=new Map(f),Fe=new Set(m),ye=null,we=!1,Ne,_=await ys({overlay:B,plan:{operationId:`${p}:${x.operationId}`,intents:I.map(D=>D.exists===!1?{kind:"delete",path:D.file}:{kind:"upsert",path:D.file,content:D.content})},buildCandidate:async()=>({}),prepareHistory:async()=>(ye=await Yl(`${p}:${x.operationId}`,X,I,b.historyTransition),ye=await Zl(ye),b),reverify:async()=>{},writeCandidate:async()=>{let D=await As(I,P);if(!D.ok)throw new Error(D.reason);return{snapshots:D.snapshots}},validateCandidate:async({candidate:D})=>{Ne=Lh(x,F);let pe=await Po(F,{changed:!0,minimumVersion:j+1,publish:!1,affectedCompositionKeys:Ne});if(pe.failedRoutes.length>0)throw new jn(pe.failedRoutes);let fe=nu(ie,pe.candidateRouteStates??[]),Ie=tu(fe,G);return{...D,rebuild:pe,routeSnapshots:fe,resultVersion:Ie}},publishCandidate:async({candidate:D,history:pe})=>{if(!pe)throw new Error("history cursor intent is missing");await l.publishPrepared(pe),we=!0;let fe=D.resultVersion??j+1;return{composition:L,requestId:p,kind:x.kind,target:x.target,ok:!0,resultVersion:fe,affectedFiles:F,...x.output?{output:x.output}:{}}},swapCandidate:({candidate:D,receipt:pe})=>{D.routeSnapshots&&Ao(D.routeSnapshots),D.rebuild?.candidateSourceCache&&br(f,D.rebuild.candidateSourceCache),Xl(pe.snapshots)},finalizeCandidate:async()=>{await Kn(ye)},emitCommitted:({candidate:D,published:pe})=>ws(pe,D.rebuild??{rebuiltRoutes:[],failedRoutes:[]}),rollbackCandidate:async({history:D,receipt:pe})=>{if(we)throw new Error("history cursor was published before transaction finalization failed");if(pe){let fe=await As(P,pe.snapshots);if(!fe.ok)throw new Error(fe.reason)}Ao(ie),br(f,te),zl(Fe),D&&await l.discardPrepared?.(D),await Kn(ye)}});if(_.ok)return _.published;if(_.stage==="precheck"||_.stage==="build")try{await Kn(ye)}catch(D){let pe=await To(qe(D));return{composition:L,requestId:p,kind:x.kind,target:x.target,ok:!1,resultVersion:j,error:{code:pe,message:"Unable to clear an uncommitted transaction journal."}}}if(_.recoveryRequired){let D=await To(_.reason);return{composition:L,requestId:p,kind:x.kind,target:x.target,ok:!1,resultVersion:j,affectedFiles:F,error:{code:D===V.RECOVERY_PERSIST_FAILED?D:V.ROLLBACK_FAILED,message:_.reason}}}return{composition:L,requestId:p,kind:x.kind,target:x.target,ok:!1,resultVersion:j,affectedFiles:F,error:{code:_.error instanceof jn?V.ROUTE_REBUILD_FAILED:ou(_.stage),message:qe(_.error),..._.error instanceof jn?{details:{failedRoutes:_.error.failedRoutes}}:{}}}}function eu(){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 tu(p,b){return p.find(I=>I.key===b)?.state.graph?.version??o.initialVersions.get(b)??0}function nu(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 Ao(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 Ts(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 Te(p,x)}function Jn(p,b){let x=i.get(o.resolveSelector(b).key)??null;return!x||!ru(x,p)?null:x}function ru(p,b){if(p.documentIndex?.entriesByKey.has(b)||p.graph?.elements.has(b))return!0;let x=ot(b);return x&&x!==b?p.graph?.elements.has(x)===!0:!1}function ce(p,b,x,I){return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Q(p),error:{code:b,message:x,...I?{details:I}:{}}}}function ou(p){return p==="validate"?V.ROUTE_REBUILD_FAILED:p==="publish"?V.HISTORY_COMMIT_FAILED:V.WRITE_IO_ERROR}async function To(p){if(g=!0,!l.markRecoveryRequired)return V.RECOVERY_REQUIRED;try{return await l.markRecoveryRequired(p),V.RECOVERY_REQUIRED}catch{return V.RECOVERY_PERSIST_FAILED}}function qh(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 Fs(p){return p==="VERSION_STALE"?V.VERSION_STALE:p==="CROSS_PAGE_MOVE_UNSUPPORTED"?V.CROSS_PAGE_MOVE_UNSUPPORTED:V.UNSUPPORTED_OPERATION}async function iu(p){if(p.target.kind==="route"){let x=i.get(o.resolveSelector(p.target.composition).key)??null;return x?(x.graph||await Ts(x.key),x):ce(p,V.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 Ts(x.key),x):ce(p,V.ROUTE_NOT_FOUND,"Composition not found for page-unit target.")}if(p.target.kind!=="node")return ce(p,V.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 Ts(b.key),ru(b,p.target.key)?b:ce(p,V.NODE_NOT_FOUND,`Target key not found: ${p.target.key}`)):ce(p,V.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=Eh(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 Te(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:qe(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=Jn(p,b),P=ot(p)??p;if(I?.graph&&I.topology&&I.capabilities&&I.detailProjections){let F=I.detailProjections.get(P);if(F){let L=I.graph.elements.get(P);if(!L)throw new Error(`Key not found: ${p}`);let G=zw(p,P,x),X=new Map;if(F.isRepeat&&G?.instanceIndex!==void 0)for(let ie of L.attributes??[])X.set(ie.name,dl({file:L.sourceFile,source:f.get(L.sourceFile)??"",element:L,propertyName:ie.name,selectionRef:G,graph:I.graph,sources:f}));let B=Lg({element:L,graph:I.graph,source:f.get(L.sourceFile),documentVersion:I.graph.version,selectionRef:x,isRepeat:F.isRepeat,propertyProvenance:F.propertyProvenances,repeatTargets:X}),j=$g(P,I.graph,I.topology,I.capabilities,F.textSources,F.provenances,F.dynamicData,B);return p===P?j:fh(j,p,I.document??null,I.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${p}`)},getRenderDetail(p,b){let x=Jn(p,b),I=ot(p)??p;if(x?.graph&&x.topology&&x.capabilities&&x.detailProjections){let P=x.detailProjections.get(I);if(P){let F=jg(I,x.graph,x.topology,x.capabilities,P.textSources,P.writeTarget,P.provenances,P.conditional,P.componentSemantic,P.styleSource,P.dynamicData);return p===I?F:dh(F,p,x.document??null,x.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${p}`)},getClassNameSource(p,b){let x=Jn(p,b),I=ot(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 F=f.get(P.sourceFile);if(F===void 0)throw new Error(`Source not loaded: ${P.sourceFile}`);return ga({key:I,route:{composition:x.composition,routeId:x.routeId,graph:x.graph,source:F}})},refreshSourceForKey:$h,async execute(p){if(await S,g)return ce(p,V.RECOVERY_REQUIRED,"The edit engine requires explicit recovery before accepting mutations.");if(p.kind==="source-edit")return Vh(p);if(p.kind==="insert-page-resource")return Kh(p);if(p.kind==="delete-page-source")return Uh(p);let b=await iu(p);if("ok"in b)return b;await Wl(p);let x=await iu(p);if("ok"in x)return x;let I=x;if(p.target.kind==="page-unit"){let j=p;return p.kind==="insert-child"||p.kind==="replace-node"?Jh(j,I):p.kind==="move-node"||p.kind==="remove-node"?Xh(j,I):ce(p,V.UNSUPPORTED_OPERATION,"Only page-unit insert-child, replace-node, move-node, and remove-node are currently supported by the page composition transaction.")}let F=p.params,L=p.target.kind==="node"?p.target.key:null;if(F.kind==="move-node"&&"kind"in F.target&&F.target.kind==="source-sibling"){let j=F.target,ie=L?I.document?.entries.find(D=>D.key===L):null,te=I.document?.entries.find(D=>D.key===j.anchorKey),Fe=ie?.pageCompositionActionScope,ye=Fe?.kind==="source-siblings"?Fe.siblingKeys:null,we=ye?.indexOf(ie?.key??"")??-1,Ne=ye?.indexOf(j.anchorKey)??-1,_=j.relation==="before"?we-1:we+1;if(!ie||!te||!ye||we<0||Ne!==_||te.pageCompositionActionScope?.kind!=="source-siblings"||te.pageCompositionActionScope.siblingKeys.length!==ye.length||te.pageCompositionActionScope.siblingKeys.some((D,pe)=>D!==ye[pe])||!ie.operationSummary.canMove)return ce(p,V.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:Q(p),error:{code:p.target.kind==="route"?V.ROUTE_NOT_FOUND:V.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 G=uN(I,I.graph,I.capabilities,f,i),X=await new ts(G).plan(p);if(!X.ok)return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Q(p),error:{code:wo(X.errorCode),message:X.reason}};let B=X.plan;if(B.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:Q(p),affectedFiles:[]}:{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Q(p),error:{code:V.PLAN_FAILED,message:"Planner could not generate a valid execution plan"}};u+=1;try{if(B.steps.some(ie=>ie.type==="invoke-external-adapter")){let ie=await d.execute(B);if(!ie.ok)return ce(p,wo(ie.errorCode),ie.reason);let te={composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!0,resultVersion:Math.max(Q(p),ie.resultVersion),affectedFiles:ie.affectedFiles,...ie.selectionRef?{selectionRef:ie.selectionRef}:{}};return ws(te,{rebuiltRoutes:[],failedRoutes:[]}),te}let j=await d.prepareRewritePlan(B);return j.ok?await Un({request:p,filePlan:j.filePlan,...j.selectionRef?{selectionRef:j.selectionRef}:{}}):ce(p,wo(j.errorCode),j.reason)}catch(j){return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Q(p),error:{code:V.INTERNAL_ERROR,message:qe(j)}}}finally{u-=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:Re(o.entries[0].key),error:{code:V.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting undo."}};u+=1;try{return await ql("undo")}finally{u-=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:Re(o.entries[0].key),error:{code:V.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting redo."}};u+=1;try{return await ql("redo")}finally{u-=1}},notifyFileChanged(p){Ul([p])},getAffectedCompositions(p){return Mh(p)},subscribe(p){return r.subscribe(p)}}}function rN(e){return e instanceof Error&&"code"in e&&(e.code==="ENOENT"||e.code==="ENOTDIR")}function oN(e,t,n,r){let o=new Map,i=new Map,s=(f,m,u)=>{let g=f.get(m)??new Set,h=g.size;return g.add(u),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 u=s(o,`${f.importedFrom}#${f.tag}`,m);return f.exportName&&f.exportName!==f.tag&&(u=s(o,`${f.importedFrom}#${f.exportName}`,m)||u),u},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&&No(f.sourceRange,h.sourceRange)));if(!m)continue;let u=m.placementUnitKey;a(f,u)}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 u of m)l=a(f,u)||l}}let d=n.placements.find(f=>f.placementKey===n.container.placementKey&&f.relation==="append");for(let f of e.entries){let m=ot(f.key)??f.key,u=t.elements.get(f.key)??t.elements.get(m);if(!u)continue;if(u.sourceFile===n.entryFile){if(n.container.sourceRange&&No(u.sourceRange,n.container.sourceRange)&&d){f.pageCompositionUnitKey=d.placementUnitKey;continue}let S=n.placements.find(E=>E.members.some(y=>y.sourceRange!==null&&(No(u.sourceRange,y.sourceRange)||lN(y.sourceRange,u.sourceRange))));if(S){f.pageCompositionUnitKey=S.placementUnitKey;continue}}let g=o.get(`${u.sourceFile}#${u.componentName}`);if(g){g.size===1&&(f.pageCompositionUnitKey=g.values().next().value);continue}let h=i.get(u.sourceFile);h?.size===1&&(f.pageCompositionUnitKey=h.values().next().value)}iN(e,t,n,r)}function iN(e,t,n,r){let o=new Map(e.entries.map(m=>[m.key,m])),i=e.entries.filter(m=>{let u=m.pageCompositionUnitKey;return u?m.parentKey?o.get(m.parentKey)?.pageCompositionUnitKey!==u:!0:!1}),s=new Map,a=(m,u)=>{s.set(m,Math.min(2,(s.get(m)??0)+u))},c=m=>n.placements.some(u=>u.members.some(g=>g.sourceRange!==null&&No(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 u=!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),u=!0)}if(!u)break}let d=m=>s.get(`${m.sourceFile}#${m.componentName}`)??s.get(`${m.sourceFile}#default`)??0;for(let m of i){m.pageCompositionActionScope={kind:"unavailable"};let u=t.elements.get(m.key);m.pageCompositionUnitKey&&u?.sourceFile===n.entryFile&&(m.pageCompositionActionScope={kind:"route-unit"})}let f=new Map;for(let m of i){let u=t.elements.get(m.key);if(!u||u.sourceFile===n.entryFile||m.key!==(ot(m.key)??m.key))continue;let g=r.get(u.sourceFile);if(!g)continue;let h=se(g.ast,{kind:"jsx-node",strategy:"source-range",sourceRange:u.sourceRange});if(!h.ok||!h.match.path.isJSXElement())continue;let S=h.match.path,E=S.parentPath;if(!E||!E.isJSXFragment()&&!(E.isJSXElement()&&_e(E))){d(u)===1&&Ih(S)&&(m.pageCompositionActionScope={kind:"route-unit"});continue}if(!Ih(E))continue;let y=f.get(E.node)??[];y.push({entry:m,element:u,parentPath:E}),f.set(E.node,y)}for(let m of f.values()){let u=m[0];if(!u)continue;let g=u.entry.pageCompositionUnitKey,h=[],S=!!(g&&d(u.element)===1);for(let y of u.parentPath.node.children){if(sN(y))continue;if(!aN(y)){S=!1;break}let v=[...t.elements.values()].find(N=>N.sourceFile===u.element.sourceFile&&N.componentName===u.element.componentName&&No(N.sourceRange,cN(y))),C=v?o.get(v.identity.key):null;if(!v||!C||C.parentKey||C.pageCompositionUnitKey!==g||d(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 Ih(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 aN(e){return!!(e&&typeof e=="object"&&e.type==="JSXElement")}function cN(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 No(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function lN(e,t){return Ch(e.startLine,e.startColumn,t.startLine,t.startColumn)<=0&&Ch(e.endLine,e.endColumn,t.endLine,t.endColumn)>=0}function Ch(e,t,n,r){return e!==n?e-n:t-r}function uN(e,t,n,r,o){let i=new Map,s=new Map,a=(d,f)=>{if(s.has(d))return;s.set(d,f);let m=t.elements.get(d);for(let u of m?.childKeys??[])a(u,f)};for(let d of t.regions)if(d.kind==="repeat-region")for(let f of d.childKeys)i.set(f,d.ownerKey),a(f,d.ownerKey);return{getNode(d){let f=c(d),m=t.elements.get(f.baseKey);return m?l(d,m):null},getChildNodes(d){let f=c(d),u=e.documentIndex?.entriesByKey.get(d)?.childKeys;if(u)return u.map(h=>{let S=ot(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(([d,f])=>({file:d,content:f}))},getRouteEntryFiles(){return[...o.values()].map(d=>d.entryFile)},getCapability(d){let f=c(d),m=n.get(f.baseKey);return m?{...m,key:d,constraints:m.constraints.map(u=>({...u})),...m.editModes?{editModes:{...m.editModes}}:{}}:{composition:e.composition,key:d,canUpdateText:!1,canRemove:!1,canInsertChild:!1,canMove:!1,constraints:[]}},getFileContent(d){return r.get(d)??""},getFileVersion(d){return Math.max(e.fileVersions.get(d)??0,t.version)},getRouteEntryFile(d){return e.routeId===d?e.entryFile:null},getComponentSemantic(d){let f=c(d);return e.detailProjections?.get(f.baseKey)?.componentSemantic??null},getClassNameSource(d){let f=c(d),m=t.elements.get(f.baseKey),u=m?r.get(m.sourceFile):void 0;return!m||u===void 0?null:ga({key:f.baseKey,route:{composition:e.composition,routeId:e.routeId,graph:t,source:u}})},getEditableTextSegmentIndex(d){let f=c(d),u=e.detailProjections?.get(f.baseKey)?.textTargets.keys()?.next();return u&&!u.done?u.value:null},async getTextWriteTarget(d,f){let m=c(d);return Ml(e.detailProjections?.get(m.baseKey)?.textTargets.get(f)??null,m.repeatIndex)},async getElementPropertyWriteTarget(d,f){let m=c(d);return Ml(e.detailProjections?.get(m.baseKey)?.elementPropertyTargets.get(f)??null,m.repeatIndex)},getPropertyState(d,f,m){let u=c(d),g=t.elements.get(u.baseKey);if(!g)return null;let S=e.detailProjections?.get(u.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(d,f,m){let u=c(d),g=t.elements.get(u.baseKey);if(!g)return{ok:!1,errorCode:"repeat-not-found",reason:`Node not found: ${d}`};let h=m?{...m,key:u.baseKey}:u.repeatIndex!==null?{key:u.baseKey,instanceIndex:u.repeatIndex}:void 0;return dl({file:g.sourceFile,source:r.get(g.sourceFile)??"",element:g,propertyName:f,selectionRef:h,graph:t,sources:r})},getTextProvenance(d,f){let m=c(d);return e.detailProjections?.get(m.baseKey)?.provenances.get(f)??null}};function c(d){let f=Ow(d);return f?{baseKey:f.baseKey,repeatIndex:uh(e.document??null,d,f.baseKey,e.documentIndex)??lh(f)}:{baseKey:d,repeatIndex:null}}function l(d,f){let m=ot(d)??d,u=e.documentIndex?.entriesByKey.get(d);return{key:d,file:f.sourceFile,component:f.componentName,tag:f.tag,structuralPath:f.identity.structuralPath,sourceRange:f.sourceRange,parentKey:u?.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 dN={"stale-version":V.VERSION_STALE,"capability-denied":V.CAPABILITY_REJECTED,"invalid-params":V.INVALID_PARAMS,"locator-miss":V.LOCATOR_FAILED,"route-not-found":V.ROUTE_NOT_FOUND,"unsupported-operation":V.UNSUPPORTED_OPERATION,"invalid-target":V.INVALID_TARGET,"ast-error":V.AST_PARSE_ERROR,"writeback-failed":V.WRITE_IO_ERROR,"rollback-failed":V.RECOVERY_REQUIRED,unknown:V.INTERNAL_ERROR};function wo(e){return dN[e]}function qe(e){return e instanceof Error&&e.message?e.message:String(e)}function Rh(e){return/\.(?:[cm]?[jt]sx?|css|scss|sass|mdx|json)$/i.test(e)}function fN(e){let t=$n(e);if(!Lw.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=>Bw.map(a=>`${s}/${a}`))}function pN(e){let n=$n(e).startsWith("src/app/")?"src/app":"app";return[`${n}/globals.css`,`${n}/global.css`]}function mN(e){return Ph(e,/\bimport\s+(?:[^'";]+?\s+from\s+)?["']([^"']+\.css(?:\?[^"']*)?)["']/g)}function gN(e){return Ph(e,/@import\s+(?:url\(\s*)?["']([^"']+)["']/g)}function Ph(e,t){let n=[];for(let r of e.matchAll(t)){let o=Ah(r[1]??"");o&&n.push(o)}return n}function wh(e,t){let n=Ah(t);return!n||n.startsWith("tailwindcss")||n.startsWith("http:")||n.startsWith("https:")?null:n.startsWith("@/")?$n(`src/${n.slice(2)}`):n.startsWith("./")||n.startsWith("../")?$n(`${hN(e)}/${n}`):n.startsWith("/")?$n(n.slice(1)):jl(n)?$n(n):null}function Ah(e){return e.split(/[?#]/,1)[0]?.trim()??""}function jl(e){return/\.css$/i.test(e)}function hN(e){let t=$n(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function yN(e){return Array.from(new Set(e))}function $n(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 xN(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 Is=class{constructor(t){this.options=t,this.fileSystem=new kr(t.files),this.engine=this.createEngine(this.fileSystem)}get status(){return this.engine.status}initializeComposition(t){return this.engine.initializeComposition(t)}getDocument(t){return jo(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 $o(r?this.engine.getObjectEditContext(t,n,r):this.engine.getObjectEditContext(t,n))}getClassNameSource(t,n){return this.engine.getClassNameSource(t,n)}getSourceTree(t){return Uo(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}getSourceFile(t){return Jo(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}resolveSourceLocation(t){return Xo(t,this.engine.getRenderDetail(t.key,t.composition))}async planOperation(t){let n=SN.safeParse(t);if(!n.success)return{result:Bo(t,n.error.issues.map(i=>i.message))};let r=new kr(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:kn(i)},a=r.getChangedFiles();if(a.length===0)return{result:s};let c=EN.parse({siteId:t.siteId,baseSnapshotId:t.baseSnapshotId,operationId:t.id,reason:`site-edit:${t.kind}`,patches:a.map(l=>vN(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 ks({projectRoot:"/snapshot",fileSystem:t,compositions:this.options.compositions,onEvent:r&&this.options.onEvent?o=>{let i=Vo(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 vN(e,t){return e.after===void 0?{path:e.path,operation:"delete",...t||e.before===void 0?{}:{expectedHash:Se(e.before)}}:{path:e.path,operation:e.before===void 0?"create":"update",...t||e.before===void 0?{}:{expectedHash:Se(e.before)},fullContent:e.after}}function kN(e){return new Is(e)}import{SiteEditOperationRequestSchema as RN}from"@vcp-dev/contracts";import Rt from"node:fs/promises";import et from"node:path";import{SITE_EDIT_SOURCE_ALLOWED_DIRS as IN,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as CN}from"@vcp-dev/contracts";var Cs=class{constructor(t){this.options=t,this.fileSystem=this.createFileSystem(),this.engine=ks({...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 Uo(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.engine.getCompositionEntryFiles()})}getSourceFile(t){return Jo(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.engine.getCompositionEntryFiles()})}resolveSourceLocation(t){return Xo(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 Rt.readFile(et.join(n,r),"utf8")},async readFileBytes(r){return Rt.readFile(et.join(n,r))},async getFileInfo(r){let o=et.join(n,...r.split("/"));try{let i=await Rt.lstat(o);return!i.isFile()||i.isSymbolicLink()?null:{path:r,sizeBytes:i.size}}catch{return null}},async writeFile(r,o){await ui(et.join(n,r),o)},async createExclusive(r,o){let i=et.join(n,r);await Rt.mkdir(et.dirname(i),{recursive:!0});let s=await Rt.open(i,"wx");try{await s.writeFile(o,"utf8")}catch(a){throw await s.close(),await Rt.rm(i,{force:!0}),a}await s.close()},async deleteFile(r){await Rt.rm(et.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=et.join(n,i),a=et.dirname(et.join(n,o));for(;a!==s&&a.startsWith(`${s}${et.sep}`);){try{await Rt.rmdir(a)}catch(c){if(c instanceof Error&&"code"in c&&c.code==="ENOENT"){a=et.dirname(a);continue}break}a=et.dirname(a)}},async exists(r){try{return await Rt.access(et.join(n,r)),!0}catch{return!1}},async listFiles(r={}){let o=r.roots??[...CN,...IN],i=[],s=new Set,a=new Set,c=0;for(let f of o)await d(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 d(f,m,u){if(r.maxDepth!==void 0&&u>r.maxDepth){a.add("max-depth");return}let g=et.join(n,...f.split("/")),h;try{h=await Rt.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 Rt.readdir(g,{withFileTypes:!0});for(let E of S)E.isSymbolicLink()||await d(`${f}/${E.name}`,m,u+1)}},getVersion(r){return t.get(r)??1},bumpVersion(r){let o=(t.get(r)??1)+1;return t.set(r,o),o}}}};function $l(e){return new Cs(e)}var Rs=class{constructor(t){this.options=t,this.listeners=new Set,this.engine=$l({projectRoot:t.projectRoot,fileSystem:t.fileSystem,compositions:t.compositions,onEvent:n=>{let r=Vo(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:jo(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:$o(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=RN.safeParse(r);if(!o.success)return Bo(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:kn(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:kn(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:kn(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 wN(e){return new Rs(e)}export{oe as FileHistoryStoreError,Zr as PageTemplateManagedSourceError,Rs as PreviewFileSystemSiteEditEngineRuntime,lf as SITE_EDIT_RAW_COLOR_LITERAL_RE,Is as SnapshotSiteEditEngineRuntime,_o as checkComponentI18nHostCompatibility,ep as computeManagedPageTemplatePaths,wN as createPreviewSiteEditEngineRuntime,kN as createSiteEditEngineRuntime,Zf as decodePageTemplateKey,gc as encodePageTemplateId,ky as instrumentSiteEditRuntimeAttributes,tp as isManagedPageTemplateSourcePath,Bd as openFileHistoryStore,ay as parseSourceModule,cy as resolveImportBase,Sk as resolveManagedPageTemplateComposition,Li as scanManagedPageTemplateCandidates,rp as scanSiteEditCompositionsFromFiles,Jr as scanSiteEditThemeStyleViolations};
|