@vcp-dev/site-edit-engine 0.10.28 → 0.10.30
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/component-i18n-host-compatibility.d.ts +18 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +8 -8
- package/dist/types.d.ts +2 -0
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
import*as Jh from"@babel/parser";import*as Wn from"@babel/types";import*as qt from"node:path";var Ns=[".tsx",".ts",".jsx",".js"],Xh=Ns.map(e=>`/index${e}`),zh=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 ou(e){let t=e.replace(/[?#].*$/,""),n=/\.([a-z0-9]+)$/i.exec(t);return n!==null&&zh.has(n[1].toLowerCase())}function iu(e){let t=[];for(let n of e.program.body)Wn.isImportDeclaration(n)&&typeof n.source.value=="string"&&Pt(n.source.value)&&t.push(n.source.value),Wn.isExportNamedDeclaration(n)&&n.source&&typeof n.source.value=="string"&&Pt(n.source.value)&&t.push(n.source.value),Wn.isExportAllDeclaration(n)&&typeof n.source.value=="string"&&Pt(n.source.value)&&t.push(n.source.value);return ws(e.program,t),t}function ws(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"&&Pt(r.value)&&t.push(r.value)}for(let r of Object.values(n))if(Array.isArray(r))for(let o of r)ws(o,t);else r&&typeof r=="object"&&ws(r,t)}function Pt(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 Wh(e,t){if(Ns.some(n=>e.endsWith(n))&&await t(e))return e;for(let n of Ns){let r=`${e}${n}`;if(await t(r))return r}for(let n of Xh){let r=`${e}${n}`;if(await t(r))return r}return null}async function xn(e,t,n){let r=await Fo(e,t,n);return r.ok?r.path:null}async function Fo(e,t,n){let r=yn(e,t);try{if(!Hh(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 Wh(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 Hh(e,t,n){if(!Pt(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 Yh}from"node:crypto";import*as su 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 Ps(e,t,n,r,o){return{ok:!1,source:e,diagnostic:bn(t,n,r,o)}}var Gh={"tsx-module":["jsx","typescript"],"ts-module":["typescript"],"next-app-entry":["jsx","typescript"]};function At(e){let{source:t,profile:n}=e;try{return{ok:!0,ast:su.parse(t,{sourceType:"module",plugins:Gh[n]})}}catch(r){return{ok:!1,source:t,diagnostic:bn("parse-failed",`AST parse failed: ${r instanceof Error?r.message:String(r)}`)}}}function As(e,t){return At({source:e,profile:au(t.kind)})}function vr(e,t){return At({source:e,profile:au(t)})}function au(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=At({source:t,profile:Sn({filePath:e,source:t})});return n.ok?{ok:!0,module:{file:e,source:t,sourceHash:`sha256:${Yh("sha256").update(t).digest("hex")}`,ast:n.ast,imports:iu(n.ast).map(r=>({specifier:r}))}}:{ok:!1,diagnostic:{path:e,code:"parse-failed",message:n.diagnostic.message}}};function Zh(e,t){return En(e,t)}function Qh(e,t){return yn(e,t)}import Fs from"@babel/generator";import*as pu from"@babel/parser";import _s from"@babel/traverse";import*as Ie from"@babel/types";import{computeSiteEditSourceIdentityKey as ey}from"@vcp-dev/contracts";var cu="data-vcp-ui-component",_o="components/ui";function Ut(e){if(!e)return!1;let t=Ts(e);return t===_o||t.startsWith(`${_o}/`)||t.includes(`/${_o}/`)||t.endsWith(`/${_o}`)}function vn(e,t){return e?e.startsWith("@/")||e.startsWith("~/")?Ut(e.slice(2)):e.startsWith("./")||e.startsWith("../")?Ut(Ts(`${qh(t)}/${e}`)):Ut(e):!1}function Ts(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 qh(e){let t=Ts(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}import{stripSiteEditRepeatInstanceKeys as ww}from"@vcp-dev/contracts";import{isSiteEditRuntimeContainerTag as Aw,isSiteEditRuntimeTextTag as Tw}from"@vcp-dev/contracts/site-edit-runtime-capability";var lu={key:"data-vcp-edit-key",parentKey:"data-vcp-edit-parent-key",movable:"data-vcp-movable",removable:"data-vcp-removable",flags:"data-vcp-flags",publicUiComponent:"data-vcp-ui-component"};var ty=typeof Fs=="function"?Fs:Fs.default,ny=typeof _s=="function"?_s:_s.default,ry=new Set(["base","body","head","html","link","meta","noscript","script","style","template","title"]),oy="suppressHydrationWarning",iy=new Set(["SiteEditBootstrap"]);function sy(e){let t=ly(e.file,e.projectRoot);if(!cy(e.source)||Ut(t))return{code:e.source,elements:[]};let n=e.attributes??lu,r=pu.parse(e.source,{sourceType:"module",plugins:["jsx","typescript"]}),o=[],i=dy(r,t);return ny(r,{JSXElement(s){let a=s.node.openingElement,c=a.name;if(!py(c)||mu(a,n.key))return;let l=gy(s)??"default",d=yy(s),f=ey(t,l,d),m=Mo(c)??"unknown",u=uy(c)?"jsx":"component-call";if(u==="component-call"&&!hy(s.node.children)&&iy.has(m))return;let g=u==="component-call"&&fy(m,i);my(a,n.key,f),g&&uu(a,cu),ay(s)&&uu(a,oy),o.push({key:f,tag:m,componentName:l,sourceFile:t,sourceKind:u})}}),o.length===0?{code:e.source,elements:o}:{code:ty(r,{jsescOption:{minimal:!0}}).code,elements:o}}function ay(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 ly(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 uy(e){return Ie.isJSXIdentifier(e)&&/^[a-z]/.test(e.name)}function Mo(e){return Ie.isJSXIdentifier(e)?e.name:Ie.isJSXMemberExpression(e)?hu(e):null}function dy(e,t){let n=new Set;for(let r of e.program.body)if(!(!Ie.isImportDeclaration(r)||!vn(r.source.value,t)))for(let o of r.specifiers)n.add(o.local.name);return n}function fy(e,t){let n=e.split(".")[0]??e;return t.has(n)}function py(e){let t=Mo(e);return!t||t==="Fragment"||t.endsWith(".Fragment")?!1:!ry.has(t)}function mu(e,t){return e.attributes.some(n=>Ie.isJSXAttribute(n)&&Ie.isJSXIdentifier(n.name,{name:t}))}function my(e,t,n){gu(e,Ie.jsxAttribute(Ie.jsxIdentifier(t),Ie.stringLiteral(n)))}function uu(e,t){mu(e,t)||gu(e,Ie.jsxAttribute(Ie.jsxIdentifier(t),null))}function gu(e,t){let n=e.attributes.findIndex(r=>Ie.isJSXSpreadAttribute(r));if(n>=0){e.attributes.splice(n,0,t);return}e.attributes.push(t)}function hu(e){return`${Ie.isJSXIdentifier(e.object)?e.object.name:hu(e.object)}.${e.property.name}`}function gy(e){let t=e;for(;t;){if(t.isFunctionDeclaration()||t.isClassDeclaration())return t.node.id?.name??null;if(t.isVariableDeclarator()&&Ie.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 hy(e){return e.some(t=>Ie.isJSXElement(t)||Ie.isJSXFragment(t))}var du=new WeakMap,Oo=new WeakMap,Os=new WeakMap;function yy(e){let t=du.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=xy(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return du.set(e.node,o),o}function xy(e){let t=Mo(e.node.openingElement.name);return!t||t==="Fragment"||t.endsWith(".Fragment")?null:/^[A-Z]/.test(t)?`component:${t}#${fu(e,t)}`:`${t}#${fu(e,t)}`}function fu(e,t){let n=yu(e)??e.getFunctionParent();if(!n)return 0;let r=Os.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=Os.get(n.node);o||(o=new Map,Os.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()?Do(n):by(n);for(let c of a)if(Mo(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 by(e){let t=Oo.get(e.node);if(t)return t;let n=[];return e.traverse({JSXElement(r){r.getFunctionParent()?.node===e.node&&!yu(r)&&n.push(r)}}),Oo.set(e.node,n),n}function yu(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 Do(e){let t=Oo.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(...Do(o));continue}o.isJSXExpressionContainer()&&n.push(...kn(o.get("expression")))}return Oo.set(e.node,n),n}function kn(e){if(e.isJSXElement())return[e];if(e.isJSXFragment())return Do(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()&&Ey(e.node)){let t=e.get("arguments")[0];return Sy(t)}return[]}function Sy(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return[t];if(t.isJSXFragment())return Do(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 Ey(e){return Ie.isMemberExpression(e.callee)&&Ie.isIdentifier(e.callee.property)&&e.callee.property.name==="map"}import{SiteEditOperationRequestSchema as DN,SiteEditPatchPlanSchema as LN}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 Lo(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 Bo(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 jo(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:vy(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 $o(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 vy(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 zR,computeSiteEditCompositionKey as WR,getSiteEditSourceDeleteProtectionReason as HR,isSiteEditTextSourcePath as GR,parseSiteEditRepeatInstanceKey as YR,SITE_EDIT_SOURCE_DELETE_CAPABILITY as ZR,stripSiteEditRepeatInstanceKeys as nt}from"@vcp-dev/contracts";import as from"node:path";import{parse as QR}from"yaml";import js from"node:path";import{TextDecoder as Iy}from"node:util";import{SITE_EDIT_SOURCE_ALLOWED_APP_FILES as bu,SITE_EDIT_SOURCE_ALLOWED_DIRS as Su,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as Eu,SiteEditCompositionContextSchema as Cy,SiteEditSourceFileResponseSchema as Ms,SiteEditSourceLocationSchema as Ry,SiteEditSourcePathSchema as Vo,SiteEditSourceTreeResponseSchema as Ny,isSiteEditTextSourcePath as wy}from"@vcp-dev/contracts";import{createHash as ky}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 Ee(e){return`sha256:${ky("sha256").update(e).digest("hex")}`}var Py=[...Eu,...bu,...Su];function $s(e){if(!e.composition)throw new Error("Composition unavailable for source access policy.");return Cy.parse(e.composition)}var Ds=2e3,Ls=12,Bs=24*1024*1024,xu=512*1024,Ay=new Set(["image/avif","image/gif","image/jpeg","image/png","image/webp","image/x-icon"]),Ty={".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"},Fy={".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"},_y=new Iy("utf-8",{fatal:!0});async function Ko(e,t={}){let n=$s(t),{files:r,truncated:o}=await $y(e,t),i=Uy(r.map(s=>s.metadata));return Ny.parse({composition:n,nodes:i,defaultPath:Jy(r.map(s=>s.metadata)),totalFiles:r.length,...o?{truncated:o}:{}})}async function Uo(e,t,n={}){let r=$s(n),o=Vo.parse(t.path),i=await My(e,o,n);if(!i)throw new Error(`Source file not found: ${o}`);if(Ks(o)){let a=Iu(o),c=await Ly(e,{path:o,sizeBytes:i.sizeBytes,mimeType:a});return Ms.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:i.sizeBytes,mimeType:a,readonly:!0,...c})}let s=await Vs(e,o);return s.ok?Ms.parse({composition:r,path:o,kind:"text",language:Cu(o),sizeBytes:s.sizeBytes,contentHash:Ee(s.content),readonly:!1,content:s.content}):Ms.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:s.sizeBytes,mimeType:"application/octet-stream",readonly:!0,previewUnavailableReason:"unsupported-mime"})}async function Vs(e,t){if(e.readFileBytes){let o=await e.readFileBytes(t),i=Oy(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 Oy(e){if(e.includes(0))return null;try{return _y.decode(e)}catch{return null}}async function My(e,t,n){if(!By(t,n))return null;let r=await Dy(e,t);return r?{path:t,sizeBytes:r.sizeBytes}:null}async function Dy(e,t){if(e.getFileInfo)return e.getFileInfo(t);if(e.listFiles){let o=vu(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(Ks(t))return{path:t,sizeBytes:0};let n=await e.readFile(t);return{path:t,sizeBytes:Buffer.byteLength(n,"utf8")}}async function Ly(e,t){if(!Ay.has(t.mimeType))return{previewUnavailableReason:"unsupported-mime"};if(t.sizeBytes>xu)return{previewUnavailableReason:"too-large"};if(!e.readFileBytes)return{previewUnavailableReason:"bytes-unavailable"};let n=await e.readFileBytes(t.path);return n.byteLength>xu?{previewUnavailableReason:"too-large"}:{contentBase64:Buffer.from(n).toString("base64")}}function By(e,t){return Eu.some(n=>n===e)||bu.some(n=>n===e)||Su.some(n=>e===n||e.startsWith(`${n}/`))?!0:!e.startsWith("app/")&&!e.startsWith("src/app/")?!1:(t.routeEntryFiles??[]).some(n=>{let r=Vo.safeParse(n);return r.success&&r.data===e})}function Jo(e,t){if(!t.sourceLocator)throw new Error(`Source location not available for key: ${e.key}`);return Ry.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 vu(e){return Array.isArray(e)?{files:e}:e}function jy(e){return["max-files","max-depth","max-total-bytes"].filter(n=>e.includes(n))}async function $y(e,t){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let n=vu(await e.listFiles({roots:Vy(t),maxFiles:Ds+1,maxDepth:Ls,maxTotalBytes:Bs+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=Vo.safeParse(a.path);if(!c.success)continue;let l=c.data;if(l.split("/").length>Ls){o.add("max-depth");continue}if(r.size>=Ds){o.add("max-files");break}if(i+a.sizeBytes>Bs){o.add("max-total-bytes");break}r.set(l,{path:l,sizeBytes:a.sizeBytes,metadata:Ky(l,a.sizeBytes,$s(t))}),i+=a.sizeBytes}return{files:[...r.values()].sort((a,c)=>a.path.localeCompare(c.path)),...o.size>0?{truncated:{reasons:jy([...o]),maxFiles:Ds,maxDepth:Ls,maxTotalBytes:Bs}}:{}}}function Vy(e){let t=new Set(Py);for(let n of e.routeEntryFiles??[]){let r=Vo.safeParse(n);r.success&&(r.data.startsWith("app/")||r.data.startsWith("src/app/"))&&t.add(r.data)}return[...t]}function Ky(e,t,n){return Ks(e)?{composition:n,path:e,kind:"binary",language:null,sizeBytes:t,mimeType:Iu(e),readonly:!0}:{composition:n,path:e,kind:"text",language:Cu(e),sizeBytes:t,readonly:!1}}function Uy(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 ku(t)}function ku(e){return e.map(t=>t.kind==="directory"?{...t,children:ku(t.children)}:t).sort((t,n)=>t.kind!==n.kind?t.kind==="directory"?-1:1:t.name.localeCompare(n.name))}function Jy(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 Ks(e){return!wy(e)}function Iu(e){let t=js.posix.extname(e).toLowerCase();return!t&&js.posix.basename(e).toLowerCase()==="favicon"?"image/x-icon":Ty[t]??"application/octet-stream"}function Cu(e){let t=js.posix.extname(e).toLowerCase();return Fy[t]??"plaintext"}import Us from"@babel/traverse";import*as Tt from"@babel/types";function Fe(e){if(e.isJSXFragment())return!0;if(!e.isJSXElement())return!1;let t=e.node.openingElement.name;if(Tt.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(Tt.isIdentifier(s)&&s.name==="Fragment"||Tt.isStringLiteral(s)&&s.value==="Fragment")&&Ru(i.parentPath)}if(!Tt.isJSXMemberExpression(t)||!Tt.isJSXIdentifier(t.property)||t.property.name!=="Fragment"||!Tt.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())&&Ru(r.parentPath)}function Ru(e){return e?.isImportDeclaration()===!0&&e.node.source.value==="react"}var en=typeof Us=="function"?Us:Us.default,Xo=new WeakMap,zo=new WeakMap;function Ft(e,t){let n=As(e,t);if(!n.ok)return Ps(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}}:Ps(e,r.diagnostic.code,r.diagnostic.message,t.kind,r.diagnostic.details)}function ae(e,t){return t.kind==="jsx-node"?Au(e,t):t.kind==="jsx-attribute"?Yy(e,t):t.kind==="value"?Zy(e,t):t.kind==="expression"?Qy(e,t):t.kind==="directive"?qy(e,t):t.kind==="export"?ex(e,t):{ok:!1,diagnostic:bn("unsupported-syntax",`Unsupported locator kind: ${t.kind}`)}}function Au(e,t){return t.strategy==="source-range"?Xy(e,t):zy(e,t)}function Xy(e,t){let n=null;if(en(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&&!fx(r.path,t.expectedIdentity)?Be("jsx-node","locator-miss","JSX node failed expected identity validation"):{ok:!0,match:r}}function zy(e,t){if(t.structuralPath===""){let r=Hy(e,t.component);if(r){let o=Gy(r);if(o)return o}}let n=null;return en(e,{JSXElement(r){if(Cr(r)!==t.component||Xs(r)!==t.structuralPath)return;let i=Le("jsx-node",r);i&&(n=i,r.stop())},JSXFragment(r){if(Cr(r)!==t.component||Xs(r)!==t.structuralPath)return;let i=Le("jsx-node",r);i&&(n=i,r.stop())}}),!n&&t.expectedRange&&(n=Wy(e,t.component,t.expectedRange)),n?{ok:!0,match:n}:Be("jsx-node","locator-miss","JSX node not found for structural-path locator")}function Wy(e,t,n){let r=null;return en(e,{JSXElement(o){if(Cr(o)!==t||!Cn(o.node,n))return;let i=Le("jsx-node",o);i&&(r=i,o.stop())},JSXFragment(o){if(Cr(o)!==t||!Cn(o.node,n))return;let i=Le("jsx-node",o);i&&(r=i,o.stop())}}),r}function Hy(e,t){let n=null;return en(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 Gy(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 Yy(e,t){let n=Au(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 Zy(e,t){let n=tx(e,t);if(!n.ok)return n;let r=nx(n.match.path,t.path??[]);return r.ok?t.expectedRange&&!Xt(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 Qy(e,t){let n=null;return en(e,{Identifier(r){if(!cx(r))return;let o=wu(r);if(!o||!Pu(o,t))return;let i=Le("expression",r);i&&(t.expectedRange&&!Xt(r.node.loc,t.expectedRange)||(n=i,r.stop()))},MemberExpression(r){let o=wu(r);if(!o||!Pu(o,t))return;let i=Le("expression",r);i&&(t.expectedRange&&!Xt(r.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:Be("expression","locator-miss","Expression not found")}function qy(e,t){let n=null;return en(e,{Program(r){let i=r.get("directives").find(a=>a.node.value.value===t.value);if(!i||t.expectedRange&&!Xt(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 ex(e,t){let n=null;return en(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&&!Xt(c.node.loc,t.expectedRange))return;n=m,r.stop();return}if(!c.isVariableDeclaration())return;let l=zs(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&&!Xt(d.node.loc,t.expectedRange))return;n=f,r.stop();return}let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=zs(o,t.exportKind==="named"?t.name:"metadata");if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node||t.expectedRange&&!Xt(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&&!Xt(o.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:Be("export","export-not-found",`Export '${dx(t)}' not found`)}function tx(e,t){let n=null;return en(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=zs(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 nx(e,t){let n=Js(e);for(let o of t){if(n=Js(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=>mx(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=Js(n);let r=Le("value",n);return r?{ok:!0,match:r}:Be("value","locator-miss","Resolved value has no source range")}function Js(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 Xt(e.loc,t)}function Xt(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 Xs(e){let t=[],n=e,r=e.node;for(;n;){if(n.isJSXElement()){if(!Fe(n)){let o=Fu(n.node.openingElement);o&&(/^[A-Z]/.test(o)?t.unshift(`component:${o}#${Nu(n,o)}`):t.unshift(`${o}#${Nu(n,o)}`))}}else n.isJSXFragment()&&n.node===r&&t.unshift("fragment");if(!n.parentPath||sx(n.parentPath)&&!ax(n.parentPath))break;n=n.parentPath}return t.join("/")}function Nu(e,t){let n=Tu(e)??e.getFunctionParent();if(!n)return 0;let r=Xo.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=0,i=Xo.get(n.node)?.get(t);if(!i){let a=Xo.get(n.node);a||(a=new Map,Xo.set(n.node,a)),i=new WeakMap,a.set(t,i)}let s=n.isJSXElement()||n.isJSXFragment()?Ir(n):rx(n);for(let a of s)if(Fu(a.node.openingElement)===t){if(i.set(a.node,o),a.node===e.node)return o;o++}return i.get(e.node)??0}function rx(e){let t=zo.get(e.node);if(t)return t;let n=[];return e.traverse({JSXElement(r){r.getFunctionParent()?.node===e.node&&!Tu(r)&&n.push(r)}}),zo.set(e.node,n),n}function Tu(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 Ir(e){let t=zo.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(...Ir(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...Ir(o));continue}o.isJSXExpressionContainer()&&n.push(...Jt(o.get("expression")))}return zo.set(e.node,n),n}function Jt(e){if(e.isJSXElement())return Fe(e)?Ir(e):[e];if(e.isJSXFragment())return Ir(e);if(e.isParenthesizedExpression())return Jt(e.get("expression"));if(e.isLogicalExpression()&&ox(e.node.operator))return Jt(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(...Jt(c))}if(s.isReturnStatement()){let a=s.get("argument");a.isExpression()&&i.push(...Jt(a));break}}return i}else if(o.node&&o.isExpression())return Jt(o)}}}}return e.isConditionalExpression()?[...Jt(e.get("consequent")),...Jt(e.get("alternate"))]:e.isArrayExpression()?e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:Jt(t)):[]}function ox(e){return e==="&&"||e==="||"||e==="??"}function Fu(e){return e.name.type==="JSXIdentifier"?e.name.name:e.name.type==="JSXMemberExpression"?ix(e.name):null}function ix(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 sx(e){return!!(e.isFunctionDeclaration()||e.isFunctionExpression()||e.isArrowFunctionExpression())}function ax(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 wu(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 Pu(e,t){return e.base===t.base&&lx(e.path,t.path??[])}function lx(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 ux(e){return e.key.type==="Identifier"?e.key.name:e.key.type==="StringLiteral"?e.key.value:null}function dx(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 fx(e,t){return Cr(e)!==t.component?!1:Xs(e)===t.structuralPath}function px(e,t){return!e.isJSXAttribute()||e.node.name.type!=="JSXIdentifier"?!1:e.node.name.name===t}function zs(e,t){return e.get("declarations").find(n=>!n.isVariableDeclarator()||n.node.id.type!=="Identifier"?!1:n.node.id.name===t)}function mx(e,t){return e.isObjectProperty()?ux(e.node)===t:!1}import*as Ou from"@babel/parser";import{arrayExpression as bx,booleanLiteral as Sx,identifier as Ex,jsxAttribute as vx,jsxExpressionContainer as kx,jsxIdentifier as Ix,nullLiteral as Cx,numericLiteral as Rx,objectExpression as Nx,objectProperty as wx,stringLiteral as Hs}from"@babel/types";import Ws from"@babel/generator";var gx=typeof Ws=="function"?Ws:Ws.default;function hx(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 Wo(e){let{ast:t,source:n}=e;try{let r=hx(n),i=gx(t,{comments:!0,jsescOption:{minimal:!0,quotes:"single"}},n).code;return r!=="2"&&(i=xx(i,r)),{ok:!0,source:i}}catch(r){return K(n,"printer-failed",`AST print failed: ${r instanceof Error?r.message:String(r)}`)}}function _u(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:_u(e),afterSourceHash:_u(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 Ce(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 Ho(e,t){return Wo({ast:e,source:t})}function Px(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=Px(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 tn(e){return typeof e=="string"?Hs(e):typeof e=="number"?Rx(e):typeof e=="boolean"?Sx(e):e===null?Cx():Array.isArray(e)?bx(e.map(t=>tn(t))):Nx(Object.entries(e).map(([t,n])=>{let r=wx(Gs(t),tn(n));return t==="__proto__"&&(r.computed=!0),r}))}function Ax(e){return typeof e=="string"?Hs(e):kx(tn(e))}function Nr(e,t){return vx(Ix(e),Ax(t))}function Go(e,t){try{let r=Ou.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 Gs(e){return/^[$A-Z_][0-9A-Z_$]*$/i.test(e)?Ex(e):Hs(e)}function Yo(e){let{source:t,locator:n,segmentIndex:r,newText:o}=e,i=Ce(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=Tx(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=Fx(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 Tx(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=_x(r.get("expression"));o.length>0&&t.push(...o)}}return t}function Fx(e,t){let n=e.match(/^\s*/)?.[0]??"",r=e.match(/\s*$/)?.[0]??"";return`${n}${t.trim()}${r}`}function _x(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 Ys}from"@babel/types";function Gn(e){let{source:t,locator:n}=e,r=Ce(t,"jsx-node");if(!r.ok)return r.result;let o=ae(r.ast,n);return o.ok?(Ox(o.match.path),me(r.ast,t,{kind:"remove-node",target:"jsx-node",inverse:"insert-child"})):{ok:!1,source:t,diagnostic:o.diagnostic}}function Ox(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(Ys());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(Ys());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(Ys());return}e.remove()}import{cloneNode as Mx}from"@babel/types";function Zo(e){let t=Ce(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=Go(e.source,e.node.jsx);return r.ok?(n.match.path.replaceWith(Mx(r.node,!0)),me(t.ast,e.source,{kind:"replace-node",target:"jsx-node",inverse:"replace-node"})):r.result}import{cloneNode as zx}from"@babel/types";import Zs from"@babel/traverse";import*as q from"@babel/types";function wr(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 Dx=typeof Zs=="function"?Zs:Zs.default;function gt(e,t,n,r){if(!e.ok)return e;let o=mt(n,t);if(!o)return e;let i=Lx(t,o,r);return i?{...e,selectionRef:i}:e}function Lx(e,t,n){let r=Bx(e,t);if(!r)return;let o=n.sourceLocator?Mu(n.sourceLocator):void 0,i=n.targetParentLocator?Mu(n.targetParentLocator):void 0,s=n.file??i?.file??o?.file,a=n.component??$x(r)??i?.component??o?.component;if(!(!s||!a))return{key:wr(s,a,Vx(r))}}function Mu(e){return e.strategy==="structural-path"?{file:e.file,component:e.component,structuralPath:e.structuralPath}:e.expectedIdentity}function Bx(e,t){let n=Vu(e,t);return!n||n.node.type!=="JSXElement"?null:n}function Vu(e,t){let n=null;return Dx(e,{JSXElement(r){r.node===t&&(n=r,r.stop())},JSXFragment(r){r.node===t&&(n=r,r.stop())}}),n}function mt(e,t){if(!e)return null;if(q.isJSXElement(e))return Xx(t,e)?Du(e.children,t):e;if(q.isJSXFragment(e))return Du(e.children,t);if(q.isJSXExpressionContainer(e)||q.isParenthesizedExpression(e)||q.isTSAsExpression(e)||q.isTSSatisfiesExpression(e)||q.isTSTypeAssertion(e)||q.isTSNonNullExpression(e))return mt(e.expression,t);if(q.isLogicalExpression(e))return mt(e.right,t);if(q.isConditionalExpression(e))return mt(e.consequent,t)??mt(e.alternate,t);if(q.isCallExpression(e)||q.isOptionalCallExpression(e))return Ku(e)?jx(e.arguments[0],t):null;if(q.isArrayExpression(e))for(let n of e.elements){if(!n)continue;let r=mt(n,t);if(r)return r}return null}function Du(e,t){for(let n of e){let r=mt(n,t);if(r)return r}return null}function jx(e,t){return!e||!q.isArrowFunctionExpression(e)&&!q.isFunctionExpression(e)?null:q.isBlockStatement(e.body)?Pr(e.body.body,t):mt(e.body,t)}function Pr(e,t){for(let n of e){if(q.isReturnStatement(n)){let r=mt(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=Lu(n.consequent,t);if(r)return r;let o=n.alternate?Lu(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 Lu(e,t){return q.isBlockStatement(e)?Pr(e.body,t):Pr([e],t)}function $x(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 Bu=new WeakMap,ju=new WeakMap,Qs=new WeakMap;function Vx(e){let t=Bu.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=Kx(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return Bu.set(e.node,o),o}function Kx(e){let t=Uu(e.node.openingElement.name);return!t||Fe(e)?null:/^[A-Z]/.test(t)?`component:${t}#${$u(e,t)}`:`${t}#${$u(e,t)}`}function $u(e,t){let n=Ux(e);if(!n)return 0;let r=Qs.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=Qs.get(n.node);o||(o=new Map,Qs.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(Uu(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 Ux(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=ju.get(e.node);if(t)return t;let n=[],r=e.get("children");for(let o of r)if(!Array.isArray(o)){if(o.isJSXElement()){if(Fe(o)){n.push(...Rn(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...Rn(o));continue}o.isJSXExpressionContainer()&&n.push(..._t(o.get("expression")))}return ju.set(e.node,n),n}function _t(e){if(e.isJSXElement())return Fe(e)?Rn(e):[e];if(e.isJSXFragment())return Rn(e);if(e.isParenthesizedExpression())return _t(e.get("expression"));if(e.isLogicalExpression())return _t(e.get("right"));if(e.isConditionalExpression())return[..._t(e.get("consequent")),..._t(e.get("alternate"))];if(e.isArrayExpression())return e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:_t(t));if((e.isCallExpression()||e.isOptionalCallExpression())&&Ku(e.node)){let t=e.get("arguments"),n=Array.isArray(t)?t[0]:void 0;return n?Jx(n):[]}return[]}function Jx(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 _t(t.get("expression"));if(t.isLogicalExpression()||t.isConditionalExpression())return _t(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(..._t(s))}if(!r.isReturnStatement())continue;let o=r.get("argument");return o.node&&n.push(..._t(o)),n}return n}function Ku(e){let t=e.callee;return(q.isMemberExpression(t)||q.isOptionalMemberExpression(t))&&q.isIdentifier(t.property)&&t.property.name==="map"&&!t.computed}function Xx(e,t){let n=Vu(e,t);return n?Fe(n):!1}function Uu(e){return q.isJSXIdentifier(e)?e.name:q.isJSXMemberExpression(e)?Ju(e):q.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function Ju(e){return`${q.isJSXIdentifier(e.object)?e.object.name:Ju(e.object)}.${e.property.name}`}function nn(e,t){if(t.parentPath===e&&t.listKey==="children"&&qs(e))return e;if(!t.parentPath||t.listKey!=="children")return null;let n=t.parentPath;if(!qs(n))return null;let r=n;for(;r&&r!==e;){if(!qs(r)||!Fe(r)||r.listKey!=="children")return null;r=r.parentPath}return r===e?n:null}function qs(e){return e.isJSXElement()||e.isJSXFragment()}function Yn(e){let{source:t,locator:n,node:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=Ce(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 I=c.match.path.node;if(!I.closingElement||I.openingElement.selfClosing)return K(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let d=Go(t,r.jsx);if(!d.ok)return d.result;let f=zx(d.node,!0),m=l.node.children,u={...s,targetParentLocator:n},g=I=>s?gt(I,a.ast,f,u):I;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 b=nn(c.match.path,h.match.path);if(!b)return K(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");l=b;let E=l.node.children,v=E.findIndex(I=>I===h.match.path.node);return v===-1?K(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(E.splice(o==="before"?v:v+1,0,f),g(me(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"})))}import*as Xu from"@babel/parser";import{cloneNode as Wx}from"@babel/types";function Qo(e){let{source:t,locator:n,expression:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=Ce(t,"jsx-node");if(!a.ok)return a.result;let c=Hx(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 v=nn(l.match.path,E.match.path);if(!v)return K(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");d=v,f=E.match.path.node}else if(o==="before"||o==="after")return K(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let m=Wx(c.node,!0),u=d.node.children,g={...s,targetParentLocator:n},h=E=>s?gt(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 b=u.findIndex(E=>E===f);return b===-1?K(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(u.splice(o==="before"?b:b+1,0,m),h(me(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"})))}function Hx(e,t){try{let r=Xu.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 Gx,nullLiteral as ea}from"@babel/types";import*as rn from"@babel/types";import*as zu from"@babel/types";function Ar(e,t){let n=e.parentPath;if(!n?.isConditionalExpression()||e.key!=="consequent"||!zu.isNullLiteral(n.node.alternate))return e;let r=n.parentPath;return!r?.isJSXExpressionContainer()||r.parentPath?.node!==t.node||r.listKey!=="children"?e:r}function Zn(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=Ce(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 I=l.match.path.node;if(!I.closingElement||I.openingElement.selfClosing)return K(t,"self-closing-element","Cannot move child into self-closing element","jsx-node")}let f=null;if(i){let I=ae(a.ast,i);if(!I.ok)return{ok:!1,source:t,diagnostic:I.diagnostic};let R=I.match.path.isJSXElement()?Ar(I.match.path,l.match.path):I.match.path,A=nn(l.match.path,R);if(!A)return K(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");d=A,f=R}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=Gx(u.node,!0);if(!rn.isJSXElement(g)&&!rn.isJSXExpressionContainer(g)&&!rn.isJSXFragment(g)&&!rn.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");Yx(u);let b=d.node.children,E={...s,sourceLocator:n,targetParentLocator:r};if(o==="append")return b.push(g),gt(Ho(a.ast,t),a.ast,g,E);if(o==="prepend")return b.unshift(g),gt(Ho(a.ast,t),a.ast,g,E);let v=m-(h!==-1&&h<m?1:0);return b.splice(o==="before"?v:v+1,0,g),gt(Ho(a.ast,t),a.ast,g,E)}function Yx(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(ea());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(ea());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(ea());return}e.remove()}import*as Wu from"@babel/parser";import{cloneNode as Zx,nullLiteral as ta}from"@babel/types";function qo(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,repeatExpression:s,selectionContext:a}=e,c=Ce(t,"jsx-node");if(!c.ok)return c.result;let l=Qx(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 I=f.match.path.node;if(!I.closingElement||I.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 I=ae(c.ast,i);if(!I.ok)return{ok:!1,source:t,diagnostic:I.diagnostic};let R=nn(f.match.path,I.match.path);if(!R)return K(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");m=R,u=I.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=Zx(l.node,!0);qx(d.match.path);let b={...a,sourceLocator:n,targetParentLocator:r},E=g.children;if(o==="append")return E.push(h),gt(me(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,h,b);if(o==="prepend")return E.unshift(h),gt(me(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,h,b);let v=E.findIndex(I=>I===u);return v===-1?K(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(E.splice(o==="before"?v:v+1,0,h),gt(me(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,h,b))}function Qx(e,t){try{let r=Wu.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 qx(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(ta());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(ta());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(ta());return}e.remove()}import{SiteEditSetPropsParamsSchema as eb,classifySiteEditPropertyName as tb}from"@vcp-dev/contracts";import*as Qn from"@babel/types";function ei(e){let t=eb.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=Ce(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=tb(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(Qn.isJSXAttribute),s=new Map;for(let a of i){let c=nb(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 nb(e){return Qn.isJSXIdentifier(e.name)?e.name.name:Qn.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:null}import{SiteEditOperationParamsSchema as rb}from"@vcp-dev/contracts";import*as z from"@babel/types";var Hu=["prefetch","replace","scroll","locale","onNavigate"],ob=/^on(?:Click|DoubleClick|AuxClick|MouseDown|MouseUp|PointerDown|PointerUp|TouchStart|TouchEnd|KeyDown|KeyUp|ContextMenu)(?:Capture)?$/;function ib(e){let t=e;for(;t;){if(t.isJSXElement()&&t.node.openingElement.attributes.some(n=>z.isJSXAttribute(n)&&z.isJSXIdentifier(n.name)&&ob.test(n.name.name)))return!0;t=t.parentPath}return!1}function ti(e){let t=Ce(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=rb.safeParse({kind:"set-link-target",scope:"selection",link:e.link,changes:e.changes});if(!r.success||r.data.kind!=="set-link-target")return zt(e.source,"Invalid typed link-target changes");let o=n.match.path,i=o.node,s=i.openingElement,a=fb(s.name);if(!a)return zt(e.source,"Unsupported JSX link tag");if(s.attributes.some(z.isJSXSpreadAttribute))return zt(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=ra(g);if(!h)return zt(e.source,"Unsupported JSX attribute name");let b=c.get(h)??[];b.push(g),c.set(h,b)}if([...c.values()].some(g=>g.length>1))return zt(e.source,"Duplicate JSX attributes cannot be transformed safely");let l=c.get("href")?.[0];if(l&&!db(l))return zt(e.source,"Dynamic link href cannot be transformed safely");let d=a==="a",f=d?null:cb(o,s.name);if(!d&&!f)return zt(e.source,"Only native anchors and imported next/link components are supported");if(e.link.kind==="none"&&ib(o))return zt(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=lb(t.ast,o);if(!g.ok)return zt(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")),ub(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"),Hu.forEach(g=>u.add(g))):(u.add("href"),e.link.kind==="native-link"&&Hu.forEach(g=>u.add(g))),s.attributes=s.attributes.filter(g=>{if(!z.isJSXAttribute(g))return!0;let h=ra(g);return!h||!u.has(h)}),e.link.kind!=="none"&&s.attributes.push(z.jsxAttribute(z.jsxIdentifier("href"),z.stringLiteral(e.link.href))),sb(s,e.changes),me(t.ast,e.source,{kind:"set-link-target",target:"jsx-node",inverse:"set-link-target"})}function sb(e,t){for(let n of t){let r=e.attributes.find(s=>z.isJSXAttribute(s)&&ra(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(na(n.value)),i=z.jsxAttribute(z.jsxIdentifier(n.name),o);r&&z.isJSXAttribute(r)?r.value=i.value:e.attributes.push(i)}}function na(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=>na(t))):typeof e=="object"?z.objectExpression(Object.entries(e).map(([t,n])=>z.objectProperty(z.isValidIdentifier(t)?z.identifier(t):z.stringLiteral(t),na(n)))):z.nullLiteral()}function ab(e){return z.isImportDefaultSpecifier(e)||z.isImportSpecifier(e)&&e.importKind!=="type"&&(z.isIdentifier(e.imported,{name:"default"})||z.isStringLiteral(e.imported,{value:"default"}))}function Gu(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||!Gu(n.path))return null;let r=n.path.parentPath;return!r?.isImportDeclaration()||r.node.source.value!=="next/link"?null:t.name}function lb(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(ab);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 ub(e,t,n){let r=n.scope.getProgramParent();r.crawl();let o=r.getBinding(t);if(!o||!Gu(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 db(e){return!e.value||z.isStringLiteral(e.value)}function fb(e){return z.isJSXIdentifier(e)?e.name:null}function ra(e){return z.isJSXIdentifier(e.name)?e.name.name:null}function zt(e,t){return K(e,"unsupported-syntax",t,"jsx-node")}import*as Ke from"@babel/types";import{classifySiteEditPropertyName as Yu}from"@vcp-dev/contracts";function ni(e){let t=Yu(e.name),n=Yu(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(!Zu(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=Ce(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)&&mb(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 Zu(t)?Ke.memberExpression(Ke.identifier(e),Ke.identifier(t)):Ke.memberExpression(Ke.identifier(e),Ke.stringLiteral(t),!0)}function Zu(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(e)}function mb(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 hb,identifier as Tr,importDeclaration as yb,importDefaultSpecifier as xb,importNamespaceSpecifier as bb,importSpecifier as Sb,isImportDefaultSpecifier as Qu,isImportNamespaceSpecifier as qu,isImportSpecifier as ed,stringLiteral as Eb}from"@babel/types";function qn(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(b=>!Ab(b));if(o!==-1){let b=r[o],E=b&&typeof b=="object"&&"kind"in b?b.kind:void 0;return K(t,"unsupported-syntax",`Unsupported import spec kind: ${String(E)}`)}let i=Nb(r);if(!i.ok)return K(t,"unsupported-syntax",i.message);let s=Ce(t);if(!s.ok)return s.result;let{ast:a}=s,c=a.program,l=c.body.filter(b=>b.type==="ImportDeclaration"&&b.source.value===n),d=new Set(l.flatMap(b=>b.specifiers.flatMap(E=>{let v=Tb(b,E);return v?[v]:[]}))),f=i.imports.filter(b=>!d.has(sd(b)));if(f.length===0)return Rr(t,t,{kind:"add-import",target:"import",inverse:"remove-import"});let m=wb(c.body),u=f.find(b=>m.has(oa(b)));if(u)return K(t,"unsupported-syntax",`Import local binding already exists: ${oa(u)}`);let g=Rb(f);if(g.reduce((b,E)=>b+E.length,0)!==f.length)return K(t,"unsupported-syntax","Unsupported import specifier grouping");for(let b of g){if(!od(nd(b)))return K(t,"unsupported-syntax","Unsupported import specifier combination");let E=l.find(v=>vb(v,b));if(E)kb(E,b);else{let v=yb(td(b),Eb(n));Pb(c.body,v),l.push(v)}}return me(a,t,{kind:"add-import",target:"import",inverse:"remove-import"})}function vb(e,t){return e.importKind==="type"?!1:od(Cb(Ib(e),nd(t)))}function kb(e,t){let n=!1,r=new Set(e.specifiers.map(o=>ia(o)));for(let o of td(t)){let i=ia(o);r.has(i)||(e.specifiers.push(o),r.add(i),n=!0)}return id(e.specifiers),{changed:n}}function td(e){let t=e.map(n=>{switch(n.kind){case"named":return Sb(n.local?Tr(n.local):Tr(n.imported),Tr(n.imported));case"default":return xb(Tr(n.local));case"namespace":return bb(Tr(n.local));default:return n}});return id(t),t}function nd(e){let t=rd();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 Ib(e){let t=rd();for(let n of e.specifiers)Qu(n)?t.defaultLocals.add(n.local.name):qu(n)?t.namespaceLocals.add(n.local.name):t.hasNamed=!0;return t}function rd(){return{defaultLocals:new Set,hasNamed:!1,namespaceLocals:new Set}}function Cb(e,t){return{defaultLocals:new Set([...e.defaultLocals,...t.defaultLocals]),hasNamed:e.hasNamed||t.hasNamed,namespaceLocals:new Set([...e.namespaceLocals,...t.namespaceLocals])}}function od(e){return e.defaultLocals.size>1||e.namespaceLocals.size>1?!1:!(e.hasNamed&&e.namespaceLocals.size>0)}function id(e){let t=[...e.filter(n=>Qu(n)),...e.filter(n=>qu(n)),...e.filter(n=>ed(n))];e.splice(0,e.length,...t)}function Rb(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 Nb(e){let t=new Map,n=new Map;for(let r of e){let o=sd(r);if(t.has(o))continue;let i=oa(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 wb(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(hb(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 Pb(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 Ab(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 sd(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 oa(e){return e.kind==="named"?e.local??e.imported:e.local}function Tb(e,t){return e.importKind==="type"||ed(t)&&t.importKind==="type"?null:ia(t)}function ia(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 er(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(d=>!_b(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=Ce(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=>Fb(d,f))),l.specifiers.length===0&&a.body.splice(c,1),me(s,t,{kind:"remove-import",target:"import",inverse:"add-import"}))}function Fb(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 _b(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=si(t,n);return o.ok?(o.path.replaceWith(tn(r)),me(o.ast,t,{kind:"update-value",target:"value",inverse:"restore-value"})):o.result}function ri(e){let{source:t,locator:n,index:r,value:o}=e,i=si(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,tn(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 oi(e){let{source:t,locator:n,index:r}=e,o=si(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 ii(e){let{source:t,locator:n,fromIndex:r,toIndex:o}=e,i=si(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 si(e,t){let n=Ce(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 ai(e){let t=Ce(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)&&Ob(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)):tn(e.value.value),s=o[0];if(s)s.value=i,s.shorthand=!1;else{let a=Xe.objectProperty(Gs(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 Ob(e){return Xe.isIdentifier(e)?e.name:Xe.isStringLiteral(e)?e.value:Xe.isNumericLiteral(e)?String(e.value):null}import{isSiteEditRuntimeContainerTag as Mb,isSiteEditRuntimeVoidElementTag as Db}from"@vcp-dev/contracts/site-edit-runtime-capability";function tr(e){if(!e.composition)throw new Error("Composition unavailable for render source graph.");return e.composition}function Lb(e,t,n){let r=tr(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(R=>({kind:R.kind,message:R.reason})),a=i.isOpaque,l=o.parentKey===null&&i.componentName==="Page",d=i.tag.toLowerCase(),f=i.tag!==d,m=!f&&Db(d),u=f||Mb(d),g=f&&i.childKeys.length>0&&!i.isPublicUiComponent,h=i.textSegments.length>0&&i.textSegments.some(R=>R.editable);m&&!s.some(R=>R.kind==="void-element")&&s.push({kind:"void-element",message:`Element '${i.tag}' is void: children cannot be inserted`}),!m&&!u&&!s.some(R=>R.kind==="void-element")&&s.push({kind:"void-element",message:`Element '${i.tag}' cannot contain structured children`});let b=h&&(!a||i.importedFrom==="next/link"),E=!i.isPublicUiComponent&&!m&&u&&(!a||g);return{composition:r,key:e,canUpdateText:b,canInsertChild:E,canMove:!l,canRemove:!l,constraints:s}}function ad(e,t){let n=new Map;for(let r of e.nodes.keys())n.set(r,Lb(r,e,t));return n}function sa(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=Bb(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:ld(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:cd(e.route.source,o),valueRaw:s?cd(e.route.source,s):null,attrRange:ld(o),diagnostics:[]}}function ud(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 Bb(e,t){let n=At({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:jb(t.sourceRange)});return!r.ok||r.match.node.type!=="JSXElement"?null:r.match.node}function dd(e){let t=At({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 cd(e,t){return t.start==null||t.end==null?"":e.slice(t.start,t.end)}function ld(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 jb(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function fd(){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 $b}from"node:crypto";import ci from"node:fs/promises";import aa from"node:path";import{setTimeout as Vb}from"node:timers/promises";var Kb={async mkdir(e,t){await ci.mkdir(e,t)},async writeFile(e,t,n){await ci.writeFile(e,t,n)},async rename(e,t){await ci.rename(e,t)},async rm(e,t){await ci.rm(e,t)}},Ub=new Set(["EACCES","EBUSY","EPERM"]),Jb=[10,20,40,80,160];async function Xb(e,t,n){for(let r of Jb)try{await e.rename(t,n);return}catch(o){if(!zb(o))throw o;await Vb(r)}await e.rename(t,n)}function zb(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&Ub.has(e.code)}async function li(e,t,n=Kb){let r=aa.dirname(e),o=aa.basename(e),i=aa.join(r,`.${o}.${process.pid}.${$b()}.tmp`),s=!1;try{await n.mkdir(r,{recursive:!0}),await n.writeFile(i,t,"utf8"),await Xb(n,i,e),s=!0}finally{if(!s)try{await n.rm(i,{force:!0})}catch{}}}import ca from"@babel/traverse";import*as S from"@babel/types";import*as ue from"@babel/types";function Ot(e,t={}){if(ue.isTSAsExpression(e)||ue.isTSSatisfiesExpression(e)||ue.isTSNonNullExpression(e)||ue.isTypeCastExpression(e)||ue.isParenthesizedExpression(e))return Ot(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=Ot(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=Wb(r.key);if(o===null)return{status:"unresolved"};let i=Ot(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 Wb(e){return ue.isIdentifier(e)?e.name:ue.isStringLiteral(e)?e.value:ue.isNumericLiteral(e)?String(e.value):null}var Hb=typeof ca=="function"?ca:ca.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 Gb(e){return/^[A-Z]/.test(e)}function pa(e){let t=e.openingElement;return S.isJSXIdentifier(t.name)?t.name.name==="Fragment":S.isJSXMemberExpression(t.name)?t.name.property.name==="Fragment":!1}function rr(e){return S.isJSXFragment(e)}function md(e){return S.isJSXIdentifier(e.name)?e.name.name:S.isJSXMemberExpression(e.name)?gd(e.name):S.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:"unknown"}function gd(e){return S.isJSXIdentifier(e.object)?`${e.object.name}.${e.property.name}`:S.isJSXMemberExpression(e.object)?`${gd(e.object)}.${e.property.name}`:e.property.name}function Yb(e){return e.split(".")[0]??e}function Zb(e){let t=e;for(;t;){let n=t.node;if(S.isFunctionDeclaration(n)&&n.id||S.isVariableDeclarator(n)&&S.isIdentifier(n.id))return n.id.name;if(S.isExportDefaultDeclaration(n)){let r=n.declaration;if(S.isFunctionDeclaration(r)&&r.id)return r.id.name;if(S.isFunctionDeclaration(r)&&!r.id)return"default"}t=t.parentPath}return null}function Qb(){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 qb(e){let t=new Map;for(let n of e.program.body){if(!S.isImportDeclaration(n))continue;let r=n.source.value;for(let o of n.specifiers)if(S.isImportDefaultSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"default"});else if(S.isImportNamespaceSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"*"});else if(S.isImportSpecifier(o)){let i=S.isIdentifier(o.imported)?o.imported.name:o.imported.value;t.set(o.local.name,{specifier:r,exportName:i})}}return t}function Wt(e,t=[]){if(S.isIdentifier(e))return t.push(e.name),t;if(S.isObjectPattern(e)){for(let n of e.properties)S.isObjectProperty(n)?Wt(n.value,t):S.isRestElement(n)&&Wt(n.argument,t);return t}if(S.isArrayPattern(e)){for(let n of e.elements)n&&(S.isRestElement(n)?Wt(n.argument,t):Wt(n,t));return t}return S.isAssignmentPattern(e)?(Wt(e.left,t),t):(S.isRestElement(e)&&Wt(e.argument,t),t)}function vt(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 eS(e,t,n){e.set(t,{resolved:!0,value:n})}function ma(e,t){e.set(t,{resolved:!1})}function hd(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(S.isTSAsExpression(e)||S.isTSSatisfiesExpression(e)||S.isTSNonNullExpression(e)||S.isTypeCastExpression(e)||S.isParenthesizedExpression(e))return $e(e.expression,t,n);if(S.isLogicalExpression(e))return ui([$e(e.left,t,n),$e(e.right,t,n)]);if(S.isBinaryExpression(e))return ui([S.isExpression(e.left)?$e(e.left,t,n):null,S.isExpression(e.right)?$e(e.right,t,n):null]);if(S.isConditionalExpression(e))return ui([$e(e.consequent,t,n),$e(e.alternate,t,n)]);if(S.isTemplateLiteral(e))return ui(e.expressions.filter(S.isExpression).map(i=>$e(i,t,n)));if(S.isIdentifier(e))return{kind:"identifier",expression:e.name,base:e.name,path:[]};if(!S.isMemberExpression(e)&&!S.isOptionalMemberExpression(e))return null;let r=[],o=e;for(;S.isMemberExpression(o)||S.isOptionalMemberExpression(o);){if(o.computed)if(S.isNumericLiteral(o.property))r.unshift({kind:"index",index:o.property.value});else if(S.isStringLiteral(o.property))r.unshift({kind:"property",name:o.property.value});else if(n&&S.isExpression(o.property)){let i=on(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(!S.isIdentifier(o.property))return null;r.unshift({kind:"property",name:o.property.name})}o=o.object}return S.isIdentifier(o)?{kind:r.some(i=>i.kind==="index")?"index-expression":"member-expression",expression:vt(e,t),base:o.name,path:r}:null}function ui(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 on(e,t){if(S.isStringLiteral(e)||S.isNumericLiteral(e)||S.isBooleanLiteral(e))return e.value;if(S.isNullLiteral(e))return null;if(S.isTemplateLiteral(e))return e.expressions.length===0&&e.quasis.length===1?e.quasis[0].value.cooked??e.quasis[0].value.raw:void 0;if(S.isIdentifier(e)){let n=_r(e.name,t.valueScopes);return n.kind==="resolved"?n.value:void 0}if(S.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||S.isSpreadElement(r))return;let o=on(r,t);if(o===void 0)return;n.push(o)}return n}if(S.isObjectExpression(e)){let n={};for(let r of e.properties){if(!S.isObjectProperty(r)||r.computed||!S.isExpression(r.value))return;let o=null;if(S.isIdentifier(r.key)?o=r.key.name:S.isStringLiteral(r.key)&&(o=r.key.value),!o)return;let i;if(r.shorthand){if(!S.isIdentifier(r.value))return;let s=_r(r.value.name,t.valueScopes);if(s.kind!=="resolved")return;i=s.value}else i=on(r.value,t);if(i===void 0)return;n[o]=i}return n}if(S.isMemberExpression(e)){let n=$e(e,"",t);if(!n)return;let r=_r(n.base,t.valueScopes);if(r.kind!=="resolved")return;let o=hd(r.value,n.path);return o.kind==="resolved"?o.value:void 0}if(S.isCallExpression(e))return xd(e,t)??void 0}function yd(e,t,n){let r=$e(e,n,t);if(!r)return S.isMemberExpression(e)||S.isBinaryExpression(e)||S.isLogicalExpression(e)||S.isConditionalExpression(e)||S.isCallExpression(e)?{value:vt(e,n),source:null}:null;let o=_r(r.base,t.valueScopes),i=r.kind==="identifier"?o:o.kind==="resolved"?hd(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 la(e,t,n,r,o,i){return{file:e,componentName:t,elements:n,regions:r,ordinalTracker:Qb(),parentStack:[],valueScopes:i,importMap:o}}function da(e,t,n){for(let r of e)for(let o of r.declarations){for(let s of Wt(o.id))ma(n,s);if(!S.isIdentifier(o.id)||!o.init||!S.isExpression(o.init))continue;let i=on(o.init,t);i!==void 0&&eS(n,o.id.name,i)}}function tS(e){let t=[];for(let n of e){if(S.isVariableDeclaration(n)){t.push(n);continue}S.isExportNamedDeclaration(n)&&n.declaration&&S.isVariableDeclaration(n.declaration)&&t.push(n.declaration)}return t}function nS(e,t,n){let r=[],o=0;for(let i of e)if(S.isJSXText(i)){let s=i.value.trim();s&&r.push({index:o++,value:s,sourceRange:Ge(i),editable:!0,source:null})}else if(S.isJSXExpressionContainer(i)&&S.isStringLiteral(i.expression))r.push({index:o++,value:i.expression.value,sourceRange:Ge(i),editable:!0,source:null});else if(S.isJSXExpressionContainer(i)&&S.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:vt(s,n),sourceRange:Ge(i),editable:!0,source:$e(s,n,t)})}else if(S.isJSXExpressionContainer(i)&&S.isExpression(i.expression)){let s=yd(i.expression,t,n);s&&r.push({index:o++,value:s.value,sourceRange:Ge(i),editable:!0,source:s.source})}return r}function rS(e,t,n){let r=[];for(let[o,i]of e.attributes.entries()){if(!S.isJSXAttribute(i))continue;let s=iS(i.name);if(!s)continue;let a=vt(i,n);if(S.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(S.isJSXExpressionContainer(i.value)&&S.isExpression(i.value.expression)){let c=on(i.value.expression,t);if(s==="className"){let u=typeof c=="string"?c:c===void 0?xd(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=yd(i.value.expression,t,n);if(c!==void 0){r.push({name:s,value:fS(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=sS(i.value.expression,t),f=$e(i.value.expression,n,t),m=l?.value??vt(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 oS(e,t,n){return e.attributes.flatMap((r,o)=>!S.isJSXSpreadAttribute(r)||!S.isExpression(r.argument)?[]:[{raw:vt(r.argument,n),sourceRange:Ge(r),order:o,source:$e(r.argument,n,t)}])}function iS(e){return S.isJSXIdentifier(e)?e.name:S.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function sS(e,t){return Ot(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=on(n,t);return r===void 0?{status:"unresolved"}:{status:"resolved",value:r}}})}function xd(e,t){let n=nr(e,t);return n&&n.map(o=>o.trim()).filter(Boolean).join(" ")||null}function nr(e,t){if(S.isStringLiteral(e))return[e.value];if(S.isTemplateLiteral(e))return e.expressions.length>0?null:[e.quasis.map(n=>n.value.cooked??"").join("")];if(S.isNullLiteral(e))return[];if(S.isBooleanLiteral(e))return e.value?null:[];if(S.isIdentifier(e)||S.isMemberExpression(e)){if(S.isIdentifier(e)&&e.name==="undefined")return[];let n=on(e,t);return typeof n=="string"?[n]:null}if(S.isConditionalExpression(e)){let n=nr(e.consequent,t),r=nr(e.alternate,t);return!n||!r?null:[...n,...r]}if(S.isLogicalExpression(e)){if(e.operator!=="&&")return null;let n=on(e.left,t);return n===!1||n===null?[]:nr(e.right,t)}if(S.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||S.isSpreadElement(r))return null;let o=nr(r,t);if(!o)return null;n.push(...o)}return n}if(S.isObjectExpression(e)){let n=[];for(let r of e.properties){if(!S.isObjectProperty(r))return null;let o=cS(r.key);if(!o)return null;n.push(o)}return n}if(S.isCallExpression(e)){let n=aS(e.callee);if(!n||!["cn","clsx","twMerge"].includes(n))return null;let r=[];for(let o of e.arguments){if(!S.isExpression(o))return null;let i=nr(o,t);if(!i)return null;r.push(...i)}return r}return null}function aS(e){return S.isIdentifier(e)?e.name:S.isMemberExpression(e)&&S.isIdentifier(e.property)?e.property.name:null}function cS(e){return S.isIdentifier(e)?e.name:S.isStringLiteral(e)?e.value:null}function lS(e,t){let n=e.attributes.find(r=>S.isJSXAttribute(r)&&S.isJSXIdentifier(r.name)&&r.name.name===t);return!n||!S.isJSXAttribute(n)||!S.isJSXExpressionContainer(n.value)?null:n.value.expression}function uS(e,t){for(let n of t){let r=lS(e,n);if(r)return r}return null}function dS(e){return S.isJSXIdentifier(e.name)?e.name.name:null}function fS(e){return e===null?"null":typeof e=="boolean"?e?"true":"false":JSON.stringify(e)}function pS(e){if(!S.isCallExpression(e)&&!S.isOptionalCallExpression(e))return null;let t=e.callee;return!S.isMemberExpression(t)&&!S.isOptionalMemberExpression(t)||!S.isIdentifier(t.property)||t.property.name!=="map"||t.computed||!S.isExpression(t.object)?null:{call:e,collection:t.object,callback:e.arguments[0]}}function ua(e){return S.isArrowFunctionExpression(e)||S.isFunctionExpression(e)}function mS(e){return e==="render"||e==="itemRender"||e==="rowRender"||e==="children"}function gS(e){return e==="empty"||e==="emptyRender"||e==="loading"||e==="loadingRender"||e==="error"||e==="errorRender"||e==="fallback"||e==="headerRender"||e==="footerRender"}function pd(e,t,n,r){if(!e||!S.isExpression(e))return null;let o={kind:"repeat-template",collectionExpression:vt(e,n),collectionSource:$e(e,n,r)};if(t){let i=t.params[0],s=t.params[1];S.isIdentifier(i)&&(o.itemParamName=i.name),S.isIdentifier(s)&&(o.indexParamName=s.name)}return o}function Ht(e,t,n){if(!e)return[];if(S.isJSXElement(e)){if(pa(e))return gi(e.children,t,n);let r=pi(e,t,n);return r?[r]:[]}return rr(e)?mi(e,t,n):S.isParenthesizedExpression(e)?Ht(e.expression,t,n):S.isExpression(e)?hi(e,t,n):[]}function di(e,t,n){let r=new Map;for(let o of e.params)for(let i of Wt(o))ma(r,i);t.valueScopes.push(r);try{if(!S.isBlockStatement(e.body))return Ht(e.body,t,n);let o=new Map;t.valueScopes.push(o);try{return bd(e.body.body,t,n)}finally{t.valueScopes.pop()}}finally{t.valueScopes.pop()}}function bd(e,t,n){let r=[];for(let o of e){if(S.isVariableDeclaration(o)){let i=t.valueScopes[t.valueScopes.length-1];if(i){da([o],t,i);for(let s of o.declarations)S.isIdentifier(s.id)&&(S.isJSXElement(s.init)||S.isJSXFragment(s.init))&&r.push(...Ht(s.init,t,n))}continue}r.push(...fa(o,t,n))}return r}function fa(e,t,n){if(S.isReturnStatement(e))return e.argument?Ht(e.argument,t,n):[];if(S.isBlockStatement(e))return Nn(e.body,t,n);if(S.isIfStatement(e)){let r=S.isBlockStatement(e.consequent)?Nn(e.consequent.body,t,n):fa(e.consequent,t,n),o=e.alternate?S.isBlockStatement(e.alternate)?Nn(e.alternate.body,t,n):fa(e.alternate,t,n):[];return[...r,...o]}if(S.isSwitchStatement(e))return Nn(e.cases.flatMap(r=>r.consequent),t,n);if(S.isTryStatement(e)){let r=Nn(e.block.body,t,n);return e.handler&&r.push(...Nn(e.handler.body.body,t,n)),e.finalizer&&r.push(...Nn(e.finalizer.body,t,n)),r}return[]}function Nn(e,t,n){let r=new Map;t.valueScopes.push(r);try{return bd(e,t,n)}finally{t.valueScopes.pop()}}function fi(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 hS(e,t,n,r){let o=uS(e.openingElement,["items","dataSource","data"]),i={key:t,tag:md(e.openingElement)};n.parentStack.push(i);try{for(let s of e.openingElement.attributes){if(!S.isJSXAttribute(s))continue;let a=dS(s);if(!a||!S.isJSXExpressionContainer(s.value))continue;let c=s.value.expression;if(!S.isJSXEmptyExpression(c)){if(mS(a)&&ua(c)){let l=di(c,n,r),d=pd(o,c,r,n);fi(n,"repeat-region",t,s,l,d?[d]:void 0);continue}if(gS(a)){let l=ua(c)?di(c,n,r):Ht(c,n,r);fi(n,"conditional-region",t,s,l)}}}if(o)for(let s of e.children){if(!S.isJSXExpressionContainer(s)||!ua(s.expression))continue;let a=di(s.expression,n,r),c=pd(o,s.expression,r,n);fi(n,"repeat-region",t,s,a,c?[c]:void 0)}}finally{n.parentStack.pop()}}function pi(e,t,n){let r=md(e.openingElement);if(r==="Fragment"||pa(e))return gi(e.children,t,n),null;let o=t.parentStack[t.parentStack.length-1]??null,i=o?.key??null,s=Gb(r),a;if(s){let R=t.ordinalTracker.getOrdinal(i,r);a=`component:${r}#${R}`}else{let R=t.ordinalTracker.getOrdinal(i,r);a=`${r}#${R}`}let c=o?t.elements.get(o.key)?.identity.structuralPath:void 0,l=c?`${c}/${a}`:a,d=wr(t.file,t.componentName,l),f={file:t.file,component:t.componentName,structuralPath:l,key:d},m=s?"component-boundary":null,u=nS(e.children,t,n),g=rS(e.openingElement,t,n),h=oS(e.openingElement,t,n),b,E,v=!1;if(s){let R=t.importMap.get(r)??t.importMap.get(Yb(r));R&&(b=R.specifier,E=R.exportName,v=vn(R.specifier,t.file))}let I={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,...v?{isPublicUiComponent:!0}:{},importedFrom:b,exportName:E};return t.elements.set(d,I),i&&t.elements.has(i)&&t.elements.get(i).childKeys.push(d),hS(e,d,t,n),(!s||e.children.length>0)&&(t.parentStack.push({key:d,tag:r}),yS(e.children,t,n),t.parentStack.pop()),d}function mi(e,t,n){return gi(e.children,t,n)}function gi(e,t,n){let r=[];for(let o of e)if(S.isJSXElement(o))if(pa(o))r.push(...gi(o.children,t,n));else{let i=pi(o,t,n);i&&r.push(i)}else rr(o)?r.push(...mi(o,t,n)):S.isJSXExpressionContainer(o)&&r.push(...hi(o.expression,t,n));return r}function yS(e,t,n){for(let r of e)S.isJSXElement(r)?pi(r,t,n):rr(r)?mi(r,t,n):S.isJSXExpressionContainer(r)&&hi(r.expression,t,n)}function xS(e){return e==="&&"||e==="||"||e==="??"}function hi(e,t,n){if(S.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:vt(r.collection,n),collectionSource:$e(r.collection,n,t)};if(S.isArrowFunctionExpression(a)||S.isFunctionExpression(a)){let d=a.params[0],f=a.params[1];S.isIdentifier(d)&&(c.itemParamName=d.name),S.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),(S.isArrowFunctionExpression(a)||S.isFunctionExpression(a))&&l.childKeys.push(...di(a,t,n)),l.childKeys}if(S.isConditionalExpression(e)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:vt(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(S.isLogicalExpression(e)&&xS(e.operator)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:vt(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(S.isParenthesizedExpression(e))return hi(e.expression,t,n);if(S.isJSXElement(e)){let o=pi(e,t,n);return o?[o]:[]}return rr(e)?mi(e,t,n):[]}function bS(e){let t=e.argument;return t&&(S.isExpression(t)||rr(t))?t:null}function Or(e,t){let n=[];for(let r of e){if(S.isReturnStatement(r)){let o=bS(r);o&&n.push({argument:o,statement:r,condition:t});continue}if(S.isIfStatement(r)){let o=S.isBlockStatement(r.consequent)?r.consequent.body:[r.consequent];if(n.push(...Or(o,r.test)),r.alternate){let i=S.isBlockStatement(r.alternate)?r.alternate.body:[r.alternate];n.push(...Or(i,r.test))}continue}if(S.isSwitchStatement(r))for(let o of r.cases){let i=o.test?S.binaryExpression("===",r.discriminant,o.test):r.discriminant;n.push(...Or(o.consequent,i))}}return n}function Sd(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=qb(r);Hb(r,{"FunctionDeclaration|FunctionExpression|ArrowFunctionExpression"(f){let m=Zb(f);if(!m)return;let u=f.node,g=[];if(S.isArrowFunctionExpression(u))S.isExpression(u.body)||rr(u.body)?g=[{argument:u.body,statement:S.returnStatement(S.isExpression(u.body)?u.body:null)}]:S.isBlockStatement(u.body)&&(g=Or(u.body.body));else{let R=u.body;S.isBlockStatement(R)&&(g=Or(R.body))}if(g.length===0){f.skip();return}let h=new Map;da(tS(r.program.body),la(t,m,i,s,l,[h]),h);let b=new Map;for(let R of u.params)for(let A of Wt(R))ma(b,A);let E=S.isBlockStatement(u.body)?u.body.body:[],v=g[0]?.statement??null;for(let R of E){if(v&&R===v)break;S.isVariableDeclaration(R)&&da([R],la(t,m,i,s,l,[h,b]),b)}let I=la(t,m,i,s,l,[h,b]);for(let R of g){let A=Ht(R.argument,I,n);for(let T of A)a.includes(T)||a.push(T);if(R.condition){let T={kind:"conditional-branch",conditionExpression:vt(R.condition,n),conditionSource:$e(R.condition,n,I)};fi(I,"conditional-region","",R.statement,A,[T])}}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 ga(e,t,n,r){return[...e.map(o=>({...o})),{fromFile:t,specifier:n,targetPath:r}]}function yi(e,t,n){return{...e,details:{...e.details??{},entryFile:t,importStack:n.map(r=>({...r}))}}}async function Ed(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 v=`${E.path}\0${E.code}\0${E.message}\0${JSON.stringify(E.details??{})}`;m.has(v)||(m.add(v),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:v,source:I,depth:R,diagnosticEntryFile:A,importStack:T}=E;if(h.has(v))continue;h.add(v),c.set(v,I);let C=a(v,I);if(!C.ok){u(yi(C.diagnostic,A,T));continue}d.set(v,C.module);let{graph:P,localImports:O}=Sd(C.module);for(let D of P.elements.values())if(D.importedFrom&&Pt(D.importedFrom)){let U=D.importedFrom,ee=await Fo(v,U,r);ee.ok?(D.importedFrom=ee.path,Ut(ee.path)&&(D.isPublicUiComponent=!0)):vn(U,v)||u(yi(ee.diagnostic,A,ga(T,v,U,ee.diagnostic.path)))}if(l.set(v,P),!(R>=i))for(let D of O){if(ou(D))continue;let U=await Fo(v,D,r);if(!U.ok){vn(D,v)||u(yi(U.diagnostic,A,ga(T,v,D,U.diagnostic.path)));continue}let ee=U.path;if(h.has(ee)||Ut(ee))continue;let Re=ga(T,v,D,ee);try{let Q=await n(ee);g.push({file:ee,source:Q,depth:R+1,diagnosticEntryFile:A,importStack:Re})}catch(Q){u(yi({path:ee,code:"import-read-failed",message:`Failed to read imported file: ${ee}`,details:{fromFile:v,specifier:D,reason:Q instanceof Error?Q.message:String(Q)}},A,Re))}}}let b=SS(e,l,s,(o.additionalEntries??[]).map(E=>E.file));return b.diagnostics=f,{graph:b,allSources:c,diagnostics:f,parsedModules:d,entryModule:d.get(e)??null}}function SS(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 ES}from"@vcp-dev/contracts";var vS={affectedCompositions:[]};function Nd(e){let t=null,n=new WeakMap;async function r(){return t??=kS(e),t}return{async prepareAppend(o){let i=await e.readIndex(),s=await e.stageAppend(Cd(o),{durableManifest:!1}),a;try{a=await e.previewStagedAppend(s.entryId,i.digest)}catch(l){throw await e.discardStage(s.stageId),l}let c={kind:"append",entry:o,historyTransition:a};return n.set(c,{expectedDigest:i.digest,stageId:s.stageId,entryId:s.entryId}),c},async prepareUndo(){let i=(await r()).undo.at(-1);if(!i?.historyId)return null;let s=await e.readIndex(),a=s.entryIds.indexOf(i.historyId);if(a<0)throw new Error("undo entry is missing from index");let c=a-1,l=await e.previewCursor(c,s.digest),d={kind:"undo",entry:i,historyTransition:l};return n.set(d,{expectedDigest:s.digest,cursor:c}),d},async prepareRedo(){let i=(await r()).redo.at(-1);if(!i?.historyId)return null;let s=await e.readIndex(),a=s.entryIds.indexOf(i.historyId);if(a<0)throw new Error("redo entry is missing from index");let c=a,l=await e.previewCursor(c,s.digest),d={kind:"redo",entry:i,historyTransition:l};return n.set(d,{expectedDigest:s.digest,cursor:c}),d},async publishPrepared(o){let i=n.get(o);if(!i)throw new Error("history mutation was not prepared");let s=await r();if(o.kind==="append"){if(!i.entryId)throw new Error("staged entry id is missing");let a=await e.publishStagedAppend(i.entryId,i.expectedDigest,i.stageId);vd(a,o.historyTransition),o.entry.historyId=i.entryId,s.entryIds=[...a.entryIds],s.cursor=a.cursor,s.undo.push(o.entry),s.redo.length=0}else{if(i.cursor===void 0)throw new Error("prepared cursor is missing");let a=await e.setCursor(i.cursor,i.expectedDigest);if(vd(a,o.historyTransition),o.kind==="undo"){if(s.undo.at(-1)!==o.entry)throw new Error("undo state changed before publish");s.undo.pop(),s.redo.push(o.entry)}else{if(s.redo.at(-1)!==o.entry)throw new Error("redo state changed before publish");s.redo.pop(),s.undo.push(o.entry)}s.cursor=i.cursor}n.delete(o)},async discardPrepared(o){let i=n.get(o);if(!i)return;let s=o.historyTransition;if(s){let a=await e.readIndex();if(a.digest===s.publishedIndexDigest&&a.cursor===s.publishedCursor&&a.currentId===s.publishedCurrentId)throw new Error("cannot discard a history mutation whose index was published")}i.stageId&&await e.discardStage(i.stageId),n.delete(o)},async peekUndo(){return(await r()).undo.at(-1)??null},async pushUndo(o){let i=await r(),s=o;if(s.historyId){let l=i.entryIds.indexOf(s.historyId);if(l>=0)try{await e.setCursor(l),i.undo.push(o),i.cursor=l;return}catch(d){throw i.redo.push(o),d}}let a=await e.append(Cd(o)),c=a.currentId;if(!c)throw new Error("history store did not publish an entry");o.historyId=c,i.entryIds=[...a.entryIds],i.cursor=a.cursor,i.undo.push(o),i.redo.length=0},async popUndo(){return(await r()).undo.pop()??null},async peekRedo(){return(await r()).redo.at(-1)??null},async pushRedo(o){let i=await r(),s=o;if(!s.historyId)throw i.undo.push(o),new Error("cannot move an unpersisted history entry to redo");let a=i.entryIds.indexOf(s.historyId);if(a<0)throw i.undo.push(o),new Error("history entry is missing from the durable index");try{await e.setCursor(a-1),i.cursor=a-1,i.redo.push(o)}catch(c){throw i.undo.push(o),c}},async popRedo(){return(await r()).redo.pop()??null},async clearRedo(){(await r()).redo.length=0},async getStatus(){let o=await e.readStatus();return{canUndo:o.canUndo,canRedo:o.canRedo,undoDepth:o.undoDepth,redoDepth:o.redoDepth,recoveryRequired:o.recoveryRequired}},async markRecoveryRequired(o){await e.markRecoveryRequired(o)}}}function vd(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")}async function kS(e){let t=await e.readIndex(),n=await Promise.all(t.undoIds.map(async o=>kd(e,o))),r=await Promise.all(t.redoIds.map(async o=>kd(e,o)));return{undo:n.reverse(),redo:r.reverse(),entryIds:[...t.entryIds],cursor:t.cursor}}async function kd(e,t){let n=await e.readEntry(t),r=IS(n),o=r.provenance??vS;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 Id(e,n,r.preSnapshots),postSnapshots:await Id(e,n,r.postSnapshots)}}async function Id(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(NS(r,o.blobName))).toString("utf8"):"";return{file:o.file,content:i,version:o.version,exists:o.exists,...o.sha256?{sha256:o.sha256}:{}}}))}function Cd(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=CS(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 IS(e){if(!Pd(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:wd(t.provenance)}:{},preSnapshots:Rd(t.preSnapshots,"preSnapshots"),postSnapshots:Rd(t.postSnapshots,"postSnapshots")}}function CS(e){if(e.provenance!==void 0)return wd(e.provenance);if(e.composition)return{initiatingComposition:e.composition,affectedCompositions:[]}}function wd(e){let t=ES.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 Rd(e,t){return e.map((n,r)=>{if(!Pd(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&&!RS(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 RS(e){return/^sha256:[0-9a-f]{64}$/.test(e)}function NS(e,t){let n=e.get(t);if(!n)throw new Error(`durable history blob is missing: ${t}`);return n}function Pd(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{COMPONENT_I18N_FILE_SUFFIX as wS,parseComponentI18nResourcesJson as PS,resolveSiteTextDirection as AS,SiteLocaleSchema as TS}from"@vcp-dev/contracts";var FS=["i18next","react-i18next"],_S="components/ui/site-locale-provider.tsx",OS="components/ui/component-i18n-provider.tsx",Ad="app/layout.tsx";async function ya(e){let t=e.files.filter(m=>m.path.endsWith(wS));if(t.length===0)return{ok:!0};for(let m of["package.json",Ad,_S,OS])if(!await e.exists(m))return wn(`Target snapshot is missing required i18n host file: ${m}`);let n;try{n=JSON.parse(await e.readFile("package.json"))}catch{return wn("Target snapshot package.json is invalid.")}let r=Td(n)&&Td(n.dependencies)?n.dependencies:{},o=FS.filter(m=>typeof r[m]!="string"||r[m].trim().length===0);if(o.length>0)return wn(`Target snapshot must already declare: ${o.join(", ")}.`);let i=await e.readFile(Ad),s=ha(i,"html","lang"),a=ha(i,"html","dir"),c=ha(i,"SiteLocaleProvider","locale"),l=TS.safeParse(s);if(!l.success||!a||!c||s!==c||a!==AS(l.data))return wn("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 wn("Target snapshot root layout is not wired to SiteLocaleProvider.");let d=l.data,f=d.split("-")[0];for(let m of t){let u=PS(m.content);if(!u.success)return wn(`Component i18n resource is invalid: ${m.path}.`);if(!Object.hasOwn(u.data,d)&&!Object.hasOwn(u.data,f))return wn(`Component i18n resource ${m.path} has no locale for ${d} or ${f}.`)}return{ok:!0}}function ha(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 Td(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function wn(e){return{ok:!1,message:e}}import{randomBytes as GS}from"node:crypto";import bi from"node:path";import{parse as Vd}from"@babel/parser";import YS from"@babel/traverse";import*as Kd from"@babel/types";import{COMPONENT_I18N_FILE_SUFFIX as ba,PageResourceArtifactSchema as ZS,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as QS,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as qS,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as eE,parseComponentI18nResourcesJson as tE}from"@vcp-dev/contracts";var _d=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\(/i,Od=/\b(?:bg-black|bg-white|text-white|text-black)(?:\b|\/)/g,MS=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke)-\[#(?:[0-9a-fA-F]{3,8})\](?:\/\d+)?/g,DS=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*#[0-9a-fA-F]{3,8}[^'"]*['"]/g,LS=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*rgba?\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,BS=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,jS=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,$S=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*(?:oklch|lab|lch|hsla?)\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,VS=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*(?:oklch|lab|lch|hsla?)\([^)]+\)[^'"]*['"]/gi,KS=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*color-mix\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,US=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*color-mix\([^'"]*['"]/gi,JS=/\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,XS=/var\(\s*--(?:_|private-|vcp-)[^)]+\)/gi,zS=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\([^)]*\)/gi;function Mr(e,t){let n=xi([...ht(e,MS),...ht(e,DS),...ht(e,LS),...ht(e,t.includeRgbBackgroundImage?BS:jS),...t.includeExtendedColorFunctions?[...ht(e,$S),...ht(e,VS)]:[]]),r=xi([...ht(e,KS),...ht(e,US)]).filter(o=>t.colorMixPolicy==="always"||_d.test(o));return n.push(...r.filter(o=>!n.includes(o))),t.rejectTailwindPalette&&n.push(...ht(e,JS).filter(o=>!n.includes(o))),t.rejectAnyRawColorLiteral&&n.push(...ht(e,zS).filter(o=>!n.includes(o))),{hardCodedSurfaceHits:xi(ht(e,Od)),hardCodedSurfaceOccurrences:HS(e),rawColorHits:n,privateTokenHits:t.rejectPrivateTokens?xi(ht(e,XS)):[]}}function ht(e,t){return e.match(new RegExp(t.source,t.flags))??[]}var Fd=160,WS=/((?:[a-z][a-z0-9-]*(?:\[[^\]]*\])?:)+)$/;function HS(e){let t=new RegExp(Od.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>Fd?`${u.slice(0,Fd-1)}\u2026`:u})}return o}function xi(e){return[...new Set(e)]}var Sa="{{$INSTANCE}}",nE=/\{\{\$PAGE_ROUTE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,rE=/\{\{\$PAGE_TITLE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,Ea="components/site/generated",oE=/\.(?:tsx?|json)$/,iE=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,sE=["react","react/","next","next/","lucide-react","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],aE=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),xa=YS,cE=typeof xa=="function"?xa:xa.default;async function va(e){let t=ZS.safeParse(e.artifact);if(!t.success)return Ae("Page resource artifact failed contract validation.");let n=t.data,r=e.randomHex??(()=>GS(4).toString("hex")),o=Math.max(1,Math.min(e.maxAttempts??5,5)),i=yE(r());if(!i)return Ae("Random instance suffix must be 8 lowercase hex chars.");let s=`${xE(n.resource_id)}-${i}`,a=new Map,c=new Map,l=[];for(let I of n.pages){let R=I.final_route.slice(1);a.set(I.template_page_id,I.final_route),c.set(I.template_page_id,I.title),l.push({template_page_id:I.template_page_id,title:I.title,final_route:I.final_route,route_file_path:`app/${R}/page.tsx`})}let d=[],f=new Set,m=new Set,u=new Map,g=new Map,h=[],b=new Set(n.pages.flatMap(I=>I.components.map(R=>R.component_id)));for(let I of n.components){if(!b.has(I.component_id))continue;let R=Md({materialization:I.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c});if(!R.ok)return R;for(let A of R.files){let T=Ld(A,f,d);if(T)return T}m.add(R.entry),g.set(R.entry,R.entryExport),u.set(I.component_id,R.entry)}for(let[I,R]of n.pages.entries()){let A=l[I],T=Md({materialization:R.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c,pageEntryTarget:A.route_file_path,pageTitle:A.title});if(!T.ok)return T;for(let C of T.files){let P=Ld(C,f,d);if(P)return P}m.add(T.entry),g.set(T.entry,T.entryExport),h.push({entry:T.entry,declaredComponentIds:new Set(R.components.map(C=>C.component_id))})}let E=uE(d,m,s,u,h,g);if(!E.ok)return E;for(let I of d)if(await e.exists(I.file))return!I.file.startsWith("app/")&&o>1?va({...e,randomHex:r,maxAttempts:o-1}):{ok:!1,code:"MATERIALIZATION_CONFLICT",message:`Page resource create-only target already exists: ${I.file}`,path:I.file};let v=dE(d);return v||(d.sort((I,R)=>I.file.localeCompare(R.file)),{ok:!0,packageInstanceId:s,pages:l,files:d})}function Md(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:Dd(o.pathTemplate,e.packageInstanceId);if(!s)return Ae("Materialization path cannot be mapped into the package namespace.",o.pathTemplate);let a=lE(o.content,e.packageInstanceId,e.routeByPage,e.titleByPage);if(!a.ok)return a;let c=i&&e.pageTitle!==void 0?pE(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??Dd(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 lE(e,t,n,r){let o,i=e.replace(nE,(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(rE,(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(Sa,t);return a.includes("{{$PAGE_ROUTE:")||a.includes("{{$PAGE_TITLE:")||a.includes("{{$INSTANCE}}")?Ae("Materialization contains an unresolved placeholder."):{ok:!0,data:a}}function Dd(e,t){let n=`${Ea}/${t}`;if(e.split(Sa).length>2)return null;let o=e.replace(Sa,t),i=`${Ea}/${t}/`,s=o.startsWith(i)?o:`${n}/${o}`,a=bi.posix.normalize(s);return a!==s||!a.startsWith(`${n}/`)||!oE.test(a)||iE.test(a)?null:a}function Ld(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 uE(e,t,n,r,o,i){let s=new Set(e.map(u=>u.file)),a=`${Ea}/${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(ba)&&!tE(u.content).success)return Ae("Materialization component i18n resources are invalid.",u.file);continue}try{let h=Vd(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 v=E.source.value,I=gE(u.file,v,s,a);if(!I.allowed)return Ae(`Materialization import is outside the controlled package: ${v}`,u.file);I.internalPath&&c.get(u.file).add(I.internalPath)}let b;if(cE(h,{Identifier(E){E.isReferencedIdentifier()&&aE.has(E.node.name)&&(b??=E.node.name,E.stop())},JSXAttribute(E){E.node.name.type==="JSXIdentifier"&&E.node.name.name==="style"&&(b??="inline style",E.stop())},JSXOpeningElement(E){E.node.name.type==="JSXIdentifier"&&E.node.name.name.toLowerCase()==="style"&&(b??="style element",E.stop())}}),b)return Ae(`Materialization source uses forbidden capability: ${b}`,u.file)}catch{return Ae("Materialization source must parse as TS/TSX.",u.file)}let g=Mr(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||!fE(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=$d(u.entry,c);for(let h of u.declaredComponentIds){let b=r.get(h);if(!b||!g.has(b))return Ae(`Page entry does not reach declared component: ${h}`,u.entry)}for(let h of g){let b=d.get(h);if(b&&!u.declaredComponentIds.has(b))return Ae(`Page entry imports undeclared component: ${b}`,u.entry)}}let f=new Set;for(let u of t)for(let g of $d(u,c))f.add(g);if(f.size!==e.length)return Ae("Every materialization file must be reachable from a package entry.");let m=hE(e,l,c);return m||{ok:!0}}function dE(e){if(e.length>QS)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>qS)return Ae("Page resource file exceeds the content byte limit.",n.file);t+=r}return t>eE?Ae("Page resource exceeds the aggregate content byte limit."):null}function fE(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 pE(e,t,n){let r;try{r=Vd(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=Bd(s.init);if(a?.type!=="ObjectExpression")return{ok:!0,data:e};let c=a.properties.find(d=>d.type==="ObjectProperty"&&!d.computed&&mE(d.key));if(!c||c.type!=="ObjectProperty")return{ok:!0,data:e};let l=Bd(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 Bd(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression"||t?.type==="TSNonNullExpression";)t=t.expression;return t&&Kd.isExpression(t)?t:null}function mE(e){return e.type==="Identifier"&&e.name==="title"||e.type==="StringLiteral"&&e.value==="title"}function gE(e,t,n,r){if(t.startsWith(`@/${r}/`)){let s=t.slice(2),a=jd(s,n);return a?{allowed:!0,internalPath:a}:{allowed:!1}}if(!t.startsWith("."))return{allowed:sE.some(s=>s.endsWith("/")?t.startsWith(s):t===s)};if(t.includes("\\")||t.includes("\0"))return{allowed:!1};let o=bi.posix.normalize(bi.posix.join(bi.posix.dirname(e),t)),i=jd(o,n);return i&&(i.startsWith(`${r}/`)||i.startsWith("app/"))?{allowed:!0,internalPath:i}:{allowed:!1}}function jd(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 hE(e,t,n){let r=new Set(e.map(o=>o.file));for(let o of e){if(!o.file.endsWith(ba))continue;let i=o.file.slice(0,-ba.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 $d(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 yE(e){return/^[a-f0-9]{8}$/.test(e)?e:null}function xE(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 bE}from"node:crypto";import Gt from"node:path";import{parse as SE}from"@babel/parser";import EE from"@babel/traverse";import{COMPONENT_I18N_FILE_SUFFIX as Si,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as Ud,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as vE,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as kE,SiteEditMaterializationSchema as IE,parseComponentI18nResourcesJson as CE}from"@vcp-dev/contracts";var Ca="components/site/generated",Jd="{{$INSTANCE}}",Ei=5,RE=/^[a-z][a-z0-9-]{0,48}$/,NE=/^[a-f0-9]{8}$/,Xd=/\.tsx?$/,wE=/\.json$/,PE=/\.(?:tsx?|json)$/,AE=/^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/,TE=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,FE=["react","react/","next","next/","lucide-react","react-i18next","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],ka=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),Ia=EE,_E=typeof Ia=="function"?Ia:Ia.default;function OE(e){let t=Array.isArray(e.manifest.files)?e.manifest.files:[];if(t.length>Ud)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file count exceeds the reusable limit."}};let n=XE(t);if(n)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Static prefab resolves duplicate target path: ${n}`,path:n}};let r=IE.safeParse(e.manifest);if(!r.success)return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab manifest failed schema validation."}};let o=KE(e.generatedRoot);if(!o)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Generated root must be ${Ca}.`,path:e.generatedRoot}};if(!Zd(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=Hd(r.data.files),s=Hd(e.controlledFiles);if(!zE(i,s))return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Controlled file list must exactly match the manifest file templates."}};if(i.size>Ud)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>vE)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>kE?{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 ME(e){let t=OE(e);if(!t.ok)return t;let n=Object.keys(e.manifest.projectDependencies??{}),r=new Set(e.availableHostDependencies??[]),o=n.find(d=>!AE.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??FE,...i],a=t.data.generatedRoot,c=Zd(e.manifest.instanceBaseName),l=Math.max(1,Math.min(Ei,e.maxAttempts??Ei));for(let d=0;d<l;d+=1){let f=UE(e.instanceNameGenerator?.()??bE(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=qd(a,m),g=DE({manifest:e.manifest,generatedRoot:a,instanceName:m,instanceRoot:u,allowedExternalImports:s});if(!g.ok)return g;if(!await LE(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 Yd(e){let t=Math.max(1,Math.min(Ei,e.maxAttempts??Ei));for(let n=0;n<t;n+=1){let r=await ME({...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 DE(e){let t=[],n=new Set;for(let i of e.manifest.files){let s=zd({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=zd({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=BE(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 LE(e,t,n){if(await e(t))return!0;for(let r of n)if(await e(r.path))return!0;return!1}function zd(e){if(e.pathTemplate.split(Jd).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(Jd,e.instanceName),n=JE(t);return n?qd(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||!PE.test(n)||TE.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 BE(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(wE.test(f.path)){if(f.path.endsWith(Si)){let g=CE(f.content);if(!g.success)return Pn("MATERIALIZATION_DATA_UNSUPPORTED",g.error.message,f.path);c.set(f.path,new Set)}else try{JSON.parse(f.content)}catch{return Pn("MATERIALIZATION_DATA_UNSUPPORTED","Static prefab JSON file must contain valid JSON.",f.path)}continue}let m;try{m=SE(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=Mr(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(!Xd.test(f.path))continue;let m=s.get(f.path),u=null;if(_E(m,{ImportDeclaration(g){let h=Wd({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(Si))){let b=jE({importer:f.path,imported:h.internalPath,source:g.node.source.value,ast:m});b.ok?c.get(h.internalPath).add(f.path):(u??=b.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=Wd({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=Gd(g.node);h&&ka.has(h)&&(u??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${h}.`,file:f.path},g.stop())},OptionalMemberExpression(g){let h=Gd(g.node);h&&ka.has(h)&&(u??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${h}.`,file:f.path},g.stop())},Identifier(g){g.isReferencedIdentifier()&&ka.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(!Xd.test(n))return Pn("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must be a .ts/.tsx source module.",n);let l=s.get(n);if(!l)return Pn("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must resolve to a controlled source file.",n);if(!$E(l,r))return Pn("MATERIALIZATION_EXPORT_MISSING","Static prefab entry does not declare the manifest export.",n);for(let[f,m]of c)if(m.size!==1)return Pn("MATERIALIZATION_IMPORT_FORBIDDEN","Each component .i18n.json file must have exactly one same-name Client Component static importer.",f);return VE(n,a).size!==e.length?Pn("MATERIALIZATION_ENTRY_INVALID","Every controlled source file must be reachable from the entry module.",n):{ok:!0,data:{kind:"static-prefab-materialization",instanceName:"",generatedRoot:Ca,instanceRoot:"",entry:{path:"",export:{kind:"default"}},files:[]}}}function Wd(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 jE(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,-Si.length),i=`./${r}${Si}`;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 $E(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 VE(e,t){let n=new Set,r=[e];for(;r.length>0;){let o=r.pop();n.has(o)||(n.add(o),r.push(...t.get(o)??[]))}return n}function Pn(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{file:n}:{}}}}function KE(e){let t=Qd(e);return t===Ca?t:null}function UE(e){let t=e.trim().toLowerCase();return NE.test(t)?t:null}function Zd(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 RE.test(t)?t:null}function Qd(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 JE(e){let t=Qd(e);return!t||t!==e?null:t}function qd(...e){return Gt.posix.join(...e)}function Hd(e){return new Set(e.map(t=>t.pathTemplate))}function XE(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 zE(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function Gd(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 $a}from"node:crypto";import _a from"@babel/traverse";function Ra(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 WE}from"node:crypto";import ef from"node:path";import*as sf from"@babel/parser";import Na from"@babel/generator";import*as Ue from"@babel/types";var tf=typeof Na=="function"?Na:Na.default;function Pa(e){let t=cf(e);if(t)return{ok:!1,error:t};let n=e.projection,r=Fa(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=YE(n,o),s={jsx:`<${e.component.localName} />`},a=HE(e);if(i){let u=wa(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??(Ta(c,n.container.sourceRange)?n.container.sourceHash:null);if(!c||!l)return Dr("Route page composition does not expose a verifiable container boundary.");let d=Br(c),f=rf(e.source,d,l,"Route page composition container");if(!f.ok)return f.result;let m=o.anchorSourceRange?Br(o.anchorSourceRange):void 0;if(m){if(!o.anchorSourceHash)return Dr("Route page composition placement does not expose a verifiable anchor boundary.");let u=rf(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 HE(e){let t=ev(e.entryFile,e.component.source);return e.component.exportName==="default"?{kind:"add-import",moduleSpecifier:t,imports:[{kind:"default",local:e.component.localName}]}:{kind:"add-import",moduleSpecifier:t,imports:[{kind:"named",imported:e.component.exportName,local:e.component.localName===e.component.exportName?void 0:e.component.localName}]}}function vi(e){if(e.locator.root.kind!=="expression"||e.locator.path?.length)return An(e.source,"Root expression rewrite requires an exact expression locator.");let t=vr(e.source,"value");if(!t.ok)return An(e.source,t.diagnostic.message);let n=ae(t.ast,e.locator);if(!n.ok)return An(e.source,n.diagnostic.message);let r=n.match.path;if(!r.isExpression())return An(e.source,"Resolved value locator does not point to an expression.");let o=or(e.source,r.node.start??null,r.node.end??null);if(!o||o!==e.expectedSourceHash)return An(e.source,"Root expression hash no longer matches the current source.");if(e.action.kind==="remove")return r.replaceWith(Ue.nullLiteral()),{ok:!0,source:tf(t.ast,{}).code};let i;try{i=sf.parseExpression(e.action.jsx,{plugins:["jsx","typescript"]})}catch(s){return An(e.source,s instanceof Error?s.message:String(s))}return!Ue.isJSXElement(i)&&!Ue.isJSXFragment(i)?An(e.source,"Root expression rewrite requires a JSX insertion expression."):(e.action.kind==="replace"?r.replaceWith(i):r.replaceWith(GE(r.node,i,e.action.placement,e.action.replaceOriginal)),{ok:!0,source:tf(t.ast,{}).code})}function GE(e,t,n,r){if(Ue.isNullLiteral(e)||r)return t;let o=Ue.isJSXFragment(e)?[...e.children]:[Ue.isJSXElement(e)?e:Ue.jsxExpressionContainer(e)],s=n==="before"||n==="prepend"?[t,...o]:[...o,t];return Ue.jsxFragment(Ue.jsxOpeningFragment(),Ue.jsxClosingFragment(),s)}function An(e,t){return{ok:!1,source:e,diagnostic:{message:t}}}function Aa(e){let t=cf(e);if(t)return{ok:!1,error:t};let n=e.projection,r=lf(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(ZE(n,o)){let h=wa(e);return h.ok?e.operation==="remove-node"&&!nf(n,o.placementUnitKey)?Dr("The last editable page unit cannot be deleted."):e.operation==="move-node"?Dr("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=Br(o.sourceRange),a=Ft(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?[]:[Lr(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=wa(e);return h.ok?nf(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}}}:Dr("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||!qE(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=Fa(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=Br(f),u=Ft(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?[]:[Lr(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,b=d.anchorSourceHash;if(!h||!b)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=Br(h),v=Ft(e.source,E);return!v.ok||!v.match.node?{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:v.ok===!1?v.diagnostic.message:"Route page composition target anchor could not be resolved.",diagnostics:v.ok?[]:[Lr(v.diagnostic)]}}:or(e.source,v.match.node.start??null,v.match.node.end??null)!==b?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 nf(e,t){for(let n of e.placementUnitByKey.values())if(n.placementUnitKey!==t&&n.members.length>0)return!0;return!1}function YE(e,t){let n=e.placementUnitByKey.get(t.placementUnitKey);return n&&e.container.kind!=="jsx-container"&&Ta(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 ZE(e,t){return e.container.kind!=="jsx-container"&&Ta(t.sourceRange,e.mutationTarget.sourceRange)&&t.sourceHash===e.mutationTarget.sourceHash}function wa(e){let t=e.projection.mutationTarget,n={kind:"value",root:{kind:"expression",sourceRange:t.sourceRange}},r=Ft(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?[]:[Lr(r.diagnostic)]}}}:or(e.source,r.match.node.start??null,r.match.node.end??null)!==t.sourceHash?{ok:!1,result:af("Route mutation target hash no longer matches the current source.")}:{ok:!0,locator:n,sourceHash:t.sourceHash}}function rf(e,t,n,r){let o=Ft(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?[]:[Lr(o.diagnostic)]}}}:or(e,o.match.node.start??null,o.match.node.end??null)!==n?{ok:!1,result:af(`${r} hash no longer matches the current source.`)}:{ok:!0}}function af(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function Dr(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 Lr(e){return{code:"UNSUPPORTED_PAGE_SHAPE",message:e.message,details:{astCode:e.code}}}function cf(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&&!QE(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 QE(e,t){return e.routeId===t.routeId&&e.effectiveTemplateId===t.effectiveTemplateId}function qE(e,t){return e.routeId===t.routeId&&e.templateId===t.effectiveTemplateId}function ev(e,t){let n=ef.posix.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=ef.posix.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function Br(e){return{kind:"jsx-node",strategy:"source-range",sourceRange:e}}function or(e,t,n){return t==null||n==null?null:`sha256:${WE("sha256").update(e.slice(t,n)).digest("hex")}`}function Ta(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 tv=typeof _a=="function"?_a:_a.default;function pf(e){if(!e.ast)return kt(e,[Ve("UNSUPPORTED_PAGE_SHAPE","SourceGraph entry AST is required",{reason:"parsed-ast-required"})]);let t=lv(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=dv(t);if(!n.ok)return kt(e,[n.diagnostic]);let r=n.expression;if(r.isIdentifier()){let o=pv(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(gv(r,t))return kt(e,[Ve("INDIRECT_RETURN_ONLY","Route default export only returns through an indirect function boundary")]);if(r.isNullLiteral())return Ma(e,t,"virtual-route-root",r);if(mv(r)){let o=bv({input:e,source:e.source,expression:r});return Oa(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)&&!sn(r)){let o=Ba(r),i=ff({input:e,containerKind:"virtual-route-root",sourceKind:"jsx-element",source:e.source,containerPath:r,members:[o]});return Oa(e,t,i,{kind:"virtual-route-root",sourceKind:"jsx-element"},r)}if(r.isJSXElement()||r.isJSXFragment()){let o=yv(r);if(!o.ok)return kt(e,[o.diagnostic]);let i=ir(o.path);if(i.unsupported)return kt(e,[Ve("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);if(hv(e.source,r,i.members))return Ma(e,t,"starter-placeholder",r);let s=r.isJSXFragment()||Fe(r);if(i.members.length===0&&s)return Ma(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=ff({input:e,containerKind:a,sourceKind:c,source:e.source,containerPath:o.path,members:i.members});return Oa(e,t,l,{kind:a,sourceKind:c},r)}return kt(e,[Ve("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")])}function Fa(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 lf(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 mf(e){return e.ok?nv(e.projection):rv(e.projection)}function nv(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,b)=>gf(e,d,h,b,e.container.placementKey)),m=f.filter(({member:h})=>h.isBusinessMember).map(({sourceMember:h})=>iv(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:ov(e,a),sourceMembers:i,businessMembers:s,placementUnits:n,placements:c}}function rv(e){let t=e.diagnostics.map(sv);return{status:"unsupported",version:e.version,composition:e.composition,reason:av(e.diagnostics),diagnostics:t}}function ov(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 gf(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)=>gf(e,t,a,c,i))]}function iv(e,t,n){return{key:`business:${e}:${t.key}`,sourceMemberKey:t.key,containerKey:e,label:t.label,isIndependent:n}}function sv(e){return{code:cv(e),message:e.message}}function av(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 cv(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 lv(e){let t=null;return tv(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=uv(o.path);i&&(t=i,n.stop())}}),t}function uv(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 dv(e){let t=e.get("body");if(!t.isBlockStatement()){let s=$r(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(!fv(s))return{ok:!1,diagnostic:Ve("UNSUPPORTED_PAGE_SHAPE","Route guard return shape is not statically safe",{reason:"guard-shape"})};continue}if(hf(s)||yf(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=$r(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 fv(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(hf(o)||yf(o))return null;return r}function hf(e){return e.isForStatement()||e.isForInStatement()||e.isForOfStatement()||e.isWhileStatement()||e.isDoWhileStatement()||e.isSwitchStatement()||e.isTryStatement()||e.isWithStatement()}function yf(e){let t=!1;return e.traverse({Function(n){n.skip()},ReturnStatement(){t=!0}}),t}function pv(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=$r(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 mv(e){return e.isConditionalExpression()?uf($r(e.get("consequent")))&&uf($r(e.get("alternate"))):!1}function uf(e){return!!(e&&(e.isJSXElement()||e.isJSXFragment()||e.isNullLiteral()))}function $r(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 gv(e,t){if(e.isIdentifier())return df(e.node.name,t);if(e.isCallExpression()){let n=e.get("callee");if(n.isIdentifier())return df(n.node.name,t)}return!1}function df(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 hv(e,t,n){return e.includes("DESIGN_PLAN_REPLACE_ME")&&t.isJSXElement()&&n.length>0&&La(t)}function La(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(!La(t))return!1;continue}if(t.isJSXElement()&&!La(t))return!1}return!0}function yv(e){let t=e;if(e.isJSXFragment()||Fe(e)){let r=jr(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=jr(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(jr(o).length<=1)return{ok:!0,path:t};t=o}return{ok:!0,path:t}}function jr(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(...jr(n));continue}n.isJSXElement()&&(Fe(n)?t.push(...jr(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:ja(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=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({...Ba(o,i?.members),sourceRange:yt(r.node.loc),parentSourceRange:yt(e.node.loc)});continue}if(o.isJSXSpreadChild()){n=!0;continue}t.push({memberKey:ja(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=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({...Ba(r,o?.members),parentSourceRange:yt(e.node.loc)})}}return{members:t,unsupported:n}}function Ba(e,t){let n=e.isJSXElement()&&sn(e)?t??ir(e).members:[],r=e.isJSXElement()&&!sn(e)&&!Fe(e);return{memberKey:ja(e.node.type,e.node.start,e.node.end),kind:"jsx-element",nodeType:e.node.type,sourceRange:yt(e.node.loc),businessMemberCount:r?1:xf(n),parentSourceRange:yt(e.parentPath?.node.loc),children:n,isBusinessMember:r,label:xv(e)}}function sn(e){let t=e.node.openingElement.name;return t.type==="JSXIdentifier"&&t.name[0]===t.name[0]?.toLowerCase()}function xv(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 xf(e){return e.reduce((t,n)=>t+n.businessMemberCount,0)}function ki(e){return e.length===0?0:Math.max(1,xf(e))}function ff(e){let t=yt(e.containerPath.node.loc),n=Va(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:ki(e.members)<=1,memberCount:ki(e.members),sourceRange:t,sourceHash:n,relation:"append",containerSourceRange:t,containerSourceHash:n,anchorSourceRange:null,anchorSourceHash:null,members:e.members}}function bv(e){let t=yt(e.expression.node.loc),n=Va(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 bf(e,t){let n=yt(t.node.loc),r=Va(e.source,t.node.start,t.node.end);return!n||!r?null:{kind:"expression",documentVersion:e.version,sourceRange:n,sourceHash:r}}function Oa(e,t,n,r,o){let i=bf(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=Sv(e,n,s),c=Ra(a),l={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:Ef(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 Sv(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:ki(g)<=1,memberCount:ki(g),sourceRange:m,sourceHash:m?Da(e.source,m):null,relation:l,containerSourceRange:h,containerSourceHash:h?Da(e.source,h):null,anchorSourceRange:u,anchorSourceHash:u?Da(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 Ma(e,t,n,r){let o=bf(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=Ra([a]),l={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:Ef(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 Sf([e.route,e.entryFile,String(e.version),t,n,r?`${r.startLine}:${r.startColumn}-${r.endLine}:${r.endColumn}`:"no-range"])}function ja(e,t,n){return Sf(["member",e,String(t??-1),String(n??-1)])}function Sf(e){return`pc_${$a("sha256").update(e.join("\0")).digest("hex").slice(0,24)}`}function Va(e,t,n){return t==null||n==null?null:`sha256:${$a("sha256").update(e.slice(t,n)).digest("hex")}`}function Da(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:${$a("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 Ef(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 Fv}from"@vcp-dev/contracts";import wF from"node:fs";import AF from"node:path";var vv=/^page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function Vr(e){let t=e.map(r=>Tv(r.path)),n=kv(t);return n?t.filter(r=>Cv(n,r)).map(r=>({routeId:Rv(n,r),entryFile:r})).sort((r,o)=>r.routeId.localeCompare(o.routeId)):[]}function Ka(e,t=""){let r=((e??"/").trim()||"/").split(/[?#]/,1)[0]||"/",o=r.startsWith("/")?r:`/${r}`,i=Av(t),s=i&&(o===i||o.startsWith(`${i}/`))?o.slice(i.length)||"/":o,a=s.startsWith("/")?s:`/${s}`;return a==="/"?"/":a.replace(/\/+$/,"")}function kv(e){return e.some(r=>r.startsWith("app/")&&!Iv(r))?"app":e.some(r=>r.startsWith("src/app/"))?"src/app":null}function Iv(e){return/^(?:src\/)?app\/(?:_vcp|\.vcp)/.test(e)}function Cv(e,t){if(!t.startsWith(`${e}/`))return!1;let n=t.slice(t.lastIndexOf("/")+1);return vv.test(n)?t.slice(e.length+1,-n.length-1).split("/").filter(Boolean).every(r=>!r.startsWith("_")&&!r.startsWith(".")):!1}function Rv(e,t){let n=t.slice(e.length+1).split("/").slice(0,-1).map(wv).filter(r=>!!r);return n.length===0?"/":`/${n.join("/")}`}function Nv(e){return e.startsWith("(")&&e.endsWith(")")}function wv(e){return!e||e.startsWith("@")||e.startsWith("_")||Nv(e)?null:Pv(e)}function Pv(e){return e.replace(/^\((?:\.|\.\.|\.\.\.)\)/,"")}function Av(e){let t=e.trim();return!t||t==="/"?"":(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"")}function Tv(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}var Kr=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="PageTemplateManagedSourceError"}};function et(e,t={}){throw new Kr("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Invalid page-template source (${e}): ${t.path??t.routeId??t.templateId??""}`,{reason:e,...t})}function Ua(e){return Fv.safeParse(e).success||et("invalid-template-id",{templateId:e}),Buffer.from(e,"utf8").toString("base64url")}function vf(e){/^[A-Za-z0-9_-]{1,255}$/.test(e)||et("invalid-template-key",{path:e});let t;try{t=new TextDecoder("utf-8",{fatal:!0}).decode(Buffer.from(e,"base64url"))}catch{return et("invalid-template-key",{path:e})}return Ua(t)!==e&&et("noncanonical-template-key",{path:e}),t}function _v(e){let t=Ka(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("(")||Ov(r)&&!kf(r)))&&et("invalid-public-route",{routeId:e}),t}function Ov(e){return e.includes("[")||e.includes("]")}function kf(e){return/^\[\[\.\.\.[^\[\]]+\]\]$|^\[[^\[\]]+\]$/.test(e)}function If(e){return e.some(kf)}function Cf(e,t,n="app"){n!=="app"&&n!=="src/app"&&et("invalid-app-root");let r=_v(e),o=Ua(t),i=If(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))&&et("path-too-long",{path:a}),{appRoot:n,routeRoot:s,templateKey:o,templateEntryFile:a}}function Rf(e){return/^(?:src\/)?app\/\.vcp\/page-templates\//.test(e)}function Nf(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===".")&&et("invalid-file-path",{path:i}),n.has(i)&&et("duplicate-file-path",{path:i}),n.set(i,o)}return n}function Ci(e){let t=Nf(e.files),n=Vr([...t.keys()].map(i=>({path:i}))),r=new Map;for(let i of n){if(r.has(i.routeId))throw new Kr("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(!Rf(i))continue;let s=/^(app|src\/app)\/\.vcp\/page-templates\/(.+)\/page\.tsx$/.exec(i);s||et("candidate-must-be-single-page",{path:i});let a=s[1],c=s[2].split("/"),l=If(c),d=l?c[0]:c.pop(),f=l?c.slice(1):c,m=vf(d),u=f.length?`/${f.join("/")}`:"/";Cf(u,m,a).templateEntryFile!==i&&et("candidate-path-mismatch",{path:i,routeId:u});let h=r.get(u);(!h||!h.startsWith(`${a}/`))&&et("canonical-entry-missing",{path:i,routeId:u}),o.push({routeId:u,templateId:m,entryFile:i,canonicalEntryFile:h,appRoot:a})}return o.sort((i,s)=>Ii(i.routeId,s.routeId)||Ii(i.templateId,s.templateId))}function wf(e){let t=Nf(e.files),n=Ci({files:t}),r=Vr([...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)=>Ii(o.context.routeId,i.context.routeId)||(o.context.effectiveTemplateId===void 0?-1:i.context.effectiveTemplateId===void 0?1:Ii(o.context.effectiveTemplateId,i.context.effectiveTemplateId)))}function Mv(e){let t=Ka(e.selector.routeId),n=wf({files:e.files}),r=n.find(i=>i.context.routeId===t&&i.context.effectiveTemplateId===void 0);(!r||r.entryFile!==e.canonicalEntryFile)&&et("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||et("template-selection-not-found",{routeId:t,templateId:e.selector.templateId}),{...o,mode:e.selector.templateId===void 0?"direct":"candidate",effectiveEntryFile:o.entryFile}}function Ii(e,t){return e<t?-1:e>t?1:0}import{HOME_PAGE_URL_PATH as Hv}from"@vcp-dev/contracts";import{parse as T_}from"@babel/parser";import{parse as jF}from"@babel/parser";import{FormBlockIdSchema as VF,FormSpecV1Schema as KF}from"@vcp-dev/contracts";var Ur="components/site/generated/forms",UF=`${Ur}/vcp-form-runtime.tsx`,Ri="[A-Za-z0-9][A-Za-z0-9_-]{0,127}",JF=new RegExp(`^${Ur}/form-(${Ri})\\.spec\\.ts$`),XF=new RegExp(`^${Ur}/form-(${Ri})\\.tsx$`),zF=new RegExp(`^@/${Ur}/form-(${Ri})$`),WF=new RegExp(`(?:^|/)${Ur}/form-(${Ri})(?:\\.tsx?)?$`);var HF=Symbol("invalid-literal");import{createHash as ZF}from"node:crypto";import{posix as qF}from"node:path";import{parse as t_}from"@babel/parser";import{FormSpecV1Schema as r_}from"@vcp-dev/contracts";var o_=Symbol("dynamic");import{parse as Dv}from"@babel/parser";function Ni(e){return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&typeof t.type=="string"):[]}var Lv=/^(?:src\/)?app\/(.*)page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function Pf(e){let t=Lv.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 Bv(e){let t=e;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function Af(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function jv(e){let t=e;for(;t&&(t.type==="TSAsExpression"||t.type==="TSSatisfiesExpression"||t.type==="ParenthesizedExpression");)t=t.expression??null;return t}function Ja(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(Ja);if(t?.type==="ObjectExpression"){let n={};for(let r of Ni(t.properties)){if(r.type!=="ObjectProperty"||r.computed)throw new Error("dynamic object property");let o=Af(r.key);if(!o)throw new Error("unsupported object key");n[o]=Ja(r.value)}return n}throw new Error(`unsupported static value: ${t?.type??"unknown"}`)}function Xa(e,t){let n=[],r=Pf(t);if(r===null)return{found:!1,seo:null,diagnostics:n};let o;try{o=Dv(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 Ni(o.program.body)){let d=l.type==="ExportNamedDeclaration"?l.declaration:l;if(d?.type==="VariableDeclaration")for(let f of Ni(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=jv(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 Ni(s.properties)){if(l.type!=="ObjectProperty"||l.computed)continue;let d=Af(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=Bv(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=Ja(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 $v}from"@babel/parser";var Tf=["page","anchor","external","email","phone","group","file"],Vv=["link","cta"],_f=["description","badge","iconKey"],za=["label","targetType","href","role","openInNewTab","nofollow","children",..._f],Kv=new Set(za);function Xr(e){return Array.isArray(e)?e:[]}function Jr(e){let t=e;return t?.type==="StringLiteral"&&typeof t.value=="string"?t.value:void 0}function Uv(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function Ff(e){let t=e;return t?.type==="BooleanLiteral"&&typeof t.value=="boolean"?t.value:void 0}function Wa(e){let t=[],n;try{n=$v(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 Xr(n.program.body)){let s=i.type==="ExportNamedDeclaration"?i.declaration:i;if(s?.type==="VariableDeclaration")for(let a of Xr(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 Xr(r.elements).forEach((i,s)=>{let a=Of(i,`NAV_ITEMS[${s}]`,t);a&&o.push(a)}),{items:o,diagnostics:t}}function Of(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 Xr(e.properties)){if(l.type!=="ObjectProperty"||l.computed)continue;let d=Uv(l.key);d&&(r[d]=l.value)}let o=Jr(r.label),i=Jr(r.targetType);if(!o)return n.push({severity:"fatal",path:`${t}.label`,message:"label must be a static string"}),null;if(!i||!Tf.includes(i))return n.push({severity:"fatal",path:`${t}.targetType`,message:`targetType must be one of ${Tf.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 _f){if(r[l]===void 0)continue;let d=Jr(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))Kv.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 ${za.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=[];Xr(r.children.elements).forEach((d,f)=>{let m=Of(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=Jr(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=Jr(r.role);if(c!==void 0&&(Vv.includes(c)?s.role=c:n.push({severity:"warning",path:`${t}.role`,message:"role ignored: not link/cta"})),r.openInNewTab!==void 0){let l=Ff(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=Ff(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 Jv}from"@babel/parser";function zr(e){return Array.isArray(e)?e:[]}function Mf(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression";)t=t.expression;return t?.type==="ArrayExpression"?t:void 0}function Xv(e){let t;try{t=Jv(e,{sourceType:"module",plugins:["typescript","jsx"],tokens:!0})}catch{return{status:"unsupported"}}let n=[];for(let o of zr(t.program.body)){let i=o.type==="ExportNamedDeclaration"?o.declaration:o;if(i?.type==="VariableDeclaration")for(let s of zr(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=Mf(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 Ha(e,t){let n=Df(t);if(!n)return{status:"unsupported",source:e};let r=Xv(e);if(r.status!=="ok")return{status:r.status,source:e};let o=r.array;if(Wa(e).diagnostics.some(({severity:l})=>l==="fatal"))return{status:"unsupported",source:e};let s=[],a=l=>{let d=zr(l.elements);for(let[f,m]of d.entries()){if(Wv(m,n)){let g=d[f+1],h=d[f-1],b=m.start,E=m.end;if(typeof b!="number"||typeof E!="number")continue;if(g&&typeof g.start=="number")s.push({start:b,end:g.start});else if(h&&typeof h.end=="number")s.push({start:h.end,end:E});else{let v=/^\s*,/.exec(e.slice(E));s.push({start:b,end:v?E+v[0].length:E})}continue}let u=zv(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 zv(e){if(e.type==="ObjectExpression")for(let t of zr(e.properties)){if(t.type!=="ObjectProperty")continue;let n=t.key;if((n?.name??n?.value)==="children")return Mf(t.value)}}function Df(e){let t=e.trim();return t.startsWith("/")?t==="/"?t:t.replace(/\/+$/,""):null}function Wv(e,t){if(e.type!=="ObjectExpression")return!1;let n,r;for(let o of zr(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"&&Df(n??"")===t}import{estimateNavLabelWidth as m_}from"@vcp-dev/contracts";import{parse as y_}from"@babel/parser";var Gv="components/site/generated/",Wr=[".tsx",".ts",".jsx",".js"];function Lf(e){if(e.expectedUrlPath===Hv)return{ok:!1,code:"HOME_PAGE_LOCKED",message:"The homepage source is protected from deletion."};let t=new Set(Vr(Object.keys(e.files).map(h=>({path:h}))).map(h=>h.entryFile)),n=Object.entries(e.files).filter(([h,b])=>{let E=h.replace(/\\/g,"/");if(!t.has(E))return!1;let v=Xa(b,E);return v.found&&v.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=Ci({files:new Map(Object.entries(e.files))});for(let b of h)b.canonicalEntryFile===r&&o.add(b.entryFile)}catch(h){return{ok:!1,code:"SOURCE_DEPENDENCY_UNSAFE",message:h instanceof Error?h.message:"Invalid page template source."}}let i=Yv(e.files);if(!i.ok)return i.error;let s=i.graph,a=ek(o,s),c=tk(o,a,s),l=[...a].filter(h=>!c.has(h)).sort((h,b)=>h.localeCompare(b)),d=[...o,...[...c].sort((h,b)=>h.localeCompare(b))],f=new Set(d),m=d.map(h=>({operation:"delete",file:h})),u=[],g=[];for(let[h,b]of Object.entries(e.files))if(!f.has(h)){if(b.includes("NAV_ITEMS")){let E=Ha(b,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}`)}b.includes(e.expectedUrlPath)&&!b.includes("NAV_ITEMS")&&g.push(`preserved_link:${h}`)}return{ok:!0,edits:m,deletedFiles:d,updatedFiles:u,preservedSharedFiles:l,warnings:g}}function Yv(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")||!Zv(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(Qv(c))continue;let l=yn(r,c),d=qv(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 Zv(e){let t=e.toLowerCase();return Wr.some(n=>t.endsWith(n))}function Qv(e){return!!(/\.([a-z0-9]+)$/i.exec(e)&&!Wr.some(n=>e.endsWith(n)))}function qv(e,t){let n=e.replace(/\\/g,"/");return(Wr.some(o=>n.endsWith(o))?[n]:[...Wr.map(o=>`${n}${o}`),...Wr.map(o=>`${n}/index${o}`)]).find(o=>t.has(o))??null}function ek(e,t){let n=new Set,r=[...e].flatMap(o=>[...t.get(o)??[]]);for(;r.length>0;){let o=r.pop();!o.startsWith(Gv)||n.has(o)||(n.add(o),r.push(...t.get(o)??[]))}return n}function tk(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 Lp from"@babel/parser";import*as de from"@babel/types";import*as Ji from"node:path";import*as xe from"@babel/types";function Bf(e){if(e.path.isVariableDeclarator()){let n=e.path.get("init");return n?.isExpression()?{expressionPath:n}:null}if(!e.path.isIdentifier()||!e.path.parentPath?.isVariableDeclarator())return null;let t=e.path.parentPath.get("init");return t?.isExpression()?{expressionPath:t}:null}function Mt(e){if(e.path.isObjectPattern()||e.path.isArrayPattern())return Tn(e.path.node,e.identifier.name);if(e.path.isVariableDeclarator()){let n=e.path.node.id;if(xe.isObjectPattern(n)||xe.isArrayPattern(n))return Tn(n,e.identifier.name)}if(!e.path.isIdentifier())return!1;let t=e.path.parentPath;for(;t;){if(t.isAssignmentPattern()){let n=t.get("left");if(rk(e.path,n))return!0}if(t.isFunction()||t.isVariableDeclarator())return!1;t=t.parentPath}return!1}function Tn(e,t,n=!1){return xe.isIdentifier(e)?e.name===t&&n:xe.isObjectPattern(e)?e.properties.some(r=>xe.isObjectProperty(r)?Tn(r.value,t,n):Tn(r.argument,t,n)):xe.isArrayPattern(e)?e.elements.some(r=>{if(!r)return!1;let o=xe.isRestElement(r)?r.argument:r;return Tn(o,t,n)}):xe.isAssignmentPattern(e)?Tn(e.left,t,!0):xe.isRestElement(e)?Tn(e.argument,t,n):!1}function sr(e,t){if(e.path.isObjectPattern()){if(t){let r=It(e.path.node,t.base),[o,...i]=r??[];if(o?.kind==="property")return{propName:o.name,remainingPath:[...i,...t.path],hasDefault:Mt(e)}}return t?{propName:t.base,remainingPath:t.path,hasDefault:Mt(e)}:null}if(e.path.isVariableDeclarator()){let r=e.path.get("init");if(r?.isExpression()){let o=jf(r),i=!1,s=o?o.initBinding&&Ga(o.initBinding)?(i=Mt(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=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||Mt(e)}}}}let n=sk(e);if(n){let r=nk(n,e);if(r){let[s,...a]=r.path;return!s||s.kind!=="property"?null:{propName:s.name,remainingPath:[...a,...t?.path??[]],hasDefault:r.hasDefault||Mt(e)}}if(n.findParent(s=>s.isVariableDeclarator()))return null;let o=ok(e);if(o){let[s,...a]=o;return!s||s.kind!=="property"?null:{propName:s.name,remainingPath:[...a,...t?.path??[]],hasDefault:Mt(e)}}let i=Hr(n.node);return i?{propName:i,remainingPath:t?.path??[],hasDefault:Mt(e)}:null}if(Ga(e)){let[r,...o]=t?.path??[];return!r||r.kind!=="property"?null:{propName:r.name,remainingPath:o,hasDefault:Mt(e)}}return null}function nk(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=jf(r);if(!o)return null;let{initBinding:i,initPathPrefix:s}=o;if(!i)return null;let a=!1,c=Ga(i)?(a=Mt(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=It(n.node.id,t.identifier.name);return l?{path:[...c,...l],hasDefault:a||Mt(t)}:null}function jf(e){if(e.isIdentifier())return{initBinding:e.scope.getBinding(e.node.name),initPathPrefix:[]};if(!e.isMemberExpression())return null;let t=ak(e.node);return t?{initBinding:e.scope.getBinding(t.base),initPathPrefix:t.path}:null}function Ga(e){return e.path.isIdentifier()&&e.path.key===0&&Array.isArray(e.path.container)&&e.path.parentPath?.isFunction()===!0}function rk(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function ok(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 $f(e,t,n){if(e.path.isVariableDeclarator()){let a=e.path.get("id");if(!Array.isArray(a)&&(a.isObjectPattern()||a.isArrayPattern())){let c=wi(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=Hr(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=ik(e);if(!r)return null;let o=r.parentPath;if(!o?.isObjectProperty())return null;let i=Hr(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 wi(e,t){if(e.isObjectPattern()){for(let n of e.get("properties"))if(n.isObjectProperty()){let r=Hr(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=wi(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=wi(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=wi(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=Hr(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 ik(e){if(!e.path.isIdentifier())return null;let t=e.path.parentPath;return t?.isAssignmentPattern()&&t.node.left===e.path.node?t:null}function sk(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 Hr(e){return e.computed?null:xe.isIdentifier(e.key)?e.key.name:xe.isStringLiteral(e.key)?e.key.value:null}function ak(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 Xf from"@babel/parser";import Qa from"@babel/traverse";import*as ar from"@babel/types";import*as ce from"@babel/types";function Ti(e,t=[]){if(e.isIdentifier()){let n=e.scope.getBinding(e.node.name);return n?Pi(n,t):null}if(e.isMemberExpression()){let n=pk(e.node),r=ck(e.node);if(!n||r===null)return null;let o=e.scope.getBinding(n);return o?Pi(o,[...r,...t]):null}return e.isAwaitExpression()||Za(e.node)?an(gk(e.node),t,"awaited or fetched expression"):null}function ck(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 Pi(e,t=[]){let n=lk(e,t);if(n)return n;let r=uk(e,t);if(r)return r;let o=dk(e,t);return o||null}function Yr(e){return e?.kind==="api-source"}function lk(e,t){if(e.path.isVariableDeclarator()&&ce.isIdentifier(e.path.node.id)){let s=e.path.get("init");if(s?.isCallExpression()&&Ya(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()&&ce.isObjectPattern(e.path.node.id)){let s=e.path.node.id.properties.find(c=>ce.isObjectProperty(c)&&Uf(c)==="data"&&Gr(c.value,e.identifier.name)),a=e.path.get("init");if(s&&a?.isCallExpression()&&Ya(a.node))return an(e.identifier.name,t,"query hook data binding")}let n=fk(e);if(!n||Uf(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()||!Ya(i.node)?null:an(e.identifier.name,t,"query hook data binding")}function uk(e,t){if(e.path.isVariableDeclarator()&&ce.isArrayPattern(e.path.node.id)){let a=e.path.get("init");if(!a?.isCallExpression()||!Kf(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:Vf(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()||!Kf(o.node)||n.node.elements.findIndex(a=>a===e.path.node)!==0)return null;let s=n.node.elements[1];return ce.isIdentifier(s)&&Vf(e,s.name)?an(e.identifier.name,t,"state setter is updated by API data"):null}function dk(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"):Za(r.node)?an(e.identifier.name,t,"fetch-backed binding result"):null:null}function fk(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 Gr(e,t){return ce.isIdentifier(e)?e.name===t:ce.isAssignmentPattern(e)?Gr(e.left,t):ce.isObjectPattern(e)?e.properties.some(n=>ce.isObjectProperty(n)?Gr(n.value,t):Gr(n.argument,t)):ce.isArrayPattern(e)?e.elements.some(n=>!!n&&Gr(ce.isRestElement(n)?n.argument:n,t)):!1}function Vf(e,t){let n=!1,r=!1;return e.scope.path.traverse({CallExpression(i){Za(i.node)&&(n=!0),(mk(i.node.callee,t)||i.node.arguments.some(s=>ce.isIdentifier(s)&&s.name===t))&&(r=!0)}}),n&&r}function Ya(e){let t=Fi(e.callee);return t==="useQuery"||t==="useSWR"||t==="useSuspenseQuery"}function Kf(e){return Fi(e.callee)==="useState"}function Za(e){return Ai(e,t=>ce.isCallExpression(t)&&Fi(t.callee)==="fetch")}function pk(e){let t=e;for(;ce.isMemberExpression(t);)t=t.object;return ce.isIdentifier(t)?t.name:null}function Uf(e){return e.computed?null:ce.isIdentifier(e.key)?e.key.name:ce.isStringLiteral(e.key)?e.key.value:null}function Fi(e){return ce.isIdentifier(e)?e.name:ce.isMemberExpression(e)&&ce.isIdentifier(e.property)?e.property.name:null}function mk(e,t){return Ai(e,n=>ce.isIdentifier(n)&&n.name===t)}function Ai(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)&&Ai(i,t))return!0;continue}if(ce.isNode(o)&&Ai(o,t))return!0}return!1}function gk(e){return ce.isIdentifier(e)?e.name:ce.isCallExpression(e)?Fi(e.callee)??"api":ce.isAwaitExpression(e)?"awaited-api":"api"}function an(e,t,n){return{kind:"api-source",readonly:!0,sourceId:e,displayPath:hk(e,t),reason:n}}function hk(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}var zf=typeof Qa=="function"?Qa:Qa.default;function Wf(e,t){let n=Gf(e);if(!n)return{allowed:!0};let r=!1;return zf(n,{CallExpression(o){if(!Yf(o.node,t.sourceRange)||!yk(o.node))return;let i=o.get("callee");if(!i.isMemberExpression())return;let s=i.get("object");Array.isArray(s)||!s.isExpression()||Yr(Ti(s))&&(r=!0,o.stop())}}),r?{allowed:!1,reason:"Cannot add data-backed items to a dynamic API list"}:{allowed:!0}}function Hf(e,t){let n=Gf(e);if(!n)return{allowed:!0};let r=!1;return zf(n,{JSXExpressionContainer(o){Yf(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 Gf(e){try{return Xf.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function yk(e){let t=e.callee;return ar.isMemberExpression(t)&&ar.isIdentifier(t.property)&&t.property.name==="map"}function Yf(e,t){let n=e.loc;return n?Jf({line:n.start.line,column:n.start.column},{line:t.startLine,column:t.startColumn})>=0&&Jf({line:n.end.line,column:n.end.column},{line:t.endLine,column:t.endColumn})<=0:!1}function Jf(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 Zf from"@babel/parser";import qa from"@babel/traverse";import*as Te from"@babel/types";import*as cr from"node:path";var Ct=typeof qa=="function"?qa:qa.default;function Je(e){try{return Zf.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function ec(e){return e.computed?Te.isStringLiteral(e.key)||Te.isNumericLiteral(e.key)?String(e.key.value):null:xk(e.key)}function xk(e){return Te.isIdentifier(e)?e.name:Te.isStringLiteral(e)||Te.isNumericLiteral(e)?String(e.value):null}function Fn(e){return Te.isParenthesizedExpression(e)||Te.isTSAsExpression(e)||Te.isTSSatisfiesExpression(e)||Te.isTSNonNullExpression(e)||Te.isTSTypeAssertion(e)?Fn(e.expression):Te.isExpression(e)?e:null}function tc(e){if(Te.isIdentifier(e))return[e.name];if((Te.isMemberExpression(e)||Te.isOptionalMemberExpression(e))&&!e.computed&&Te.isIdentifier(e.property)){let t=Fn(e.object),n=t?tc(t):null;return n?[...n,e.property.name]:null}return null}function _n(e,t){return t.startsWith("@/")?t.slice(2).replace(/\\/g,"/"):t.startsWith(".")?cr.normalize(cr.join(cr.dirname(e),t)).replace(/\\/g,"/"):t}function st(e,t){return _i(e)===_i(t)}function _i(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 ep(e,t,n){let r=op(e,t);if(ip(e,r),sp(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){up(s,r)&&o.push(s)}}),o.length!==1?{ok:!1,reason:"Cannot move prop-backed repeat child without a single unambiguous component call site"}:Oi(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 tp(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 bk(i,n))o=r(s)||o}return[...n.values()]}function bk(e,t){let n=[],r=Sk(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=Zr(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=_n(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())st(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=>st(l.file,i)&&On(l.namespace,a));if(c.length>0){let l=cn(s.exported);for(let d of c){let f=Zr(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=Zr(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=_n(e.file,o.source.value),s=o.exported;if(s){let a=cn(s);for(let c of t.values())st(c.file,i)&&n.push({file:e.file,namespace:nc(a,c.namespace),exportName:c.exportName});continue}for(let a of t.values())st(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 On(e,t){return e===t||e?.startsWith(`${t}.`)===!0}function Zr(e,t,n){return!On(e,t)||!e?null:e===t?n:`${n}${e.slice(t.length)}`}function Sk(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=_n(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=>st(d.file,s)&&On(d.namespace,"default"));for(let d of l){let f=Zr(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=>st(f.file,s)&&On(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())st(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=Fn(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=Zr(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`${_i(e.file)}#${t}`}function cn(e){return J.isIdentifier(e)?e.name:e.value}function np(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 oc(e){let t=Ek(e),n=[],r=sp(e.ast,t);return Ct(e.ast,{JSXElement(o){st(e.file,e.sourceFile)&&Oi(o)===e.sourceComponent||up(o,t)&&n.push({file:e.file,path:o})}}),{callSites:n,hasUnsafeReference:r}}function rp(){return{localBindings:new Set,namespaceMembers:new Map,hasUnsupportedAlias:!1}}function op(e,t){let n=rp();return Ct(e,{Program(r){let o=r.scope.getBinding(t);o&&n.localBindings.add(o),r.stop()}}),n}function Ek(e){let t=rp();return st(e.file,e.sourceFile)&&vk(t,op(e.ast,e.sourceComponent)),Ct(e.ast,{ImportDeclaration(n){let r=n.node,o=r.source.value;if(typeof o!="string")return;let i=_n(e.file,o),s=e.componentIdentities.filter(a=>st(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=>On(d.namespace,"default"));if(l.length>0){let d=t.namespaceMembers.get(c)??new Set;for(let f of l){let m=qf(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=>On(f.namespace,l));if(d.length>0){let f=t.namespaceMembers.get(c)??new Set;for(let m of d){let u=qf(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)}}}}}),ip(e.ast,t),t}function vk(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 ip(e,t){Ct(e,{VariableDeclarator(n){if(!n.node.init)return;let r=Fn(n.node.init);if(r){if(J.isIdentifier(n.node.id)){let o=Mn(r,t,n),i=n.scope.getBinding(n.node.id.name);o&&i&&rc(t,i,o);return}if(J.isObjectPattern(n.node.id)){let o=Mn(r,t,n);o?.unsupported||o?.local?t.hasUnsupportedAlias=!0:o&&o.namespaceMembers.size>0&&lp(n.node.id,o.namespaceMembers,t,n)}}}})}function sp(e,t){if(t.hasUnsupportedAlias)return!0;let n=!1;return Ct(e,{ReferencedIdentifier(r){if(n){r.stop();return}kk(r)||!r.isIdentifier()||!ap(r,t)||Ik(r,t)||Ck(r)||(n=!0,r.stop())}}),n}function kk(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 ap(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)&&Mn(r.node,t,r)?r:null}function Ik(e,t){let n=e.findParent(c=>c.isVariableDeclarator());if(!n?.isVariableDeclarator())return!1;let r=n.get("init");if(!r?.isExpression()||!Qf(e,r))return!1;let o=ap(e,t);if(!o)return!1;if(Fn(r.node)===o.node)return!!Mn(r.node,t,r);let s=e.findParent(c=>c.isObjectProperty());if(!s?.isObjectProperty())return!1;let a=s.get("value");return a.isExpression()&&Qf(e,a)&&!!Mn(a.node,t,a)}function Ck(e){let t=e.parentPath;return t?.isExportDefaultDeclaration()&&t.node.declaration===e.node?!0:!!(t?.isExportSpecifier()&&t.node.local===e.node)}function Qf(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function Mn(e,t,n){let r=Fn(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 Rk(r,t,n);let o=tc(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?cp(s,o.slice(1).join(".")):null}function Rk(e,t,n){let r=new Set,o=!1;for(let i of e.properties){if(!J.isObjectProperty(i))continue;let s=ec(i);if(!s||!J.isExpression(i.value)){J.isExpression(i.value)&&(o||=Mn(i.value,t,n)!==null);continue}let a=Mn(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 cp(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 rc(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 lp(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&&rc(n,c,{local:!1,namespaceMembers:new Set(t),unsupported:!1})}else n.hasUnsupportedAlias=!0;continue}if(!J.isObjectProperty(o))continue;let i=ec(o);if(!i){n.hasUnsupportedAlias=!0;continue}let s=cp(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&&rc(n,c,s);continue}if(J.isObjectPattern(a)&&s.namespaceMembers.size>0){lp(a,s.namespaceMembers,n,r);continue}n.hasUnsupportedAlias=!0}}function qf(e,t){if(!On(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 up(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=dp(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 dp(e){if(J.isJSXIdentifier(e))return[e.name];if(J.isJSXMemberExpression(e)){let t=dp(e.object);return t?[...t,e.property.name]:null}return null}function Oi(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 fp(e,t){let n=Je(e);if(!n||!t.tag||!t.importedFrom||!t.exportName)return Number.POSITIVE_INFINITY;let r=oc({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 Dt(e,t){let n=ge(e);return!!(n&&at(t,n))}function at(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:Mi(e,t)}function dr(e,t){let n=ge(t);return n?e.slice(n.start,n.end):""}function pp(e,t){return e.start===t.start&&e.end===t.end}function Mi(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 Di(e,t){return ic(e,t).length>0}function Li(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()&&!Nk(o,n,r)))return!0;o=o.parentPath}return!1}function Nk(e,t,n){let r=ge(e.node.consequent);if(r&&at(r,t)&&!at(r,n))return!1;let o=e.node.alternate?ge(e.node.alternate):null;return!(o&&at(o,t)&&!at(o,n))}function ic(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()&&sc(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 sc(e){return e==="&&"||e==="||"||e==="??"}function mp(e,t){let n=ge(e.consequent);if(n&&at(n,t))return n;let r=ge(e.alternate);return r&&at(r,t)?r:null}function gp(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=np(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=tp(r,{file:e.sourceFile,exportName:n.exportName}),i=[];for(let a of r){let c=oc({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!st(s.file,e.targetFile)||Oi(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 _k}from"@vcp-dev/contracts";function Bi(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 Qr();let a=s.target,c=a.locator;if(a.sourceKind==="repeat-template"){let l=o?.instanceIndex;if(l===void 0)return Qr();let d=wk(a,l,o?.instanceCount);if(!d)return Qr();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"?Qr():{ok:!0,target:{kind:"jsx-attribute"}}}function Qr(){return{ok:!1,code:"unsupported-binding",reason:"Property does not have a safe typed binding write target for this scope and operation"}}function wk(e,t,n){if(!e.locator||!Number.isInteger(t)||t<0)return null;let r=e.collectionPathMap?.length??e.collectionIndexMap?.length;if(r!==void 0&&(t>=r||n!==void 0&&n!==r))return null;let o=e.collectionPathMap?.[t];if(o)return{...e.locator,path:o};let i=e.locator.path??[],s=i.findLastIndex(c=>c.kind==="index");if(s<0)return null;let a=i.map((c,l)=>l===s&&c.kind==="index"?{kind:"index",index:e.collectionIndexMap?.[t]??t}:c);return{...e.locator,path:a}}import*as Lt from"@babel/types";import{SiteEditSetPropsParamsSchema as Pk}from"@vcp-dev/contracts";function hp(e){let t=e.changes??(e.change?[e.change]:[]);if(!Pk.safeParse({kind:"set-props",scope:"selection",changes:t}).success)return qr("invalid-change","Repeat property changes are invalid");if(t.length!==1||t[0].name!==e.target.propertyName)return qr("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=Ce(e.source,"value");if(!o.ok)return qr("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 qr("unsupported-object",`Repeat item ${s} is not a writable object expression`);let l=s===e.target.sourceItemIndex?Ak(r):Tk(c.match.path.node,r.name);if(!l)return qr("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 Ak(e){return e.operation==="set"?{kind:"value",value:e.value}:{kind:"undefined"}}function Tk(e,t){let n=e.properties.filter(i=>Lt.isObjectProperty(i)&&Fk(i.key)===t);if(n.length>1)return null;let r=n[0];if(!r)return{kind:"undefined"};if(!Lt.isExpression(r.value))return null;let o=Ot(r.value);return o.status==="undefined"?{kind:"undefined"}:o.status!=="resolved"?null:{kind:"value",value:o.value}}function Fk(e){return Lt.isIdentifier(e)?e.name:Lt.isStringLiteral(e)?e.value:Lt.isNumericLiteral(e)?String(e.value):null}function qr(e,t){return{ok:!1,errorCode:e,reason:t}}function yp(e){if(e.change.name!=="className"&&e.change.name!=="class")return eo("unsupported-owner",`No specialized property owner is available for '${e.change.name}'`);let t=e.classNameSource;if(!t||t.filePath!==e.node.file)return eo("owner-source-unavailable","className source details are unavailable for the selected node");if(e.change.name==="class"&&t.sourceKind==="missing")return eo("owner-source-unavailable","The class alias requires an existing className source");if(t.sourceKind==="expression")return eo("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 eo("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 eo(e,t){return{ok:!1,errorCode:e,reason:t}}async function bp(e){let t=_k.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 Ok(e,r);if(o){if(!o.ok)return ln("owner-plan-failed",o.reason);xp(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(Lk(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=Bi({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"){ac(n,{type:"update-value",order:n.length,file:c.file,locator:c.locator,value:r.value});continue}if(c.kind==="repeat-property"){let l=hp({source:e.getFileContent(c.target.sourceFile),target:c.target,changes:[r]});if(!l.ok)return ln("repeat-target-failed",l.reason);xp(n,l.steps);continue}ac(n,{type:"set-property-changes",order:n.length,file:e.node.file,locator:Mk(e.node),scope:e.scope,changes:[r]})}return n.forEach((r,o)=>{r.order=o}),Dk(n)?ln("step-conflict","Property changes resolve to conflicting write steps"):{ok:!0,steps:n}}async function Ok(e,t){return t.name!=="className"&&t.name!=="class"?null:yp({node:e.node,change:t,classNameSource:e.classNameSource})}function Mk(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 Dk(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 xp(e,t){for(let n of t)ac(e,{...n,order:e.length})}function ac(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 Lk(e,t){if(t.operation!=="set"||e.status!=="direct")return!1;let n=e.attribute?.resolution;return n?.status==="resolved"?cc(n.value,t.value):e.attribute?.source===null&&e.attribute.value===t.value}function cc(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)=>cc(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=>cc(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 G from"@babel/types";function lc(e,t,n){let r=bt(t,n);return r?Bt(e,r):null}function Bt(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=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:G.isOptionalMemberExpression(c)&&c.optional?"?.map":".map",collectionNeedsParens:ji(d.node),callbackPath:r,collectionPath:d}}function to(e,t){return!!(e&&t&&e.callStart===t.callStart&&e.callEnd===t.callEnd&&e.callbackStart===t.callbackStart&&e.callbackEnd===t.callbackEnd)}function Bk(e,t){let n=ge(e.node);return n?jk(t).some(r=>{let o=ge(r);return r===e.node||!!(o&&o.start===n.start&&o.end===n.end)}):!1}function jk(e){let t=e.callbackPath.node.body;return G.isBlockStatement(t)?un(t.body):dn(t)}function un(e){let t=[];for(let n of e){if(G.isReturnStatement(n)){n.argument&&t.push(...dn(n.argument));continue}if(G.isBlockStatement(n)){t.push(...un(n.body));continue}if(G.isIfStatement(n)){let r=G.isBlockStatement(n.consequent)?n.consequent.body:[n.consequent];if(t.push(...un(r)),n.alternate){let o=G.isBlockStatement(n.alternate)?n.alternate.body:[n.alternate];t.push(...un(o))}continue}if(G.isSwitchStatement(n)){for(let r of n.cases)t.push(...un(r.consequent));continue}G.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 G.isJSXElement(e)?$k(e)?Sp(e.children):[e]:G.isJSXFragment(e)?Sp(e.children):G.isParenthesizedExpression(e)||G.isTSAsExpression(e)||G.isTSSatisfiesExpression(e)||G.isTSNonNullExpression(e)||G.isTSTypeAssertion(e)?dn(e.expression):G.isConditionalExpression(e)?[...dn(e.consequent),...dn(e.alternate)]:G.isLogicalExpression(e)&&sc(e.operator)?dn(e.right):[]}function Sp(e){return e.flatMap(t=>G.isJSXElement(t)||G.isJSXFragment(t)?dn(t):G.isJSXExpressionContainer(t)&&(G.isJSXElement(t.expression)||G.isJSXFragment(t.expression)||G.isConditionalExpression(t.expression)||G.isLogicalExpression(t.expression))?dn(t.expression):[])}function $k(e){let t=e.openingElement.name;return G.isJSXIdentifier(t)?t.name==="Fragment":G.isJSXMemberExpression(t)&&t.property.name==="Fragment"}function Ep(e,t){return!!(e&&t&&e.callbackStart<t.callbackStart&&e.callbackEnd>t.callbackEnd)}function ji(e){return!(G.isIdentifier(e)||G.isThisExpression(e)||G.isMemberExpression(e)||G.isOptionalMemberExpression(e)||G.isCallExpression(e)||G.isOptionalCallExpression(e))}function vp(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 fr(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:Mi(n,t);if(!o)return t.isRepeatItemRoot===!0;let i=Bt(e,o);return i?Bk(o,i):t.isRepeatItemRoot===!0}function kp(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:Mi(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 uc(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 Vk(e,t){let n=ge(e.node);if(!n)return[];let r=new Set,o=(i,s)=>{let a=s.scope.getBinding(i);!a||Dt(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=uc(i.node.name);s&&o(s,i)}}),[...r].sort()}function dc(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=Ar(o.match.path,i.match.path);if(Di(s,i.match.path))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let a=Vk(s,i.match.path);return a.length>0?{ok:!1,bindingNames:a}:{ok:!0}}function Cp(e){let t=e;for(;ve.isTSQualifiedName(t);)t=t.left;return ve.isIdentifier(t)?t.name:null}function no(e,t){e.isIdentifier()&&e.isReferencedIdentifier()&&t(e),e.traverse({ReferencedIdentifier(n){n.isIdentifier()&&t(n)}})}function $i(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 fc(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=Ip(e),i=Ip(t);if(!o||!i||!pp(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=mp(s.node,n);if(a&&!at(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&&at(a,n)&&!at(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())&&vp(s)){let a=ge(s.node.body)??ge(s.node);if(a&&!at(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 Ip(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 fn(e,t,n){return n.scope.getBinding(t)===e}function pc(e,t,n,r={}){if(!r.preserveConditionalBoundary&&Di(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=>$i(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||Dt(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=uc(c.node.name);l&&a(l,c)}}),s.size>0?{ok:!1,bindingNames:[...s].sort()}:{ok:!0}}function mc(e,t,n){let r=ge(e.node);if(!r)return{ok:!0};let o=new Set(n.callbackPath.node.params.flatMap(s=>$i(s)).map(s=>n.callbackPath.scope.getBinding(s)?.path.node).filter(Boolean)),i=new Set;return no(e,s=>{let a=s.scope.getBinding(s.node.name);!a||Dt(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 Rp(e,t){let n=new Set(e.callbackPath.node.params.flatMap(a=>$i(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=Cp(l);d&&o(d,c)}}});return r.size>0?{ok:!1,bindingNames:[...r].sort()}:{ok:!0}}function gc(e,t){let n=ge(e.node),r=new Set;return no(e,o=>{let i=o.scope.getBinding(o.node.name);i&&(n&&Dt(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 Np(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 wp(e,t){return{...e,callbackParams:t}}function hc(e,t){return`${e.collectionNeedsParens?`(${e.collectionExpression})`:e.collectionExpression}${e.mapOperator}((${e.callbackParams.join(", ")}) => ${t})`}function ro(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 Pp(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 Dn(e){return{file:e.file,component:e.component}}function Kk(e){return e.target.kind==="node"?e.target.key:null}function Uk(e){return"kind"in e}function Vi(e){return!Uk(e)}function Ec(e,t){let n=Ji.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=Ji.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function yc(e,t){let n=e.getFileContent(t.file);if(!n)return;let r=Ft(n,he(t));if(r.ok)return n.slice(r.match.start,r.match.end)}function kc(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 Jk(e){if(e.isNumericLiteral())return!0;if(!e.isUnaryExpression({operator:"-"}))return!1;let t=e.get("argument");return!Array.isArray(t)&&t.isNumericLiteral()}function Xk(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 xc(e){return e==="Cannot edit repeat-backed child node structure with a generic node operation"}function zk(e){let t=ep(e.ast,e.sourceNode.component,e.targetParent.component);if(!t.ok)return{ok:!1,reason:t.reason};let n=fc(t.path,e.targetParentPath);if(!n.ok)return{ok:!1,reason:n.reason};let r=Wk({source:e.source,sourceContext:e.sourceContext,callSitePath:t.path,targetParentPath:e.targetParentPath});if(!r.ok)return r;let o=Bp(r.collectionExpression);return{ok:!0,context:{...e.sourceContext,collectionExpression:r.collectionExpression,collectionNeedsParens:o?ji(o):!0}}}function Wk(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||Dt(a.path.node,t))return;let c=Yk(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=Qk(e.callSitePath,c.propName,e.source);if(!l.ok){o=l.reason;return}let d=Hk(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=gc(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:qk(e.source,t,[...n.values()])}}function Hk(e,t){if(t.length===0)return e;let n=Bp(e);if(!n)return null;let r=ji(n)?`(${e})`:e;for(let o of t){if(o.kind==="property"){r=Gk(o.name)?`${r}.${o.name}`:`${r}[${JSON.stringify(o.name)}]`;continue}r=`${r}[${o.index}]`}return r}function Gk(e){return/^[$A-Z_a-z][$\w]*$/.test(e)}function Yk(e,t,n){let r=Zk(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 Zk(e,t){let n=e.parentPath;if(!n||!n.isMemberExpression()&&!n.isOptionalMemberExpression()||n.node.object!==e.node||!Dt(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 Qk(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=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 qk(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 Bp(e){try{let n=Lp.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 eI(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||Dt(s.path.node,t))return;let a=Ap(s,e.sourceFile,e.targetFile);if(a){let c=e.targetParentPath.scope.getBinding(a.localName);if(c){let d=Ap(c,e.targetFile,e.targetFile);(!d||d.moduleFile!==a.moduleFile||!tI(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 no(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 tI(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 Ap(e,t,n){let r=nI(e),o=r?.parentPath;if(!r||!o?.isImportDeclaration())return null;let i=o.node.source.value;if(typeof i!="string")return null;let s=_n(t,i),a=i.startsWith(".")?Ec(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 nI(e){let t=e.path;for(;t&&!t.isImportDeclaration();){if(t.isImportSpecifier()||t.isImportDefaultSpecifier()||t.isImportNamespaceSpecifier())return t;t=t.parentPath}return null}function Tp(e,t,n,r){let o=ic(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=rI(a.conditionPath,c);if(s.push(a.conditionPath),a.kind==="logical"){i=`${l} ${a.operator} ${iI(i)}`;continue}i=a.branch==="consequent"?`${l} ? ${i} : null`:`${l} ? null : ${i}`}return{sourceJsx:i,conditionPaths:s}}function rI(e,t){return oI(e.node)?t:`(${t})`}function oI(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 iI(e){return e.trim().startsWith("<")?e:`(${e})`}var sI={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 Ki(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=sI[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 aI(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 cI(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 Fp(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 _p(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n+=1;return`${e}${n}`}function lI(e,t){if(!e.component)return{localName:"Component"};let n=e.component,r=kc(e),o=Je(t);if(n.exportName!=="default"){let a=o?cI(o,n.source,n.exportName):null;if(a)return{localName:a};let c=o?_p(r,Fp(o)):r;return{localName:c,importStep:bc(e,c)}}if(!o)return{localName:r,importStep:bc(e,r)};let i=aI(o,n.source);if(i)return{localName:i};let s=_p(r,Fp(o));return{localName:s,importStep:bc(e,s)}}function uI(e,t){if(e.kind==="native-tag")return e.text?`<${e.tag}>${e.text}</${e.tag}>`:`<${e.tag} />`;let n=t??kc(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 dI(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?fI(e.props):void 0;return{kind:e.kind,component:{source:e.component.source,exportName:e.component.exportName},...t?{props:t}:{}}}function fI(e){return Object.fromEntries(Object.entries(e).filter(t=>vc(t[1])))}function vc(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(vc):typeof e=="object"?Object.values(e).every(vc):!1}function bc(e,t=kc(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 Op(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 pI(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 Ic(e,t=e.path){return{kind:"value",root:e.root,path:t&&t.length>0?t:void 0,expectedRange:e.expectedRange}}function oo(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:Ic(e,t.slice(0,n)),index:r.index}}return null}function Sc(e,t){return e.locator?e.collectionPathMap?.[t]?Ic(e.locator,e.collectionPathMap[t]):oo(e.locator)?gI(e.locator,hI(t,e.collectionIndexMap)):null:null}function mI(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:jp(o,t)}function jp(e,t){let[n,...r]=e;if(!n)return t;if(n.kind!=="property")return;let o=jp(r,t);return o===void 0?void 0:{[n.name]:o}}function gI(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},Ic(e,i)}return null}function hI(e,t){return t?.[e]??e}function Mp(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 yI(e,t){return xI(e.root,t.root)&&SI(e.path??[],t.path??[])}function xI(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&&bI(e.sourceRange,t.sourceRange)}}function bI(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function SI(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 Ui=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(!Vi(r.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};let o=Op(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=Kk(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):Dp(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 Dp(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?bp({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=Sc(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=Sc(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(!Jk(a.match.path))return{ok:!0,value:r};let c=Xk(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=Sc(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=oo(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=ro(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||fp(n,t)>1)return null;let r=Ec(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(!Vi(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=ro(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=Wf(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=Ki(r,n.params.node);if(g)return{ok:!1,errorCode:"unsupported-operation",reason:g};let h=[],b=0,E=n.params.node.kind==="component-call"?lI(n.params.node,this.graph.getFileContent(r.file)):void 0,v=E?.importStep;return v&&h.push({order:b++,file:r.file,type:"add-import",moduleSpecifier:v.moduleSpecifier,imports:v.imports}),h.push({order:b++,file:r.file,type:"insert-child",parentLocator:he(r),node:{jsx:uI(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(!Vi(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:dI(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(!Vi(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=oo(a.locator);if(!c)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child requires an array-backed target"};let l=mI(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"?Mp(0,a.collectionIndexMap):Mp(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=ro(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:")||kp(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=bt(l,r),f=bt(l,o);if(!d||!f)return null;let m=Bt(c,d),u=Bt(c,f);if(!to(m,u))return null;if(a&&(s==="before"||s==="after")){let h=bt(l,a),b=h?Bt(c,h):null;if(!to(m,b))return null}if(Li(d,f))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child across statement-level conditional branches"};let g=dc(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:Dn(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=bt(l,r),f=bt(l,o);if(!d||!f)return null;let m=Bt(c,d);if(!m)return null;let u=Bt(c,f);if(to(m,u))return null;if(u&&!Ep(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 I=lc(c,l,a);if(u&&!to(u,I)||!u&&I)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 I=Ki(o,{kind:"native-tag",tag:r.tag});if(I)return{ok:!1,errorCode:"unsupported-operation",reason:I}}let g=yc(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(Li(d,f))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let h=Tp(c,d,f,g);for(let I of h.conditionPaths){let R=mc(I,f,m);if(!R.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its condition depends on bindings outside the target scope: ${R.bindingNames.join(", ")}`}}let b=pc(d,f,m,{preserveConditionalBoundary:h.conditionPaths.length>0});if(!b.ok)return{ok:!1,errorCode:"unsupported-operation",reason:b.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${b.bindingNames.join(", ")}`};let E=Rp(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 v=m;if(r.component!==o.component){let I=zk({source:c,ast:l,sourceContext:m,sourceNode:r,targetParent:o,targetParentPath:f});if(!I.ok)return{ok:!1,errorCode:"unsupported-operation",reason:I.reason};v=I.context}else{let I=gc(m.collectionPath,f);if(!I.ok)return{ok:!1,errorCode:"unsupported-operation",reason:I.reason??`Cannot move repeat-backed child because the repeat collection is not visible at the target: ${I.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:hc(v,h.sourceJsx),selectionContext:Dn(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=gp({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=fc(m.callSitePath,g);if(!h.ok)return{ok:!1,errorCode:"unsupported-operation",reason:h.reason};let b=Bt(c,u);if(!b)return null;if(Bt(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")&&lc(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=Ki(o,{kind:"native-tag",tag:r.tag});if(O)return{ok:!1,errorCode:"unsupported-operation",reason:O}}let v=yc(this.graph,r);if(!v)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(Li(u,g))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let I=Tp(c,u,g,v);for(let O of I.conditionPaths){let D=mc(O,g,b);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 R=pc(u,g,b,{preserveConditionalBoundary:I.conditionPaths.length>0});if(!R.ok)return{ok:!1,errorCode:"unsupported-operation",reason:R.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${R.bindingNames.join(", ")}`};let A=eI({sourceFile:r.file,targetFile:o.file,sourceContext:b,targetParentPath:g});if(!A.ok)return{ok:!1,errorCode:"unsupported-operation",reason:A.reason};let T=Np(b);if(!T.ok)return{ok:!1,errorCode:"unsupported-operation",reason:T.reason};let C=wp(b,T.callbackParams),P=[{order:0,file:r.file,type:"remove-node",locator:he(r),removeWhitespace:!0}];for(let O of A.imports)P.push({order:P.length,file:o.file,type:"add-import",moduleSpecifier:O.moduleSpecifier,imports:O.imports});return P.push({order:P.length,file:o.file,type:"insert-jsx-expression-child",parentLocator:he(o),expression:hc(C,I.sourceJsx),placement:s,anchorLocator:a?he(a):void 0,selectionContext:Dn(o)}),this.buildPlan(t,n,P,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 I=n.params.target,R=this.graph.getNode(I.anchorKey);if(!R||r.file!==R.file||r.component!==R.component)return{ok:!1,errorCode:"locator-miss",reason:"Source sibling move requires a sibling in the same component file"};let A=this.graph.getFileVersion(r.file);if(n.documentVersion!==A)return{ok:!1,errorCode:"stale-version",reason:`Document version ${n.documentVersion} is stale or otherwise does not match source sibling file version (current: ${A})`};let T=this.graph.getFileContent(r.file),C=Je(T),P=C?bt(C,r):null,O=C?bt(C,R):null,D=P?.parentPath,U=O?.parentPath;if(!P||!O||!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:I.relation,anchorLocator:he(R),selectionContext:Dn(r)}],o):{ok:!1,errorCode:"locator-miss",reason:"Source Fragment has no stable source range"}}let i=Op(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(pI(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 I=n.params.target.relation,R=i.anchorNode&&(I==="before"||I==="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:I,anchorSourceId:R?.kind==="external-entry"?R.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=ro(r,c,m);if(u&&!xc(u)&&!Pp(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 I=c,R=await this.graph.getTextWriteTarget(f.key,0);if(I?.kind==="value-binding"&&R?.kind==="value-binding"&&I.locator&&R.locator){let A=oo(I.locator),T=oo(R.locator);if(A&&T&&I.file===R.file&&yI(A.locator,T.locator)){let C=A.index,P=T.index,O=d==="before"?P-(C<P?1:0):P+(C<P?0:1);return this.buildPlan(t,n,[{order:0,file:I.file,type:"move-array-item",locator:A.locator,fromIndex:C,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=xc(u)?u:g;if(h&&xc(h)){let I=this.planRepeatTemplateInternalMove(t,n,r,s,o,d,f);if(I)return I;let R=this.planRepeatTemplateHoistMove(t,n,r,s,o,d,f);if(R)return R;let A=this.planCrossFileRepeatTemplateHoistMove(t,n,r,s,o,d,f);return A||{ok:!1,errorCode:"unsupported-operation",reason:h}}if(g)return{ok:!1,errorCode:"unsupported-operation",reason:g};let b=await this.getUpstreamBackedDescendantReason(r);if(b)return{ok:!1,errorCode:"unsupported-operation",reason:b};if(r.tag&&r.tag.toLowerCase()===r.tag){let I=Ki(s,{kind:"native-tag",tag:r.tag});if(I)return{ok:!1,errorCode:"unsupported-operation",reason:I}}if(l)return this.planCrossFileMove(t,n,r,s,o,d,f);let E=dc(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 v=[{order:0,file:r.file,type:"move-node",locator:he(r),targetParentLocator:he(s),placement:d,anchorLocator:f?he(f):void 0,selectionContext:Dn(s)}];return this.buildPlan(t,n,v,o)}planCrossFileMove(t,n,r,o,i,s,a){let c=[],l=0,d=this.graph.getFileContent(r.file),f=yc(this.graph,r)??`<${r.component} />`,m=Hf(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,b={moduleSpecifier:Ec(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:b.moduleSpecifier,imports:b.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:Dn(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:Dn(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 Dp(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 Pc from"@babel/generator";import{parse as MI}from"@babel/parser";import Ac from"@babel/traverse";import*as N from"@babel/types";import*as $t from"@babel/types";import Cc from"@babel/generator";import*as be from"@babel/types";var EI=typeof Cc=="function"?Cc:Cc.default,vI=/(?:token|secret|key|password|authorization|cookie|signature|credential)/i,kI=/^((?:https?:)?\/\/)[^/@\s]+@/i,II=/(\/(?:token|secret|api[-_]?key|password|credential|signature)\/)[^/?#]+/gi;function Vp(e,t){let n=jt(e.callee);if(!n)return null;if(n==="fetch")return Rc(e.arguments[0],"GET",t,["fetch call"]);if(n.startsWith("axios.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if($p(r))return Rc(e.arguments[0],r,t,["axios client contract"])}if(n.startsWith("ky.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if($p(r))return Rc(e.arguments[0],r,t,["ky client contract"])}return null}function Rc(e,t,n,r){if(!e||be.isSpreadElement(e)||be.isJSXNamespacedName(e))return wI(t,n,r,"missing url argument");let o=io(e);return{sourceKind:NI(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 io(e){if(be.isStringLiteral(e))return Xi(e.value);if(be.isTemplateLiteral(e))return Xi(CI(e));if(be.isBinaryExpression(e)&&e.operator==="+"){let t=io(e.left),n=io(e.right);return!t&&!n?void 0:Xi(`${t??Nc(e.left)}${n??Nc(e.right)}`)}if(be.isMemberExpression(e)){let t=Kp(e);if(t)return`env:${t}`}if(!(be.isCallExpression(e)&&jt(e.callee)==="new URL")){if(be.isNewExpression(e)&&be.isIdentifier(e.callee,{name:"URL"})){let[t,n]=e.arguments,r=t&&!be.isSpreadElement(t)?io(t):void 0,o=n&&!be.isSpreadElement(n)?io(n):void 0;return o&&r?Xi(`${o} + ${r}`):r??o}if(be.isIdentifier(e))return`:${e.name}`}}function CI(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+=Nc(r))}return t}function Nc(e){if(be.isIdentifier(e))return`:${e.name}`;if(be.isMemberExpression(e)){let t=Kp(e);if(t)return`env:${t}`}return`:${RI(e)}`}function RI(e){return EI(e,{comments:!1}).code.replace(/[^a-zA-Z0-9_$]+/g,"_").replace(/^_+|_+$/g,"")||"param"}function Xi(e){let[t]=e.split("#"),[n,r]=t.split("?"),o=n.replace(kI,"$1<redacted>@").replace(II,"$1<redacted>");if(!r)return o;let i=r.split("&").map(s=>{let[a]=s.split("=");return a?vI.test(a)?`${a}=<redacted>`:`${a}=:${a}`:""}).filter(Boolean).join("&");return i?`${o}?${i}`:o}function NI(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 wI(e,t,n,r){return{sourceKind:"unknown-api",method:e,confidence:"partial",evidence:[{file:t.file,reason:[...n,r].join("; ")}]}}function $p(e){return["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(e)}function Kp(e){return!be.isMemberExpression(e.object)||!be.isIdentifier(e.object.object,{name:"process"})||!PI(e.object.property,"env")?null:be.isIdentifier(e.property)?e.property.name:be.isStringLiteral(e.property)?e.property.value:null}function PI(e,t){return be.isIdentifier(e)&&e.name===t}function jt(e){if(be.isIdentifier(e))return e.name;if(be.isMemberExpression(e)){let t=jt(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 AI=new Set(["list","listStrict","get","getStrict","getByUrl","getByUrlStrict","schema","categories"]),TI=new Set(["getConfig","submit"]);function Up(e,t){let n=FI(jt(e.callee),t);if(!n)return null;let r="cms.collections.";if(n.startsWith(r)){let i=n.slice(r.length);if(!AI.has(i))return null;let s=wc(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(!TI.has(i))return null;let s=wc(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=wc(e,0)??_I(e,0,"path")??"/cms/:path",s=OI(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 FI(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 Jp(e,t){let n=jt(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 Xp(e){let t=jt(e.callee);return typeof t=="string"&&t.startsWith("cms.field.")}function wc(e,t){let n=e.arguments[t];return $t.isStringLiteral(n)?n.value:null}function _I(e,t,n){let r=e.arguments[t];if(!$t.isObjectExpression(r))return null;for(let o of r.properties)if($t.isObjectProperty(o)&&!o.computed&&($t.isIdentifier(o.key)&&o.key.name===n||$t.isStringLiteral(o.key)&&o.key.value===n)&&$t.isStringLiteral(o.value))return o.value.value;return null}function OI(e){return/^\/collections\/([^/]+)(?:\/|$)/.exec(e)?.[1]??null}var Fc=typeof Ac=="function"?Ac:Ac.default,gM=typeof Pc=="function"?Pc:Pc.default,DI={maxFunctionDepth:8,maxImportDepth:6},LI=new Set(["src","href","alt","poster","content","title","aria-label"]);async function Zp(e){let t=e.fileCache??new Map,n=Mc(e.file,e.source,t),r={file:e.file,analysis:n,readFile:e.readFile,exists:e.exists,fileCache:t,options:{...DI,...e.options},variableCache:new Map,functionDepth:0,importDepth:0,paramSources:new Map,resolvingVariables:new Set,resolvingComponentProps:new Set,scopeVariables:dm(n,e.element.componentName)};await Qp(e.element.componentName,e.graph,r);let o=[];o.push(...await KI(e.element,e.graph,r),...await UI(e.element,e.graph,r));for(let s of e.element.textSegments){let a=await JI(s,e.element,e.graph,r);a&&o.push(Hi(a,"text","children"))}for(let s of e.element.attributes??[]){let a=VI(s,e.element);if(!a)continue;let c=await tm(s.source,e.element,e.graph,r);c&&o.push(Hi(c,a,s.name))}let i=iC(o).sort(lm);return{hasDynamicData:i.length>0,bindings:i}}async function Qp(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 qp(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 em(l.sourceFile,n);if(!f)continue;let m=Yi(f,n,{importDepth:n.importDepth+1});m.paramSources.clear(),m.scopeVariables=dm(f,l.componentName),await Qp(l.componentName,t,m);let u=await BI(l,m);for(let[g,h]of u){if(!h)continue;let b=a.get(g)??[];b.push(h),a.set(g,b)}}finally{n.resolvingComponentProps.delete(d)}}}let c=new Map;for(let[l,d]of a){let f=am(d);f.length===1&&c.set(l,f[0])}$I(o,c,n)}async function qp(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 em(e,r))?.imports.get(t);if(!s||!Pt(s.source))return!1;let a=await mm(e,s.source,r.exists);return a?a===n?!0:qp(a,s.importedName,n,r,o):!1}async function BI(e,t){let n=new Map;Fc(t.analysis.ast,{JSXElement(o){if(jI(o.node,e.sourceRange)){for(let i of o.node.openingElement.attributes)!N.isJSXAttribute(i)||!N.isJSXIdentifier(i.name)||!N.isJSXExpressionContainer(i.value)||!N.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 jI(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 em(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 Mc(e,r,t.fileCache)}function $I(e,t,n){if(N.isIdentifier(e)){t.size>0&&n.paramSources.set(e.name,Oc(Object.fromEntries(t),n.file));return}if(N.isObjectPattern(e))for(let r of e.properties){if(!N.isObjectProperty(r)||r.computed||!N.isIdentifier(r.key))continue;let o=t.get(r.key.name);if(!o)continue;let i=N.isAssignmentPattern(r.value)?r.value.left:r.value;N.isIdentifier(i)&&n.paramSources.set(i.name,ze(o))}}function VI(e,t){return e.name==="dangerouslySetInnerHTML"?"richtext":LI.has(e.name)?"attribute":t.importedFrom||/^[A-Z]/.test(t.tag)?"component-prop":null}async function KI(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 Gi(i.collectionSource,n);s&&r.push(Hi(Ln(s),"repeat-region",i.collectionExpression))}return r}async function UI(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 Gi(i.conditionSource,n);s&&r.push(Hi(Ln(s),"conditional-region",i.conditionExpression))}return r}async function JI(e,t,n,r){return tm(e.source,t,n,r)}async function tm(e,t,n,r){let o=await XI(e,t,n,r);return o||Gi(e,r)}async function XI(e,t,n,r){if(!e)return null;let o=zI(e.base,t,n);if(!o)return null;let i=await Gi(o.collectionSource,r);return i?lo(i,e.path,!0):null}function zI(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 Gi(e,t){if(!e)return null;let n=await nm(e.base,t);return n?lo(n,e.path,!1):null}async function nm(e,t){let n=t.paramSources.get(e);if(n)return ze(n);if(t.variableCache.has(e))return sC(t.variableCache.get(e)??null);if(t.resolvingVariables.has(e))return null;t.resolvingVariables.add(e);let r=await WI(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 fm(i,t);if(s){let a=Yi(s,t,{importDepth:t.importDepth+1}),c=pm(i,s);if(c){let f=(await Bn(c,[],a)).returnSource;return t.variableCache.set(e,f?ze(f):null),t.resolvingVariables.delete(e),f}let l=s.variables.get(i.importedName);if(l){let 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 WI(e,t){let n=t.analysis.stateSetters.get(e);if(!n)return null;let r=[];Fc(t.analysis.ast,{CallExpression(o){if(N.isIdentifier(o.node.callee,{name:n})){let i=o.node.arguments[0];N.isExpression(i)&&r.push(i);return}o.node.arguments.some(i=>N.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(N.isIdentifier(e))return nm(e.name,t);if(N.isMemberExpression(e)||N.isOptionalMemberExpression(e)){let n=N.isMemberExpression(e)?Jp(e,{file:t.file}):null;if(n)return sm(n);let r=await HI(e,t);if(!r)return null;let o=rC(e);return lo(r,o,!1)}if(N.isAwaitExpression(e))return N.isExpression(e.argument)?je(e.argument,t):null;if(N.isCallExpression(e))return rm(e,t);if(N.isObjectExpression(e)){let n=await om(e,t);return Object.keys(n).length>0?Oc(n,t.file):null}if(N.isConditionalExpression(e)){let n=await je(e.consequent,t),r=await je(e.alternate,t);return co(Wp(n,r))}if(N.isLogicalExpression(e)){let n=await je(e.left,t),r=await je(e.right,t);return co(Wp(n,r))}return N.isTSAsExpression(e)||N.isTSSatisfiesExpression(e)||N.isTSNonNullExpression(e)||N.isTypeCastExpression(e)||N.isParenthesizedExpression(e)?je(e.expression,t):null}async function HI(e,t){let n=e;for(;N.isMemberExpression(n)||N.isOptionalMemberExpression(n);)n=n.object;return N.isExpression(n)?je(n,t):null}async function rm(e,t){let n=Up(e,{file:t.file,imports:t.analysis.imports});if(n)return sm(n);if(Xp(e)){let f=e.arguments[0];if(f&&N.isExpression(f))return co(await je(f,t))}let r=await GI(e,t);if(r)return r;let o=Vp(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 QI(e,t);if(i)return i;let s=await qI(e,t);if(s)return s;let a=await eC(e,t);if(a)return a;let c=await tC(e,t);if(c)return c;let l=[];for(let f of e.arguments)if(N.isExpression(f)){let m=await je(f,t);m&&l.push(m)}let d=am(l);return d.length===1?co(d[0]):null}async function GI(e,t){let n=jt(e.callee);if(n!=="useQuery"&&n!=="useSuspenseQuery"&&n!=="useInfiniteQuery"&&n!=="useSWR")return null;if(n==="useSWR"){let i=ZI(e.arguments[0],t.file,"SWR key"),s=e.arguments[1];if(N.isIdentifier(s)){let a=await ao(s.name,t);if(a)return(await Bn(a.node,i?[i]:[],a.context)).returnSource??i}return i}let r=e.arguments[0];if(!N.isObjectExpression(r))return zi(t.file,`${n} without static options`);let o=YI(r,"queryFn");if(!o)return zi(t.file,`${n} without queryFn`);if(N.isIdentifier(o)){let i=await ao(o.name,t);return i?(await Bn(i.node,[],i.context)).returnSource:zi(t.file,`${n} queryFn unresolved`)}return N.isArrowFunctionExpression(o)||N.isFunctionExpression(o)?(await Bn(o,[],t)).returnSource:N.isCallExpression(o)?rm(o,t):null}function YI(e,t){for(let n of e.properties){if(!N.isObjectProperty(n)||!N.isExpression(n.value))continue;if(im(n)===t)return n.value}return null}function ZI(e,t,n){return N.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 QI(e,t){if(!N.isMemberExpression(e.callee)||!N.isIdentifier(e.callee.property))return null;let n=e.callee.property.name;if(!["map","filter","slice","sort","toSorted"].includes(n))return null;let r=N.isExpression(e.callee.object)?await je(e.callee.object,t):null;if(!r)return null;if(n!=="map")return Ln(r);let o=e.arguments[0];if(N.isIdentifier(o)){let i=await ao(o.name,t);if(!i)return Ln(r);let s=await Bn(i.node,[r],i.context);return{...Ln(r),...s.objectReturnMap??s.returnSource?.fieldMap?{fieldMap:s.objectReturnMap??s.returnSource.fieldMap}:{}}}if(N.isArrowFunctionExpression(o)||N.isFunctionExpression(o)){let i=await Bn(o,[r],t);return{...Ln(r),...i.objectReturnMap??i.returnSource?.fieldMap?{fieldMap:i.objectReturnMap??i.returnSource.fieldMap}:{}}}return Ln(r)}async function qI(e,t){return!N.isMemberExpression(e.callee)||!N.isIdentifier(e.callee.property,{name:"json"})||!N.isExpression(e.callee.object)?null:je(e.callee.object,t)}async function eC(e,t){return!N.isMemberExpression(e.callee)||!N.isIdentifier(e.callee.property,{name:"then"})||!N.isExpression(e.callee.object)?null:co(await je(e.callee.object,t))}async function tC(e,t){if(!N.isIdentifier(e.callee))return null;let n=await ao(e.callee.name,t);if(!n)return null;let r=[];for(let i of e.arguments){if(!N.isExpression(i)){r.push(zi(t.file,`unsupported argument for ${e.callee.name}`));continue}let s=await je(i,t);r.push(s)}return(await Bn(n.node,r,n.context)).returnSource}async function ao(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 fm(r,t);if(!o)return null;let i=Yi(o,t,{importDepth:t.importDepth+1}),s=pm(r,o);return s?{node:s,context:i}:ao(r.importedName,i)}async function Bn(e,t,n){if(n.functionDepth>=n.options.maxFunctionDepth)return{returnSource:null};let r=Yi(n.analysis,n,{functionDepth:n.functionDepth+1});r.scopeVariables=n.analysis.functionVariables.get(e),e.params.forEach((c,l)=>{let d=t[l];d&&Tc(c,oC(d),r)});let o=nC(e),i=null,s,a=!1;for(let c of o){if(N.isObjectExpression(c)){s={...s??{},...await om(c,r)},i=i??Oc(s,n.file);continue}let l=await je(c,r);if(l){if(!i){i=l;continue}let d=_c(i,l);if(!d){a=!0,i=null;continue}i=d}}return{returnSource:a?null:i,...s?{objectReturnMap:s}:{}}}function Tc(e,t,n){if(N.isIdentifier(e)){n.paramSources.set(e.name,ze(t));return}if(N.isAssignmentPattern(e)){Tc(e.left,t,n);return}if(N.isObjectPattern(e))for(let r of e.properties){if(!N.isObjectProperty(r)||r.computed||!N.isIdentifier(r.key))continue;let o=lo(t,[{kind:"property",name:r.key.name}],!0),i=N.isAssignmentPattern(r.value)?r.value.left:r.value;Tc(i,o,n)}}function nC(e){if(N.isArrowFunctionExpression(e)&&N.isExpression(e.body))return[e.body];let t=[],n=e.body;if(!N.isBlockStatement(n))return t;let r=o=>{if(N.isFunction(o)&&o!==e)return;if(N.isReturnStatement(o)){o.argument&&N.isExpression(o.argument)&&t.push(o.argument);return}let i=N.VISITOR_KEYS[o.type];for(let s of i??[]){let a=o[s];if(Array.isArray(a))for(let c of a)N.isNode(c)&&r(c);else N.isNode(a)&&r(a)}};return r(n),t}async function om(e,t){let n={};for(let r of e.properties){if(!N.isObjectProperty(r))continue;let o=im(r);if(!o||!N.isExpression(r.value))continue;let i=await je(r.value,t);i&&(n[o]=i)}return n}function im(e){return N.isIdentifier(e.key)&&!e.computed?e.key.name:N.isStringLiteral(e.key)?e.key.value:null}function rC(e){let t=[],n=e;for(;N.isMemberExpression(n)||N.isOptionalMemberExpression(n);){let r=n.property;n.computed?N.isStringLiteral(r)?t.unshift({kind:"property",name:r.value}):N.isNumericLiteral(r)&&t.unshift({kind:"index",index:r.value}):N.isIdentifier(r)&&t.unshift({kind:"property",name:r.name}),n=n.object}return N.isIdentifier(n),t}function lo(e,t,n){if(t.length===0)return ze(e);let r=t[0];if(r?.kind==="property"&&e.fieldMap?.[r.name])return lo(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=so(o.valuePath,"data.items[]"),o.cmsFieldRoot=!1,o):i[0]==="fields"?(o.fieldPath=so(o.fieldPath,i.slice(1).join(".")),o.cmsFieldRoot=!0,o):o.cmsFieldRoot||n||o.fieldMap?(o.fieldPath=so(o.fieldPath,i.join(".")),o):(o.valuePath=so(o.valuePath,zp(t)),o)}return o.valuePath=so(o.valuePath,zp(t)),o}function zp(e){return e.map(t=>t.kind==="property"?t.name:`[${t.index}]`).join(".").replace(/\.\[/g,"[")}function so(e,t){return t?e?t.startsWith("[")?`${e}${t}`:`${e}.${t}`:t:e}function sm(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 Ln(e){let t=ze(e);return t.sourceType==="cms-field"&&!t.valuePath&&(t.valuePath="items[]"),t}function oC(e){let t=ze(e);return t.valuePath=void 0,t.sourceType==="cms-field"&&(t.cmsFieldRoot=!1),t}function co(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 Wp(e,t){return e?t?_c(e,t):ze(e):t?ze(t):null}function _c(e,t){if(Wi(e)!==Wi(t))return null;let n=um(e.confidence,t.confidence)<=0?e.confidence:t.confidence;return{...e,confidence:n,evidence:[...e.evidence,...t.evidence]}}function am(e){let t=new Map;for(let n of e){let r=Wi(n),o=t.get(r);t.set(r,o?_c(o,n):ze(n))}return[...t.values()]}function Wi(e){let t=e.fieldMap?Object.fromEntries(Object.entries(e.fieldMap).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>[n,Wi(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 Oc(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 zi(e,t){return{sourceKind:"unknown-api",sourceType:"api-field",confidence:"unknown",readonly:!0,evidence:[{file:e,reason:t}]}}function Hi(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 cm(e){let t=[...e].sort(lm),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 iC(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 lm(e,t){return Hp(e.targetKind)-Hp(t.targetKind)||um(e.confidence,t.confidence)||Gp(e.sourceKind)-Gp(t.sourceKind)||e.targetName.localeCompare(t.targetName)}function Hp(e){return{"repeat-region":0,"conditional-region":1,text:2,richtext:3,attribute:4,"component-prop":5}[e]}function Gp(e){return e.startsWith("vcp-cms-")?0:e==="site-api-route"?1:e==="external-api"?2:3}function um(e,t){let n={exact:0,"safe-derived":1,partial:2,unknown:3};return n[e]-n[t]}function Mc(e,t,n){let r=n.get(e);if(r?.source===t)return r;let o=MI(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 Fc(o,{ImportDeclaration(s){let a=s.node.source.value;for(let c of s.node.specifiers)N.isImportSpecifier(c)&&N.isIdentifier(c.local)?i.imports.set(c.local.name,{source:a,importedName:N.isIdentifier(c.imported)?c.imported.name:c.imported.value,localName:c.local.name,isDefault:!1}):N.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&&(N.isFunctionDeclaration(a.node)||N.isFunctionExpression(a.node)||N.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,N.isExpression(s.node.init)?s.node.init:null);if(N.isArrayPattern(s.node.id)&&N.isCallExpression(s.node.init)&&jt(s.node.init.callee)==="useState"){let[d,f]=s.node.id.elements;N.isIdentifier(d)&&N.isIdentifier(f)&&i.stateSetters.set(d.name,f.name)}N.isIdentifier(s.node.id)&&Yp(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(!N.isExportSpecifier(l))continue;let d=N.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(N.isFunctionDeclaration(a)&&a.id?.name&&i.functions.set(a.id.name,a),N.isVariableDeclaration(a))for(let l of a.declarations)N.isIdentifier(l.id)&&Yp(l.init)&&i.functions.set(l.id.name,l.init)},ExportDefaultDeclaration(s){let a=s.node.declaration;if((N.isFunctionDeclaration(a)||N.isFunctionExpression(a)||N.isArrowFunctionExpression(a))&&i.functions.set("default",a),N.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||N.isVoidPattern(e)?[]:N.isIdentifier(e)?[e.name]:N.isObjectPattern(e)?e.properties.flatMap(t=>N.isObjectProperty(t)?gr(t.value):gr(t.argument)):N.isArrayPattern(e)?e.elements.flatMap(t=>t?gr(N.isRestElement(t)?t.argument:t):[]):N.isAssignmentPattern(e)?gr(e.left):N.isRestElement(e)?gr(e.argument):[]}function Yp(e){return N.isFunctionExpression(e)||N.isArrowFunctionExpression(e)}function dm(e,t){let n=e.functions.get(t)??e.functions.get("default");return n?e.functionVariables.get(n):void 0}async function fm(e,t){let n=await mm(t.file,e.source,t.exists);if(!n)return null;let r=await t.readFile(n);return Mc(n,r,t.fileCache)}function pm(e,t){return e.isDefault?t.functions.get("default")??t.functions.get(e.localName)??null:t.functions.get(e.importedName)??null}async function mm(e,t,n){return Pt(t)?xn(e,t,n):null}function Yi(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 sC(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 Lc from"@babel/parser";import Dc from"@babel/traverse";import*as Y from"@babel/types";import{classifySiteEditPropertyName as aC}from"@vcp-dev/contracts";var Bc=typeof Dc=="function"?Dc:Dc.default;function jc(e){let t=aC(e.propertyName);if(t.owner!=="generic")return ct("invalid-property",t.diagnostic?.message??`Property '${e.propertyName}' is not a generic property`);let n=e.selectionRef;if(!n)return ct("missing-selection-ref","A repeat property target requires a complete selection reference");if(n.key!==e.element.identity.key)return ct("selection-mismatch","Selection reference does not identify the requested element");if(n.instanceIndex===void 0)return ct("missing-instance-index","A repeat property target requires an instance index");let r;try{r=Lc.parse(e.source,{sourceType:"module",plugins:["typescript","jsx"]})}catch(b){return ct("repeat-not-found",`Unable to parse repeat source: ${b instanceof Error?b.message:String(b)}`)}let o=cC(r,e.element.sourceRange);if(!o)return ct("repeat-not-found","The selected element is not inside a supported map repeat");if(!Y.isIdentifier(o.callback.params[0]))return ct("unsupported-callback","Repeat property materialization requires an identifier callback item");let i=lC(r,o.collection,e.file,e.sources);if(!i)return ct("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[b,E]of s.elements.entries()){if(!E||!Y.isObjectExpression(E)||!Sm(E))return ct("unsafe-collection","Repeat materialization requires an array of local static objects without spreads");let v=[{kind:"index",index:b}];l.push(v),d.push({kind:"value",root:a.root,path:v})}let f=d.length;if(n.instanceCount!==void 0&&n.instanceCount!==f)return ct("count-mismatch",`Selection reports ${n.instanceCount} instances but the source collection has ${f}`);let m=n.instanceIndex;if(m>=f)return ct("index-out-of-range",`Selected repeat instance ${m} is outside the source collection`);let u=s.elements[m];if(!u||!Y.isObjectExpression(u))return ct("unsafe-collection","Selected repeat item is not an object");let g=gC(e.element,e.propertyName),h=pC(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},(b,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:mC(u,e.propertyName),...g?{property:g}:{},selectionRef:n}:ct("unsafe-property-source",`Property '${e.propertyName}' has a dynamic or unsupported source in the repeat item`)}function cC(e,t){let n=[];return Bc(e,{CallExpression(r){let o=gm(r.node);o&&ym(o.callback,t)&&n.push({...o,span:hm(r.node)})},OptionalCallExpression(r){let o=gm(r.node);o&&ym(o.callback,t)&&n.push({...o,span:hm(r.node)})}}),n.sort((r,o)=>r.span-o.span),n[0]??null}function gm(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 lC(e,t,n,r){let o=uo(t);if(o&&Y.isArrayExpression(o))return{array:o,locator:{kind:"value",root:{kind:"expression",sourceRange:vm(o)}},sourceFile:n};if(!Y.isIdentifier(t))return null;let i=[];if(Bc(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=uo(i[0].init);return!s||!Y.isArrayExpression(s)?null:{array:s,locator:{kind:"value",root:{kind:"binding",name:t.name}},sourceFile:n}}return uC(e,t.name,n,r)}function uC(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=fC(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=Lc.parse(c,{sourceType:"module",plugins:["typescript","jsx"]})}catch{return null}let d=dC(l,a),f=d?uo(d):null;return!f||!Y.isArrayExpression(f)?null:{array:f,locator:{kind:"value",root:{kind:"binding",name:a}},sourceFile:s}}return null}function dC(e,t){let n=null;return Bc(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 fC(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 uo(e){return Y.isParenthesizedExpression(e)?uo(e.expression):Y.isTSAsExpression(e)?bm(e.typeAnnotation)?uo(e.expression):null:Y.isTSSatisfiesExpression(e)?null:e}function bm(e){return Y.isTSTypeReference(e)&&Y.isIdentifier(e.typeName)&&e.typeName.name==="const"}function Sm(e){return e.properties.every(t=>!Y.isObjectProperty(t)||t.computed||!Y.isExpression(t.value)?!1:Zi(t.value))}function Zi(e){if(Y.isTSAsExpression(e)&&bm(e.typeAnnotation))return Zi(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:Zi(n));if(Y.isObjectExpression(e))return Sm(e);let t=Ot(e);return t.status==="resolved"||t.status==="undefined"}function pC(e,t){let n=e.properties.filter(o=>Y.isObjectProperty(o)&&Em(o.key)===t);if(n.length>1)return null;let r=n[0];return r?Y.isExpression(r.value)?Zi(r.value)?"static":Y.isIdentifier(r.value)||Y.isMemberExpression(r.value)?"binding":null:null:"missing"}function mC(e,t){let n=e.properties.filter(o=>Y.isObjectProperty(o)&&Em(o.key)===t);if(n.length>1)return{status:"unresolved"};let r=n[0];return!r||!Y.isExpression(r.value)?{status:"undefined"}:Ot(r.value)}function gC(e,t){let n=e.attributes?.filter(r=>r.name===t)??[];return n.length===1?n[0]:void 0}function Em(e){return Y.isIdentifier(e)?e.name:Y.isStringLiteral(e)?e.value:Y.isNumericLiteral(e)?String(e.value):null}function vm(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 hm(e){return e.start==null||e.end==null?Number.MAX_SAFE_INTEGER:e.end-e.start}function ym(e,t){let n=vm(e);return xm(n.startLine,n.startColumn,t.startLine,t.startColumn)<=0&&xm(n.endLine,n.endColumn,t.endLine,t.endColumn)>=0}function xm(e,t,n,r){return e===n?t-r:e-n}function ct(e,t){return{ok:!1,errorCode:e,reason:t}}import{classifySiteEditPropertyName as nR}from"@vcp-dev/contracts";import*as Z from"@babel/types";import go from"node:path";import*as j from"@babel/types";import*as Nm from"@babel/parser";import $c from"@babel/traverse";import*as re from"@babel/types";function Qi(e,t){let n=[],r=e;for(;re.isMemberExpression(r);){if(r.computed)if(re.isNumericLiteral(r.property))n.unshift({kind:"index",index:r.property.value});else if(re.isStringLiteral(r.property))n.unshift({kind:"property",name:r.property.value});else return null;else{if(!re.isIdentifier(r.property))return null;n.unshift({kind:"property",name:r.property.name})}r=r.object}return!re.isIdentifier(r)||r.name!==t?null:n}function km(e){if(re.isIdentifier(e))return{base:e.name,path:[]};if(!re.isMemberExpression(e))return null;let t=[],n=e;for(;re.isMemberExpression(n);){if(n.computed)if(re.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(re.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else{if(!re.isIdentifier(n.property))return null;t.unshift({kind:"property",name:n.property.name})}n=n.object}return re.isIdentifier(n)?{base:n.name,path:t}:null}function tt(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 Im(e){let{resolveBindingTarget:t}=e;async function n(i,s,a,c,l,d,f){if(re.isStringLiteral(i)||re.isNumericLiteral(i)||re.isBooleanLiteral(i))return i.value;if(re.isNullLiteral(i))return null;if(re.isTemplateLiteral(i))return i.expressions.length===0&&i.quasis.length===1?i.quasis[0].value.cooked??i.quasis[0].value.raw:void 0;if(re.isTSAsExpression(i)||re.isTSSatisfiesExpression(i)||re.isTSNonNullExpression(i))return await n(i.expression,s,a,c,l,d,f);if(re.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(re.isArrayExpression(i)){let m=[];for(let u of i.elements){if(!u||re.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(re.isObjectExpression(i)){let m={};for(let u of i.properties){if(!re.isObjectProperty(u)||u.computed)return;let g=null;if(re.isIdentifier(u.key)?g=u.key.name:re.isStringLiteral(u.key)&&(g=u.key.value),!g)return;if(u.shorthand){if(!re.isIdentifier(u.value))return;let b=await r(u.value,s,a,c,l,d,f);if(b===void 0)return;m[g]=b;continue}if(!re.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(re.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:tt(g.value,m.path)}}async function r(i,s,a,c,l,d,f){if(!re.isSpreadElement(i))return await n(i,s,a,c,l,d,f)}async function o(i,s,a,c,l,d,f){if(re.isIdentifier(i))return{base:i.name,path:[]};if(!re.isMemberExpression(i))return null;let m=[],u=i;for(;re.isMemberExpression(u);){if(u.computed){let g=u.property;if(re.isNumericLiteral(g))m.unshift({kind:"index",index:g.value});else if(re.isStringLiteral(g))m.unshift({kind:"property",name:g.value});else{let h=re.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(!re.isIdentifier(u.property))return null;m.unshift({kind:"property",name:u.property.name})}u=u.object}return re.isIdentifier(u)?{base:u.name,path:m}:null}return{normalizeExpressionWithScope:o,evaluateStaticExpression:n}}var wm=typeof $c=="function"?$c:$c.default,Cm=new WeakMap;function Pm(e){try{return Nm.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function qi(e,t,n){let r=e.get(t);if(r?.source===n)return r.ast;let o=Pm(n);return e.set(t,{source:n,ast:o}),o}function es(e,t){let n=null,r=-1;for(let o of fo(e).expressions){let i=o.node.loc;if(!i||!Kc(i,t))continue;let s=(o.node.end??0)-(o.node.start??0);s>=r&&(n=o,r=s)}return n}function Am(e,t){let n=null,r=Number.POSITIVE_INFINITY;for(let o of fo(e).expressions){if(!hC(o.node.loc,t))continue;let i=(o.node.end??0)-(o.node.start??0);i<=r&&(n=o,r=i)}return n}function Vc(e,t){let n=null,r=Number.POSITIVE_INFINITY;for(let o of fo(e).jsxElements){let i=o.node.loc;if(!i||!Kc(i,t))continue;let s=(o.node.end??0)-(o.node.start??0);s<=r&&(n=o,r=s)}return n}function fo(e){let t=Cm.get(e);if(t)return t;let n={expressions:[],jsxElements:[]};return wm(e,{Expression(r){n.expressions.push(r)},JSXElement(r){n.jsxElements.push(r)}}),Cm.set(e,n),n}function hC(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 Kc(e,t){let n=Rm({line:e.start.line,column:e.start.column},{line:t.startLine,column:t.startColumn}),r=Rm({line:e.end.line,column:e.end.column},{line:t.endLine,column:t.endColumn});return n>=0&&r<=0}function ts(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 Rm(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 Uc(e,t);let n=km(e);return n?n.path.reduce((r,o)=>o.kind==="property"?`${r}.${o.name}`:`${r}[${o.index}]`,n.base):""}function Uc(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function po(e,t,n){let r=null,o=Number.POSITIVE_INFINITY;for(let i of fo(e).expressions){if(Uc(i.node,t)!==n)continue;let s=(i.node.end??0)-(i.node.start??0);s<=o&&(r=i,o=s)}return r}function Tm(e,t,n,r){let o=null,i=Number.POSITIVE_INFINITY;for(let s of fo(e).expressions){if(Uc(s.node,t)!==n)continue;let a=s.node.loc;if(!a||!Kc(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 mo(e){let t=null;if(wm(e,{Program(n){t=n.scope,n.stop()}}),!t)throw new Error("Unable to determine program scope");return t}async function Vt(e,t,n){let r=n.get(e);if(r)return r;let o=await t(e),i=Pm(o),s={source:o,ast:i};return n.set(e,s),s}function yC(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 xC(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 bC(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 SC(e,t){let n=bC(e.path);if(!n)return null;let r=sr(e,t);return r?{...n,...r}:null}function EC(e,t,n,r){return e.importedFrom===t?r?e.exportName===r:!0:e.sourceFile===t&&e.tag===n}function Jc(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 Xc(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 Fm(e){let{resolveExternalExpression:t,resolveCollectionCallTarget:n,evaluateStaticExpression:r,resolveSourceInfoProvenance:o,buildExpressionSourceInfo:i}=e;async function s(u){let{currentFile:g,binding:h,readFile:b,exists:E,fileCache:v,visited:I}=u,R=`${g}::${h.kind}::${h.identifier.name}`;if(I.has(R))return null;I.add(R);try{let A=await a({currentFile:g,binding:h,readFile:b,exists:E,fileCache:v,visited:I});if(A)return A;if(h.path.isImportSpecifier()||h.path.isImportDefaultSpecifier())return await f({currentFile:g,binding:h,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,fileCache:v,visited:I});if(h.kind==="param")return null;if(h.path.isVariableDeclarator()){let T=h.path.node.init;if(!T||!j.isExpression(T))return null;let C=xC(T);if(C&&!h.path.scope.getBinding("Proxy")&&!h.path.scope.getBinding("Reflect")){let D=h.path.scope.getBinding(C),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 P=h.path.get("init");if(P&&!Array.isArray(P)&&P.isExpression()){let D=await t({currentFile:g,expressionPath:P,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:v,visited:I});if(D)return D;if(P.isCallExpression()){let U=await n({currentFile:g,callPath:P,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:v,visited:I});if(U)return U}}let O=await r(T,h.path.scope,g,b,E,v,I);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 T=h.path.parentPath.node.declaration;if(!j.isExpression(T))return null;let C=await r(T,h.path.scope,g,b,E,v,I);return C===void 0?null:{kind:"static",file:g,root:{kind:"binding",name:h.identifier.name},value:C,sourceKind:"binding"}}return null}finally{I.delete(R)}}async function a(u){let{currentFile:g,binding:h,readFile:b,exists:E,fileCache:v,visited:I}=u;if(!h.path.isVariableDeclarator()||!h.path.get("id").isArrayPattern())return null;let R=h.path,A=R.node.init;if(!A||!j.isCallExpression(A))return null;let T=yC(A);if(!T||!j.isArrayPattern(R.node.id)||R.node.id.elements.findIndex(U=>j.isIdentifier(U)&&U.name===h.identifier.name)!==0)return null;let P=T==="useReducer"?1:0,O=A.arguments[P];if(!O||!j.isExpression(O))return null;let D=await r(O,R.scope,g,b,E,v,I);return D===void 0?null:{kind:"static",file:g,root:{kind:"hook-state",name:h.identifier.name,hook:T},value:D,sourceKind:"binding"}}async function c(u){let g=SC(u.binding,u.sourceInfo);if(!g||!u.graph)return null;let h=[...u.graph.elements.values()].filter(T=>EC(T,u.currentFile,g.componentName,g.exportName));if(h.length!==1)return null;let b=h[0],E=b.attributes?.find(T=>T.name===g.propName);if(E&&!E.source){let T=await l({caller:b,propName:g.propName,remainingPath:g.remainingPath,readFile:u.readFile,fileCache:u.fileCache});if(T)return Jc(T,{componentName:g.componentName,propName:g.propName,file:b.sourceFile})}if(!E?.source){let T=await d({caller:b,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(T)return Jc(T,{componentName:g.componentName,propName:g.propName,file:b.sourceFile});let C=$f(u.binding,g.componentName,g.propName);if(!C||C.propName!==g.propName)return null;let P=await r(C.expressionPath.node,C.expressionPath.scope,u.currentFile,u.readFile,u.exists,u.fileCache,u.visited);if(P===void 0)return null;let O=g.remainingPath;return O.length>0&&tt(P,O)===void 0?null:{kind:"value",file:u.currentFile,root:{kind:"binding",name:g.propName},path:O,sourceKind:"binding",semanticKind:"component-prop",displayExpression:C.displayPath,chainPrefix:[{kind:"component-prop",file:u.currentFile,displayName:C.displayPath,canEditHere:!0}],editMode:"upstream",diagnostics:[]}}let v=await Vt(b.sourceFile,u.readFile,u.fileCache);if(!v.ast)return null;let I=Tm(v.ast,v.source,E.source.expression,E.sourceRange)??po(v.ast,v.source,E.source.expression);if(!I)return null;let R={...E.source,expression:yr(E.source.expression,g.remainingPath),path:[...E.source.path,...g.remainingPath]},A=await o({currentFile:b.sourceFile,expressionPath:I,sourceInfo:R,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 A?Jc(A.kind==="external"?A:{...A,displayExpression:R.expression},{componentName:g.componentName,propName:g.propName,file:b.sourceFile}):null}async function l(u){let g=await Vt(u.caller.sourceFile,u.readFile,u.fileCache);if(!g.ast)return null;let h=Vc(g.ast,u.caller.sourceRange);if(!h)return null;let b=h.get("openingElement").get("attributes").find(R=>R.isJSXAttribute()&&R.node.name.type==="JSXIdentifier"&&R.node.name.name===u.propName);if(!b?.isJSXAttribute())return null;let E=b.get("value"),v=E.isStringLiteral()?E:E.isJSXExpressionContainer()?E.get("expression"):null;if(!v?.isExpression())return null;let I=ts(v.node);return I?{kind:"value",file:u.caller.sourceFile,root:{kind:"expression",sourceRange:I},path:u.remainingPath,sourceKind:"binding",semanticKind:"component-prop",displayExpression:u.propName,editMode:"upstream",diagnostics:[]}:null}async function d(u){let g=await Vt(u.caller.sourceFile,u.readFile,u.fileCache);if(!g.ast)return null;let h=Vc(g.ast,u.caller.sourceRange);if(!h)return null;let b=h.get("openingElement");for(let E of b.get("attributes")){if(!E.isJSXSpreadAttribute())continue;let v=E.get("argument");if(!v.isExpression())continue;let I=await i({expression:v.node,scope:v.scope,source:g.source,currentFile:u.caller.sourceFile,readFile:u.readFile,exists:u.exists,fileCache:u.fileCache,visited:u.visited});if(!I)continue;let R=[{kind:"property",name:u.propName},...u.remainingPath],A={...I,expression:yr(I.expression,R),path:[...I.path,...R]},T=await o({currentFile:u.caller.sourceFile,expressionPath:v,sourceInfo:A,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(T)return T.kind==="external"?T:{...T,displayExpression:A.expression}}return null}async function f(u){let{currentFile:g,binding:h,readFile:b,exists:E,fileCache:v,visited:I}=u,R=h.path.parentPath;if(!R||!R.isImportDeclaration())return null;let A=R.node.source.value;if(typeof A!="string")return null;let T=await xn(g,A,E);if(!T)return null;if(h.path.isImportDefaultSpecifier()){let ee=await Vt(T,b,v),Re=ee.ast?Xc(ee.ast,"default"):null,Q=await m({file:T,exportName:"default",readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:v,visited:I});return!Q||Q.kind!=="static"?null:{kind:"static",file:Re?.kind==="default-expression"?Q.file:T,root:Re?.kind==="default-expression"?Q.root:{kind:"default-export"},value:Q.value,sourceKind:"imported-binding"}}if(!h.path.isImportSpecifier())return null;let C=h.path.node.imported,P=j.isIdentifier(C)?C.name:C.value,O=await Vt(T,b,v),D=O.ast?Xc(O.ast,P):null,U=await m({file:T,exportName:P,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:v,visited:I});return U?U.kind==="external"?U:{kind:"static",file:D?.kind==="re-export"?U.file:T,root:D?.kind==="re-export"||U.root.kind==="binding"&&U.root.name!==D?.name?U.root:{kind:"named-export",name:P},value:U.value,sourceKind:"imported-binding"}:null}async function m(u){let{file:g,exportName:h,readFile:b,exists:E,fileCache:v,visited:I}=u,R=`export::${g}::${h}`;if(!I.has(R)){I.add(R);try{let A=await Vt(g,b,v);if(!A.ast)return;let T=Xc(A.ast,h);if(!T)return;if(T.kind==="default-expression"){let D=T.expression;if(!D||!j.isIdentifier(D))return;let U=mo(A.ast).getBinding(D.name);return U?await s({currentFile:g,binding:U,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:v,visited:I})??void 0:void 0}if(T.kind==="re-export"){if(!T.source||!T.name)return;let D=await xn(g,T.source,E);return D?m({...u,file:D,exportName:T.name}):void 0}let C=T.name;if(!C)return;let P=mo(A.ast).getBinding(C);return P?await s({currentFile:g,binding:P,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:v,visited:I})??void 0:void 0}finally{I.delete(R)}}}return{resolveExportValue:m,resolveComponentPropBinding:c,resolveBindingTarget:s}}import*as H from"@babel/types";function Wc(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()||!vC(s,r)?null:{callPath:s,basePath:i}}function vC(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 Mm(e,t){let n=e.get("callee");if(!n.isMemberExpression())return null;let r=n.get("object");return Array.isArray(r)||!r.isExpression()?null:Ti(r,t)}function _m(e,t){return e?H.isNumericLiteral(e)&&Number.isInteger(e.value)?e.value:null:t}function Om(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=zc(i,t,n,r,o);return typeof s=="number"?s:void 0}function zc(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=Qi(e,t);if(i)return tt(r,i);let s=Qi(e,n);return s?tt(o,s):void 0}if(H.isBinaryExpression(e)&&e.operator==="-"){let i=H.isExpression(e.left)?zc(e.left,t,n,r,o):void 0,s=H.isExpression(e.right)?zc(e.right,t,n,r,o):void 0;return typeof i=="number"&&typeof s=="number"?i-s:void 0}}function kC(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 IC(e,t,n){let r=jn(e,t,n);return typeof r=="boolean"?r:void 0}function jn(e,t,n){if(H.isStringLiteral(e)||H.isNumericLiteral(e)||H.isBooleanLiteral(e))return e.value;if(H.isNullLiteral(e))return null;if(H.isIdentifier(e))return e.name===t?n:void 0;if(H.isMemberExpression(e)){let r=Qi(e,t);return r?tt(n,r):void 0}if(H.isUnaryExpression(e)&&e.operator==="!"){let r=jn(e.argument,t,n);return r===void 0?void 0:!r}if(H.isLogicalExpression(e)){let r=jn(e.left,t,n);if(r===void 0)return;if(e.operator==="&&")return r&&jn(e.right,t,n);if(e.operator==="||")return r||jn(e.right,t,n)}if(H.isBinaryExpression(e)){let r=H.isExpression(e.left)?jn(e.left,t,n):void 0,o=H.isExpression(e.right)?jn(e.right,t,n):void 0;if(r===void 0||o===void 0)return;switch(e.operator){case"===":return r===o;case"!==":return r!==o;case"==":return r==o;case"!=":return r!=o;default:return}}}function Dm(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 Lm(e){return e.some(t=>t.kind==="dynamic")}function CC(e){return typeof e=="string"?{kind:"property",name:e}:Number.isInteger(e)?{kind:"index",index:e}:null}function Bm(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 RC(e,t){let n=[],r=[];for(let o of t){let i=tt(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 jm(e){let{resolveBindingTarget:t,evaluateStaticExpression:n,buildExpressionSourceInfo:r,resolveSourceInfoProvenance:o}=e;async function i(u){let{currentFile:g,callPath:h,readFile:b,exists:E,fileCache:v,visited:I}=u,R=h.node.callee;if(!H.isMemberExpression(R)||!H.isIdentifier(R.property)||R.property.name!=="map")return null;let A=h.get("callee");if(!A.isMemberExpression())return null;let T=A.get("object");if(Array.isArray(T)||!T.isExpression())return null;let C=await s({currentFile:g,expressionPath:T,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:v,visited:I});return!C||!Array.isArray(C.value)||C.value.length===0?null:C}async function s(u){let{currentFile:g,expressionPath:h,readFile:b,exists:E,fileCache:v,visited:I}=u;if(h.isIdentifier()){let R=h.scope.getBinding(h.node.name);if(!R)return null;let A=await t({currentFile:g,binding:R,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:v,visited:I});return A?.kind==="static"?A:null}if(h.isCallExpression())return c({currentFile:g,callPath:h,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:v,visited:I});if(h.isTSAsExpression()||h.isTSSatisfiesExpression()||h.isTSNonNullExpression()){let R=h.get("expression");if(!Array.isArray(R)&&R.isExpression())return s({...u,expressionPath:R})}if(h.isArrayExpression()){let R=ts(h.node);if(!R)return null;let A=await n(h.node,h.scope,g,b,E,v,I);return Array.isArray(A)?{kind:"static",file:g,root:{kind:"expression",sourceRange:R},value:A,sourceKind:"binding"}:null}if(h.isMemberExpression()){let R=await r({expression:h.node,scope:h.scope,currentFile:g,readFile:b,exists:E,fileCache:v,visited:I});if(!R)return null;let A=await o({currentFile:g,expressionPath:h,sourceInfo:R,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:v,visited:I});if(!A||A.kind==="external")return null;let T=await a({currentFile:g,expressionPath:h,provenance:A,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:v,visited:I});if(!T||T.kind!=="static")return null;if(A.collectionPathMap?.length){let P=RC(T.value,A.collectionPathMap);if(P)return{kind:"static",file:A.file,root:A.root,value:P.value,sourceKind:A.sourceKind,collectionPathMap:P.collectionPathMap}}let C=tt(T.value,A.path);return Array.isArray(C)?{kind:"static",file:A.file,root:A.root,value:C,sourceKind:A.sourceKind,pathPrefix:A.path,collectionIndexMap:A.collectionIndexMap,collectionPathMap:A.collectionPathMap}:null}return null}async function a(u){let{provenance:g}=u;if(g.root.kind==="binding"){let v=u.expressionPath.scope.getBinding(g.root.name);if(!v&&g.file!==u.currentFile){let I=await Vt(g.file,u.readFile,u.fileCache);v=I.ast?mo(I.ast).getBinding(g.root.name):void 0}return v?await t({currentFile:g.file,binding:v,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 Vt(g.file,u.readFile,u.fileCache);if(!h.ast)return null;let b=Am(h.ast,g.root.sourceRange);if(!b)return null;let E=await n(b.node,b.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 b=g.get("callee");if(!b.isMemberExpression())return null;let E=b.get("object");if(Array.isArray(E)||!E.isExpression())return null;let v=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(!v||!Array.isArray(v.value))return null;let[I]=g.node.arguments;if(!H.isArrowFunctionExpression(I)&&!H.isFunctionExpression(I))return null;let R=I.params[0];if(!H.isIdentifier(R))return null;let A=kC(I);if(!A)return null;let T=[],C=[],P=[];for(let[O,D]of v.value.entries()){let U=IC(A,R.name,D);if(typeof U!="boolean")return null;if(U){T.push(D),C.push(v.collectionIndexMap?.[O]??O);let ee=v.collectionPathMap?.[O];ee&&P.push(ee)}}return{...v,value:T,pathPrefix:v.pathPrefix,collectionIndexMap:C,...P.length>0?{collectionPathMap:P}:{}}}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 b=g.get("callee");if(!b.isMemberExpression())return null;let E=b.get("object");if(Array.isArray(E)||!E.isExpression())return null;let v=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(!v||!Array.isArray(v.value))return null;let[I,R]=g.node.arguments,A=_m(I,0),T=_m(R,v.value.length);if(A===null||T===null)return null;let C=Math.max(0,A<0?v.value.length+A:A),P=Math.max(0,T<0?v.value.length+T:T),O=v.value.map((U,ee)=>v.collectionIndexMap?.[ee]??ee).slice(C,P),D=v.collectionPathMap?.slice(C,P);return{...v,value:v.value.slice(C,P),pathPrefix:v.pathPrefix,collectionIndexMap:O,...D?{collectionPathMap:D}:{}}}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 b=g.get("callee");if(!b.isMemberExpression())return null;let E=b.get("object");if(Array.isArray(E)||!E.isExpression())return null;let v=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(!v||!Array.isArray(v.value))return null;let[I]=g.node.arguments;if(!H.isArrowFunctionExpression(I)&&!H.isFunctionExpression(I))return null;let[R,A]=I.params;if(!H.isIdentifier(R)||!H.isIdentifier(A))return null;let T=v.value.map((P,O)=>({value:P,sourceIndex:v.collectionIndexMap?.[O]??O,originalIndex:O})),C=[...T];for(let P of T)for(let O of T)if(Om(I,R.name,A.name,P.value,O.value)===void 0)return null;return C.sort((P,O)=>{let D=Om(I,R.name,A.name,P.value,O.value)??0;return D===0?P.originalIndex-O.originalIndex:D}),{...v,value:C.map(P=>P.value),pathPrefix:v.pathPrefix,collectionIndexMap:C.map(P=>P.sourceIndex),...v.collectionPathMap?{collectionPathMap:C.map(P=>v.collectionPathMap?.[P.originalIndex]).filter(P=>!!P)}:{}}}async function m(u){let g=null,h,b=[];for(let v of u.segments){if(v.kind!=="dynamic")continue;let I=await r({expression:v.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(!I)return null;let R=Wc(u.expressionPath,I.base);if(!R)return null;let A=await i({currentFile:u.currentFile,callPath:R.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(!A||!Array.isArray(A.value))return null;let T=A.value.map((C,P)=>{let O=tt(A.value,[{kind:"index",index:P},...R.basePath,...I.path]);return CC(O)});if(T.some(C=>C===null)||g!==null&&g!==T.length)return null;g=T.length,h??=A.collectionIndexMap,b.push(T)}if(g===null||g===0)return null;let E=[];for(let v=0;v<g;v+=1){let I=[...u.rootPath],R=0;for(let A of u.segments){if(A.kind==="dynamic"){let T=b[R]?.[v];if(!T)return null;I.push(T),R+=1;continue}I.push({...A})}E.push(I)}return{...h?{collectionIndexMap:h}:{},collectionPathMap:E}}return{resolveRepeatCollectionTarget:i,resolveCollectionCallTarget:c,resolveDynamicMemberPathMap:m}}var{normalizeExpressionWithScope:NC,evaluateStaticExpression:ns}=Im({resolveBindingTarget:e=>qc(e)}),{resolveRepeatCollectionTarget:wC,resolveCollectionCallTarget:PC,resolveDynamicMemberPathMap:AC}=jm({resolveBindingTarget:e=>qc(e),evaluateStaticExpression:ns,buildExpressionSourceInfo:Kt,resolveSourceInfoProvenance:St}),{resolveExportValue:TC,resolveComponentPropBinding:FC,resolveBindingTarget:qc}=Fm({resolveExternalExpression:tl,resolveCollectionCallTarget:PC,evaluateStaticExpression:ns,resolveSourceInfoProvenance:St,buildExpressionSourceInfo:Kt});function Wm(e){return new Map([...e].map(t=>[t.file,{source:t.source,ast:t.ast}]))}function $m(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 Hm(e){let{file:t,source:n,segment:r,readFile:o,exists:i}=e,s=e.fileCache??new Map,a=qi(s,t,n);if(!a)return null;let c=es(a,r.sourceRange);if(!c)return null;let l=await Kt({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:o,exists:i,fileCache:s,visited:new Set});if(!l){let m=await il({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?Yc(m,hr(c.node,n)):null}let d=new Set,f=await eR({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?Yc(f,l.expression):null}async function xr(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=qi(i,t,n);if(!s)return null;let a=e.sourceRange?es(s,e.sourceRange):e.expression!==void 0?po(s,n,e.expression):null;if(!a)return null;let c=sl(a);if(!c.isIdentifier()&&!c.isMemberExpression())return null;let l=new Set,d=await Kt({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 tR({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 Yc(f,e.expression??hr(c.node,n))}async function el(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=qi(i,t,n);if(!s)return lt("unsupported-expression","Unable to parse source for provenance resolution");let a=new Set;return e.target.kind==="text-segment"?_C({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}):OC({file:t,source:n,ast:s,candidate:e.target.candidate,readFile:r,exists:o,graph:e.graph,fileCache:i,visited:a})}async function Kt(e){if(Z.isIdentifier(e.expression))return{kind:"identifier",expression:e.expression.name,base:e.expression.name,path:[]};if(!Z.isMemberExpression(e.expression))return null;let t=await NC(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 Yc(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 _C(e){let{file:t,source:n,ast:r,segment:o,readFile:i,exists:s,fileCache:a,visited:c}=e,l=es(r,o.sourceRange),d=l?await Kt({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 Vm(t,o.value);let m=await il({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"?zm(t,m):Qc(t,hr(l.node,n),m):MC({expression:l.node,scope:l.scope,currentFile:t,source:n,readFile:i,exists:s,fileCache:a,visited:c,functionCallContracts:e.functionCallContracts})}if(!l)return lt("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=Zc(l.node);if(m)return lt(m.code,m.message);let u=l.scope.getBinding(d.base);if(u?.path.isVariableDeclarator()){let g=Zc(u.path.node.init);if(g)return lt(g.code,g.message)}return u?.path.isVariableDeclarator()&&Z.isCallExpression(u.path.node.init)?DC("unsupported-expression",qm(u.path.node.init,e.functionCallContracts)):lt("unsupported-expression",`Unable to resolve provenance for expression "${d.expression}"`)}return f.kind==="external"?zm(t,f):Qc(t,d.expression,f)}async function OC(e){let{file:t,source:n,ast:r,candidate:o,readFile:i,exists:s,fileCache:a,visited:c}=e;if(!o.conditionSource)return lt("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let l=po(r,n,o.conditionExpression);if(!l)return lt("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 lt("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);if(d.kind==="external")return lt("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let f=Qc(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 Vm(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 MC(e){let t=await Ym(e);if(t.length===0)return lt("unsupported-expression",`Unsupported expression type: ${e.expression.type}`);if(LC(e.expression))return Gm(t);if(Qm(e.expression))return lt("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 lt("dynamic-key","Computed member expressions are not supported for provenance resolution");let[n]=t;return lt(n.code,n.message)}function lt(e,t){return{finalSource:null,chain:[],confidence:"unknown",editMode:"unsupported",diagnostics:[{code:e,message:t}]}}function DC(e,t){return Gm([{code:e,message:t}])}function Gm(e){return{finalSource:null,chain:[],confidence:"partial",editMode:"readonly",diagnostics:e}}function LC(e){return Z.isCallExpression(e)||Z.isConditionalExpression(e)||Z.isLogicalExpression(e)||Z.isBinaryExpression(e)}function ho(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 Ym(e){let{expression:t,scope:n,currentFile:r,readFile:o,exists:i,fileCache:s,visited:a,functionCallContracts:c}=e,l=Zc(t);if(l)return[l];if(Z.isCallExpression(t))return[{code:"unsupported-expression",message:qm(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 ns(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)?ho([...await Hc(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)?ho([...await Hc(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)?ho([...await Hc(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 Zc(e){return Qm(e)?Km("i18n helpers require a static message id string"):KC(e)?Km("CMS helpers require static entry id and field path string arguments"):null}async function Hc(...e){let t=e[e.length-1],n=e.slice(0,-1),r=[];for(let o of n)r.push(...await Ym({...t,expression:o}));return r}function BC(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:[jC(e.sourceType)]}}async function tl(e){for(let n of zC){if(!Um(e.expressionPath,n.helperNames))continue;let r=await n.resolve(e);if(r)return Xm(Jm(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(!Um(e.expressionPath,n.helperNames))continue;let r=await n.resolve(t);if(r)return Xm(Jm(r),e.externalAdapters)}return null}function jC(e){return{code:"missing-adapter",message:`No external adapter is registered for ${e}`}}function $C(e){return{code:"external-source-readonly",message:e}}function Km(e){return{code:"unsupported-expression",message:e}}function nl(e){return!e||!Z.isCallExpression(e)?null:Z.isIdentifier(e.callee)?e.callee.name:Z.isMemberExpression(e.callee)&&!e.callee.computed&&Z.isIdentifier(e.callee.object)&&Z.isIdentifier(e.callee.property)?`${e.callee.object.name}.${e.callee.property.name}`:null}function Um(e,t){if(!t||t.length===0)return!0;let n=nl(e.node);return n?t.includes(n):!1}function Jm(e){return"match"in e?{match:e.match,editMode:e.editMode,diagnostics:ho(e.diagnostics??[])}:{match:e,diagnostics:[]}}function Xm(e,t){let n=BC(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:ho([...e.diagnostics,...e.editMode==="readonly"||n.editMode==="readonly"?n.diagnostics:[]])}}function VC(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 KC(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 Zm(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 Qm(e){return Zm(e)===null}async function UC(e,t,n){let r=new Set,o=go.posix.dirname(e);for(;r.add(o),!(o==="."||o==="/");){let i=go.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"]:[go.posix.join(i,"locales"),go.posix.join(i,"messages")];for(let a of s){let c=go.posix.join(a,`${t}.json`);if(await n(c))return c}}return null}async function JC(e){let t=Zm(e.expressionPath.node);if(typeof t!="string"||t.length===0)return null;let n="en",r=await UC(e.currentFile,n,e.exists);return r?{sourceType:"i18n-message",sourceId:`${n}:${t}`,file:r,displayPath:t}:null}async function XC(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 ns(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:[$C("API mapping transforms must stay readonly until a reversible mapping strategy is registered")]}:i}var zC=[{helperNames:["getCmsField"],resolve:({expressionPath:e})=>VC(e)},{helperNames:["apiField"],resolve:e=>XC(e)},{helperNames:["t","intl.formatMessage"],resolve:({currentFile:e,expressionPath:t,exists:n})=>JC({currentFile:e,expressionPath:t,exists:n})}];function rl(e){return{...e,editMode:"readonly",diagnostics:[{code:"unsupported-expression",message:"Derived display values are readonly because no identity-preserving write target exists"}]}}function zm(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 Qc(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=qC(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 WC=[{helperName:"formatPrice",purity:"pure",sourceArgIndex:0},{helperName:"formatDate",purity:"pure",sourceArgIndex:0},{helperName:"pickLabel",purity:"pure",sourceArgIndex:0}];function ol(e,t){let n=[...WC,...t??[]];for(let r=n.length-1;r>=0;r-=1){let o=n[r];if(o?.helperName===e)return o}return null}function qm(e,t){let n=e.callee;return Z.isIdentifier(n)&&ol(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 il(e){let t=await tl(e);if(t)return t;let n=await eg({...e,expressionPath:e.expressionPath});if(n)return n;if(e.expressionPath.isTemplateLiteral()){let r=e.expressionPath.node.expressions[0],o=e.expressionPath.get("expressions.0");if(e.expressionPath.node.expressions.length===1&&r&&o&&!Array.isArray(o)&&o.isExpression()){let i=await Kt({expression:o.node,scope:o.scope,source:e.fileCache.get(e.currentFile)?.source,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(i){let s=await St({...e,expressionPath:o,sourceInfo:i});if(s&&s.kind==="value")return{...s,displayExpression:i.expression,editMode:"readonly",diagnostics:[{code:"unsupported-expression",message:"Mixed expressions are recognized but remain readonly until a safer composition editing strategy is available"}]}}}}return await ZC(e)}async function eg(e){let t=await Rt({...e,allowComposed:!1});if(t?.kind!=="source")return null;let n=sl(e.expressionPath);return n.isIdentifier()||n.isMemberExpression()?t.provenance:rl(t.provenance)}async function Rt(e){let t=sl(e.expressionPath),n=YC(e.currentFile,t.node);if(n&&e.visited.has(n))return null;n&&e.visited.add(n);try{if(t.isStringLiteral()||t.isNumericLiteral()||t.isBooleanLiteral()||t.isNullLiteral())return{kind:"none"};if(t.isIdentifier()){let r=await Kt({expression:t.node,scope:t.scope,source:e.fileCache.get(e.currentFile)?.source,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(!r)return null;let o=await St({currentFile:e.currentFile,expressionPath:t,sourceInfo:r,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});return!o||o.kind==="external"?null:{kind:"source",provenance:o}}if(t.isMemberExpression()){let r=await Kt({expression:t.node,scope:t.scope,source:e.fileCache.get(e.currentFile)?.source,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(!r)return null;let o=await St({currentFile:e.currentFile,expressionPath:t,sourceInfo:r,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});return!o||o.kind==="external"?null:{kind:"source",provenance:o}}if(t.isConditionalExpression()){let r=t.get("test"),o=t.get("consequent"),i=t.get("alternate");if(Array.isArray(r)||Array.isArray(o)||Array.isArray(i)||!r.isExpression()||!o.isExpression()||!i.isExpression())return null;let s=await Rt({...e,expressionPath:r,allowComposed:!0}),a=await Rt({...e,expressionPath:o,allowComposed:!1}),c=await Rt({...e,expressionPath:i,allowComposed:!1});return Gc(s,a,c)}if(t.isCallExpression())return HC({...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 Gc(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 Gc(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 sl(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 HC(e){let t=nl(e.expressionPath.node);if(t==="Math.round"||t==="Math.floor"||t==="Math.ceil"||t==="Math.trunc"||t==="useCountUp"){let r=e.expressionPath.get("arguments.0");return!r||Array.isArray(r)||!r.isExpression()?null:Rt({...e,expressionPath:r,allowComposed:!1})}let n=e.expressionPath.get("callee");if(n.isMemberExpression()&&!n.node.computed){let r=n.node.property;if(Z.isIdentifier(r)&&(r.name==="toFixed"||r.name==="toString")){let o=n.get("object");return Array.isArray(o)||!o.isExpression()?null:Rt({...e,expressionPath:o,allowComposed:!1})}}return null}function Gc(...e){let t=null;for(let n of e){if(!n)return null;if(n.kind!=="none"){if(!t){t=n.provenance;continue}if(!GC(t,n.provenance))return null}}return t?{kind:"source",provenance:t}:{kind:"none"}}function GC(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 YC(e,t){return t.start==null||t.end==null?null:`safe-derived:${e}:${t.start}:${t.end}`}async function ZC(e){if(!e.expressionPath.isCallExpression())return null;let t=nl(e.expressionPath.node);if(!t)return null;let n=ol(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 tg({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?rl(i):null}async function tg(e){let t=await tl({currentFile:e.currentFile,expressionPath:e.argumentPath,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(t)return t;let n=await Kt({expression:e.argumentPath.node,scope:e.argumentPath.scope,source:e.fileCache.get(e.currentFile)?.source,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(n){let r=await St({currentFile:e.currentFile,expressionPath:e.argumentPath,sourceInfo:n,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});return!r||r.kind==="external"?r:{...r,displayExpression:n.expression}}return await il({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 QC(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=ol(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 tg({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?rl(a):null}function qC(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 eR(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=Wc(e.expressionPath,t.base);if(n){let l=await wC({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=Mm(n.callPath,[...n.basePath,...t.path]);return Yr(h)?$m(e.currentFile,h.sourceId,h.displayPath):null}let d=Bm(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 tt(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 TC({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 tt(m.value,u)===void 0?null:{kind:"value",file:m.file,root:m.root,path:u,sourceKind:"imported-binding",collectionIndexMap:m.collectionIndexMap}}let o=Bf(r);if(o){let l=o.expressionPath,d=await Kt({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:yr(d.expression,t.path),path:[...d.path,...t.path]}});if(f)return f}if(t.path.length===0){let f=await eg({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 FC({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 QC({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=Pi(r,t.path);if(Yr(s))return $m(e.currentFile,s.sourceId,s.displayPath);let a=await qc({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:tt(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 tR(e){let t=Dm(e.expressionPath.node);if(!t||!Lm(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 AC({...e,rootPath:n.path,segments:t.segments});return r?{...n,path:r.collectionPathMap[0]??n.path,sourceKind:"repeat-template",displayExpression:hr(e.expressionPath.node,e.fileCache.get(e.currentFile)?.source),...r.collectionIndexMap?{collectionIndexMap:r.collectionIndexMap}:{},collectionPathMap:r.collectionPathMap}:null}async function ng(e){let t=nR(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 oR(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`}):rR(e,s.attribute)}async function rR(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 oR(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:iR(r,e.propertyName)}}function iR(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 rg(e){let{key:t,element:n,graph:r,provenances:o}=e,i=aR(t,n,r),s=i?.tag??($n(n.tag)?n.tag:n.componentName),a=i?.identity.key??og(n,r)??t,c=uR(i),l=dR(t,n,r,o,i),d=sR(t,n,r,o,a);return{componentName:s,instanceKey:a,templateOwner:lR(i??n,s),...c.length>0?{variantKeys:c}:{},...l.length>0?{slotKeys:l}:{},editableStrategy:d,impactScope:fR(d),alternativeStrategies:pR(d)}}function sR(e,t,n,r,o){for(let i of r.values())if(i?.editMode==="upstream")return"upstream";return al(e,n)?"instance":!$n(t.tag)&&t.sourceFile!==n.routeId&&o!==e?"template":"instance"}function og(e,t){if($n(e.tag))return e.identity.key;let n=[...t.elements.values()].filter(r=>r.importedFrom===e.sourceFile&&cR(r,e.componentName));return n.length!==1?null:n[0].identity.key}function aR(e,t,n){if($n(t.tag))return t;let r=al(e,n);if(r)return r;let o=og(t,n);return o?n.elements.get(o)??null:null}function cR(e,t){return e.exportName===t||e.tag===t||e.exportName==="default"}function lR(e,t){return $n(e.tag)&&e.importedFrom?`${e.importedFrom}#${t}`:`${e.sourceFile}#${t}`}function uR(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 dR(e,t,n,r,o){let i=new Set,s=al(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&&$n(t.tag)&&t.childKeys.length>0&&i.add("children"),[...i]}function al(e,t){let n=t.elements.get(e)?.parentKey??null;for(;n;){let r=t.elements.get(n);if(!r)break;if($n(r.tag))return r;n=r.parentKey}return null}function $n(e){return/^[A-Z]/.test(e)}function fR(e){switch(e){case"template":return"component-template";case"upstream":return"upstream-source";default:return"current-instance"}}function pR(e){switch(e){case"template":return["instance"];case"upstream":return["template"];default:return["template"]}}function ag(e){let t=e.isRepeat??(e.graph?vR(e.element,e.graph):!1),n=e.propertyProvenance??new Map,r=e.repeatTargets??new Map,o=ER(e.element.attributes??[]),i=[...r.values()].some(d=>d.ok),s=o.map(d=>mR({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:kR(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 mR(e){let{attribute:t,provenance:n,repeatTarget:r}=e,o=e.selectionRef?.instanceIndex!==void 0&&r?.ok===!0?r:null,i=gR(t,n,e.isRepeat),s=["selection","template"].map(b=>({scope:b,result:Bi({state:n,scope:b,operation:"set",selectionRef:e.selectionRef,isRepeat:e.isRepeat,repeatTarget:r})})),a=s.find(({result:b})=>b.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=hR(t,n,l,e.isRepeat),f=c?bR(c,e.element,t.name):void 0,m=s.filter(({result:b})=>b.ok).map(({scope:b})=>b),u=m.length>0?xR(n,o,e.element):"unsupported",g=o?"repeat-item":e.isRepeat?"repeat-template":"node",h=SR(t,n,r);if(m.length===0&&h.length===0){let b=s.find(({result:E})=>!E.ok)?.result;b&&!b.ok&&h.push({code:b.code,message:b.reason})}return{name:t.name,source:i,resolution:d,editMode:u,sourceScope:g,allowedWriteScopes:m,...f?{effectiveWriteTarget:f}:{},diagnostics:h}}function gR(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 hR(e,t,n,r){return n?ig(n.selectedResolution):t?.status==="blocked"?{status:"unresolved"}:r&&t?.status==="binding"?{status:"unresolved"}:ig(yR(e))}function yR(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 ig(e){return!e||e.status==="unresolved"?{status:"unresolved"}:e.status==="undefined"?{status:"undefined"}:{status:"resolved",value:e.value}}function xR(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 bR(e,t,n){return e.kind==="repeat-property"?{kind:"value-path",file:e.target.sourceFile,isProxy:e.target.sourceFile!==t.sourceFile,displayPath:sg({...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:sg(e.locator)}:{kind:"jsx-node",file:t.sourceFile,isProxy:!1,displayPath:t.componentName+" > "+n}}function SR(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 ER(e){let t=new Set;return e.filter(n=>t.has(n.name)?!1:(t.add(n.name),!0))}function vR(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 sg(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 kR(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 IR(e){return e==="api-field"||e==="cms-field"||e==="i18n-message"||e==="config-entry"}var CR=160;function cg(e,t,n,r={}){let o=tr(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 lg(e,t,n,r,o,i,s,a,c,l,d){let f=tr(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=mg(m.textSegments,s),b=gg(e,t,m,g,h),E=h?PR(h):void 0,v=AR(i,h),I=m.textSegments.map(C=>({index:C.index,value:C.value,editable:hg(C,g,s?.get(C.index)??null),source:o.get(C.index)??null})),R=fg(m,t),A=m.childKeys.map(C=>{let P=t.elements.get(C);return P?{key:C,tag:P.tag,label:P.tag}:null}).filter(C=>C!==null),T=[];if(m.parentKey){let C=t.elements.get(m.parentKey);if(C)for(let P of C.childKeys){if(P===e)continue;let O=t.elements.get(P);O&&T.push({key:P,tag:O.tag,label:O.tag})}}return{composition:f,key:e,tag:m.tag,componentName:m.componentName,sourceFile:m.sourceFile,sourceLocator:dg(m),label:m.tag,capabilities:b,writeTarget:i,effectiveWriteTarget:v,provenanceChain:E,componentSemantic:c,styleSource:l,conditional:a,...d?{dynamicData:d}:{},textSegments:I,boundaryKind:m.boundaryKind,isOpaque:m.isOpaque,ancestors:R,children:A,siblings:T}}function ug(e,t,n,r,o,i,s,a){let c=tr(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=mg(l.textSegments,i),u=RR(l);return{composition:c,key:e,tag:l.tag,...u?{linkSourceKind:u}:{},componentName:l.componentName,sourceFile:l.sourceFile,sourceLocator:dg(l),label:l.tag,capabilities:gg(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:hg(g,f,i?.get(g.index)??null),source:h?{kind:h.kind}:null}}),boundaryKind:l.boundaryKind,isOpaque:l.isOpaque,ancestors:fg(l,t)}}function RR(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 dg(e){return{sourceFile:e.sourceFile,componentName:e.componentName,openingElementRange:NR(e.sourceRange),structuralPath:e.identity.structuralPath,...wR(e.textSegments)}}function fg(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 NR(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function wR(e){let t=e.map(n=>n.value.trim()).filter(Boolean).join(" ").replace(/\s+/g," ").trim();return t?{textPreview:t.slice(0,CR)}:{}}function pg(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 mg(e,t){if(!t)return null;for(let n of e){let r=t.get(n.index);if(r)return r}return null}function gg(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&&yg(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 hg(e,t,n){return!e.editable||!t.canUpdateText?!1:n?yg(n.editMode):!0}function yg(e){return e==="direct"||e==="proxy"||e==="upstream"}function PR(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 AR(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}:IR(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 cl=["set-class-name-source","apply-style-draft"];function xg(e){let t=e.attributes?.find(n=>n.name==="className");if(!t)return{kind:"class-name-source",className:"",sourceKind:"missing",editable:!0,operationBoundary:cl,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:cl,sourcePath:n}}return{kind:"class-name-source",className:t.value,sourceKind:t.resolvedValue===void 0?"static-attribute":"static-expression",editable:!0,operationBoundary:cl}}function bg(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}),Sg(i,r,o,t,e)}}return{nodes:t,rootKeys:[...e.rootKeys]}}function Sg(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}),Sg(s,t,n,r,o))}}import Eg from"node:path";function ul(){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 kg(e,t,n){let r=[],o=new Set;for(let i of e.intents){let s=OR(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 rs(e){let t=()=>TR(e);return e.mutex?e.mutex.runExclusive(t):t()}async function TR(e){let t=await kg(e.plan,e.overlay,e.exists);if(!t.ok)return{ok:!1,stage:"precheck",reason:t.reason,error:t,recoveryRequired:!1};let n=FR(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 ll({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 ll({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 ll({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 vg("swap",l,"Live state swap failed after durable publish.")}try{await e.finalizeCandidate?.(c)}catch(l){return vg("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 FR(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 ll(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:_R(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 vg(e,t,n){return{ok:!1,stage:e,reason:n,error:t,recoveryRequired:!0}}function _R(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 OR(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)||Eg.isAbsolute(e))return{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`};let t=Eg.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 MR=50,DR=8*1024*1024;function Ng(e,t={}){let n=[],r=[],o=t.externalAdapters??[],i=Math.max(0,t.maxUndoEntries??MR),s=Math.max(0,t.maxUndoBytes??DR);return{prepareRewritePlan:a,execute:c,executeFilePlan:l,undo:d,redo:f};async function a(C){let P=[...C.steps].sort((Q,fe)=>Q.order-fe.order),O=P.filter(Q=>Q.type!=="invoke-external-adapter");if(O.length!==P.length)return{ok:!1,errorCode:"unsupported-operation",reason:"External adapter writes require a transactional prepare/commit/rollback contract."};let D=new Set(O.map(Q=>Q.file)),U=await v(D),ee=new Map(U.map(Q=>[Q.file,Q.exists===!1?"":Q.content])),Re;for(let Q of O){let fe=Rg(Q,ee.get(Q.file)??"");if(!fe.ok)return{ok:!1,errorCode:fe.errorCode,reason:fe.reason};ee.set(Q.file,fe.source),Re=fe.selectionRef??Re}return{ok:!0,filePlan:{operationId:C.operationId,kind:"source-edit",target:C.target,documentVersion:C.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}))},...Re?{selectionRef:Re}:{}}}async function c(C){let P=[...C.steps].sort((Oe,Yt)=>Oe.order-Yt.order),O=P.filter(Oe=>Oe.type!=="invoke-external-adapter"),D=P.filter(Oe=>Oe.type==="invoke-external-adapter"),U=new Set(O.map(Oe=>Oe.file));if(O.length>0&&D.length>0)return{ok:!1,operationId:C.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 b(C,D);let ee=await v(U),Re=new Map;for(let Oe of ee)Re.set(Oe.file,Oe.exists===!1?"":Oe.content);let Q;for(let Oe of O){let Yt=Re.get(Oe.file)??"",Zt=Rg(Oe,Yt);if(!Zt.ok)return{ok:!1,operationId:C.operationId,errorCode:Zt.errorCode,reason:Zt.reason,rolledBack:!1};Re.set(Oe.file,Zt.source),Zt.selectionRef&&(Q=Zt.selectionRef)}let fe=await R([...Re].map(([Oe,Yt])=>({file:Oe,content:Yt,exists:!0,version:0,sha256:Ee(Yt)})),ee);return fe.ok===!1?{ok:!1,operationId:C.operationId,errorCode:fe.rolledBack?"writeback-failed":"rollback-failed",reason:fe.reason,rolledBack:fe.rolledBack}:(n.push({operationId:C.operationId,preSnapshots:ee,postSnapshots:fe.snapshots,plan:C}),m(),r.length=0,{ok:!0,operationId:C.operationId,kind:C.kind,target:C.target,resultVersion:Math.max(...fe.snapshots.map(Oe=>Oe.version)),affectedFiles:[...U],...Q?{selectionRef:Q}:{}})}async function l(C){let P=new Set(C.edits.map(fe=>fe.file)),O=await v(P),D=E(C,O);if(D)return{ok:!1,operationId:C.operationId,errorCode:"stale-version",reason:D.reason,affectedFiles:[D.file],rolledBack:!1};let U=new Map(O.map(fe=>[fe.file,fe])),ee=C.edits.find(fe=>fe.operation==="create-only"&&U.get(fe.file)?.exists!==!1);if(ee)return{ok:!1,operationId:C.operationId,errorCode:"stale-version",reason:`MATERIALIZATION_INSTANCE_CONFLICT: create-only target already exists: ${ee.file}`,affectedFiles:[ee.file],rolledBack:!1};let Re=C.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 R(Re,O,new Set(C.edits.filter(fe=>fe.operation==="create-only").map(fe=>fe.file)));return Q.ok===!1?{ok:!1,operationId:C.operationId,errorCode:Q.rolledBack?"writeback-failed":"rollback-failed",reason:Q.reason,rolledBack:Q.rolledBack}:(n.push({operationId:C.operationId,preSnapshots:O,postSnapshots:Q.snapshots,plan:{operationId:C.operationId,kind:C.kind,target:C.target,documentVersion:C.documentVersion,steps:[],preSnapshots:O}}),m(),r.length=0,{ok:!0,operationId:C.operationId,kind:C.kind,target:C.target,resultVersion:Math.max(...Q.snapshots.map(fe=>fe.version)),affectedFiles:[...P]})}async function d(){let C=n.at(-1);if(!C)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to undo"};let P=await R(C.preSnapshots,C.postSnapshots);return P.ok===!1?{ok:!1,operationId:C.operationId,errorCode:P.rolledBack?"writeback-failed":"rollback-failed",reason:P.reason,rolledBack:P.rolledBack}:(n.pop(),r.push(C),{ok:!0,operationId:C.operationId,kind:C.plan.kind,target:C.plan.target,resultVersion:Math.max(...P.snapshots.map(O=>O.version)),affectedFiles:C.preSnapshots.map(O=>O.file)})}async function f(){let C=r.at(-1);if(!C)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to redo"};let P=await R(C.postSnapshots,C.preSnapshots);return P.ok===!1?{ok:!1,operationId:C.operationId,errorCode:P.rolledBack?"writeback-failed":"rollback-failed",reason:P.reason,rolledBack:P.rolledBack}:(r.pop(),n.push(C),m(),{ok:!0,operationId:C.operationId,kind:C.plan.kind,target:C.plan.target,resultVersion:Math.max(...P.snapshots.map(O=>O.version)),affectedFiles:C.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((C,P)=>C+g(P),0)}function g(C){return h(C.preSnapshots)+h(C.postSnapshots)}function h(C){return C.reduce((P,O)=>P+O.file.length+O.content.length,0)}async function b(C,P){let O=[];for(let D of P){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:C.operationId,errorCode:"unsupported-operation",reason:`No external adapter registered for ${D.sourceType}`,rolledBack:!1};let Re=await ee.execute(D);if(!Re.ok)return{ok:!1,operationId:C.operationId,errorCode:"writeback-failed",reason:Re.reason??`External adapter failed for ${D.sourceType}`,rolledBack:!1};O.push(D.file)}return{ok:!0,operationId:C.operationId,kind:C.kind,target:C.target,resultVersion:0,affectedFiles:O}}function E(C,P){if(C.conflictPolicy!=="compare-and-swap")return null;let O=new Map(P.map(D=>[D.file,D]));for(let D of C.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=O.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 v(C){let P=[];for(let O of C)P.push(await I(O));return P}async function I(C){if(!await e.exists(C))return{file:C,content:"",version:0,exists:!1};let O=Math.max(1,e.getVersion(C)),D=await e.readFile(C);return{file:C,content:D,version:O,exists:!0,sha256:Ee(D)}}async function R(C,P,O=new Set){let D=[];try{for(let U of C){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 A(U);let ee=e.bumpVersion(U.file);D.push(U.file),U.version=ee}}catch(U){let ee=await T(P.filter(Q=>D.includes(Q.file)));if(ee.ok===!1)return{ok:!1,reason:`Writeback failed, then rollback failed for ${ee.failedFiles.join(", ")}: ${Cg(U)}`,rolledBack:!1,instanceConflict:Ig(U)};let Re=Ig(U);return{ok:!1,reason:`${Re?"MATERIALIZATION_INSTANCE_CONFLICT: ":""}Writeback failed and committed files were restored: ${Cg(U)}`,rolledBack:!0,instanceConflict:Re}}return{ok:!0,snapshots:C.map(LR)}}async function A(C){if(C.exists===!1){await e.deleteFile(C.file);return}await e.writeFile(C.file,C.content)}async function T(C){let P=[];for(let O of C)try{await A(O),e.bumpVersion(O.file)}catch{P.push(O.file)}return P.length===0?{ok:!0}:{ok:!1,failedFiles:P}}}function Ig(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="EEXIST"}function LR(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 Cg(e){return e instanceof Error?e.message:String(e)}function Rg(e,t){switch(e.type){case"invoke-external-adapter":return{ok:!1,reason:"External adapter steps must be executed asynchronously",errorCode:"unsupported-operation"};case"add-import":return We(qn({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-import":return We(er({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-node":return We(Gn({source:t,locator:e.locator,removeWhitespace:e.removeWhitespace}));case"insert-child":return We(Yn({source:t,locator:e.parentLocator,node:e.node,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"update-text":return We(Yo({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(ri({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(oi({source:t,locator:e.locator,index:e.index}));case"move-array-item":return We(ii({source:t,locator:e.locator,fromIndex:e.fromIndex,toIndex:e.toIndex}));case"move-node":return We(Zn({source:t,locator:e.locator,targetParentLocator:e.targetParentLocator,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"move-repeat-template-child":return We(qo({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 BR(e,t);case"set-property-changes":return We(ei({source:t,locator:e.locator,changes:e.changes}));case"set-link-target":return We(ti({source:t,locator:e.locator,link:e.link,changes:e.changes}));case"set-property-binding":return We(ni({source:t,locator:e.locator,name:e.name,object:e.object,property:e.property}));case"upsert-object-property":return We(ai({source:t,objectLocator:e.locator,name:e.name,value:e.value}));default:return{ok:!1,reason:`Unknown step type: ${e.type}`,errorCode:"unknown"}}}function BR(e,t){let{request:n}=e;if(n.newAttrRaw!==null&&!dd(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:ud({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 os,SiteEditCompositionContextSchema as jR,SiteEditCompositionSelectorSchema as $R}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 wg(e,t){throw new Ye("INVALID_COMPOSITION",e,{value:t})}function is(e){let t=jR.safeParse(e);return t.success?t.data:wg("Invalid SiteEditCompositionContext.",e)}function Pg(e){let t=[],n=new Map,r=new Map;for(let l of e.compositions){let d=is(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=os(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=is(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=os(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=$R.safeParse(l);if(!d.success)return wg("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=is(l),f=os(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=is(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=os(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 VR,stripSiteEditRepeatInstanceKeys as Ag}from"@vcp-dev/contracts";function Tg(e){let t=new Map,n=new Map,r=new Map;for(let o of e.entries){t.set(o.key,o);let i=Ag(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 KR(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 dl(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 Fg(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)=>VR(u,g),c=(u,g,h)=>{let b=o.get(u);if(!b)return a(u,h);let E=a(u,h),v={...b,key:E,parentKey:g,childKeys:[]};return i.push(v),v.childKeys=b.childKeys.flatMap(I=>l(I,h,E)),E},l=(u,g,h)=>{if(!r.has(u))return[c(u,h,g)];let b=f(u,g),E=[];for(let v=0;v<b;v+=1)E.push(c(u,h,[...g,v]));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 b of m(u)){let E=n.get(b);if(E){for(let v of[...E.textTargets.values(),...E.elementPropertyTargets.values()])if(!(v?.kind!=="value-binding"||v.sourceKind!=="repeat-template"))for(let I of UR(v))I.length<=g.length||JR(I,g)&&h.add(I[g.length])}}return h.size>0?h.size:KR(n.get(u))}function m(u){let g=s.get(u);if(g)return g;let h=[u],b=o.get(u);for(let E of b?.childKeys??[])h.push(...m(E));return s.set(u,h),h}}function _g(e){let t=e.parts.at(-1);return typeof t?.repeatIndex=="number"?t.repeatIndex:null}function Og(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((Ag(s.key)??s.key)===n){if(s.key===t)return i;i+=1}return null}function UR(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 JR(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 Mg(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 Dg(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 Lg(e){return{path:e.path,code:e.code,message:e.message,...e.details?{details:JSON.parse(JSON.stringify(e.details))}:{}}}function XR(e){return e.map(t=>`${t.code} (${t.path}): ${t.message}`).join("; ")}var yo=class extends Error{constructor(t){let n=t.map(Lg);super(XR(n)),this.name="RouteBuildDiagnosticsError",this.diagnostics=n}};function Bg(e,t){let n=t instanceof Error&&t.message?t.message:String(t);return t instanceof yo?{routeId:e,message:n,diagnostics:t.diagnostics.map(Lg)}:{routeId:e,message:n}}function fl(e){return e.map(({routeId:t,message:n})=>`${t}: ${n}`).join("; ")}function pl(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 jg(e,t){for(let n of t){if(n.exists===!1){e.delete(n.file);continue}e.set(n.file,n.content)}}function ml(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 $g(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 qR=/^(?:src\/)?app\/.*\/?page\.[cm]?[jt]sx?$/,eN=["layout.tsx","layout.ts","layout.jsx","layout.js","layout.mjs","layout.cjs"],Vg=32,Kg=256;function tN(e){return{expectedIndexDigest:e.digest,publishedIndexDigest:e.digest,publishedCursor:e.cursor,publishedCurrentId:e.currentId}}var Ug={maxEntries:50,maxBytes:8*1024*1024};function nN(){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 li(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 rN(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 oN(){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>Ug.maxEntries||iN(e)>Ug.maxBytes;)e.shift()}}function iN(e){return e.reduce((t,n)=>t+sN(n),0)}function sN(e){return Jg(e.preSnapshots)+Jg(e.postSnapshots)+aN(e.provenance)}function aN(e){return e?new TextEncoder().encode(JSON.stringify(e)).byteLength:0}function Jg(e){return e.reduce((t,n)=>t+n.file.length+n.content.length,0)}function Xg(e,t){return{key:WR(e),composition:e,routeId:e.routeId,entryFile:t,graph:null,topology:null,capabilities:null,document:null,pageComposition:null,pageCompositionProjection:null,documentIndex:null,pagePlacementByKey:null,pagePlacementUnitByKey:null,pageUnitByKey:null,pagePlacementsByUnitKey:null,dependencyFiles:new Set([t]),detailProjections:null,fileVersions:new Map,styleContext:null}}var cs=class extends Error{constructor(t){super(t.reason),this.result=t}},Vn=class extends Error{constructor(t){super(fl(t)),this.failedRoutes=t}};function zg(e,t){if(!e)return;let n=[...t];if(n.some(o=>o?.entries.some(i=>i.key===e.key)))return e;let r=nt(e.key)??e.key;for(let o of n){let i=o?.entries.find(s=>(nt(s.key)??s.key)===r);if(i)return{...e,key:i.key}}return e}function cN(e,t,n){if(!n)return;let r=nt(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 lN=/\.(?:[cm]?[jt]sx?)$/i,uN=/\.json$/i,dN=/\.(?:css|scss|sass)$/i,fN=/\.mdx$/i,pN=/\.ya?ml$/i;function mN(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 gN(e){return{kind:e.isProxy?"component-proxy":"jsx-node",file:e.file,componentName:e.componentName,isProxy:e.isProxy}}function hN(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=Qg(await e.listFiles(r)),i=new Map(o.files.map(a=>[a.path,a]));for(let[a,c]of n)if(yN(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 yN(e,t){return t.length===0?!0:t.some(n=>e===n||e.startsWith(`${n}/`))}function Qg(e){return Array.isArray(e)?{files:e}:e}function xN(e){if(!GR(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!==ZR||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=HR(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(lN.test(e.path)){let t=At({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(uN.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(dN.test(e.path)){let t=Wg({content:e.content,path:e.path,profile:"css"});if(!t.ok)return t}if(fN.test(e.path)){let t=Wg({content:e.content,path:e.path,profile:"mdx"});if(!t.ok)return t}if(pN.test(e.path))try{QR(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`YAML parse failed: ${Qe(t)}`,details:{path:e.path}}}return{ok:!0}}function Wg({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 Jh from"@babel/parser";import*as Hn from"@babel/types";import*as qt from"node:path";var ws=[".tsx",".ts",".jsx",".js"],Xh=ws.map(e=>`/index${e}`),zh=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 ou(e){let t=e.replace(/[?#].*$/,""),n=/\.([a-z0-9]+)$/i.exec(t);return n!==null&&zh.has(n[1].toLowerCase())}function iu(e){let t=[];for(let n of e.program.body)Hn.isImportDeclaration(n)&&typeof n.source.value=="string"&&Pt(n.source.value)&&t.push(n.source.value),Hn.isExportNamedDeclaration(n)&&n.source&&typeof n.source.value=="string"&&Pt(n.source.value)&&t.push(n.source.value),Hn.isExportAllDeclaration(n)&&typeof n.source.value=="string"&&Pt(n.source.value)&&t.push(n.source.value);return Ps(e.program,t),t}function Ps(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"&&Pt(r.value)&&t.push(r.value)}for(let r of Object.values(n))if(Array.isArray(r))for(let o of r)Ps(o,t);else r&&typeof r=="object"&&Ps(r,t)}function Pt(e){return e.startsWith("./")||e.startsWith("../")||e.startsWith("@/")}function xn(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 Hh(e,t){if(ws.some(n=>e.endsWith(n))&&await t(e))return e;for(let n of ws){let r=`${e}${n}`;if(await t(r))return r}for(let n of Xh){let r=`${e}${n}`;if(await t(r))return r}return null}async function bn(e,t,n){let r=await Fo(e,t,n);return r.ok?r.path:null}async function Fo(e,t,n){let r=xn(e,t);try{if(!Wh(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 Hh(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 Wh(e,t,n){if(!Pt(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 Yh}from"node:crypto";import*as su from"@babel/parser";function Sn(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:Sn(t,n,r,o)}}function As(e,t,n,r,o){return{ok:!1,source:e,diagnostic:Sn(t,n,r,o)}}var Gh={"tsx-module":["jsx","typescript"],"ts-module":["typescript"],"next-app-entry":["jsx","typescript"]};function At(e){let{source:t,profile:n}=e;try{return{ok:!0,ast:su.parse(t,{sourceType:"module",plugins:Gh[n]})}}catch(r){return{ok:!1,source:t,diagnostic:Sn("parse-failed",`AST parse failed: ${r instanceof Error?r.message:String(r)}`)}}}function Ts(e,t){return At({source:e,profile:au(t.kind)})}function vr(e,t){return At({source:e,profile:au(t)})}function au(e){return"next-app-entry"}function En(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 vn=(e,t)=>{let n=At({source:t,profile:En({filePath:e,source:t})});return n.ok?{ok:!0,module:{file:e,source:t,sourceHash:`sha256:${Yh("sha256").update(t).digest("hex")}`,ast:n.ast,imports:iu(n.ast).map(r=>({specifier:r}))}}:{ok:!1,diagnostic:{path:e,code:"parse-failed",message:n.diagnostic.message}}};function Zh(e,t){return vn(e,t)}function Qh(e,t){return xn(e,t)}import{COMPONENT_I18N_FILE_SUFFIX as qh,parseComponentI18nResourcesJson as ey,resolveSiteTextDirection as ty,SiteLocaleSchema as ny}from"@vcp-dev/contracts";var ry=["i18next","react-i18next"],oy="components/ui/site-locale-provider.tsx",iy="components/ui/component-i18n-provider.tsx",cu="app/layout.tsx";async function _o(e){let t=e.files.filter(m=>m.path.endsWith(qh));if(t.length===0)return{ok:!0};for(let m of["package.json",cu,oy,iy])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=lu(n)&&lu(n.dependencies)?n.dependencies:{},o=ry.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(cu),s=Fs(i,"html","lang"),a=Fs(i,"html","dir"),c=Fs(i,"SiteLocaleProvider","locale"),l=ny.safeParse(s);if(!l.success||!a||!c||s!==c||a!==ty(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=ey(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 Fs(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 lu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function en(e){return{ok:!1,message:e}}import Os from"@babel/generator";import*as gu from"@babel/parser";import Ms from"@babel/traverse";import*as Ce from"@babel/types";import{computeSiteEditSourceIdentityKey as ay}from"@vcp-dev/contracts";var uu="data-vcp-ui-component",Oo="components/ui";function Ut(e){if(!e)return!1;let t=_s(e);return t===Oo||t.startsWith(`${Oo}/`)||t.includes(`/${Oo}/`)||t.endsWith(`/${Oo}`)}function kn(e,t){return e?e.startsWith("@/")||e.startsWith("~/")?Ut(e.slice(2)):e.startsWith("./")||e.startsWith("../")?Ut(_s(`${sy(t)}/${e}`)):Ut(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 sy(e){let t=_s(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}import{stripSiteEditRepeatInstanceKeys as Aw}from"@vcp-dev/contracts";import{isSiteEditRuntimeContainerTag as Fw,isSiteEditRuntimeTextTag as _w}from"@vcp-dev/contracts/site-edit-runtime-capability";var du={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 cy=typeof Os=="function"?Os:Os.default,ly=typeof Ms=="function"?Ms:Ms.default,uy=new Set(["base","body","head","html","link","meta","noscript","script","style","template","title"]),dy="suppressHydrationWarning",fy=new Set(["SiteEditBootstrap"]);function py(e){let t=hy(e.file,e.projectRoot);if(!gy(e.source)||Ut(t))return{code:e.source,elements:[]};let n=e.attributes??du,r=gu.parse(e.source,{sourceType:"module",plugins:["jsx","typescript"]}),o=[],i=xy(r,t);return ly(r,{JSXElement(s){let a=s.node.openingElement,c=a.name;if(!Sy(c)||hu(a,n.key))return;let l=vy(s)??"default",d=Iy(s),f=ay(t,l,d),m=Lo(c)??"unknown",u=yy(c)?"jsx":"component-call";if(u==="component-call"&&!ky(s.node.children)&&fy.has(m))return;let g=u==="component-call"&&by(m,i);Ey(a,n.key,f),g&&fu(a,uu),my(s)&&fu(a,dy),o.push({key:f,tag:m,componentName:l,sourceFile:t,sourceKind:u})}}),o.length===0?{code:e.source,elements:o}:{code:cy(r,{jsescOption:{minimal:!0}}).code,elements:o}}function my(e){return!e.findParent(t=>t.isJSXElement())}function gy(e){return/(?:^|[=(:,?;\[{>&|\n\r]|return\s+)\s*<(?:[A-Za-z][\w.:-]*|>)(?:\s|>|\/)/m.test(e)}function hy(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 yy(e){return Ce.isJSXIdentifier(e)&&/^[a-z]/.test(e.name)}function Lo(e){return Ce.isJSXIdentifier(e)?e.name:Ce.isJSXMemberExpression(e)?xu(e):null}function xy(e,t){let n=new Set;for(let r of e.program.body)if(!(!Ce.isImportDeclaration(r)||!kn(r.source.value,t)))for(let o of r.specifiers)n.add(o.local.name);return n}function by(e,t){let n=e.split(".")[0]??e;return t.has(n)}function Sy(e){let t=Lo(e);return!t||t==="Fragment"||t.endsWith(".Fragment")?!1:!uy.has(t)}function hu(e,t){return e.attributes.some(n=>Ce.isJSXAttribute(n)&&Ce.isJSXIdentifier(n.name,{name:t}))}function Ey(e,t,n){yu(e,Ce.jsxAttribute(Ce.jsxIdentifier(t),Ce.stringLiteral(n)))}function fu(e,t){hu(e,t)||yu(e,Ce.jsxAttribute(Ce.jsxIdentifier(t),null))}function yu(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 xu(e){return`${Ce.isJSXIdentifier(e.object)?e.object.name:xu(e.object)}.${e.property.name}`}function vy(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 ky(e){return e.some(t=>Ce.isJSXElement(t)||Ce.isJSXFragment(t))}var pu=new WeakMap,Mo=new WeakMap,Ls=new WeakMap;function Iy(e){let t=pu.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=Cy(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return pu.set(e.node,o),o}function Cy(e){let t=Lo(e.node.openingElement.name);return!t||t==="Fragment"||t.endsWith(".Fragment")?null:/^[A-Z]/.test(t)?`component:${t}#${mu(e,t)}`:`${t}#${mu(e,t)}`}function mu(e,t){let n=bu(e)??e.getFunctionParent();if(!n)return 0;let r=Ls.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=Ls.get(n.node);o||(o=new Map,Ls.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()?Do(n):Ry(n);for(let c of a)if(Lo(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 Ry(e){let t=Mo.get(e.node);if(t)return t;let n=[];return e.traverse({JSXElement(r){r.getFunctionParent()?.node===e.node&&!bu(r)&&n.push(r)}}),Mo.set(e.node,n),n}function bu(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 Do(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(...Do(o));continue}o.isJSXExpressionContainer()&&n.push(...In(o.get("expression")))}return Mo.set(e.node,n),n}function In(e){if(e.isJSXElement())return[e];if(e.isJSXFragment())return Do(e);if(e.isParenthesizedExpression())return In(e.get("expression"));if(e.isLogicalExpression()&&e.node.operator==="&&")return In(e.get("right"));if(e.isConditionalExpression())return[...In(e.get("consequent")),...In(e.get("alternate"))];if(e.isCallExpression()&&wy(e.node)){let t=e.get("arguments")[0];return Ny(t)}return[]}function Ny(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return[t];if(t.isJSXFragment())return Do(t);if(t.isParenthesizedExpression())return In(t.get("expression"));if(!t.isBlockStatement())return[];for(let n of t.get("body")){if(!n.isReturnStatement())continue;let r=n.get("argument");return r.node?In(r):[]}return[]}function wy(e){return Ce.isMemberExpression(e.callee)&&Ce.isIdentifier(e.callee.property)&&e.callee.property.name==="map"}import{SiteEditOperationRequestSchema as LN,SiteEditPatchPlanSchema as DN}from"@vcp-dev/contracts";function Cn(e){return{requestId:e.requestId,kind:e.kind,composition:e.composition,target:e.target,resultVersion:e.resultVersion,affectedFiles:e.affectedFiles,...e.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:Py(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:Cn(e.result),at:n}:e.type==="operation-failed"?{type:"site-edit.operation.failed",siteId:t.siteId,requestId:e.requestId,composition:e.composition,error:e.error,at:n}:e.type==="capability-changed"?{type:"site-edit.capability.changed",siteId:t.siteId,composition:e.composition,keys:e.keys,at:n}:e.type==="graph-invalidated"?{type:"site-edit.graph.invalidated",siteId:t.siteId,composition:e.composition,at:n}:e.type==="graph-ready"?{type:"site-edit.graph.ready",siteId:t.siteId,composition:e.composition,version:e.version,at:n}:e.type==="graph-error"?{type:"site-edit.graph.error",siteId:t.siteId,composition:e.composition,message:e.message,at:n}:null}function Py(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 zR,computeSiteEditCompositionKey as HR,getSiteEditSourceDeleteProtectionReason as WR,isSiteEditTextSourcePath as GR,parseSiteEditRepeatInstanceKey as YR,SITE_EDIT_SOURCE_DELETE_CAPABILITY as ZR,stripSiteEditRepeatInstanceKeys as nt}from"@vcp-dev/contracts";import cs from"node:path";import{parse as QR}from"yaml";import Vs from"node:path";import{TextDecoder as Ty}from"node:util";import{SITE_EDIT_SOURCE_ALLOWED_APP_FILES as Eu,SITE_EDIT_SOURCE_ALLOWED_DIRS as vu,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as ku,SiteEditCompositionContextSchema as Fy,SiteEditSourceFileResponseSchema as Ds,SiteEditSourceLocationSchema as _y,SiteEditSourcePathSchema as Ko,SiteEditSourceTreeResponseSchema as Oy,isSiteEditTextSourcePath as My}from"@vcp-dev/contracts";import{createHash as Ay}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 Ee(e){return`sha256:${Ay("sha256").update(e).digest("hex")}`}var Ly=[...ku,...Eu,...vu];function Ks(e){if(!e.composition)throw new Error("Composition unavailable for source access policy.");return Fy.parse(e.composition)}var Bs=2e3,js=12,$s=24*1024*1024,Su=512*1024,Dy=new Set(["image/avif","image/gif","image/jpeg","image/png","image/webp","image/x-icon"]),By={".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"},jy={".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"},$y=new Ty("utf-8",{fatal:!0});async function Uo(e,t={}){let n=Ks(t),{files:r,truncated:o}=await Hy(e,t),i=Yy(r.map(s=>s.metadata));return Oy.parse({composition:n,nodes:i,defaultPath:Zy(r.map(s=>s.metadata)),totalFiles:r.length,...o?{truncated:o}:{}})}async function Jo(e,t,n={}){let r=Ks(n),o=Ko.parse(t.path),i=await Ky(e,o,n);if(!i)throw new Error(`Source file not found: ${o}`);if(Js(o)){let a=Ru(o),c=await Jy(e,{path:o,sizeBytes:i.sizeBytes,mimeType:a});return Ds.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:i.sizeBytes,mimeType:a,readonly:!0,...c})}let s=await Us(e,o);return s.ok?Ds.parse({composition:r,path:o,kind:"text",language:Nu(o),sizeBytes:s.sizeBytes,contentHash:Ee(s.content),readonly:!1,content:s.content}):Ds.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:s.sizeBytes,mimeType:"application/octet-stream",readonly:!0,previewUnavailableReason:"unsupported-mime"})}async function Us(e,t){if(e.readFileBytes){let o=await e.readFileBytes(t),i=Vy(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 Vy(e){if(e.includes(0))return null;try{return $y.decode(e)}catch{return null}}async function Ky(e,t,n){if(!Xy(t,n))return null;let r=await Uy(e,t);return r?{path:t,sizeBytes:r.sizeBytes}:null}async function Uy(e,t){if(e.getFileInfo)return e.getFileInfo(t);if(e.listFiles){let o=Iu(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(Js(t))return{path:t,sizeBytes:0};let n=await e.readFile(t);return{path:t,sizeBytes:Buffer.byteLength(n,"utf8")}}async function Jy(e,t){if(!Dy.has(t.mimeType))return{previewUnavailableReason:"unsupported-mime"};if(t.sizeBytes>Su)return{previewUnavailableReason:"too-large"};if(!e.readFileBytes)return{previewUnavailableReason:"bytes-unavailable"};let n=await e.readFileBytes(t.path);return n.byteLength>Su?{previewUnavailableReason:"too-large"}:{contentBase64:Buffer.from(n).toString("base64")}}function Xy(e,t){return ku.some(n=>n===e)||Eu.some(n=>n===e)||vu.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 _y.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 Iu(e){return Array.isArray(e)?{files:e}:e}function zy(e){return["max-files","max-depth","max-total-bytes"].filter(n=>e.includes(n))}async function Hy(e,t){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let n=Iu(await e.listFiles({roots:Wy(t),maxFiles:Bs+1,maxDepth:js,maxTotalBytes:$s+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>js){o.add("max-depth");continue}if(r.size>=Bs){o.add("max-files");break}if(i+a.sizeBytes>$s){o.add("max-total-bytes");break}r.set(l,{path:l,sizeBytes:a.sizeBytes,metadata:Gy(l,a.sizeBytes,Ks(t))}),i+=a.sizeBytes}return{files:[...r.values()].sort((a,c)=>a.path.localeCompare(c.path)),...o.size>0?{truncated:{reasons:zy([...o]),maxFiles:Bs,maxDepth:js,maxTotalBytes:$s}}:{}}}function Wy(e){let t=new Set(Ly);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 Gy(e,t,n){return Js(e)?{composition:n,path:e,kind:"binary",language:null,sizeBytes:t,mimeType:Ru(e),readonly:!0}:{composition:n,path:e,kind:"text",language:Nu(e),sizeBytes:t,readonly:!1}}function Yy(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 Cu(t)}function Cu(e){return e.map(t=>t.kind==="directory"?{...t,children:Cu(t.children)}:t).sort((t,n)=>t.kind!==n.kind?t.kind==="directory"?-1:1:t.name.localeCompare(n.name))}function Zy(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 Js(e){return!My(e)}function Ru(e){let t=Vs.posix.extname(e).toLowerCase();return!t&&Vs.posix.basename(e).toLowerCase()==="favicon"?"image/x-icon":By[t]??"application/octet-stream"}function Nu(e){let t=Vs.posix.extname(e).toLowerCase();return jy[t]??"plaintext"}import Xs from"@babel/traverse";import*as Tt from"@babel/types";function Fe(e){if(e.isJSXFragment())return!0;if(!e.isJSXElement())return!1;let t=e.node.openingElement.name;if(Tt.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(Tt.isIdentifier(s)&&s.name==="Fragment"||Tt.isStringLiteral(s)&&s.value==="Fragment")&&wu(i.parentPath)}if(!Tt.isJSXMemberExpression(t)||!Tt.isJSXIdentifier(t.property)||t.property.name!=="Fragment"||!Tt.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())&&wu(r.parentPath)}function wu(e){return e?.isImportDeclaration()===!0&&e.node.source.value==="react"}var tn=typeof Xs=="function"?Xs:Xs.default,zo=new WeakMap,Ho=new WeakMap;function Ft(e,t){let n=Ts(e,t);if(!n.ok)return As(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}}:As(e,r.diagnostic.code,r.diagnostic.message,t.kind,r.diagnostic.details)}function ae(e,t){return t.kind==="jsx-node"?Fu(e,t):t.kind==="jsx-attribute"?rx(e,t):t.kind==="value"?ox(e,t):t.kind==="expression"?ix(e,t):t.kind==="directive"?sx(e,t):t.kind==="export"?ax(e,t):{ok:!1,diagnostic:Sn("unsupported-syntax",`Unsupported locator kind: ${t.kind}`)}}function Fu(e,t){return t.strategy==="source-range"?Qy(e,t):qy(e,t)}function Qy(e,t){let n=null;if(tn(e,{JSXElement(o){if(!Rn(o.node,t.sourceRange))return;let i=De("jsx-node",o);if(i){if(!n){n=i;return}i.end-i.start<n.end-n.start&&(n=i)}},JSXFragment(o){if(!Rn(o.node,t.sourceRange))return;let i=De("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXExpressionContainer(o){if(!Rn(o.node,t.sourceRange))return;let i=De("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXText(o){if(!Rn(o.node,t.sourceRange))return;let i=De("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)}}),!n)return Be("jsx-node","locator-miss","JSX node not found for source-range locator");let r=n;return t.expectedIdentity&&!bx(r.path,t.expectedIdentity)?Be("jsx-node","locator-miss","JSX node failed expected identity validation"):{ok:!0,match:r}}function qy(e,t){if(t.structuralPath===""){let r=tx(e,t.component);if(r){let o=nx(r);if(o)return o}}let n=null;return tn(e,{JSXElement(r){if(Cr(r)!==t.component||Hs(r)!==t.structuralPath)return;let i=De("jsx-node",r);i&&(n=i,r.stop())},JSXFragment(r){if(Cr(r)!==t.component||Hs(r)!==t.structuralPath)return;let i=De("jsx-node",r);i&&(n=i,r.stop())}}),!n&&t.expectedRange&&(n=ex(e,t.component,t.expectedRange)),n?{ok:!0,match:n}:Be("jsx-node","locator-miss","JSX node not found for structural-path locator")}function ex(e,t,n){let r=null;return tn(e,{JSXElement(o){if(Cr(o)!==t||!Rn(o.node,n))return;let i=De("jsx-node",o);i&&(r=i,o.stop())},JSXFragment(o){if(Cr(o)!==t||!Rn(o.node,n))return;let i=De("jsx-node",o);i&&(r=i,o.stop())}}),r}function tx(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 nx(e){if(e.isArrowFunctionExpression()){let t=e.get("body");if(t.isBlockStatement()){let r=t.get("body").find(o=>o.isReturnStatement());if(r){let o=r.get("argument");if((o.isParenthesizedExpression()?o.get("expression"):o).isJSXFragment())return Be("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}return null}return(t.isParenthesizedExpression()?t.get("expression"):t).isJSXFragment()?Be("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target"):null}if(e.isFunctionDeclaration()||e.isFunctionExpression()){let t=e.get("body");if(t.isBlockStatement()){let n=t.get("body").find(r=>r.isReturnStatement());if(n){let r=n.get("argument");if((r.isParenthesizedExpression()?r.get("expression"):r).isJSXFragment())return Be("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}}}return null}function rx(e,t){let n=Fu(e,t.element);if(!n.ok)return n;let s=n.match.path.get("openingElement").get("attributes").find(c=>Sx(c,t.name));if(!s||!s.isJSXAttribute())return Be("jsx-attribute","locator-miss",`JSX attribute '${t.name}' not found`);let a=De("jsx-attribute",s);return a?{ok:!0,match:a}:Be("jsx-attribute","locator-miss",`JSX attribute '${t.name}' has no source range`)}function ox(e,t){let n=cx(e,t);if(!n.ok)return n;let r=lx(n.match.path,t.path??[]);return r.ok?t.expectedRange&&!Xt(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 ix(e,t){let n=null;return tn(e,{Identifier(r){if(!gx(r))return;let o=Au(r);if(!o||!Tu(o,t))return;let i=De("expression",r);i&&(t.expectedRange&&!Xt(r.node.loc,t.expectedRange)||(n=i,r.stop()))},MemberExpression(r){let o=Au(r);if(!o||!Tu(o,t))return;let i=De("expression",r);i&&(t.expectedRange&&!Xt(r.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:Be("expression","locator-miss","Expression not found")}function sx(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&&!Xt(i.node.loc,t.expectedRange))return;let s=De("directive",i);s&&(n=s,r.stop())}}),n?{ok:!0,match:n}:Be("directive","locator-miss",`Directive '${t.value}' not found`)}function ax(e,t){let n=null;return tn(e,{ExportNamedDeclaration(r){if(t.exportKind==="generate-metadata"){let c=r.get("declaration");if(c.isFunctionDeclaration()&&c.node.id?.name==="generateMetadata"){let m=De("export",c);if(!m||t.expectedRange&&!Xt(c.node.loc,t.expectedRange))return;n=m,r.stop();return}if(!c.isVariableDeclaration())return;let l=Ws(c,"generateMetadata");if(!l||!l.isVariableDeclarator())return;let d=l.get("init");if(!d.node)return;let f=De("export",d);if(!f||t.expectedRange&&!Xt(d.node.loc,t.expectedRange))return;n=f,r.stop();return}let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=Ws(o,t.exportKind==="named"?t.name:"metadata");if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node||t.expectedRange&&!Xt(s.node.loc,t.expectedRange))return;let a=De("export",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(t.exportKind!=="default")return;let o=r.get("declaration"),i=De("export",o);i&&(t.expectedRange&&!Xt(o.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:Be("export","export-not-found",`Export '${xx(t)}' not found`)}function cx(e,t){let n=null;return tn(e,{Expression(r){if(n||t.root.kind!=="expression"||!Rn(r.node,t.root.sourceRange))return;let o=De("value",r);o&&(n=o,r.stop())},VariableDeclarator(r){if(n)return;if(t.root.kind==="binding"){if(r.node.id.type!=="Identifier"||r.node.id.name!==t.root.name)return;let u=r.get("init");if(!u.node)return;let g=De("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=De("value",f);m&&(n=m,r.stop())},ExportNamedDeclaration(r){if(n||t.root.kind!=="named-export")return;let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=Ws(o,t.root.name);if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node)return;let a=De("value",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(n||t.root.kind!=="default-export")return;let o=r.get("declaration"),i=De("value",o);i&&(n=i,r.stop())}}),n?{ok:!0,match:n}:Be("value",t.root.kind==="named-export"||t.root.kind==="default-export"?"export-not-found":t.root.kind==="expression"?"locator-miss":"binding-not-found","Value root was not found")}function lx(e,t){let n=zs(e);for(let o of t){if(n=zs(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=>Ex(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=zs(n);let r=De("value",n);return r?{ok:!0,match:r}:Be("value","locator-miss","Resolved value has no source range")}function zs(e){let t=e;for(;t.isTSAsExpression()||t.isTSSatisfiesExpression()||t.isTSNonNullExpression();)t=t.get("expression");return t}function De(e,t){let n=t.node;return n.start==null||n.end==null?null:{locatorKind:e,node:n,start:n.start,end:n.end,path:t}}function Rn(e,t){return Xt(e.loc,t)}function Xt(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 Hs(e){let t=[],n=e,r=e.node;for(;n;){if(n.isJSXElement()){if(!Fe(n)){let o=Ou(n.node.openingElement);o&&(/^[A-Z]/.test(o)?t.unshift(`component:${o}#${Pu(n,o)}`):t.unshift(`${o}#${Pu(n,o)}`))}}else n.isJSXFragment()&&n.node===r&&t.unshift("fragment");if(!n.parentPath||px(n.parentPath)&&!mx(n.parentPath))break;n=n.parentPath}return t.join("/")}function Pu(e,t){let n=_u(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):ux(n);for(let a of s)if(Ou(a.node.openingElement)===t){if(i.set(a.node,o),a.node===e.node)return o;o++}return i.get(e.node)??0}function ux(e){let t=Ho.get(e.node);if(t)return t;let n=[];return e.traverse({JSXElement(r){r.getFunctionParent()?.node===e.node&&!_u(r)&&n.push(r)}}),Ho.set(e.node,n),n}function _u(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 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(Fe(o)){n.push(...Ir(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...Ir(o));continue}o.isJSXExpressionContainer()&&n.push(...Jt(o.get("expression")))}return Ho.set(e.node,n),n}function Jt(e){if(e.isJSXElement())return Fe(e)?Ir(e):[e];if(e.isJSXFragment())return Ir(e);if(e.isParenthesizedExpression())return Jt(e.get("expression"));if(e.isLogicalExpression()&&dx(e.node.operator))return Jt(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(...Jt(c))}if(s.isReturnStatement()){let a=s.get("argument");a.isExpression()&&i.push(...Jt(a));break}}return i}else if(o.node&&o.isExpression())return Jt(o)}}}}return e.isConditionalExpression()?[...Jt(e.get("consequent")),...Jt(e.get("alternate"))]:e.isArrayExpression()?e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:Jt(t)):[]}function dx(e){return e==="&&"||e==="||"||e==="??"}function Ou(e){return e.name.type==="JSXIdentifier"?e.name.name:e.name.type==="JSXMemberExpression"?fx(e.name):null}function fx(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 px(e){return!!(e.isFunctionDeclaration()||e.isFunctionExpression()||e.isArrowFunctionExpression())}function mx(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 gx(e){return!(!e.isExpression()||e.parentPath?.isMemberExpression({property:e.node}))}function Au(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 Tu(e,t){return e.base===t.base&&hx(e.path,t.path??[])}function hx(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 yx(e){return e.key.type==="Identifier"?e.key.name:e.key.type==="StringLiteral"?e.key.value:null}function xx(e){return e.exportKind==="named"?e.name:e.exportKind}function Be(e,t,n,r){return{ok:!1,diagnostic:Sn(t,n,e,r)}}function bx(e,t){return Cr(e)!==t.component?!1:Hs(e)===t.structuralPath}function Sx(e,t){return!e.isJSXAttribute()||e.node.name.type!=="JSXIdentifier"?!1:e.node.name.name===t}function Ws(e,t){return e.get("declarations").find(n=>!n.isVariableDeclarator()||n.node.id.type!=="Identifier"?!1:n.node.id.name===t)}function Ex(e,t){return e.isObjectProperty()?yx(e.node)===t:!1}import*as Lu from"@babel/parser";import{arrayExpression as Rx,booleanLiteral as Nx,identifier as wx,jsxAttribute as Px,jsxExpressionContainer as Ax,jsxIdentifier as Tx,nullLiteral as Fx,numericLiteral as _x,objectExpression as Ox,objectProperty as Mx,stringLiteral as Ys}from"@babel/types";import Gs from"@babel/generator";var vx=typeof Gs=="function"?Gs:Gs.default;function kx(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 Ix(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 Cx(e,t){return e.split(`
|
|
3
|
+
`).map(r=>Ix(r,t)).join(`
|
|
4
|
+
`)}function Wo(e){let{ast:t,source:n}=e;try{let r=kx(n),i=vx(t,{comments:!0,jsescOption:{minimal:!0,quotes:"single"}},n).code;return r!=="2"&&(i=Cx(i,r)),{ok:!0,source:i}}catch(r){return K(n,"printer-failed",`AST print failed: ${r instanceof Error?r.message:String(r)}`)}}function Mu(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:Mu(e),afterSourceHash:Mu(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 Re(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 Lx(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 Wn(e,t,n){let r=Lx(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"?Ys(e):typeof e=="number"?_x(e):typeof e=="boolean"?Nx(e):e===null?Fx():Array.isArray(e)?Rx(e.map(t=>nn(t))):Ox(Object.entries(e).map(([t,n])=>{let r=Mx(Zs(t),nn(n));return t==="__proto__"&&(r.computed=!0),r}))}function Dx(e){return typeof e=="string"?Ys(e):Ax(nn(e))}function Nr(e,t){return Px(Tx(e),Dx(t))}function Yo(e,t){try{let r=Lu.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 Zs(e){return/^[$A-Z_][0-9A-Z_$]*$/i.test(e)?wx(e):Ys(e)}function Zo(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=Bx(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=jx(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 Bx(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=$x(r.get("expression"));o.length>0&&t.push(...o)}}return t}function jx(e,t){let n=e.match(/^\s*/)?.[0]??"",r=e.match(/\s*$/)?.[0]??"";return`${n}${t.trim()}${r}`}function $x(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 Qs}from"@babel/types";function Gn(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?(Vx(o.match.path),me(r.ast,t,{kind:"remove-node",target:"jsx-node",inverse:"insert-child"})):{ok:!1,source:t,diagnostic:o.diagnostic}}function Vx(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(Qs());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(Qs());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(Qs());return}e.remove()}import{cloneNode as Kx}from"@babel/types";function Qo(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=Yo(e.source,e.node.jsx);return r.ok?(n.match.path.replaceWith(Kx(r.node,!0)),me(t.ast,e.source,{kind:"replace-node",target:"jsx-node",inverse:"replace-node"})):r.result}import{cloneNode as qx}from"@babel/types";import qs from"@babel/traverse";import*as q from"@babel/types";function wr(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 Ux=typeof qs=="function"?qs:qs.default;function gt(e,t,n,r){if(!e.ok)return e;let o=mt(n,t);if(!o)return e;let i=Jx(t,o,r);return i?{...e,selectionRef:i}:e}function Jx(e,t,n){let r=Xx(e,t);if(!r)return;let o=n.sourceLocator?Du(n.sourceLocator):void 0,i=n.targetParentLocator?Du(n.targetParentLocator):void 0,s=n.file??i?.file??o?.file,a=n.component??Hx(r)??i?.component??o?.component;if(!(!s||!a))return{key:wr(s,a,Wx(r))}}function Du(e){return e.strategy==="structural-path"?{file:e.file,component:e.component,structuralPath:e.structuralPath}:e.expectedIdentity}function Xx(e,t){let n=Uu(e,t);return!n||n.node.type!=="JSXElement"?null:n}function Uu(e,t){let n=null;return Ux(e,{JSXElement(r){r.node===t&&(n=r,r.stop())},JSXFragment(r){r.node===t&&(n=r,r.stop())}}),n}function mt(e,t){if(!e)return null;if(q.isJSXElement(e))return Qx(t,e)?Bu(e.children,t):e;if(q.isJSXFragment(e))return Bu(e.children,t);if(q.isJSXExpressionContainer(e)||q.isParenthesizedExpression(e)||q.isTSAsExpression(e)||q.isTSSatisfiesExpression(e)||q.isTSTypeAssertion(e)||q.isTSNonNullExpression(e))return mt(e.expression,t);if(q.isLogicalExpression(e))return mt(e.right,t);if(q.isConditionalExpression(e))return mt(e.consequent,t)??mt(e.alternate,t);if(q.isCallExpression(e)||q.isOptionalCallExpression(e))return Ju(e)?zx(e.arguments[0],t):null;if(q.isArrayExpression(e))for(let n of e.elements){if(!n)continue;let r=mt(n,t);if(r)return r}return null}function Bu(e,t){for(let n of e){let r=mt(n,t);if(r)return r}return null}function zx(e,t){return!e||!q.isArrowFunctionExpression(e)&&!q.isFunctionExpression(e)?null:q.isBlockStatement(e.body)?Pr(e.body.body,t):mt(e.body,t)}function Pr(e,t){for(let n of e){if(q.isReturnStatement(n)){let r=mt(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=ju(n.consequent,t);if(r)return r;let o=n.alternate?ju(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 ju(e,t){return q.isBlockStatement(e)?Pr(e.body,t):Pr([e],t)}function Hx(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 $u=new WeakMap,Vu=new WeakMap,ea=new WeakMap;function Wx(e){let t=$u.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=Gx(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return $u.set(e.node,o),o}function Gx(e){let t=Xu(e.node.openingElement.name);return!t||Fe(e)?null:/^[A-Z]/.test(t)?`component:${t}#${Ku(e,t)}`:`${t}#${Ku(e,t)}`}function Ku(e,t){let n=Yx(e);if(!n)return 0;let r=ea.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=ea.get(n.node);o||(o=new Map,ea.set(n.node,o));let i=o.get(t);i||(i=new WeakMap,o.set(t,i));let s=0;for(let a of Nn(n))if(Xu(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 Yx(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 Nn(e){let t=Vu.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(...Nn(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...Nn(o));continue}o.isJSXExpressionContainer()&&n.push(..._t(o.get("expression")))}return Vu.set(e.node,n),n}function _t(e){if(e.isJSXElement())return Fe(e)?Nn(e):[e];if(e.isJSXFragment())return Nn(e);if(e.isParenthesizedExpression())return _t(e.get("expression"));if(e.isLogicalExpression())return _t(e.get("right"));if(e.isConditionalExpression())return[..._t(e.get("consequent")),..._t(e.get("alternate"))];if(e.isArrayExpression())return e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:_t(t));if((e.isCallExpression()||e.isOptionalCallExpression())&&Ju(e.node)){let t=e.get("arguments"),n=Array.isArray(t)?t[0]:void 0;return n?Zx(n):[]}return[]}function Zx(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return Fe(t)?Nn(t):[t];if(t.isJSXFragment())return Nn(t);if(t.isParenthesizedExpression())return _t(t.get("expression"));if(t.isLogicalExpression()||t.isConditionalExpression())return _t(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(..._t(s))}if(!r.isReturnStatement())continue;let o=r.get("argument");return o.node&&n.push(..._t(o)),n}return n}function Ju(e){let t=e.callee;return(q.isMemberExpression(t)||q.isOptionalMemberExpression(t))&&q.isIdentifier(t.property)&&t.property.name==="map"&&!t.computed}function Qx(e,t){let n=Uu(e,t);return n?Fe(n):!1}function Xu(e){return q.isJSXIdentifier(e)?e.name:q.isJSXMemberExpression(e)?zu(e):q.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function zu(e){return`${q.isJSXIdentifier(e.object)?e.object.name:zu(e.object)}.${e.property.name}`}function rn(e,t){if(t.parentPath===e&&t.listKey==="children"&&ta(e))return e;if(!t.parentPath||t.listKey!=="children")return null;let n=t.parentPath;if(!ta(n))return null;let r=n;for(;r&&r!==e;){if(!ta(r)||!Fe(r)||r.listKey!=="children")return null;r=r.parentPath}return r===e?n:null}function ta(e){return e.isJSXElement()||e.isJSXFragment()}function Yn(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 I=c.match.path.node;if(!I.closingElement||I.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=qx(d.node,!0),m=l.node.children,u={...s,targetParentLocator:n},g=I=>s?gt(I,a.ast,f,u):I;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 b=rn(c.match.path,h.match.path);if(!b)return K(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");l=b;let E=l.node.children,v=E.findIndex(I=>I===h.match.path.node);return v===-1?K(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(E.splice(o==="before"?v:v+1,0,f),g(me(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"})))}import*as Hu from"@babel/parser";import{cloneNode as eb}from"@babel/types";function qo(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=tb(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 v=rn(l.match.path,E.match.path);if(!v)return K(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");d=v,f=E.match.path.node}else if(o==="before"||o==="after")return K(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let m=eb(c.node,!0),u=d.node.children,g={...s,targetParentLocator:n},h=E=>s?gt(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 b=u.findIndex(E=>E===f);return b===-1?K(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(u.splice(o==="before"?b:b+1,0,m),h(me(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"})))}function tb(e,t){try{let r=Hu.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 nb,nullLiteral as na}from"@babel/types";import*as on from"@babel/types";import*as Wu from"@babel/types";function Ar(e,t){let n=e.parentPath;if(!n?.isConditionalExpression()||e.key!=="consequent"||!Wu.isNullLiteral(n.node.alternate))return e;let r=n.parentPath;return!r?.isJSXExpressionContainer()||r.parentPath?.node!==t.node||r.listKey!=="children"?e:r}function Zn(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 I=l.match.path.node;if(!I.closingElement||I.openingElement.selfClosing)return K(t,"self-closing-element","Cannot move child into self-closing element","jsx-node")}let f=null;if(i){let I=ae(a.ast,i);if(!I.ok)return{ok:!1,source:t,diagnostic:I.diagnostic};let R=I.match.path.isJSXElement()?Ar(I.match.path,l.match.path):I.match.path,A=rn(l.match.path,R);if(!A)return K(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");d=A,f=R}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=nb(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");rb(u);let b=d.node.children,E={...s,sourceLocator:n,targetParentLocator:r};if(o==="append")return b.push(g),gt(Go(a.ast,t),a.ast,g,E);if(o==="prepend")return b.unshift(g),gt(Go(a.ast,t),a.ast,g,E);let v=m-(h!==-1&&h<m?1:0);return b.splice(o==="before"?v:v+1,0,g),gt(Go(a.ast,t),a.ast,g,E)}function rb(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(na());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(na());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(na());return}e.remove()}import*as Gu from"@babel/parser";import{cloneNode as ob,nullLiteral as ra}from"@babel/types";function ei(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=ib(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 I=f.match.path.node;if(!I.closingElement||I.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 I=ae(c.ast,i);if(!I.ok)return{ok:!1,source:t,diagnostic:I.diagnostic};let R=rn(f.match.path,I.match.path);if(!R)return K(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");m=R,u=I.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=ob(l.node,!0);sb(d.match.path);let b={...a,sourceLocator:n,targetParentLocator:r},E=g.children;if(o==="append")return E.push(h),gt(me(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,h,b);if(o==="prepend")return E.unshift(h),gt(me(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,h,b);let v=E.findIndex(I=>I===u);return v===-1?K(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(E.splice(o==="before"?v:v+1,0,h),gt(me(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,h,b))}function ib(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","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 sb(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(ra());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(ra());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(ra());return}e.remove()}import{SiteEditSetPropsParamsSchema as ab,classifySiteEditPropertyName as cb}from"@vcp-dev/contracts";import*as Qn from"@babel/types";function ti(e){let t=ab.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=Wn(n.ast,e.locator,e.source);if(!r.ok)return r.result;for(let a of t.data.changes){let c=cb(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(Qn.isJSXAttribute),s=new Map;for(let a of i){let c=lb(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 lb(e){return Qn.isJSXIdentifier(e.name)?e.name.name:Qn.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:null}import{SiteEditOperationParamsSchema as ub}from"@vcp-dev/contracts";import*as z from"@babel/types";var Yu=["prefetch","replace","scroll","locale","onNavigate"],db=/^on(?:Click|DoubleClick|AuxClick|MouseDown|MouseUp|PointerDown|PointerUp|TouchStart|TouchEnd|KeyDown|KeyUp|ContextMenu)(?:Capture)?$/;function fb(e){let t=e;for(;t;){if(t.isJSXElement()&&t.node.openingElement.attributes.some(n=>z.isJSXAttribute(n)&&z.isJSXIdentifier(n.name)&&db.test(n.name.name)))return!0;t=t.parentPath}return!1}function ni(e){let t=Re(e.source,"jsx-node");if(!t.ok)return t.result;let n=Wn(t.ast,e.locator,e.source);if(!n.ok)return n.result;let r=ub.safeParse({kind:"set-link-target",scope:"selection",link:e.link,changes:e.changes});if(!r.success||r.data.kind!=="set-link-target")return zt(e.source,"Invalid typed link-target changes");let o=n.match.path,i=o.node,s=i.openingElement,a=bb(s.name);if(!a)return zt(e.source,"Unsupported JSX link tag");if(s.attributes.some(z.isJSXSpreadAttribute))return zt(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=ia(g);if(!h)return zt(e.source,"Unsupported JSX attribute name");let b=c.get(h)??[];b.push(g),c.set(h,b)}if([...c.values()].some(g=>g.length>1))return zt(e.source,"Duplicate JSX attributes cannot be transformed safely");let l=c.get("href")?.[0];if(l&&!xb(l))return zt(e.source,"Dynamic link href cannot be transformed safely");let d=a==="a",f=d?null:gb(o,s.name);if(!d&&!f)return zt(e.source,"Only native anchors and imported next/link components are supported");if(e.link.kind==="none"&&fb(o))return zt(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=hb(t.ast,o);if(!g.ok)return zt(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")),yb(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"),Yu.forEach(g=>u.add(g))):(u.add("href"),e.link.kind==="native-link"&&Yu.forEach(g=>u.add(g))),s.attributes=s.attributes.filter(g=>{if(!z.isJSXAttribute(g))return!0;let h=ia(g);return!h||!u.has(h)}),e.link.kind!=="none"&&s.attributes.push(z.jsxAttribute(z.jsxIdentifier("href"),z.stringLiteral(e.link.href))),pb(s,e.changes),me(t.ast,e.source,{kind:"set-link-target",target:"jsx-node",inverse:"set-link-target"})}function pb(e,t){for(let n of t){let r=e.attributes.find(s=>z.isJSXAttribute(s)&&ia(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(oa(n.value)),i=z.jsxAttribute(z.jsxIdentifier(n.name),o);r&&z.isJSXAttribute(r)?r.value=i.value:e.attributes.push(i)}}function oa(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=>oa(t))):typeof e=="object"?z.objectExpression(Object.entries(e).map(([t,n])=>z.objectProperty(z.isValidIdentifier(t)?z.identifier(t):z.stringLiteral(t),oa(n)))):z.nullLiteral()}function mb(e){return z.isImportDefaultSpecifier(e)||z.isImportSpecifier(e)&&e.importKind!=="type"&&(z.isIdentifier(e.imported,{name:"default"})||z.isStringLiteral(e.imported,{value:"default"}))}function Zu(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 gb(e,t){if(!z.isJSXIdentifier(t))return null;let n=e.scope.getBinding(t.name);if(!n||!Zu(n.path))return null;let r=n.path.parentPath;return!r?.isImportDeclaration()||r.node.source.value!=="next/link"?null:t.name}function hb(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(mb);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 yb(e,t,n){let r=n.scope.getProgramParent();r.crawl();let o=r.getBinding(t);if(!o||!Zu(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 xb(e){return!e.value||z.isStringLiteral(e.value)}function bb(e){return z.isJSXIdentifier(e)?e.name:null}function ia(e){return z.isJSXIdentifier(e.name)?e.name.name:null}function zt(e,t){return K(e,"unsupported-syntax",t,"jsx-node")}import*as Ke from"@babel/types";import{classifySiteEditPropertyName as Qu}from"@vcp-dev/contracts";function ri(e){let t=Qu(e.name),n=Qu(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(!qu(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=Wn(r.ast,e.locator,e.source);if(!o.ok)return o.result;let i=o.match.path.node.openingElement,s=i.attributes.filter(l=>Ke.isJSXAttribute(l)&&Eb(l)===e.name);if(s.length>1)return K(e.source,"unsupported-syntax",`JSX attribute '${e.name}' has multiple sources`,"jsx-node");let a=Sb(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 Sb(e,t){return qu(t)?Ke.memberExpression(Ke.identifier(e),Ke.identifier(t)):Ke.memberExpression(Ke.identifier(e),Ke.stringLiteral(t),!0)}function qu(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(e)}function Eb(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 kb,identifier as Tr,importDeclaration as Ib,importDefaultSpecifier as Cb,importNamespaceSpecifier as Rb,importSpecifier as Nb,isImportDefaultSpecifier as ed,isImportNamespaceSpecifier as td,isImportSpecifier as nd,stringLiteral as wb}from"@babel/types";function qn(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(b=>!Db(b));if(o!==-1){let b=r[o],E=b&&typeof b=="object"&&"kind"in b?b.kind:void 0;return K(t,"unsupported-syntax",`Unsupported import spec kind: ${String(E)}`)}let i=Ob(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(b=>b.type==="ImportDeclaration"&&b.source.value===n),d=new Set(l.flatMap(b=>b.specifiers.flatMap(E=>{let v=Bb(b,E);return v?[v]:[]}))),f=i.imports.filter(b=>!d.has(cd(b)));if(f.length===0)return Rr(t,t,{kind:"add-import",target:"import",inverse:"remove-import"});let m=Mb(c.body),u=f.find(b=>m.has(sa(b)));if(u)return K(t,"unsupported-syntax",`Import local binding already exists: ${sa(u)}`);let g=_b(f);if(g.reduce((b,E)=>b+E.length,0)!==f.length)return K(t,"unsupported-syntax","Unsupported import specifier grouping");for(let b of g){if(!sd(od(b)))return K(t,"unsupported-syntax","Unsupported import specifier combination");let E=l.find(v=>Pb(v,b));if(E)Ab(E,b);else{let v=Ib(rd(b),wb(n));Lb(c.body,v),l.push(v)}}return me(a,t,{kind:"add-import",target:"import",inverse:"remove-import"})}function Pb(e,t){return e.importKind==="type"?!1:sd(Fb(Tb(e),od(t)))}function Ab(e,t){let n=!1,r=new Set(e.specifiers.map(o=>aa(o)));for(let o of rd(t)){let i=aa(o);r.has(i)||(e.specifiers.push(o),r.add(i),n=!0)}return ad(e.specifiers),{changed:n}}function rd(e){let t=e.map(n=>{switch(n.kind){case"named":return Nb(n.local?Tr(n.local):Tr(n.imported),Tr(n.imported));case"default":return Cb(Tr(n.local));case"namespace":return Rb(Tr(n.local));default:return n}});return ad(t),t}function od(e){let t=id();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 Tb(e){let t=id();for(let n of e.specifiers)ed(n)?t.defaultLocals.add(n.local.name):td(n)?t.namespaceLocals.add(n.local.name):t.hasNamed=!0;return t}function id(){return{defaultLocals:new Set,hasNamed:!1,namespaceLocals:new Set}}function Fb(e,t){return{defaultLocals:new Set([...e.defaultLocals,...t.defaultLocals]),hasNamed:e.hasNamed||t.hasNamed,namespaceLocals:new Set([...e.namespaceLocals,...t.namespaceLocals])}}function sd(e){return e.defaultLocals.size>1||e.namespaceLocals.size>1?!1:!(e.hasNamed&&e.namespaceLocals.size>0)}function ad(e){let t=[...e.filter(n=>ed(n)),...e.filter(n=>td(n)),...e.filter(n=>nd(n))];e.splice(0,e.length,...t)}function _b(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 Ob(e){let t=new Map,n=new Map;for(let r of e){let o=cd(r);if(t.has(o))continue;let i=sa(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 Mb(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(kb(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 Lb(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 Db(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 cd(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 sa(e){return e.kind==="named"?e.local??e.imported:e.local}function Bb(e,t){return e.importKind==="type"||nd(t)&&t.importKind==="type"?null:aa(t)}function aa(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 er(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(d=>!$b(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 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=>jb(d,f))),l.specifiers.length===0&&a.body.splice(c,1),me(s,t,{kind:"remove-import",target:"import",inverse:"add-import"}))}function jb(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 $b(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(nn(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,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 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=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 ci(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)&&Vb(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(Zs(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 Vb(e){return Xe.isIdentifier(e)?e.name:Xe.isStringLiteral(e)?e.value:Xe.isNumericLiteral(e)?String(e.value):null}import{isSiteEditRuntimeContainerTag as Kb,isSiteEditRuntimeVoidElementTag as Ub}from"@vcp-dev/contracts/site-edit-runtime-capability";function tr(e){if(!e.composition)throw new Error("Composition unavailable for render source graph.");return e.composition}function Jb(e,t,n){let r=tr(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(R=>({kind:R.kind,message:R.reason})),a=i.isOpaque,l=o.parentKey===null&&i.componentName==="Page",d=i.tag.toLowerCase(),f=i.tag!==d,m=!f&&Ub(d),u=f||Kb(d),g=f&&i.childKeys.length>0&&!i.isPublicUiComponent,h=i.textSegments.length>0&&i.textSegments.some(R=>R.editable);m&&!s.some(R=>R.kind==="void-element")&&s.push({kind:"void-element",message:`Element '${i.tag}' is void: children cannot be inserted`}),!m&&!u&&!s.some(R=>R.kind==="void-element")&&s.push({kind:"void-element",message:`Element '${i.tag}' cannot contain structured children`});let b=h&&(!a||i.importedFrom==="next/link"),E=!i.isPublicUiComponent&&!m&&u&&(!a||g);return{composition:r,key:e,canUpdateText:b,canInsertChild:E,canMove:!l,canRemove:!l,constraints:s}}function ld(e,t){let n=new Map;for(let r of e.nodes.keys())n.set(r,Jb(r,e,t));return n}function ca(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=Xb(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:dd(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:ud(e.route.source,o),valueRaw:s?ud(e.route.source,s):null,attrRange:dd(o),diagnostics:[]}}function fd(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 Xb(e,t){let n=At({source:e,profile:En({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:zb(t.sourceRange)});return!r.ok||r.match.node.type!=="JSXElement"?null:r.match.node}function pd(e){let t=At({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 ud(e,t){return t.start==null||t.end==null?"":e.slice(t.start,t.end)}function dd(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 zb(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function md(){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 Hb}from"node:crypto";import li from"node:fs/promises";import la from"node:path";import{setTimeout as Wb}from"node:timers/promises";var Gb={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)}},Yb=new Set(["EACCES","EBUSY","EPERM"]),Zb=[10,20,40,80,160];async function Qb(e,t,n){for(let r of Zb)try{await e.rename(t,n);return}catch(o){if(!qb(o))throw o;await Wb(r)}await e.rename(t,n)}function qb(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&Yb.has(e.code)}async function ui(e,t,n=Gb){let r=la.dirname(e),o=la.basename(e),i=la.join(r,`.${o}.${process.pid}.${Hb()}.tmp`),s=!1;try{await n.mkdir(r,{recursive:!0}),await n.writeFile(i,t,"utf8"),await Qb(n,i,e),s=!0}finally{if(!s)try{await n.rm(i,{force:!0})}catch{}}}import ua from"@babel/traverse";import*as S from"@babel/types";import*as ue from"@babel/types";function Ot(e,t={}){if(ue.isTSAsExpression(e)||ue.isTSSatisfiesExpression(e)||ue.isTSNonNullExpression(e)||ue.isTypeCastExpression(e)||ue.isParenthesizedExpression(e))return Ot(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=Ot(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=eS(r.key);if(o===null)return{status:"unresolved"};let i=Ot(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 eS(e){return ue.isIdentifier(e)?e.name:ue.isStringLiteral(e)?e.value:ue.isNumericLiteral(e)?String(e.value):null}var tS=typeof ua=="function"?ua:ua.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 nS(e){return/^[A-Z]/.test(e)}function ga(e){let t=e.openingElement;return S.isJSXIdentifier(t.name)?t.name.name==="Fragment":S.isJSXMemberExpression(t.name)?t.name.property.name==="Fragment":!1}function rr(e){return S.isJSXFragment(e)}function hd(e){return S.isJSXIdentifier(e.name)?e.name.name:S.isJSXMemberExpression(e.name)?yd(e.name):S.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:"unknown"}function yd(e){return S.isJSXIdentifier(e.object)?`${e.object.name}.${e.property.name}`:S.isJSXMemberExpression(e.object)?`${yd(e.object)}.${e.property.name}`:e.property.name}function rS(e){return e.split(".")[0]??e}function oS(e){let t=e;for(;t;){let n=t.node;if(S.isFunctionDeclaration(n)&&n.id||S.isVariableDeclarator(n)&&S.isIdentifier(n.id))return n.id.name;if(S.isExportDefaultDeclaration(n)){let r=n.declaration;if(S.isFunctionDeclaration(r)&&r.id)return r.id.name;if(S.isFunctionDeclaration(r)&&!r.id)return"default"}t=t.parentPath}return null}function iS(){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 sS(e){let t=new Map;for(let n of e.program.body){if(!S.isImportDeclaration(n))continue;let r=n.source.value;for(let o of n.specifiers)if(S.isImportDefaultSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"default"});else if(S.isImportNamespaceSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"*"});else if(S.isImportSpecifier(o)){let i=S.isIdentifier(o.imported)?o.imported.name:o.imported.value;t.set(o.local.name,{specifier:r,exportName:i})}}return t}function Ht(e,t=[]){if(S.isIdentifier(e))return t.push(e.name),t;if(S.isObjectPattern(e)){for(let n of e.properties)S.isObjectProperty(n)?Ht(n.value,t):S.isRestElement(n)&&Ht(n.argument,t);return t}if(S.isArrayPattern(e)){for(let n of e.elements)n&&(S.isRestElement(n)?Ht(n.argument,t):Ht(n,t));return t}return S.isAssignmentPattern(e)?(Ht(e.left,t),t):(S.isRestElement(e)&&Ht(e.argument,t),t)}function vt(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 aS(e,t,n){e.set(t,{resolved:!0,value:n})}function ha(e,t){e.set(t,{resolved:!1})}function xd(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(S.isTSAsExpression(e)||S.isTSSatisfiesExpression(e)||S.isTSNonNullExpression(e)||S.isTypeCastExpression(e)||S.isParenthesizedExpression(e))return $e(e.expression,t,n);if(S.isLogicalExpression(e))return di([$e(e.left,t,n),$e(e.right,t,n)]);if(S.isBinaryExpression(e))return di([S.isExpression(e.left)?$e(e.left,t,n):null,S.isExpression(e.right)?$e(e.right,t,n):null]);if(S.isConditionalExpression(e))return di([$e(e.consequent,t,n),$e(e.alternate,t,n)]);if(S.isTemplateLiteral(e))return di(e.expressions.filter(S.isExpression).map(i=>$e(i,t,n)));if(S.isIdentifier(e))return{kind:"identifier",expression:e.name,base:e.name,path:[]};if(!S.isMemberExpression(e)&&!S.isOptionalMemberExpression(e))return null;let r=[],o=e;for(;S.isMemberExpression(o)||S.isOptionalMemberExpression(o);){if(o.computed)if(S.isNumericLiteral(o.property))r.unshift({kind:"index",index:o.property.value});else if(S.isStringLiteral(o.property))r.unshift({kind:"property",name:o.property.value});else if(n&&S.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(!S.isIdentifier(o.property))return null;r.unshift({kind:"property",name:o.property.name})}o=o.object}return S.isIdentifier(o)?{kind:r.some(i=>i.kind==="index")?"index-expression":"member-expression",expression:vt(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 sn(e,t){if(S.isStringLiteral(e)||S.isNumericLiteral(e)||S.isBooleanLiteral(e))return e.value;if(S.isNullLiteral(e))return null;if(S.isTemplateLiteral(e))return e.expressions.length===0&&e.quasis.length===1?e.quasis[0].value.cooked??e.quasis[0].value.raw:void 0;if(S.isIdentifier(e)){let n=_r(e.name,t.valueScopes);return n.kind==="resolved"?n.value:void 0}if(S.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||S.isSpreadElement(r))return;let o=sn(r,t);if(o===void 0)return;n.push(o)}return n}if(S.isObjectExpression(e)){let n={};for(let r of e.properties){if(!S.isObjectProperty(r)||r.computed||!S.isExpression(r.value))return;let o=null;if(S.isIdentifier(r.key)?o=r.key.name:S.isStringLiteral(r.key)&&(o=r.key.value),!o)return;let i;if(r.shorthand){if(!S.isIdentifier(r.value))return;let s=_r(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(S.isMemberExpression(e)){let n=$e(e,"",t);if(!n)return;let r=_r(n.base,t.valueScopes);if(r.kind!=="resolved")return;let o=xd(r.value,n.path);return o.kind==="resolved"?o.value:void 0}if(S.isCallExpression(e))return Sd(e,t)??void 0}function bd(e,t,n){let r=$e(e,n,t);if(!r)return S.isMemberExpression(e)||S.isBinaryExpression(e)||S.isLogicalExpression(e)||S.isConditionalExpression(e)||S.isCallExpression(e)?{value:vt(e,n),source:null}:null;let o=_r(r.base,t.valueScopes),i=r.kind==="identifier"?o:o.kind==="resolved"?xd(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 da(e,t,n,r,o,i){return{file:e,componentName:t,elements:n,regions:r,ordinalTracker:iS(),parentStack:[],valueScopes:i,importMap:o}}function pa(e,t,n){for(let r of e)for(let o of r.declarations){for(let s of Ht(o.id))ha(n,s);if(!S.isIdentifier(o.id)||!o.init||!S.isExpression(o.init))continue;let i=sn(o.init,t);i!==void 0&&aS(n,o.id.name,i)}}function cS(e){let t=[];for(let n of e){if(S.isVariableDeclaration(n)){t.push(n);continue}S.isExportNamedDeclaration(n)&&n.declaration&&S.isVariableDeclaration(n.declaration)&&t.push(n.declaration)}return t}function lS(e,t,n){let r=[],o=0;for(let i of e)if(S.isJSXText(i)){let s=i.value.trim();s&&r.push({index:o++,value:s,sourceRange:Ge(i),editable:!0,source:null})}else if(S.isJSXExpressionContainer(i)&&S.isStringLiteral(i.expression))r.push({index:o++,value:i.expression.value,sourceRange:Ge(i),editable:!0,source:null});else if(S.isJSXExpressionContainer(i)&&S.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:vt(s,n),sourceRange:Ge(i),editable:!0,source:$e(s,n,t)})}else if(S.isJSXExpressionContainer(i)&&S.isExpression(i.expression)){let s=bd(i.expression,t,n);s&&r.push({index:o++,value:s.value,sourceRange:Ge(i),editable:!0,source:s.source})}return r}function uS(e,t,n){let r=[];for(let[o,i]of e.attributes.entries()){if(!S.isJSXAttribute(i))continue;let s=fS(i.name);if(!s)continue;let a=vt(i,n);if(S.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(S.isJSXExpressionContainer(i.value)&&S.isExpression(i.value.expression)){let c=sn(i.value.expression,t);if(s==="className"){let u=typeof c=="string"?c:c===void 0?Sd(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=bd(i.value.expression,t,n);if(c!==void 0){r.push({name:s,value:bS(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=pS(i.value.expression,t),f=$e(i.value.expression,n,t),m=l?.value??vt(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 dS(e,t,n){return e.attributes.flatMap((r,o)=>!S.isJSXSpreadAttribute(r)||!S.isExpression(r.argument)?[]:[{raw:vt(r.argument,n),sourceRange:Ge(r),order:o,source:$e(r.argument,n,t)}])}function fS(e){return S.isJSXIdentifier(e)?e.name:S.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function pS(e,t){return Ot(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=sn(n,t);return r===void 0?{status:"unresolved"}:{status:"resolved",value:r}}})}function Sd(e,t){let n=nr(e,t);return n&&n.map(o=>o.trim()).filter(Boolean).join(" ")||null}function nr(e,t){if(S.isStringLiteral(e))return[e.value];if(S.isTemplateLiteral(e))return e.expressions.length>0?null:[e.quasis.map(n=>n.value.cooked??"").join("")];if(S.isNullLiteral(e))return[];if(S.isBooleanLiteral(e))return e.value?null:[];if(S.isIdentifier(e)||S.isMemberExpression(e)){if(S.isIdentifier(e)&&e.name==="undefined")return[];let n=sn(e,t);return typeof n=="string"?[n]:null}if(S.isConditionalExpression(e)){let n=nr(e.consequent,t),r=nr(e.alternate,t);return!n||!r?null:[...n,...r]}if(S.isLogicalExpression(e)){if(e.operator!=="&&")return null;let n=sn(e.left,t);return n===!1||n===null?[]:nr(e.right,t)}if(S.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||S.isSpreadElement(r))return null;let o=nr(r,t);if(!o)return null;n.push(...o)}return n}if(S.isObjectExpression(e)){let n=[];for(let r of e.properties){if(!S.isObjectProperty(r))return null;let o=gS(r.key);if(!o)return null;n.push(o)}return n}if(S.isCallExpression(e)){let n=mS(e.callee);if(!n||!["cn","clsx","twMerge"].includes(n))return null;let r=[];for(let o of e.arguments){if(!S.isExpression(o))return null;let i=nr(o,t);if(!i)return null;r.push(...i)}return r}return null}function mS(e){return S.isIdentifier(e)?e.name:S.isMemberExpression(e)&&S.isIdentifier(e.property)?e.property.name:null}function gS(e){return S.isIdentifier(e)?e.name:S.isStringLiteral(e)?e.value:null}function hS(e,t){let n=e.attributes.find(r=>S.isJSXAttribute(r)&&S.isJSXIdentifier(r.name)&&r.name.name===t);return!n||!S.isJSXAttribute(n)||!S.isJSXExpressionContainer(n.value)?null:n.value.expression}function yS(e,t){for(let n of t){let r=hS(e,n);if(r)return r}return null}function xS(e){return S.isJSXIdentifier(e.name)?e.name.name:null}function bS(e){return e===null?"null":typeof e=="boolean"?e?"true":"false":JSON.stringify(e)}function SS(e){if(!S.isCallExpression(e)&&!S.isOptionalCallExpression(e))return null;let t=e.callee;return!S.isMemberExpression(t)&&!S.isOptionalMemberExpression(t)||!S.isIdentifier(t.property)||t.property.name!=="map"||t.computed||!S.isExpression(t.object)?null:{call:e,collection:t.object,callback:e.arguments[0]}}function fa(e){return S.isArrowFunctionExpression(e)||S.isFunctionExpression(e)}function ES(e){return e==="render"||e==="itemRender"||e==="rowRender"||e==="children"}function vS(e){return e==="empty"||e==="emptyRender"||e==="loading"||e==="loadingRender"||e==="error"||e==="errorRender"||e==="fallback"||e==="headerRender"||e==="footerRender"}function gd(e,t,n,r){if(!e||!S.isExpression(e))return null;let o={kind:"repeat-template",collectionExpression:vt(e,n),collectionSource:$e(e,n,r)};if(t){let i=t.params[0],s=t.params[1];S.isIdentifier(i)&&(o.itemParamName=i.name),S.isIdentifier(s)&&(o.indexParamName=s.name)}return o}function Wt(e,t,n){if(!e)return[];if(S.isJSXElement(e)){if(ga(e))return hi(e.children,t,n);let r=mi(e,t,n);return r?[r]:[]}return rr(e)?gi(e,t,n):S.isParenthesizedExpression(e)?Wt(e.expression,t,n):S.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 Ht(o))ha(r,i);t.valueScopes.push(r);try{if(!S.isBlockStatement(e.body))return Wt(e.body,t,n);let o=new Map;t.valueScopes.push(o);try{return Ed(e.body.body,t,n)}finally{t.valueScopes.pop()}}finally{t.valueScopes.pop()}}function Ed(e,t,n){let r=[];for(let o of e){if(S.isVariableDeclaration(o)){let i=t.valueScopes[t.valueScopes.length-1];if(i){pa([o],t,i);for(let s of o.declarations)S.isIdentifier(s.id)&&(S.isJSXElement(s.init)||S.isJSXFragment(s.init))&&r.push(...Wt(s.init,t,n))}continue}r.push(...ma(o,t,n))}return r}function ma(e,t,n){if(S.isReturnStatement(e))return e.argument?Wt(e.argument,t,n):[];if(S.isBlockStatement(e))return wn(e.body,t,n);if(S.isIfStatement(e)){let r=S.isBlockStatement(e.consequent)?wn(e.consequent.body,t,n):ma(e.consequent,t,n),o=e.alternate?S.isBlockStatement(e.alternate)?wn(e.alternate.body,t,n):ma(e.alternate,t,n):[];return[...r,...o]}if(S.isSwitchStatement(e))return wn(e.cases.flatMap(r=>r.consequent),t,n);if(S.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 Ed(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 kS(e,t,n,r){let o=yS(e.openingElement,["items","dataSource","data"]),i={key:t,tag:hd(e.openingElement)};n.parentStack.push(i);try{for(let s of e.openingElement.attributes){if(!S.isJSXAttribute(s))continue;let a=xS(s);if(!a||!S.isJSXExpressionContainer(s.value))continue;let c=s.value.expression;if(!S.isJSXEmptyExpression(c)){if(ES(a)&&fa(c)){let l=fi(c,n,r),d=gd(o,c,r,n);pi(n,"repeat-region",t,s,l,d?[d]:void 0);continue}if(vS(a)){let l=fa(c)?fi(c,n,r):Wt(c,n,r);pi(n,"conditional-region",t,s,l)}}}if(o)for(let s of e.children){if(!S.isJSXExpressionContainer(s)||!fa(s.expression))continue;let a=fi(s.expression,n,r),c=gd(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=hd(e.openingElement);if(r==="Fragment"||ga(e))return hi(e.children,t,n),null;let o=t.parentStack[t.parentStack.length-1]??null,i=o?.key??null,s=nS(r),a;if(s){let R=t.ordinalTracker.getOrdinal(i,r);a=`component:${r}#${R}`}else{let R=t.ordinalTracker.getOrdinal(i,r);a=`${r}#${R}`}let c=o?t.elements.get(o.key)?.identity.structuralPath:void 0,l=c?`${c}/${a}`:a,d=wr(t.file,t.componentName,l),f={file:t.file,component:t.componentName,structuralPath:l,key:d},m=s?"component-boundary":null,u=lS(e.children,t,n),g=uS(e.openingElement,t,n),h=dS(e.openingElement,t,n),b,E,v=!1;if(s){let R=t.importMap.get(r)??t.importMap.get(rS(r));R&&(b=R.specifier,E=R.exportName,v=kn(R.specifier,t.file))}let I={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,...v?{isPublicUiComponent:!0}:{},importedFrom:b,exportName:E};return t.elements.set(d,I),i&&t.elements.has(i)&&t.elements.get(i).childKeys.push(d),kS(e,d,t,n),(!s||e.children.length>0)&&(t.parentStack.push({key:d,tag:r}),IS(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(S.isJSXElement(o))if(ga(o))r.push(...hi(o.children,t,n));else{let i=mi(o,t,n);i&&r.push(i)}else rr(o)?r.push(...gi(o,t,n)):S.isJSXExpressionContainer(o)&&r.push(...yi(o.expression,t,n));return r}function IS(e,t,n){for(let r of e)S.isJSXElement(r)?mi(r,t,n):rr(r)?gi(r,t,n):S.isJSXExpressionContainer(r)&&yi(r.expression,t,n)}function CS(e){return e==="&&"||e==="||"||e==="??"}function yi(e,t,n){if(S.isJSXEmptyExpression(e))return[];let r=SS(e);if(r){let o=r.call,i=t.parentStack[t.parentStack.length-1]??null,s=[],a=r.callback,c={kind:"repeat-template",collectionExpression:vt(r.collection,n),collectionSource:$e(r.collection,n,t)};if(S.isArrowFunctionExpression(a)||S.isFunctionExpression(a)){let d=a.params[0],f=a.params[1];S.isIdentifier(d)&&(c.itemParamName=d.name),S.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),(S.isArrowFunctionExpression(a)||S.isFunctionExpression(a))&&l.childKeys.push(...fi(a,t,n)),l.childKeys}if(S.isConditionalExpression(e)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:vt(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(...Wt(e.consequent,t,n)),s.childKeys.push(...Wt(e.alternate,t,n)),s.childKeys}if(S.isLogicalExpression(e)&&CS(e.operator)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:vt(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(...Wt(e.right,t,n)),s.childKeys}if(S.isParenthesizedExpression(e))return yi(e.expression,t,n);if(S.isJSXElement(e)){let o=mi(e,t,n);return o?[o]:[]}return rr(e)?gi(e,t,n):[]}function RS(e){let t=e.argument;return t&&(S.isExpression(t)||rr(t))?t:null}function Or(e,t){let n=[];for(let r of e){if(S.isReturnStatement(r)){let o=RS(r);o&&n.push({argument:o,statement:r,condition:t});continue}if(S.isIfStatement(r)){let o=S.isBlockStatement(r.consequent)?r.consequent.body:[r.consequent];if(n.push(...Or(o,r.test)),r.alternate){let i=S.isBlockStatement(r.alternate)?r.alternate.body:[r.alternate];n.push(...Or(i,r.test))}continue}if(S.isSwitchStatement(r))for(let o of r.cases){let i=o.test?S.binaryExpression("===",r.discriminant,o.test):r.discriminant;n.push(...Or(o.consequent,i))}}return n}function vd(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=sS(r);tS(r,{"FunctionDeclaration|FunctionExpression|ArrowFunctionExpression"(f){let m=oS(f);if(!m)return;let u=f.node,g=[];if(S.isArrowFunctionExpression(u))S.isExpression(u.body)||rr(u.body)?g=[{argument:u.body,statement:S.returnStatement(S.isExpression(u.body)?u.body:null)}]:S.isBlockStatement(u.body)&&(g=Or(u.body.body));else{let R=u.body;S.isBlockStatement(R)&&(g=Or(R.body))}if(g.length===0){f.skip();return}let h=new Map;pa(cS(r.program.body),da(t,m,i,s,l,[h]),h);let b=new Map;for(let R of u.params)for(let A of Ht(R))ha(b,A);let E=S.isBlockStatement(u.body)?u.body.body:[],v=g[0]?.statement??null;for(let R of E){if(v&&R===v)break;S.isVariableDeclaration(R)&&pa([R],da(t,m,i,s,l,[h,b]),b)}let I=da(t,m,i,s,l,[h,b]);for(let R of g){let A=Wt(R.argument,I,n);for(let T of A)a.includes(T)||a.push(T);if(R.condition){let T={kind:"conditional-branch",conditionExpression:vt(R.condition,n),conditionSource:$e(R.condition,n,I)};pi(I,"conditional-region","",R.statement,A,[T])}}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 ya(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 kd(e,t,n,r,o={}){let i=o.maxDepth??10,s=o.version??1,a=o.parseModule??vn,c=new Map,l=new Map,d=new Map,f=[],m=new Set,u=E=>{let v=`${E.path}\0${E.code}\0${E.message}\0${JSON.stringify(E.details??{})}`;m.has(v)||(m.add(v),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:v,source:I,depth:R,diagnosticEntryFile:A,importStack:T}=E;if(h.has(v))continue;h.add(v),c.set(v,I);let C=a(v,I);if(!C.ok){u(xi(C.diagnostic,A,T));continue}d.set(v,C.module);let{graph:P,localImports:O}=vd(C.module);for(let L of P.elements.values())if(L.importedFrom&&Pt(L.importedFrom)){let U=L.importedFrom,ee=await Fo(v,U,r);ee.ok?(L.importedFrom=ee.path,Ut(ee.path)&&(L.isPublicUiComponent=!0)):kn(U,v)||u(xi(ee.diagnostic,A,ya(T,v,U,ee.diagnostic.path)))}if(l.set(v,P),!(R>=i))for(let L of O){if(ou(L))continue;let U=await Fo(v,L,r);if(!U.ok){kn(L,v)||u(xi(U.diagnostic,A,ya(T,v,L,U.diagnostic.path)));continue}let ee=U.path;if(h.has(ee)||Ut(ee))continue;let Ne=ya(T,v,L,ee);try{let Q=await n(ee);g.push({file:ee,source:Q,depth:R+1,diagnosticEntryFile:A,importStack:Ne})}catch(Q){u(xi({path:ee,code:"import-read-failed",message:`Failed to read imported file: ${ee}`,details:{fromFile:v,specifier:L,reason:Q instanceof Error?Q.message:String(Q)}},A,Ne))}}}let b=NS(e,l,s,(o.additionalEntries??[]).map(E=>E.file));return b.diagnostics=f,{graph:b,allSources:c,diagnostics:f,parsedModules:d,entryModule:d.get(e)??null}}function NS(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 wS}from"@vcp-dev/contracts";var PS={affectedCompositions:[]};function Pd(e){let t=null,n=new WeakMap;async function r(){return t??=AS(e),t}return{async prepareAppend(o){let i=await e.readIndex(),s=await e.stageAppend(Nd(o),{durableManifest:!1}),a;try{a=await e.previewStagedAppend(s.entryId,i.digest)}catch(l){throw await e.discardStage(s.stageId),l}let c={kind:"append",entry:o,historyTransition:a};return n.set(c,{expectedDigest:i.digest,stageId:s.stageId,entryId:s.entryId}),c},async prepareUndo(){let i=(await r()).undo.at(-1);if(!i?.historyId)return null;let s=await e.readIndex(),a=s.entryIds.indexOf(i.historyId);if(a<0)throw new Error("undo entry is missing from index");let c=a-1,l=await e.previewCursor(c,s.digest),d={kind:"undo",entry:i,historyTransition:l};return n.set(d,{expectedDigest:s.digest,cursor:c}),d},async prepareRedo(){let i=(await r()).redo.at(-1);if(!i?.historyId)return null;let s=await e.readIndex(),a=s.entryIds.indexOf(i.historyId);if(a<0)throw new Error("redo entry is missing from index");let c=a,l=await e.previewCursor(c,s.digest),d={kind:"redo",entry:i,historyTransition:l};return n.set(d,{expectedDigest:s.digest,cursor:c}),d},async publishPrepared(o){let i=n.get(o);if(!i)throw new Error("history mutation was not prepared");let s=await r();if(o.kind==="append"){if(!i.entryId)throw new Error("staged entry id is missing");let a=await e.publishStagedAppend(i.entryId,i.expectedDigest,i.stageId);Id(a,o.historyTransition),o.entry.historyId=i.entryId,s.entryIds=[...a.entryIds],s.cursor=a.cursor,s.undo.push(o.entry),s.redo.length=0}else{if(i.cursor===void 0)throw new Error("prepared cursor is missing");let a=await e.setCursor(i.cursor,i.expectedDigest);if(Id(a,o.historyTransition),o.kind==="undo"){if(s.undo.at(-1)!==o.entry)throw new Error("undo state changed before publish");s.undo.pop(),s.redo.push(o.entry)}else{if(s.redo.at(-1)!==o.entry)throw new Error("redo state changed before publish");s.redo.pop(),s.undo.push(o.entry)}s.cursor=i.cursor}n.delete(o)},async discardPrepared(o){let i=n.get(o);if(!i)return;let s=o.historyTransition;if(s){let a=await e.readIndex();if(a.digest===s.publishedIndexDigest&&a.cursor===s.publishedCursor&&a.currentId===s.publishedCurrentId)throw new Error("cannot discard a history mutation whose index was published")}i.stageId&&await e.discardStage(i.stageId),n.delete(o)},async peekUndo(){return(await r()).undo.at(-1)??null},async pushUndo(o){let i=await r(),s=o;if(s.historyId){let l=i.entryIds.indexOf(s.historyId);if(l>=0)try{await e.setCursor(l),i.undo.push(o),i.cursor=l;return}catch(d){throw i.redo.push(o),d}}let a=await e.append(Nd(o)),c=a.currentId;if(!c)throw new Error("history store did not publish an entry");o.historyId=c,i.entryIds=[...a.entryIds],i.cursor=a.cursor,i.undo.push(o),i.redo.length=0},async popUndo(){return(await r()).undo.pop()??null},async peekRedo(){return(await r()).redo.at(-1)??null},async pushRedo(o){let i=await r(),s=o;if(!s.historyId)throw i.undo.push(o),new Error("cannot move an unpersisted history entry to redo");let a=i.entryIds.indexOf(s.historyId);if(a<0)throw i.undo.push(o),new Error("history entry is missing from the durable index");try{await e.setCursor(a-1),i.cursor=a-1,i.redo.push(o)}catch(c){throw i.undo.push(o),c}},async popRedo(){return(await r()).redo.pop()??null},async clearRedo(){(await r()).redo.length=0},async getStatus(){let o=await e.readStatus();return{canUndo:o.canUndo,canRedo:o.canRedo,undoDepth:o.undoDepth,redoDepth:o.redoDepth,recoveryRequired:o.recoveryRequired}},async markRecoveryRequired(o){await e.markRecoveryRequired(o)}}}function Id(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")}async function AS(e){let t=await e.readIndex(),n=await Promise.all(t.undoIds.map(async o=>Cd(e,o))),r=await Promise.all(t.redoIds.map(async o=>Cd(e,o)));return{undo:n.reverse(),redo:r.reverse(),entryIds:[...t.entryIds],cursor:t.cursor}}async function Cd(e,t){let n=await e.readEntry(t),r=TS(n),o=r.provenance??PS;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 Rd(e,n,r.preSnapshots),postSnapshots:await Rd(e,n,r.postSnapshots)}}async function Rd(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(OS(r,o.blobName))).toString("utf8"):"";return{file:o.file,content:i,version:o.version,exists:o.exists,...o.sha256?{sha256:o.sha256}:{}}}))}function Nd(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=FS(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 TS(e){if(!Td(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:Ad(t.provenance)}:{},preSnapshots:wd(t.preSnapshots,"preSnapshots"),postSnapshots:wd(t.postSnapshots,"postSnapshots")}}function FS(e){if(e.provenance!==void 0)return Ad(e.provenance);if(e.composition)return{initiatingComposition:e.composition,affectedCompositions:[]}}function Ad(e){let t=wS.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 wd(e,t){return e.map((n,r)=>{if(!Td(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&&!_S(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 _S(e){return/^sha256:[0-9a-f]{64}$/.test(e)}function OS(e,t){let n=e.get(t);if(!n)throw new Error(`durable history blob is missing: ${t}`);return n}function Td(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{randomBytes as GS}from"node:crypto";import Si from"node:path";import{parse as Vd}from"@babel/parser";import YS from"@babel/traverse";import*as Kd from"@babel/types";import{COMPONENT_I18N_FILE_SUFFIX as ba,PageResourceArtifactSchema as ZS,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as QS,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as qS,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as eE,parseComponentI18nResourcesJson as tE}from"@vcp-dev/contracts";var _d=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\(/i,Od=/\b(?:bg-black|bg-white|text-white|text-black)(?:\b|\/)/g,MS=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke)-\[#(?:[0-9a-fA-F]{3,8})\](?:\/\d+)?/g,LS=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*#[0-9a-fA-F]{3,8}[^'"]*['"]/g,DS=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*rgba?\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,BS=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,jS=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,$S=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*(?:oklch|lab|lch|hsla?)\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,VS=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*(?:oklch|lab|lch|hsla?)\([^)]+\)[^'"]*['"]/gi,KS=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*color-mix\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,US=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*color-mix\([^'"]*['"]/gi,JS=/\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,XS=/var\(\s*--(?:_|private-|vcp-)[^)]+\)/gi,zS=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\([^)]*\)/gi;function Mr(e,t){let n=bi([...ht(e,MS),...ht(e,LS),...ht(e,DS),...ht(e,t.includeRgbBackgroundImage?BS:jS),...t.includeExtendedColorFunctions?[...ht(e,$S),...ht(e,VS)]:[]]),r=bi([...ht(e,KS),...ht(e,US)]).filter(o=>t.colorMixPolicy==="always"||_d.test(o));return n.push(...r.filter(o=>!n.includes(o))),t.rejectTailwindPalette&&n.push(...ht(e,JS).filter(o=>!n.includes(o))),t.rejectAnyRawColorLiteral&&n.push(...ht(e,zS).filter(o=>!n.includes(o))),{hardCodedSurfaceHits:bi(ht(e,Od)),hardCodedSurfaceOccurrences:WS(e),rawColorHits:n,privateTokenHits:t.rejectPrivateTokens?bi(ht(e,XS)):[]}}function ht(e,t){return e.match(new RegExp(t.source,t.flags))??[]}var Fd=160,HS=/((?:[a-z][a-z0-9-]*(?:\[[^\]]*\])?:)+)$/;function WS(e){let t=new RegExp(Od.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=HS.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>Fd?`${u.slice(0,Fd-1)}\u2026`:u})}return o}function bi(e){return[...new Set(e)]}var Sa="{{$INSTANCE}}",nE=/\{\{\$PAGE_ROUTE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,rE=/\{\{\$PAGE_TITLE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,Ea="components/site/generated",oE=/\.(?:tsx?|json)$/,iE=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,sE=["react","react/","next","next/","lucide-react","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],aE=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),xa=YS,cE=typeof xa=="function"?xa:xa.default;async function va(e){let t=ZS.safeParse(e.artifact);if(!t.success)return Ae("Page resource artifact failed contract validation.");let n=t.data,r=e.randomHex??(()=>GS(4).toString("hex")),o=Math.max(1,Math.min(e.maxAttempts??5,5)),i=yE(r());if(!i)return Ae("Random instance suffix must be 8 lowercase hex chars.");let s=`${xE(n.resource_id)}-${i}`,a=new Map,c=new Map,l=[];for(let I of n.pages){let R=I.final_route.slice(1);a.set(I.template_page_id,I.final_route),c.set(I.template_page_id,I.title),l.push({template_page_id:I.template_page_id,title:I.title,final_route:I.final_route,route_file_path:`app/${R}/page.tsx`})}let d=[],f=new Set,m=new Set,u=new Map,g=new Map,h=[],b=new Set(n.pages.flatMap(I=>I.components.map(R=>R.component_id)));for(let I of n.components){if(!b.has(I.component_id))continue;let R=Md({materialization:I.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c});if(!R.ok)return R;for(let A of R.files){let T=Dd(A,f,d);if(T)return T}m.add(R.entry),g.set(R.entry,R.entryExport),u.set(I.component_id,R.entry)}for(let[I,R]of n.pages.entries()){let A=l[I],T=Md({materialization:R.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c,pageEntryTarget:A.route_file_path,pageTitle:A.title});if(!T.ok)return T;for(let C of T.files){let P=Dd(C,f,d);if(P)return P}m.add(T.entry),g.set(T.entry,T.entryExport),h.push({entry:T.entry,declaredComponentIds:new Set(R.components.map(C=>C.component_id))})}let E=uE(d,m,s,u,h,g);if(!E.ok)return E;for(let I of d)if(await e.exists(I.file))return!I.file.startsWith("app/")&&o>1?va({...e,randomHex:r,maxAttempts:o-1}):{ok:!1,code:"MATERIALIZATION_CONFLICT",message:`Page resource create-only target already exists: ${I.file}`,path:I.file};let v=dE(d);return v||(d.sort((I,R)=>I.file.localeCompare(R.file)),{ok:!0,packageInstanceId:s,pages:l,files:d})}function Md(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:Ld(o.pathTemplate,e.packageInstanceId);if(!s)return Ae("Materialization path cannot be mapped into the package namespace.",o.pathTemplate);let a=lE(o.content,e.packageInstanceId,e.routeByPage,e.titleByPage);if(!a.ok)return a;let c=i&&e.pageTitle!==void 0?pE(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??Ld(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 lE(e,t,n,r){let o,i=e.replace(nE,(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(rE,(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(Sa,t);return a.includes("{{$PAGE_ROUTE:")||a.includes("{{$PAGE_TITLE:")||a.includes("{{$INSTANCE}}")?Ae("Materialization contains an unresolved placeholder."):{ok:!0,data:a}}function Ld(e,t){let n=`${Ea}/${t}`;if(e.split(Sa).length>2)return null;let o=e.replace(Sa,t),i=`${Ea}/${t}/`,s=o.startsWith(i)?o:`${n}/${o}`,a=Si.posix.normalize(s);return a!==s||!a.startsWith(`${n}/`)||!oE.test(a)||iE.test(a)?null:a}function Dd(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 uE(e,t,n,r,o,i){let s=new Set(e.map(u=>u.file)),a=`${Ea}/${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(ba)&&!tE(u.content).success)return Ae("Materialization component i18n resources are invalid.",u.file);continue}try{let h=Vd(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 v=E.source.value,I=gE(u.file,v,s,a);if(!I.allowed)return Ae(`Materialization import is outside the controlled package: ${v}`,u.file);I.internalPath&&c.get(u.file).add(I.internalPath)}let b;if(cE(h,{Identifier(E){E.isReferencedIdentifier()&&aE.has(E.node.name)&&(b??=E.node.name,E.stop())},JSXAttribute(E){E.node.name.type==="JSXIdentifier"&&E.node.name.name==="style"&&(b??="inline style",E.stop())},JSXOpeningElement(E){E.node.name.type==="JSXIdentifier"&&E.node.name.name.toLowerCase()==="style"&&(b??="style element",E.stop())}}),b)return Ae(`Materialization source uses forbidden capability: ${b}`,u.file)}catch{return Ae("Materialization source must parse as TS/TSX.",u.file)}let g=Mr(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||!fE(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=$d(u.entry,c);for(let h of u.declaredComponentIds){let b=r.get(h);if(!b||!g.has(b))return Ae(`Page entry does not reach declared component: ${h}`,u.entry)}for(let h of g){let b=d.get(h);if(b&&!u.declaredComponentIds.has(b))return Ae(`Page entry imports undeclared component: ${b}`,u.entry)}}let f=new Set;for(let u of t)for(let g of $d(u,c))f.add(g);if(f.size!==e.length)return Ae("Every materialization file must be reachable from a package entry.");let m=hE(e,l,c);return m||{ok:!0}}function dE(e){if(e.length>QS)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>qS)return Ae("Page resource file exceeds the content byte limit.",n.file);t+=r}return t>eE?Ae("Page resource exceeds the aggregate content byte limit."):null}function fE(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 pE(e,t,n){let r;try{r=Vd(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=Bd(s.init);if(a?.type!=="ObjectExpression")return{ok:!0,data:e};let c=a.properties.find(d=>d.type==="ObjectProperty"&&!d.computed&&mE(d.key));if(!c||c.type!=="ObjectProperty")return{ok:!0,data:e};let l=Bd(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 Bd(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression"||t?.type==="TSNonNullExpression";)t=t.expression;return t&&Kd.isExpression(t)?t:null}function mE(e){return e.type==="Identifier"&&e.name==="title"||e.type==="StringLiteral"&&e.value==="title"}function gE(e,t,n,r){if(t.startsWith(`@/${r}/`)){let s=t.slice(2),a=jd(s,n);return a?{allowed:!0,internalPath:a}:{allowed:!1}}if(!t.startsWith("."))return{allowed:sE.some(s=>s.endsWith("/")?t.startsWith(s):t===s)};if(t.includes("\\")||t.includes("\0"))return{allowed:!1};let o=Si.posix.normalize(Si.posix.join(Si.posix.dirname(e),t)),i=jd(o,n);return i&&(i.startsWith(`${r}/`)||i.startsWith("app/"))?{allowed:!0,internalPath:i}:{allowed:!1}}function jd(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 hE(e,t,n){let r=new Set(e.map(o=>o.file));for(let o of e){if(!o.file.endsWith(ba))continue;let i=o.file.slice(0,-ba.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 $d(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 yE(e){return/^[a-f0-9]{8}$/.test(e)?e:null}function xE(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 bE}from"node:crypto";import Gt from"node:path";import{parse as SE}from"@babel/parser";import EE from"@babel/traverse";import{COMPONENT_I18N_FILE_SUFFIX as Ei,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as Ud,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as vE,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as kE,SiteEditMaterializationSchema as IE,parseComponentI18nResourcesJson as CE}from"@vcp-dev/contracts";var Ca="components/site/generated",Jd="{{$INSTANCE}}",vi=5,RE=/^[a-z][a-z0-9-]{0,48}$/,NE=/^[a-f0-9]{8}$/,Xd=/\.tsx?$/,wE=/\.json$/,PE=/\.(?:tsx?|json)$/,AE=/^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/,TE=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,FE=["react","react/","next","next/","lucide-react","react-i18next","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],ka=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),Ia=EE,_E=typeof Ia=="function"?Ia:Ia.default;function OE(e){let t=Array.isArray(e.manifest.files)?e.manifest.files:[];if(t.length>Ud)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file count exceeds the reusable limit."}};let n=XE(t);if(n)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Static prefab resolves duplicate target path: ${n}`,path:n}};let r=IE.safeParse(e.manifest);if(!r.success)return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab manifest failed schema validation."}};let o=KE(e.generatedRoot);if(!o)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Generated root must be ${Ca}.`,path:e.generatedRoot}};if(!Zd(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=Wd(r.data.files),s=Wd(e.controlledFiles);if(!zE(i,s))return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Controlled file list must exactly match the manifest file templates."}};if(i.size>Ud)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>vE)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>kE?{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 ME(e){let t=OE(e);if(!t.ok)return t;let n=Object.keys(e.manifest.projectDependencies??{}),r=new Set(e.availableHostDependencies??[]),o=n.find(d=>!AE.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??FE,...i],a=t.data.generatedRoot,c=Zd(e.manifest.instanceBaseName),l=Math.max(1,Math.min(vi,e.maxAttempts??vi));for(let d=0;d<l;d+=1){let f=UE(e.instanceNameGenerator?.()??bE(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=qd(a,m),g=LE({manifest:e.manifest,generatedRoot:a,instanceName:m,instanceRoot:u,allowedExternalImports:s});if(!g.ok)return g;if(!await DE(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 Yd(e){let t=Math.max(1,Math.min(vi,e.maxAttempts??vi));for(let n=0;n<t;n+=1){let r=await ME({...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 LE(e){let t=[],n=new Set;for(let i of e.manifest.files){let s=zd({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=zd({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=BE(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 DE(e,t,n){if(await e(t))return!0;for(let r of n)if(await e(r.path))return!0;return!1}function zd(e){if(e.pathTemplate.split(Jd).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(Jd,e.instanceName),n=JE(t);return n?qd(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||!PE.test(n)||TE.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 BE(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(wE.test(f.path)){if(f.path.endsWith(Ei)){let g=CE(f.content);if(!g.success)return Pn("MATERIALIZATION_DATA_UNSUPPORTED",g.error.message,f.path);c.set(f.path,new Set)}else try{JSON.parse(f.content)}catch{return Pn("MATERIALIZATION_DATA_UNSUPPORTED","Static prefab JSON file must contain valid JSON.",f.path)}continue}let m;try{m=SE(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=Mr(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(!Xd.test(f.path))continue;let m=s.get(f.path),u=null;if(_E(m,{ImportDeclaration(g){let h=Hd({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(Ei))){let b=jE({importer:f.path,imported:h.internalPath,source:g.node.source.value,ast:m});b.ok?c.get(h.internalPath).add(f.path):(u??=b.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=Hd({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=Gd(g.node);h&&ka.has(h)&&(u??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${h}.`,file:f.path},g.stop())},OptionalMemberExpression(g){let h=Gd(g.node);h&&ka.has(h)&&(u??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${h}.`,file:f.path},g.stop())},Identifier(g){g.isReferencedIdentifier()&&ka.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(!Xd.test(n))return Pn("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must be a .ts/.tsx source module.",n);let l=s.get(n);if(!l)return Pn("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must resolve to a controlled source file.",n);if(!$E(l,r))return Pn("MATERIALIZATION_EXPORT_MISSING","Static prefab entry does not declare the manifest export.",n);for(let[f,m]of c)if(m.size!==1)return Pn("MATERIALIZATION_IMPORT_FORBIDDEN","Each component .i18n.json file must have exactly one same-name Client Component static importer.",f);return VE(n,a).size!==e.length?Pn("MATERIALIZATION_ENTRY_INVALID","Every controlled source file must be reachable from the entry module.",n):{ok:!0,data:{kind:"static-prefab-materialization",instanceName:"",generatedRoot:Ca,instanceRoot:"",entry:{path:"",export:{kind:"default"}},files:[]}}}function Hd(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 jE(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,-Ei.length),i=`./${r}${Ei}`;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 $E(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 VE(e,t){let n=new Set,r=[e];for(;r.length>0;){let o=r.pop();n.has(o)||(n.add(o),r.push(...t.get(o)??[]))}return n}function Pn(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{file:n}:{}}}}function KE(e){let t=Qd(e);return t===Ca?t:null}function UE(e){let t=e.trim().toLowerCase();return NE.test(t)?t:null}function Zd(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 RE.test(t)?t:null}function Qd(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 JE(e){let t=Qd(e);return!t||t!==e?null:t}function qd(...e){return Gt.posix.join(...e)}function Wd(e){return new Set(e.map(t=>t.pathTemplate))}function XE(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 zE(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function Gd(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 $a}from"node:crypto";import _a from"@babel/traverse";function Ra(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 HE}from"node:crypto";import ef from"node:path";import*as sf from"@babel/parser";import Na from"@babel/generator";import*as Ue from"@babel/types";var tf=typeof Na=="function"?Na:Na.default;function Pa(e){let t=cf(e);if(t)return{ok:!1,error:t};let n=e.projection,r=Fa(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=YE(n,o),s={jsx:`<${e.component.localName} />`},a=WE(e);if(i){let u=wa(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??(Ta(c,n.container.sourceRange)?n.container.sourceHash:null);if(!c||!l)return Lr("Route page composition does not expose a verifiable container boundary.");let d=Br(c),f=rf(e.source,d,l,"Route page composition container");if(!f.ok)return f.result;let m=o.anchorSourceRange?Br(o.anchorSourceRange):void 0;if(m){if(!o.anchorSourceHash)return Lr("Route page composition placement does not expose a verifiable anchor boundary.");let u=rf(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 WE(e){let t=ev(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 ki(e){if(e.locator.root.kind!=="expression"||e.locator.path?.length)return An(e.source,"Root expression rewrite requires an exact expression locator.");let t=vr(e.source,"value");if(!t.ok)return An(e.source,t.diagnostic.message);let n=ae(t.ast,e.locator);if(!n.ok)return An(e.source,n.diagnostic.message);let r=n.match.path;if(!r.isExpression())return An(e.source,"Resolved value locator does not point to an expression.");let o=or(e.source,r.node.start??null,r.node.end??null);if(!o||o!==e.expectedSourceHash)return An(e.source,"Root expression hash no longer matches the current source.");if(e.action.kind==="remove")return r.replaceWith(Ue.nullLiteral()),{ok:!0,source:tf(t.ast,{}).code};let i;try{i=sf.parseExpression(e.action.jsx,{plugins:["jsx","typescript"]})}catch(s){return An(e.source,s instanceof Error?s.message:String(s))}return!Ue.isJSXElement(i)&&!Ue.isJSXFragment(i)?An(e.source,"Root expression rewrite requires a JSX insertion expression."):(e.action.kind==="replace"?r.replaceWith(i):r.replaceWith(GE(r.node,i,e.action.placement,e.action.replaceOriginal)),{ok:!0,source:tf(t.ast,{}).code})}function GE(e,t,n,r){if(Ue.isNullLiteral(e)||r)return t;let o=Ue.isJSXFragment(e)?[...e.children]:[Ue.isJSXElement(e)?e:Ue.jsxExpressionContainer(e)],s=n==="before"||n==="prepend"?[t,...o]:[...o,t];return Ue.jsxFragment(Ue.jsxOpeningFragment(),Ue.jsxClosingFragment(),s)}function An(e,t){return{ok:!1,source:e,diagnostic:{message:t}}}function Aa(e){let t=cf(e);if(t)return{ok:!1,error:t};let n=e.projection,r=lf(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(ZE(n,o)){let h=wa(e);return h.ok?e.operation==="remove-node"&&!nf(n,o.placementUnitKey)?Lr("The last editable page unit cannot be deleted."):e.operation==="move-node"?Lr("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=Br(o.sourceRange),a=Ft(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?[]:[Dr(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=wa(e);return h.ok?nf(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}}}:Lr("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||!qE(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=Fa(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=Br(f),u=Ft(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?[]:[Dr(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,b=d.anchorSourceHash;if(!h||!b)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=Br(h),v=Ft(e.source,E);return!v.ok||!v.match.node?{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:v.ok===!1?v.diagnostic.message:"Route page composition target anchor could not be resolved.",diagnostics:v.ok?[]:[Dr(v.diagnostic)]}}:or(e.source,v.match.node.start??null,v.match.node.end??null)!==b?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 nf(e,t){for(let n of e.placementUnitByKey.values())if(n.placementUnitKey!==t&&n.members.length>0)return!0;return!1}function YE(e,t){let n=e.placementUnitByKey.get(t.placementUnitKey);return n&&e.container.kind!=="jsx-container"&&Ta(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 ZE(e,t){return e.container.kind!=="jsx-container"&&Ta(t.sourceRange,e.mutationTarget.sourceRange)&&t.sourceHash===e.mutationTarget.sourceHash}function wa(e){let t=e.projection.mutationTarget,n={kind:"value",root:{kind:"expression",sourceRange:t.sourceRange}},r=Ft(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?[]:[Dr(r.diagnostic)]}}}:or(e.source,r.match.node.start??null,r.match.node.end??null)!==t.sourceHash?{ok:!1,result:af("Route mutation target hash no longer matches the current source.")}:{ok:!0,locator:n,sourceHash:t.sourceHash}}function rf(e,t,n,r){let o=Ft(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?[]:[Dr(o.diagnostic)]}}}:or(e,o.match.node.start??null,o.match.node.end??null)!==n?{ok:!1,result:af(`${r} hash no longer matches the current source.`)}:{ok:!0}}function af(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function Lr(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 Dr(e){return{code:"UNSUPPORTED_PAGE_SHAPE",message:e.message,details:{astCode:e.code}}}function cf(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&&!QE(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 QE(e,t){return e.routeId===t.routeId&&e.effectiveTemplateId===t.effectiveTemplateId}function qE(e,t){return e.routeId===t.routeId&&e.templateId===t.effectiveTemplateId}function ev(e,t){let n=ef.posix.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=ef.posix.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function Br(e){return{kind:"jsx-node",strategy:"source-range",sourceRange:e}}function or(e,t,n){return t==null||n==null?null:`sha256:${HE("sha256").update(e.slice(t,n)).digest("hex")}`}function Ta(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 tv=typeof _a=="function"?_a:_a.default;function pf(e){if(!e.ast)return kt(e,[Ve("UNSUPPORTED_PAGE_SHAPE","SourceGraph entry AST is required",{reason:"parsed-ast-required"})]);let t=lv(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=dv(t);if(!n.ok)return kt(e,[n.diagnostic]);let r=n.expression;if(r.isIdentifier()){let o=pv(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(gv(r,t))return kt(e,[Ve("INDIRECT_RETURN_ONLY","Route default export only returns through an indirect function boundary")]);if(r.isNullLiteral())return Ma(e,t,"virtual-route-root",r);if(mv(r)){let o=bv({input:e,source:e.source,expression:r});return Oa(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)&&!an(r)){let o=Ba(r),i=ff({input:e,containerKind:"virtual-route-root",sourceKind:"jsx-element",source:e.source,containerPath:r,members:[o]});return Oa(e,t,i,{kind:"virtual-route-root",sourceKind:"jsx-element"},r)}if(r.isJSXElement()||r.isJSXFragment()){let o=yv(r);if(!o.ok)return kt(e,[o.diagnostic]);let i=ir(o.path);if(i.unsupported)return kt(e,[Ve("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);if(hv(e.source,r,i.members))return Ma(e,t,"starter-placeholder",r);let s=r.isJSXFragment()||Fe(r);if(i.members.length===0&&s)return Ma(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=ff({input:e,containerKind:a,sourceKind:c,source:e.source,containerPath:o.path,members:i.members});return Oa(e,t,l,{kind:a,sourceKind:c},r)}return kt(e,[Ve("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")])}function Fa(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 lf(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 mf(e){return e.ok?nv(e.projection):rv(e.projection)}function nv(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,b)=>gf(e,d,h,b,e.container.placementKey)),m=f.filter(({member:h})=>h.isBusinessMember).map(({sourceMember:h})=>iv(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:ov(e,a),sourceMembers:i,businessMembers:s,placementUnits:n,placements:c}}function rv(e){let t=e.diagnostics.map(sv);return{status:"unsupported",version:e.version,composition:e.composition,reason:av(e.diagnostics),diagnostics:t}}function ov(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 gf(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)=>gf(e,t,a,c,i))]}function iv(e,t,n){return{key:`business:${e}:${t.key}`,sourceMemberKey:t.key,containerKey:e,label:t.label,isIndependent:n}}function sv(e){return{code:cv(e),message:e.message}}function av(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 cv(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 lv(e){let t=null;return tv(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=uv(o.path);i&&(t=i,n.stop())}}),t}function uv(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 dv(e){let t=e.get("body");if(!t.isBlockStatement()){let s=$r(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(!fv(s))return{ok:!1,diagnostic:Ve("UNSUPPORTED_PAGE_SHAPE","Route guard return shape is not statically safe",{reason:"guard-shape"})};continue}if(hf(s)||yf(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=$r(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 fv(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(hf(o)||yf(o))return null;return r}function hf(e){return e.isForStatement()||e.isForInStatement()||e.isForOfStatement()||e.isWhileStatement()||e.isDoWhileStatement()||e.isSwitchStatement()||e.isTryStatement()||e.isWithStatement()}function yf(e){let t=!1;return e.traverse({Function(n){n.skip()},ReturnStatement(){t=!0}}),t}function pv(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=$r(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 mv(e){return e.isConditionalExpression()?uf($r(e.get("consequent")))&&uf($r(e.get("alternate"))):!1}function uf(e){return!!(e&&(e.isJSXElement()||e.isJSXFragment()||e.isNullLiteral()))}function $r(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 gv(e,t){if(e.isIdentifier())return df(e.node.name,t);if(e.isCallExpression()){let n=e.get("callee");if(n.isIdentifier())return df(n.node.name,t)}return!1}function df(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 hv(e,t,n){return e.includes("DESIGN_PLAN_REPLACE_ME")&&t.isJSXElement()&&n.length>0&&Da(t)}function Da(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(!Da(t))return!1;continue}if(t.isJSXElement()&&!Da(t))return!1}return!0}function yv(e){let t=e;if(e.isJSXFragment()||Fe(e)){let r=jr(e),o=r[0];if(r.length===1&&o?.isJSXElement()&&an(o))t=o;else return{ok:!0,path:t}}for(;t.isJSXElement()&&an(t);){let r=jr(t);if(r.length!==1)return{ok:!0,path:t};let o=r[0];if(!o?.isJSXElement()||!an(o))return{ok:!0,path:t};if(jr(o).length<=1)return{ok:!0,path:t};t=o}return{ok:!0,path:t}}function jr(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(...jr(n));continue}n.isJSXElement()&&(Fe(n)?t.push(...jr(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:ja(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=ir(o);n||=i.unsupported,t.push(...i.members);continue}if(o.isJSXElement()){let i=an(o)?ir(o):null;n||=i?.unsupported??!1,t.push({...Ba(o,i?.members),sourceRange:yt(r.node.loc),parentSourceRange:yt(e.node.loc)});continue}if(o.isJSXSpreadChild()){n=!0;continue}t.push({memberKey:ja(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=ir(r);n||=o.unsupported,t.push(...o.members);continue}if(r.isJSXElement()){let o=an(r)?ir(r):null;n||=o?.unsupported??!1,t.push({...Ba(r,o?.members),parentSourceRange:yt(e.node.loc)})}}return{members:t,unsupported:n}}function Ba(e,t){let n=e.isJSXElement()&&an(e)?t??ir(e).members:[],r=e.isJSXElement()&&!an(e)&&!Fe(e);return{memberKey:ja(e.node.type,e.node.start,e.node.end),kind:"jsx-element",nodeType:e.node.type,sourceRange:yt(e.node.loc),businessMemberCount:r?1:xf(n),parentSourceRange:yt(e.parentPath?.node.loc),children:n,isBusinessMember:r,label:xv(e)}}function an(e){let t=e.node.openingElement.name;return t.type==="JSXIdentifier"&&t.name[0]===t.name[0]?.toLowerCase()}function xv(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 xf(e){return e.reduce((t,n)=>t+n.businessMemberCount,0)}function Ii(e){return e.length===0?0:Math.max(1,xf(e))}function ff(e){let t=yt(e.containerPath.node.loc),n=Va(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:Ii(e.members)<=1,memberCount:Ii(e.members),sourceRange:t,sourceHash:n,relation:"append",containerSourceRange:t,containerSourceHash:n,anchorSourceRange:null,anchorSourceHash:null,members:e.members}}function bv(e){let t=yt(e.expression.node.loc),n=Va(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 bf(e,t){let n=yt(t.node.loc),r=Va(e.source,t.node.start,t.node.end);return!n||!r?null:{kind:"expression",documentVersion:e.version,sourceRange:n,sourceHash:r}}function Oa(e,t,n,r,o){let i=bf(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=Sv(e,n,s),c=Ra(a),l={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:Ef(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 Sv(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:Ii(g)<=1,memberCount:Ii(g),sourceRange:m,sourceHash:m?La(e.source,m):null,relation:l,containerSourceRange:h,containerSourceHash:h?La(e.source,h):null,anchorSourceRange:u,anchorSourceHash:u?La(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 Ma(e,t,n,r){let o=bf(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=Ra([a]),l={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:Ef(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 Sf([e.route,e.entryFile,String(e.version),t,n,r?`${r.startLine}:${r.startColumn}-${r.endLine}:${r.endColumn}`:"no-range"])}function ja(e,t,n){return Sf(["member",e,String(t??-1),String(n??-1)])}function Sf(e){return`pc_${$a("sha256").update(e.join("\0")).digest("hex").slice(0,24)}`}function Va(e,t,n){return t==null||n==null?null:`sha256:${$a("sha256").update(e.slice(t,n)).digest("hex")}`}function La(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:${$a("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 Ef(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 Fv}from"@vcp-dev/contracts";import wF from"node:fs";import AF from"node:path";var vv=/^page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function Vr(e){let t=e.map(r=>Tv(r.path)),n=kv(t);return n?t.filter(r=>Cv(n,r)).map(r=>({routeId:Rv(n,r),entryFile:r})).sort((r,o)=>r.routeId.localeCompare(o.routeId)):[]}function Ka(e,t=""){let r=((e??"/").trim()||"/").split(/[?#]/,1)[0]||"/",o=r.startsWith("/")?r:`/${r}`,i=Av(t),s=i&&(o===i||o.startsWith(`${i}/`))?o.slice(i.length)||"/":o,a=s.startsWith("/")?s:`/${s}`;return a==="/"?"/":a.replace(/\/+$/,"")}function kv(e){return e.some(r=>r.startsWith("app/")&&!Iv(r))?"app":e.some(r=>r.startsWith("src/app/"))?"src/app":null}function Iv(e){return/^(?:src\/)?app\/(?:_vcp|\.vcp)/.test(e)}function Cv(e,t){if(!t.startsWith(`${e}/`))return!1;let n=t.slice(t.lastIndexOf("/")+1);return vv.test(n)?t.slice(e.length+1,-n.length-1).split("/").filter(Boolean).every(r=>!r.startsWith("_")&&!r.startsWith(".")):!1}function Rv(e,t){let n=t.slice(e.length+1).split("/").slice(0,-1).map(wv).filter(r=>!!r);return n.length===0?"/":`/${n.join("/")}`}function Nv(e){return e.startsWith("(")&&e.endsWith(")")}function wv(e){return!e||e.startsWith("@")||e.startsWith("_")||Nv(e)?null:Pv(e)}function Pv(e){return e.replace(/^\((?:\.|\.\.|\.\.\.)\)/,"")}function Av(e){let t=e.trim();return!t||t==="/"?"":(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"")}function Tv(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}var Kr=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="PageTemplateManagedSourceError"}};function et(e,t={}){throw new Kr("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Invalid page-template source (${e}): ${t.path??t.routeId??t.templateId??""}`,{reason:e,...t})}function Ua(e){return Fv.safeParse(e).success||et("invalid-template-id",{templateId:e}),Buffer.from(e,"utf8").toString("base64url")}function vf(e){/^[A-Za-z0-9_-]{1,255}$/.test(e)||et("invalid-template-key",{path:e});let t;try{t=new TextDecoder("utf-8",{fatal:!0}).decode(Buffer.from(e,"base64url"))}catch{return et("invalid-template-key",{path:e})}return Ua(t)!==e&&et("noncanonical-template-key",{path:e}),t}function _v(e){let t=Ka(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("(")||Ov(r)&&!kf(r)))&&et("invalid-public-route",{routeId:e}),t}function Ov(e){return e.includes("[")||e.includes("]")}function kf(e){return/^\[\[\.\.\.[^\[\]]+\]\]$|^\[[^\[\]]+\]$/.test(e)}function If(e){return e.some(kf)}function Cf(e,t,n="app"){n!=="app"&&n!=="src/app"&&et("invalid-app-root");let r=_v(e),o=Ua(t),i=If(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))&&et("path-too-long",{path:a}),{appRoot:n,routeRoot:s,templateKey:o,templateEntryFile:a}}function Rf(e){return/^(?:src\/)?app\/\.vcp\/page-templates\//.test(e)}function Nf(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===".")&&et("invalid-file-path",{path:i}),n.has(i)&&et("duplicate-file-path",{path:i}),n.set(i,o)}return n}function Ri(e){let t=Nf(e.files),n=Vr([...t.keys()].map(i=>({path:i}))),r=new Map;for(let i of n){if(r.has(i.routeId))throw new Kr("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(!Rf(i))continue;let s=/^(app|src\/app)\/\.vcp\/page-templates\/(.+)\/page\.tsx$/.exec(i);s||et("candidate-must-be-single-page",{path:i});let a=s[1],c=s[2].split("/"),l=If(c),d=l?c[0]:c.pop(),f=l?c.slice(1):c,m=vf(d),u=f.length?`/${f.join("/")}`:"/";Cf(u,m,a).templateEntryFile!==i&&et("candidate-path-mismatch",{path:i,routeId:u});let h=r.get(u);(!h||!h.startsWith(`${a}/`))&&et("canonical-entry-missing",{path:i,routeId:u}),o.push({routeId:u,templateId:m,entryFile:i,canonicalEntryFile:h,appRoot:a})}return o.sort((i,s)=>Ci(i.routeId,s.routeId)||Ci(i.templateId,s.templateId))}function wf(e){let t=Nf(e.files),n=Ri({files:t}),r=Vr([...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)=>Ci(o.context.routeId,i.context.routeId)||(o.context.effectiveTemplateId===void 0?-1:i.context.effectiveTemplateId===void 0?1:Ci(o.context.effectiveTemplateId,i.context.effectiveTemplateId)))}function Mv(e){let t=Ka(e.selector.routeId),n=wf({files:e.files}),r=n.find(i=>i.context.routeId===t&&i.context.effectiveTemplateId===void 0);(!r||r.entryFile!==e.canonicalEntryFile)&&et("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||et("template-selection-not-found",{routeId:t,templateId:e.selector.templateId}),{...o,mode:e.selector.templateId===void 0?"direct":"candidate",effectiveEntryFile:o.entryFile}}function Ci(e,t){return e<t?-1:e>t?1:0}import{HOME_PAGE_URL_PATH as Wv}from"@vcp-dev/contracts";import{parse as T_}from"@babel/parser";import{parse as jF}from"@babel/parser";import{FormBlockIdSchema as VF,FormSpecV1Schema as KF}from"@vcp-dev/contracts";var Ur="components/site/generated/forms",UF=`${Ur}/vcp-form-runtime.tsx`,Ni="[A-Za-z0-9][A-Za-z0-9_-]{0,127}",JF=new RegExp(`^${Ur}/form-(${Ni})\\.spec\\.ts$`),XF=new RegExp(`^${Ur}/form-(${Ni})\\.tsx$`),zF=new RegExp(`^@/${Ur}/form-(${Ni})$`),HF=new RegExp(`(?:^|/)${Ur}/form-(${Ni})(?:\\.tsx?)?$`);var WF=Symbol("invalid-literal");import{createHash as ZF}from"node:crypto";import{posix as qF}from"node:path";import{parse as t_}from"@babel/parser";import{FormSpecV1Schema as r_}from"@vcp-dev/contracts";var o_=Symbol("dynamic");import{parse as Lv}from"@babel/parser";function wi(e){return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&typeof t.type=="string"):[]}var Dv=/^(?:src\/)?app\/(.*)page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function Pf(e){let t=Dv.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 Bv(e){let t=e;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function Af(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function jv(e){let t=e;for(;t&&(t.type==="TSAsExpression"||t.type==="TSSatisfiesExpression"||t.type==="ParenthesizedExpression");)t=t.expression??null;return t}function Ja(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(Ja);if(t?.type==="ObjectExpression"){let n={};for(let r of wi(t.properties)){if(r.type!=="ObjectProperty"||r.computed)throw new Error("dynamic object property");let o=Af(r.key);if(!o)throw new Error("unsupported object key");n[o]=Ja(r.value)}return n}throw new Error(`unsupported static value: ${t?.type??"unknown"}`)}function Xa(e,t){let n=[],r=Pf(t);if(r===null)return{found:!1,seo:null,diagnostics:n};let o;try{o=Lv(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 wi(o.program.body)){let d=l.type==="ExportNamedDeclaration"?l.declaration:l;if(d?.type==="VariableDeclaration")for(let f of wi(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=jv(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 wi(s.properties)){if(l.type!=="ObjectProperty"||l.computed)continue;let d=Af(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=Bv(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=Ja(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 $v}from"@babel/parser";var Tf=["page","anchor","external","email","phone","group","file"],Vv=["link","cta"],_f=["description","badge","iconKey"],za=["label","targetType","href","role","openInNewTab","nofollow","children",..._f],Kv=new Set(za);function Xr(e){return Array.isArray(e)?e:[]}function Jr(e){let t=e;return t?.type==="StringLiteral"&&typeof t.value=="string"?t.value:void 0}function Uv(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function Ff(e){let t=e;return t?.type==="BooleanLiteral"&&typeof t.value=="boolean"?t.value:void 0}function Ha(e){let t=[],n;try{n=$v(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 Xr(n.program.body)){let s=i.type==="ExportNamedDeclaration"?i.declaration:i;if(s?.type==="VariableDeclaration")for(let a of Xr(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 Xr(r.elements).forEach((i,s)=>{let a=Of(i,`NAV_ITEMS[${s}]`,t);a&&o.push(a)}),{items:o,diagnostics:t}}function Of(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 Xr(e.properties)){if(l.type!=="ObjectProperty"||l.computed)continue;let d=Uv(l.key);d&&(r[d]=l.value)}let o=Jr(r.label),i=Jr(r.targetType);if(!o)return n.push({severity:"fatal",path:`${t}.label`,message:"label must be a static string"}),null;if(!i||!Tf.includes(i))return n.push({severity:"fatal",path:`${t}.targetType`,message:`targetType must be one of ${Tf.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 _f){if(r[l]===void 0)continue;let d=Jr(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))Kv.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 ${za.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=[];Xr(r.children.elements).forEach((d,f)=>{let m=Of(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=Jr(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=Jr(r.role);if(c!==void 0&&(Vv.includes(c)?s.role=c:n.push({severity:"warning",path:`${t}.role`,message:"role ignored: not link/cta"})),r.openInNewTab!==void 0){let l=Ff(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=Ff(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 Jv}from"@babel/parser";function zr(e){return Array.isArray(e)?e:[]}function Mf(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression";)t=t.expression;return t?.type==="ArrayExpression"?t:void 0}function Xv(e){let t;try{t=Jv(e,{sourceType:"module",plugins:["typescript","jsx"],tokens:!0})}catch{return{status:"unsupported"}}let n=[];for(let o of zr(t.program.body)){let i=o.type==="ExportNamedDeclaration"?o.declaration:o;if(i?.type==="VariableDeclaration")for(let s of zr(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=Mf(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 Wa(e,t){let n=Lf(t);if(!n)return{status:"unsupported",source:e};let r=Xv(e);if(r.status!=="ok")return{status:r.status,source:e};let o=r.array;if(Ha(e).diagnostics.some(({severity:l})=>l==="fatal"))return{status:"unsupported",source:e};let s=[],a=l=>{let d=zr(l.elements);for(let[f,m]of d.entries()){if(Hv(m,n)){let g=d[f+1],h=d[f-1],b=m.start,E=m.end;if(typeof b!="number"||typeof E!="number")continue;if(g&&typeof g.start=="number")s.push({start:b,end:g.start});else if(h&&typeof h.end=="number")s.push({start:h.end,end:E});else{let v=/^\s*,/.exec(e.slice(E));s.push({start:b,end:v?E+v[0].length:E})}continue}let u=zv(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 zv(e){if(e.type==="ObjectExpression")for(let t of zr(e.properties)){if(t.type!=="ObjectProperty")continue;let n=t.key;if((n?.name??n?.value)==="children")return Mf(t.value)}}function Lf(e){let t=e.trim();return t.startsWith("/")?t==="/"?t:t.replace(/\/+$/,""):null}function Hv(e,t){if(e.type!=="ObjectExpression")return!1;let n,r;for(let o of zr(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"&&Lf(n??"")===t}import{estimateNavLabelWidth as m_}from"@vcp-dev/contracts";import{parse as y_}from"@babel/parser";var Gv="components/site/generated/",Hr=[".tsx",".ts",".jsx",".js"];function Df(e){if(e.expectedUrlPath===Wv)return{ok:!1,code:"HOME_PAGE_LOCKED",message:"The homepage source is protected from deletion."};let t=new Set(Vr(Object.keys(e.files).map(h=>({path:h}))).map(h=>h.entryFile)),n=Object.entries(e.files).filter(([h,b])=>{let E=h.replace(/\\/g,"/");if(!t.has(E))return!1;let v=Xa(b,E);return v.found&&v.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=Ri({files:new Map(Object.entries(e.files))});for(let b of h)b.canonicalEntryFile===r&&o.add(b.entryFile)}catch(h){return{ok:!1,code:"SOURCE_DEPENDENCY_UNSAFE",message:h instanceof Error?h.message:"Invalid page template source."}}let i=Yv(e.files);if(!i.ok)return i.error;let s=i.graph,a=ek(o,s),c=tk(o,a,s),l=[...a].filter(h=>!c.has(h)).sort((h,b)=>h.localeCompare(b)),d=[...o,...[...c].sort((h,b)=>h.localeCompare(b))],f=new Set(d),m=d.map(h=>({operation:"delete",file:h})),u=[],g=[];for(let[h,b]of Object.entries(e.files))if(!f.has(h)){if(b.includes("NAV_ITEMS")){let E=Wa(b,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}`)}b.includes(e.expectedUrlPath)&&!b.includes("NAV_ITEMS")&&g.push(`preserved_link:${h}`)}return{ok:!0,edits:m,deletedFiles:d,updatedFiles:u,preservedSharedFiles:l,warnings:g}}function Yv(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")||!Zv(r))continue;let s=vn(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(Qv(c))continue;let l=xn(r,c),d=qv(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 Zv(e){let t=e.toLowerCase();return Hr.some(n=>t.endsWith(n))}function Qv(e){return!!(/\.([a-z0-9]+)$/i.exec(e)&&!Hr.some(n=>e.endsWith(n)))}function qv(e,t){let n=e.replace(/\\/g,"/");return(Hr.some(o=>n.endsWith(o))?[n]:[...Hr.map(o=>`${n}${o}`),...Hr.map(o=>`${n}/index${o}`)]).find(o=>t.has(o))??null}function ek(e,t){let n=new Set,r=[...e].flatMap(o=>[...t.get(o)??[]]);for(;r.length>0;){let o=r.pop();!o.startsWith(Gv)||n.has(o)||(n.add(o),r.push(...t.get(o)??[]))}return n}function tk(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 Dp from"@babel/parser";import*as de from"@babel/types";import*as Xi from"node:path";import*as xe from"@babel/types";function Bf(e){if(e.path.isVariableDeclarator()){let n=e.path.get("init");return n?.isExpression()?{expressionPath:n}:null}if(!e.path.isIdentifier()||!e.path.parentPath?.isVariableDeclarator())return null;let t=e.path.parentPath.get("init");return t?.isExpression()?{expressionPath:t}:null}function Mt(e){if(e.path.isObjectPattern()||e.path.isArrayPattern())return Tn(e.path.node,e.identifier.name);if(e.path.isVariableDeclarator()){let n=e.path.node.id;if(xe.isObjectPattern(n)||xe.isArrayPattern(n))return Tn(n,e.identifier.name)}if(!e.path.isIdentifier())return!1;let t=e.path.parentPath;for(;t;){if(t.isAssignmentPattern()){let n=t.get("left");if(rk(e.path,n))return!0}if(t.isFunction()||t.isVariableDeclarator())return!1;t=t.parentPath}return!1}function Tn(e,t,n=!1){return xe.isIdentifier(e)?e.name===t&&n:xe.isObjectPattern(e)?e.properties.some(r=>xe.isObjectProperty(r)?Tn(r.value,t,n):Tn(r.argument,t,n)):xe.isArrayPattern(e)?e.elements.some(r=>{if(!r)return!1;let o=xe.isRestElement(r)?r.argument:r;return Tn(o,t,n)}):xe.isAssignmentPattern(e)?Tn(e.left,t,!0):xe.isRestElement(e)?Tn(e.argument,t,n):!1}function sr(e,t){if(e.path.isObjectPattern()){if(t){let r=It(e.path.node,t.base),[o,...i]=r??[];if(o?.kind==="property")return{propName:o.name,remainingPath:[...i,...t.path],hasDefault:Mt(e)}}return t?{propName:t.base,remainingPath:t.path,hasDefault:Mt(e)}:null}if(e.path.isVariableDeclarator()){let r=e.path.get("init");if(r?.isExpression()){let o=jf(r),i=!1,s=o?o.initBinding&&Ga(o.initBinding)?(i=Mt(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=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||Mt(e)}}}}let n=sk(e);if(n){let r=nk(n,e);if(r){let[s,...a]=r.path;return!s||s.kind!=="property"?null:{propName:s.name,remainingPath:[...a,...t?.path??[]],hasDefault:r.hasDefault||Mt(e)}}if(n.findParent(s=>s.isVariableDeclarator()))return null;let o=ok(e);if(o){let[s,...a]=o;return!s||s.kind!=="property"?null:{propName:s.name,remainingPath:[...a,...t?.path??[]],hasDefault:Mt(e)}}let i=Wr(n.node);return i?{propName:i,remainingPath:t?.path??[],hasDefault:Mt(e)}:null}if(Ga(e)){let[r,...o]=t?.path??[];return!r||r.kind!=="property"?null:{propName:r.name,remainingPath:o,hasDefault:Mt(e)}}return null}function nk(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=jf(r);if(!o)return null;let{initBinding:i,initPathPrefix:s}=o;if(!i)return null;let a=!1,c=Ga(i)?(a=Mt(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=It(n.node.id,t.identifier.name);return l?{path:[...c,...l],hasDefault:a||Mt(t)}:null}function jf(e){if(e.isIdentifier())return{initBinding:e.scope.getBinding(e.node.name),initPathPrefix:[]};if(!e.isMemberExpression())return null;let t=ak(e.node);return t?{initBinding:e.scope.getBinding(t.base),initPathPrefix:t.path}:null}function Ga(e){return e.path.isIdentifier()&&e.path.key===0&&Array.isArray(e.path.container)&&e.path.parentPath?.isFunction()===!0}function rk(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function ok(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 $f(e,t,n){if(e.path.isVariableDeclarator()){let a=e.path.get("id");if(!Array.isArray(a)&&(a.isObjectPattern()||a.isArrayPattern())){let c=Pi(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=Wr(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=ik(e);if(!r)return null;let o=r.parentPath;if(!o?.isObjectProperty())return null;let i=Wr(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 Pi(e,t){if(e.isObjectPattern()){for(let n of e.get("properties"))if(n.isObjectProperty()){let r=Wr(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=Pi(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=Pi(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=Pi(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=Wr(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 ik(e){if(!e.path.isIdentifier())return null;let t=e.path.parentPath;return t?.isAssignmentPattern()&&t.node.left===e.path.node?t:null}function sk(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 Wr(e){return e.computed?null:xe.isIdentifier(e.key)?e.key.name:xe.isStringLiteral(e.key)?e.key.value:null}function ak(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 Xf from"@babel/parser";import Qa from"@babel/traverse";import*as ar from"@babel/types";import*as ce from"@babel/types";function Fi(e,t=[]){if(e.isIdentifier()){let n=e.scope.getBinding(e.node.name);return n?Ai(n,t):null}if(e.isMemberExpression()){let n=pk(e.node),r=ck(e.node);if(!n||r===null)return null;let o=e.scope.getBinding(n);return o?Ai(o,[...r,...t]):null}return e.isAwaitExpression()||Za(e.node)?cn(gk(e.node),t,"awaited or fetched expression"):null}function ck(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 Ai(e,t=[]){let n=lk(e,t);if(n)return n;let r=uk(e,t);if(r)return r;let o=dk(e,t);return o||null}function Yr(e){return e?.kind==="api-source"}function lk(e,t){if(e.path.isVariableDeclarator()&&ce.isIdentifier(e.path.node.id)){let s=e.path.get("init");if(s?.isCallExpression()&&Ya(s.node)&&t[0]?.kind==="property"&&t[0].name==="data")return cn(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)&&Uf(c)==="data"&&Gr(c.value,e.identifier.name)),a=e.path.get("init");if(s&&a?.isCallExpression()&&Ya(a.node))return cn(e.identifier.name,t,"query hook data binding")}let n=fk(e);if(!n||Uf(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()||!Ya(i.node)?null:cn(e.identifier.name,t,"query hook data binding")}function uk(e,t){if(e.path.isVariableDeclarator()&&ce.isArrayPattern(e.path.node.id)){let a=e.path.get("init");if(!a?.isCallExpression()||!Kf(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:Vf(e,l.name)?cn(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()||!Kf(o.node)||n.node.elements.findIndex(a=>a===e.path.node)!==0)return null;let s=n.node.elements[1];return ce.isIdentifier(s)&&Vf(e,s.name)?cn(e.identifier.name,t,"state setter is updated by API data"):null}function dk(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()?cn(e.identifier.name,t,"awaited binding result"):Za(r.node)?cn(e.identifier.name,t,"fetch-backed binding result"):null:null}function fk(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 Gr(e,t){return ce.isIdentifier(e)?e.name===t:ce.isAssignmentPattern(e)?Gr(e.left,t):ce.isObjectPattern(e)?e.properties.some(n=>ce.isObjectProperty(n)?Gr(n.value,t):Gr(n.argument,t)):ce.isArrayPattern(e)?e.elements.some(n=>!!n&&Gr(ce.isRestElement(n)?n.argument:n,t)):!1}function Vf(e,t){let n=!1,r=!1;return e.scope.path.traverse({CallExpression(i){Za(i.node)&&(n=!0),(mk(i.node.callee,t)||i.node.arguments.some(s=>ce.isIdentifier(s)&&s.name===t))&&(r=!0)}}),n&&r}function Ya(e){let t=_i(e.callee);return t==="useQuery"||t==="useSWR"||t==="useSuspenseQuery"}function Kf(e){return _i(e.callee)==="useState"}function Za(e){return Ti(e,t=>ce.isCallExpression(t)&&_i(t.callee)==="fetch")}function pk(e){let t=e;for(;ce.isMemberExpression(t);)t=t.object;return ce.isIdentifier(t)?t.name:null}function Uf(e){return e.computed?null:ce.isIdentifier(e.key)?e.key.name:ce.isStringLiteral(e.key)?e.key.value:null}function _i(e){return ce.isIdentifier(e)?e.name:ce.isMemberExpression(e)&&ce.isIdentifier(e.property)?e.property.name:null}function mk(e,t){return Ti(e,n=>ce.isIdentifier(n)&&n.name===t)}function Ti(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)&&Ti(i,t))return!0;continue}if(ce.isNode(o)&&Ti(o,t))return!0}return!1}function gk(e){return ce.isIdentifier(e)?e.name:ce.isCallExpression(e)?_i(e.callee)??"api":ce.isAwaitExpression(e)?"awaited-api":"api"}function cn(e,t,n){return{kind:"api-source",readonly:!0,sourceId:e,displayPath:hk(e,t),reason:n}}function hk(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}var zf=typeof Qa=="function"?Qa:Qa.default;function Hf(e,t){let n=Gf(e);if(!n)return{allowed:!0};let r=!1;return zf(n,{CallExpression(o){if(!Yf(o.node,t.sourceRange)||!yk(o.node))return;let i=o.get("callee");if(!i.isMemberExpression())return;let s=i.get("object");Array.isArray(s)||!s.isExpression()||Yr(Fi(s))&&(r=!0,o.stop())}}),r?{allowed:!1,reason:"Cannot add data-backed items to a dynamic API list"}:{allowed:!0}}function Wf(e,t){let n=Gf(e);if(!n)return{allowed:!0};let r=!1;return zf(n,{JSXExpressionContainer(o){Yf(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 Gf(e){try{return Xf.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function yk(e){let t=e.callee;return ar.isMemberExpression(t)&&ar.isIdentifier(t.property)&&t.property.name==="map"}function Yf(e,t){let n=e.loc;return n?Jf({line:n.start.line,column:n.start.column},{line:t.startLine,column:t.startColumn})>=0&&Jf({line:n.end.line,column:n.end.column},{line:t.endLine,column:t.endColumn})<=0:!1}function Jf(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 Zf from"@babel/parser";import qa from"@babel/traverse";import*as Te from"@babel/types";import*as cr from"node:path";var Ct=typeof qa=="function"?qa:qa.default;function Je(e){try{return Zf.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function ec(e){return e.computed?Te.isStringLiteral(e.key)||Te.isNumericLiteral(e.key)?String(e.key.value):null:xk(e.key)}function xk(e){return Te.isIdentifier(e)?e.name:Te.isStringLiteral(e)||Te.isNumericLiteral(e)?String(e.value):null}function Fn(e){return Te.isParenthesizedExpression(e)||Te.isTSAsExpression(e)||Te.isTSSatisfiesExpression(e)||Te.isTSNonNullExpression(e)||Te.isTSTypeAssertion(e)?Fn(e.expression):Te.isExpression(e)?e:null}function tc(e){if(Te.isIdentifier(e))return[e.name];if((Te.isMemberExpression(e)||Te.isOptionalMemberExpression(e))&&!e.computed&&Te.isIdentifier(e.property)){let t=Fn(e.object),n=t?tc(t):null;return n?[...n,e.property.name]:null}return null}function _n(e,t){return t.startsWith("@/")?t.slice(2).replace(/\\/g,"/"):t.startsWith(".")?cr.normalize(cr.join(cr.dirname(e),t)).replace(/\\/g,"/"):t}function st(e,t){return Oi(e)===Oi(t)}function Oi(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 ep(e,t,n){let r=op(e,t);if(ip(e,r),sp(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){up(s,r)&&o.push(s)}}),o.length!==1?{ok:!1,reason:"Cannot move prop-backed repeat child without a single unambiguous component call site"}:Mi(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 tp(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 bk(i,n))o=r(s)||o}return[...n.values()]}function bk(e,t){let n=[],r=Sk(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=Zr(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=_n(e.file,o.source.value);for(let s of o.specifiers){if(J.isExportNamespaceSpecifier(s)){let l=ln(s.exported);for(let d of t.values())st(d.file,i)&&n.push({file:e.file,namespace:nc(l,d.namespace),exportName:d.exportName});continue}if(!J.isExportSpecifier(s))continue;let a=ln(s.local),c=[...t.values()].filter(l=>st(l.file,i)&&On(l.namespace,a));if(c.length>0){let l=ln(s.exported);for(let d of c){let f=Zr(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:ln(s.exported)})}continue}if(J.isExportNamedDeclaration(o)&&!o.source){for(let i of o.specifiers){if(!J.isExportSpecifier(i))continue;let s=ln(i.local),a=r.get(s)??[];if(a.length>0){let c=ln(i.exported);n.push({file:e.file,exportName:c});for(let l of a){let d=Zr(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=_n(e.file,o.source.value),s=o.exported;if(s){let a=ln(s);for(let c of t.values())st(c.file,i)&&n.push({file:e.file,namespace:nc(a,c.namespace),exportName:c.exportName});continue}for(let a of t.values())st(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 On(e,t){return e===t||e?.startsWith(`${t}.`)===!0}function Zr(e,t,n){return!On(e,t)||!e?null:e===t?n:`${n}${e.slice(t.length)}`}function Sk(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=_n(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=>st(d.file,s)&&On(d.namespace,"default"));for(let d of l){let f=Zr(d.namespace,"default",a.local.name);f&&r(a.local.name,{...d,namespace:f})}continue}if(J.isImportSpecifier(a)){let c=ln(a.imported),l=[...t.values()].filter(f=>st(f.file,s)&&On(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())st(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=Fn(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=Zr(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`${Oi(e.file)}#${t}`}function ln(e){return J.isIdentifier(e)?e.name:e.value}function np(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 oc(e){let t=Ek(e),n=[],r=sp(e.ast,t);return Ct(e.ast,{JSXElement(o){st(e.file,e.sourceFile)&&Mi(o)===e.sourceComponent||up(o,t)&&n.push({file:e.file,path:o})}}),{callSites:n,hasUnsafeReference:r}}function rp(){return{localBindings:new Set,namespaceMembers:new Map,hasUnsupportedAlias:!1}}function op(e,t){let n=rp();return Ct(e,{Program(r){let o=r.scope.getBinding(t);o&&n.localBindings.add(o),r.stop()}}),n}function Ek(e){let t=rp();return st(e.file,e.sourceFile)&&vk(t,op(e.ast,e.sourceComponent)),Ct(e.ast,{ImportDeclaration(n){let r=n.node,o=r.source.value;if(typeof o!="string")return;let i=_n(e.file,o),s=e.componentIdentities.filter(a=>st(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=>On(d.namespace,"default"));if(l.length>0){let d=t.namespaceMembers.get(c)??new Set;for(let f of l){let m=qf(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=>On(f.namespace,l));if(d.length>0){let f=t.namespaceMembers.get(c)??new Set;for(let m of d){let u=qf(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)}}}}}),ip(e.ast,t),t}function vk(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 ip(e,t){Ct(e,{VariableDeclarator(n){if(!n.node.init)return;let r=Fn(n.node.init);if(r){if(J.isIdentifier(n.node.id)){let o=Mn(r,t,n),i=n.scope.getBinding(n.node.id.name);o&&i&&rc(t,i,o);return}if(J.isObjectPattern(n.node.id)){let o=Mn(r,t,n);o?.unsupported||o?.local?t.hasUnsupportedAlias=!0:o&&o.namespaceMembers.size>0&&lp(n.node.id,o.namespaceMembers,t,n)}}}})}function sp(e,t){if(t.hasUnsupportedAlias)return!0;let n=!1;return Ct(e,{ReferencedIdentifier(r){if(n){r.stop();return}kk(r)||!r.isIdentifier()||!ap(r,t)||Ik(r,t)||Ck(r)||(n=!0,r.stop())}}),n}function kk(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 ap(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)&&Mn(r.node,t,r)?r:null}function Ik(e,t){let n=e.findParent(c=>c.isVariableDeclarator());if(!n?.isVariableDeclarator())return!1;let r=n.get("init");if(!r?.isExpression()||!Qf(e,r))return!1;let o=ap(e,t);if(!o)return!1;if(Fn(r.node)===o.node)return!!Mn(r.node,t,r);let s=e.findParent(c=>c.isObjectProperty());if(!s?.isObjectProperty())return!1;let a=s.get("value");return a.isExpression()&&Qf(e,a)&&!!Mn(a.node,t,a)}function Ck(e){let t=e.parentPath;return t?.isExportDefaultDeclaration()&&t.node.declaration===e.node?!0:!!(t?.isExportSpecifier()&&t.node.local===e.node)}function Qf(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function Mn(e,t,n){let r=Fn(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 Rk(r,t,n);let o=tc(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?cp(s,o.slice(1).join(".")):null}function Rk(e,t,n){let r=new Set,o=!1;for(let i of e.properties){if(!J.isObjectProperty(i))continue;let s=ec(i);if(!s||!J.isExpression(i.value)){J.isExpression(i.value)&&(o||=Mn(i.value,t,n)!==null);continue}let a=Mn(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 cp(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 rc(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 lp(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&&rc(n,c,{local:!1,namespaceMembers:new Set(t),unsupported:!1})}else n.hasUnsupportedAlias=!0;continue}if(!J.isObjectProperty(o))continue;let i=ec(o);if(!i){n.hasUnsupportedAlias=!0;continue}let s=cp(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&&rc(n,c,s);continue}if(J.isObjectPattern(a)&&s.namespaceMembers.size>0){lp(a,s.namespaceMembers,n,r);continue}n.hasUnsupportedAlias=!0}}function qf(e,t){if(!On(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 up(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=dp(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 dp(e){if(J.isJSXIdentifier(e))return[e.name];if(J.isJSXMemberExpression(e)){let t=dp(e.object);return t?[...t,e.property.name]:null}return null}function Mi(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 fp(e,t){let n=Je(e);if(!n||!t.tag||!t.importedFrom||!t.exportName)return Number.POSITIVE_INFINITY;let r=oc({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 Lt(e,t){let n=ge(e);return!!(n&&at(t,n))}function at(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:Li(e,t)}function dr(e,t){let n=ge(t);return n?e.slice(n.start,n.end):""}function pp(e,t){return e.start===t.start&&e.end===t.end}function Li(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 Di(e,t){return ic(e,t).length>0}function Bi(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()&&!Nk(o,n,r)))return!0;o=o.parentPath}return!1}function Nk(e,t,n){let r=ge(e.node.consequent);if(r&&at(r,t)&&!at(r,n))return!1;let o=e.node.alternate?ge(e.node.alternate):null;return!(o&&at(o,t)&&!at(o,n))}function ic(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()&&sc(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 sc(e){return e==="&&"||e==="||"||e==="??"}function mp(e,t){let n=ge(e.consequent);if(n&&at(n,t))return n;let r=ge(e.alternate);return r&&at(r,t)?r:null}function gp(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=np(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=tp(r,{file:e.sourceFile,exportName:n.exportName}),i=[];for(let a of r){let c=oc({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!st(s.file,e.targetFile)||Mi(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 _k}from"@vcp-dev/contracts";function ji(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 Qr();let a=s.target,c=a.locator;if(a.sourceKind==="repeat-template"){let l=o?.instanceIndex;if(l===void 0)return Qr();let d=wk(a,l,o?.instanceCount);if(!d)return Qr();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"?Qr():{ok:!0,target:{kind:"jsx-attribute"}}}function Qr(){return{ok:!1,code:"unsupported-binding",reason:"Property does not have a safe typed binding write target for this scope and operation"}}function wk(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 Pk}from"@vcp-dev/contracts";function hp(e){let t=e.changes??(e.change?[e.change]:[]);if(!Pk.safeParse({kind:"set-props",scope:"selection",changes:t}).success)return qr("invalid-change","Repeat property changes are invalid");if(t.length!==1||t[0].name!==e.target.propertyName)return qr("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 qr("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 qr("unsupported-object",`Repeat item ${s} is not a writable object expression`);let l=s===e.target.sourceItemIndex?Ak(r):Tk(c.match.path.node,r.name);if(!l)return qr("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 Ak(e){return e.operation==="set"?{kind:"value",value:e.value}:{kind:"undefined"}}function Tk(e,t){let n=e.properties.filter(i=>Dt.isObjectProperty(i)&&Fk(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=Ot(r.value);return o.status==="undefined"?{kind:"undefined"}:o.status!=="resolved"?null:{kind:"value",value:o.value}}function Fk(e){return Dt.isIdentifier(e)?e.name:Dt.isStringLiteral(e)?e.value:Dt.isNumericLiteral(e)?String(e.value):null}function qr(e,t){return{ok:!1,errorCode:e,reason:t}}function yp(e){if(e.change.name!=="className"&&e.change.name!=="class")return eo("unsupported-owner",`No specialized property owner is available for '${e.change.name}'`);let t=e.classNameSource;if(!t||t.filePath!==e.node.file)return eo("owner-source-unavailable","className source details are unavailable for the selected node");if(e.change.name==="class"&&t.sourceKind==="missing")return eo("owner-source-unavailable","The class alias requires an existing className source");if(t.sourceKind==="expression")return eo("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 eo("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 eo(e,t){return{ok:!1,errorCode:e,reason:t}}async function bp(e){let t=_k.safeParse({kind:"set-props",scope:e.scope,changes:e.changes});if(!t.success)return un("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 un("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 Ok(e,r);if(o){if(!o.ok)return un("owner-plan-failed",o.reason);xp(n,o.steps);continue}let i=await e.getPropertyState(e.node.key,r.name,e.selectionRef);if(!i)return un("missing-property-state",`No authoritative property state is available for '${r.name}'`);if(i.status==="blocked")return un("readonly-property",i.diagnostic?.message??`Property '${r.name}' is not writable`);if(Dk(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=ji({state:i,scope:e.scope,operation:r.operation,selectionRef:e.selectionRef,repeatTarget:s});if(!a.ok)return un(a.code,a.reason);let c=a.target;if(c.kind==="value-binding"&&r.operation==="set"){ac(n,{type:"update-value",order:n.length,file:c.file,locator:c.locator,value:r.value});continue}if(c.kind==="repeat-property"){let l=hp({source:e.getFileContent(c.target.sourceFile),target:c.target,changes:[r]});if(!l.ok)return un("repeat-target-failed",l.reason);xp(n,l.steps);continue}ac(n,{type:"set-property-changes",order:n.length,file:e.node.file,locator:Mk(e.node),scope:e.scope,changes:[r]})}return n.forEach((r,o)=>{r.order=o}),Lk(n)?un("step-conflict","Property changes resolve to conflicting write steps"):{ok:!0,steps:n}}async function Ok(e,t){return t.name!=="className"&&t.name!=="class"?null:yp({node:e.node,change:t,classNameSource:e.classNameSource})}function Mk(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 Lk(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 xp(e,t){for(let n of t)ac(e,{...n,order:e.length})}function ac(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 Dk(e,t){if(t.operation!=="set"||e.status!=="direct")return!1;let n=e.attribute?.resolution;return n?.status==="resolved"?cc(n.value,t.value):e.attribute?.source===null&&e.attribute.value===t.value}function cc(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)=>cc(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=>cc(n[i],r[i]))}return!1}function un(e,t){return{ok:!1,errorCode:e,reason:t}}import*as pr from"@babel/types";import*as G from"@babel/types";function lc(e,t,n){let r=bt(t,n);return r?Bt(e,r):null}function Bt(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=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:G.isOptionalMemberExpression(c)&&c.optional?"?.map":".map",collectionNeedsParens:$i(d.node),callbackPath:r,collectionPath:d}}function to(e,t){return!!(e&&t&&e.callStart===t.callStart&&e.callEnd===t.callEnd&&e.callbackStart===t.callbackStart&&e.callbackEnd===t.callbackEnd)}function Bk(e,t){let n=ge(e.node);return n?jk(t).some(r=>{let o=ge(r);return r===e.node||!!(o&&o.start===n.start&&o.end===n.end)}):!1}function jk(e){let t=e.callbackPath.node.body;return G.isBlockStatement(t)?dn(t.body):fn(t)}function dn(e){let t=[];for(let n of e){if(G.isReturnStatement(n)){n.argument&&t.push(...fn(n.argument));continue}if(G.isBlockStatement(n)){t.push(...dn(n.body));continue}if(G.isIfStatement(n)){let r=G.isBlockStatement(n.consequent)?n.consequent.body:[n.consequent];if(t.push(...dn(r)),n.alternate){let o=G.isBlockStatement(n.alternate)?n.alternate.body:[n.alternate];t.push(...dn(o))}continue}if(G.isSwitchStatement(n)){for(let r of n.cases)t.push(...dn(r.consequent));continue}G.isTryStatement(n)&&(t.push(...dn(n.block.body)),n.handler&&t.push(...dn(n.handler.body.body)),n.finalizer&&t.push(...dn(n.finalizer.body)))}return t}function fn(e){return G.isJSXElement(e)?$k(e)?Sp(e.children):[e]:G.isJSXFragment(e)?Sp(e.children):G.isParenthesizedExpression(e)||G.isTSAsExpression(e)||G.isTSSatisfiesExpression(e)||G.isTSNonNullExpression(e)||G.isTSTypeAssertion(e)?fn(e.expression):G.isConditionalExpression(e)?[...fn(e.consequent),...fn(e.alternate)]:G.isLogicalExpression(e)&&sc(e.operator)?fn(e.right):[]}function Sp(e){return e.flatMap(t=>G.isJSXElement(t)||G.isJSXFragment(t)?fn(t):G.isJSXExpressionContainer(t)&&(G.isJSXElement(t.expression)||G.isJSXFragment(t.expression)||G.isConditionalExpression(t.expression)||G.isLogicalExpression(t.expression))?fn(t.expression):[])}function $k(e){let t=e.openingElement.name;return G.isJSXIdentifier(t)?t.name==="Fragment":G.isJSXMemberExpression(t)&&t.property.name==="Fragment"}function Ep(e,t){return!!(e&&t&&e.callbackStart<t.callbackStart&&e.callbackEnd>t.callbackEnd)}function $i(e){return!(G.isIdentifier(e)||G.isThisExpression(e)||G.isMemberExpression(e)||G.isOptionalMemberExpression(e)||G.isCallExpression(e)||G.isOptionalCallExpression(e))}function vp(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 fr(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:Li(n,t);if(!o)return t.isRepeatItemRoot===!0;let i=Bt(e,o);return i?Bk(o,i):t.isRepeatItemRoot===!0}function kp(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:Li(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 uc(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 Vk(e,t){let n=ge(e.node);if(!n)return[];let r=new Set,o=(i,s)=>{let a=s.scope.getBinding(i);!a||Lt(a.path.node,n)||pn(a,i,t)||r.add(i)};return e.traverse({ReferencedIdentifier(i){o(i.node.name,i)},JSXOpeningElement(i){let s=uc(i.node.name);s&&o(s,i)}}),[...r].sort()}function dc(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=Ar(o.match.path,i.match.path);if(Di(s,i.match.path))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let a=Vk(s,i.match.path);return a.length>0?{ok:!1,bindingNames:a}:{ok:!0}}function Cp(e){let t=e;for(;ve.isTSQualifiedName(t);)t=t.left;return ve.isIdentifier(t)?t.name:null}function no(e,t){e.isIdentifier()&&e.isReferencedIdentifier()&&t(e),e.traverse({ReferencedIdentifier(n){n.isIdentifier()&&t(n)}})}function Vi(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 fc(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=Ip(e),i=Ip(t);if(!o||!i||!pp(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=mp(s.node,n);if(a&&!at(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&&at(a,n)&&!at(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())&&vp(s)){let a=ge(s.node.body)??ge(s.node);if(a&&!at(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 Ip(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 pn(e,t,n){return n.scope.getBinding(t)===e}function pc(e,t,n,r={}){if(!r.preserveConditionalBoundary&&Di(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=>Vi(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||Lt(d.path.node,o)||i.has(d.path.node)||pn(d,c,t)||s.add(c)};return e.traverse({ReferencedIdentifier(c){a(c.node.name,c)},JSXOpeningElement(c){let l=uc(c.node.name);l&&a(l,c)}}),s.size>0?{ok:!1,bindingNames:[...s].sort()}:{ok:!0}}function mc(e,t,n){let r=ge(e.node);if(!r)return{ok:!0};let o=new Set(n.callbackPath.node.params.flatMap(s=>Vi(s)).map(s=>n.callbackPath.scope.getBinding(s)?.path.node).filter(Boolean)),i=new Set;return no(e,s=>{let a=s.scope.getBinding(s.node.name);!a||Lt(a.path.node,r)||o.has(a.path.node)||pn(a,s.node.name,t)||i.add(s.node.name)}),i.size>0?{ok:!1,bindingNames:[...i].sort()}:{ok:!0}}function Rp(e,t){let n=new Set(e.callbackPath.node.params.flatMap(a=>Vi(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)||pn(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=Cp(l);d&&o(d,c)}}});return r.size>0?{ok:!1,bindingNames:[...r].sort()}:{ok:!0}}function gc(e,t){let n=ge(e.node),r=new Set;return no(e,o=>{let i=o.scope.getBinding(o.node.name);i&&(n&&Lt(i.path.node,n)||pn(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 Np(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 wp(e,t){return{...e,callbackParams:t}}function hc(e,t){return`${e.collectionNeedsParens?`(${e.collectionExpression})`:e.collectionExpression}${e.mapOperator}((${e.callbackParams.join(", ")}) => ${t})`}function ro(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 Pp(e,t,n,r){return e.parentKey===t.key&&e.file===t.file&&n?.kind==="value-binding"&&n.file!==e.file&&n.sourceKind!=="repeat-template"&&r?.finalSource?.kind!=="component-prop"}function Ln(e){return{file:e.file,component:e.component}}function Kk(e){return e.target.kind==="node"?e.target.key:null}function Uk(e){return"kind"in e}function Ki(e){return!Uk(e)}function Ec(e,t){let n=Xi.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=Xi.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function yc(e,t){let n=e.getFileContent(t.file);if(!n)return;let r=Ft(n,he(t));if(r.ok)return n.slice(r.match.start,r.match.end)}function kc(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 Jk(e){if(e.isNumericLiteral())return!0;if(!e.isUnaryExpression({operator:"-"}))return!1;let t=e.get("argument");return!Array.isArray(t)&&t.isNumericLiteral()}function Xk(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 xc(e){return e==="Cannot edit repeat-backed child node structure with a generic node operation"}function zk(e){let t=ep(e.ast,e.sourceNode.component,e.targetParent.component);if(!t.ok)return{ok:!1,reason:t.reason};let n=fc(t.path,e.targetParentPath);if(!n.ok)return{ok:!1,reason:n.reason};let r=Hk({source:e.source,sourceContext:e.sourceContext,callSitePath:t.path,targetParentPath:e.targetParentPath});if(!r.ok)return r;let o=Bp(r.collectionExpression);return{ok:!0,context:{...e.sourceContext,collectionExpression:r.collectionExpression,collectionNeedsParens:o?$i(o):!0}}}function Hk(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||Lt(a.path.node,t))return;let c=Yk(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=Qk(e.callSitePath,c.propName,e.source);if(!l.ok){o=l.reason;return}let d=Wk(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=gc(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}pn(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:qk(e.source,t,[...n.values()])}}function Wk(e,t){if(t.length===0)return e;let n=Bp(e);if(!n)return null;let r=$i(n)?`(${e})`:e;for(let o of t){if(o.kind==="property"){r=Gk(o.name)?`${r}.${o.name}`:`${r}[${JSON.stringify(o.name)}]`;continue}r=`${r}[${o.index}]`}return r}function Gk(e){return/^[$A-Z_a-z][$\w]*$/.test(e)}function Yk(e,t,n){let r=Zk(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 Zk(e,t){let n=e.parentPath;if(!n||!n.isMemberExpression()&&!n.isOptionalMemberExpression()||n.node.object!==e.node||!Lt(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 Qk(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=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 qk(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 Bp(e){try{let n=Dp.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 eI(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||Lt(s.path.node,t))return;let a=Ap(s,e.sourceFile,e.targetFile);if(a){let c=e.targetParentPath.scope.getBinding(a.localName);if(c){let d=Ap(c,e.targetFile,e.targetFile);(!d||d.moduleFile!==a.moduleFile||!tI(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 no(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 tI(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 Ap(e,t,n){let r=nI(e),o=r?.parentPath;if(!r||!o?.isImportDeclaration())return null;let i=o.node.source.value;if(typeof i!="string")return null;let s=_n(t,i),a=i.startsWith(".")?Ec(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 nI(e){let t=e.path;for(;t&&!t.isImportDeclaration();){if(t.isImportSpecifier()||t.isImportDefaultSpecifier()||t.isImportNamespaceSpecifier())return t;t=t.parentPath}return null}function Tp(e,t,n,r){let o=ic(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=rI(a.conditionPath,c);if(s.push(a.conditionPath),a.kind==="logical"){i=`${l} ${a.operator} ${iI(i)}`;continue}i=a.branch==="consequent"?`${l} ? ${i} : null`:`${l} ? null : ${i}`}return{sourceJsx:i,conditionPaths:s}}function rI(e,t){return oI(e.node)?t:`(${t})`}function oI(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 iI(e){return e.trim().startsWith("<")?e:`(${e})`}var sI={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 Ui(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=sI[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 aI(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 cI(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 Fp(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 _p(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n+=1;return`${e}${n}`}function lI(e,t){if(!e.component)return{localName:"Component"};let n=e.component,r=kc(e),o=Je(t);if(n.exportName!=="default"){let a=o?cI(o,n.source,n.exportName):null;if(a)return{localName:a};let c=o?_p(r,Fp(o)):r;return{localName:c,importStep:bc(e,c)}}if(!o)return{localName:r,importStep:bc(e,r)};let i=aI(o,n.source);if(i)return{localName:i};let s=_p(r,Fp(o));return{localName:s,importStep:bc(e,s)}}function uI(e,t){if(e.kind==="native-tag")return e.text?`<${e.tag}>${e.text}</${e.tag}>`:`<${e.tag} />`;let n=t??kc(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 dI(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?fI(e.props):void 0;return{kind:e.kind,component:{source:e.component.source,exportName:e.component.exportName},...t?{props:t}:{}}}function fI(e){return Object.fromEntries(Object.entries(e).filter(t=>vc(t[1])))}function vc(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(vc):typeof e=="object"?Object.values(e).every(vc):!1}function bc(e,t=kc(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 Op(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 pI(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 Ic(e,t=e.path){return{kind:"value",root:e.root,path:t&&t.length>0?t:void 0,expectedRange:e.expectedRange}}function oo(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:Ic(e,t.slice(0,n)),index:r.index}}return null}function Sc(e,t){return e.locator?e.collectionPathMap?.[t]?Ic(e.locator,e.collectionPathMap[t]):oo(e.locator)?gI(e.locator,hI(t,e.collectionIndexMap)):null:null}function mI(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:jp(o,t)}function jp(e,t){let[n,...r]=e;if(!n)return t;if(n.kind!=="property")return;let o=jp(r,t);return o===void 0?void 0:{[n.name]:o}}function gI(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},Ic(e,i)}return null}function hI(e,t){return t?.[e]??e}function Mp(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 yI(e,t){return xI(e.root,t.root)&&SI(e.path??[],t.path??[])}function xI(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&&bI(e.sourceRange,t.sourceRange)}}function bI(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function SI(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 Ji=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(!Ki(r.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};let o=Op(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=Kk(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):Lp(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 Lp(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?bp({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=Sc(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=Sc(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(!Jk(a.match.path))return{ok:!0,value:r};let c=Xk(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=Sc(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=oo(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=ro(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||fp(n,t)>1)return null;let r=Ec(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(!Ki(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=ro(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=Hf(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=Ui(r,n.params.node);if(g)return{ok:!1,errorCode:"unsupported-operation",reason:g};let h=[],b=0,E=n.params.node.kind==="component-call"?lI(n.params.node,this.graph.getFileContent(r.file)):void 0,v=E?.importStep;return v&&h.push({order:b++,file:r.file,type:"add-import",moduleSpecifier:v.moduleSpecifier,imports:v.imports}),h.push({order:b++,file:r.file,type:"insert-child",parentLocator:he(r),node:{jsx:uI(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(!Ki(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:dI(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(!Ki(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=oo(a.locator);if(!c)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child requires an array-backed target"};let l=mI(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"?Mp(0,a.collectionIndexMap):Mp(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=ro(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:")||kp(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=bt(l,r),f=bt(l,o);if(!d||!f)return null;let m=Bt(c,d),u=Bt(c,f);if(!to(m,u))return null;if(a&&(s==="before"||s==="after")){let h=bt(l,a),b=h?Bt(c,h):null;if(!to(m,b))return null}if(Bi(d,f))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child across statement-level conditional branches"};let g=dc(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:Ln(o)}],i):{ok:!1,errorCode:"unsupported-operation",reason:g.reason??`Cannot move node because it depends on bindings outside the target scope: ${g.bindingNames.join(", ")}`}}planRepeatTemplateHoistMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&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=bt(l,r),f=bt(l,o);if(!d||!f)return null;let m=Bt(c,d);if(!m)return null;let u=Bt(c,f);if(to(m,u))return null;if(u&&!Ep(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 I=lc(c,l,a);if(u&&!to(u,I)||!u&&I)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 I=Ui(o,{kind:"native-tag",tag:r.tag});if(I)return{ok:!1,errorCode:"unsupported-operation",reason:I}}let g=yc(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(Bi(d,f))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let h=Tp(c,d,f,g);for(let I of h.conditionPaths){let R=mc(I,f,m);if(!R.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its condition depends on bindings outside the target scope: ${R.bindingNames.join(", ")}`}}let b=pc(d,f,m,{preserveConditionalBoundary:h.conditionPaths.length>0});if(!b.ok)return{ok:!1,errorCode:"unsupported-operation",reason:b.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${b.bindingNames.join(", ")}`};let E=Rp(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 v=m;if(r.component!==o.component){let I=zk({source:c,ast:l,sourceContext:m,sourceNode:r,targetParent:o,targetParentPath:f});if(!I.ok)return{ok:!1,errorCode:"unsupported-operation",reason:I.reason};v=I.context}else{let I=gc(m.collectionPath,f);if(!I.ok)return{ok:!1,errorCode:"unsupported-operation",reason:I.reason??`Cannot move repeat-backed child because the repeat collection is not visible at the target: ${I.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:hc(v,h.sourceJsx),selectionContext:Ln(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=gp({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=fc(m.callSitePath,g);if(!h.ok)return{ok:!1,errorCode:"unsupported-operation",reason:h.reason};let b=Bt(c,u);if(!b)return null;if(Bt(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")&&lc(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=Ui(o,{kind:"native-tag",tag:r.tag});if(O)return{ok:!1,errorCode:"unsupported-operation",reason:O}}let v=yc(this.graph,r);if(!v)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(Bi(u,g))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let I=Tp(c,u,g,v);for(let O of I.conditionPaths){let L=mc(O,g,b);if(!L.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its condition depends on bindings outside the target scope: ${L.bindingNames.join(", ")}`}}let R=pc(u,g,b,{preserveConditionalBoundary:I.conditionPaths.length>0});if(!R.ok)return{ok:!1,errorCode:"unsupported-operation",reason:R.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${R.bindingNames.join(", ")}`};let A=eI({sourceFile:r.file,targetFile:o.file,sourceContext:b,targetParentPath:g});if(!A.ok)return{ok:!1,errorCode:"unsupported-operation",reason:A.reason};let T=Np(b);if(!T.ok)return{ok:!1,errorCode:"unsupported-operation",reason:T.reason};let C=wp(b,T.callbackParams),P=[{order:0,file:r.file,type:"remove-node",locator:he(r),removeWhitespace:!0}];for(let O of A.imports)P.push({order:P.length,file:o.file,type:"add-import",moduleSpecifier:O.moduleSpecifier,imports:O.imports});return P.push({order:P.length,file:o.file,type:"insert-jsx-expression-child",parentLocator:he(o),expression:hc(C,I.sourceJsx),placement:s,anchorLocator:a?he(a):void 0,selectionContext:Ln(o)}),this.buildPlan(t,n,P,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 I=n.params.target,R=this.graph.getNode(I.anchorKey);if(!R||r.file!==R.file||r.component!==R.component)return{ok:!1,errorCode:"locator-miss",reason:"Source sibling move requires a sibling in the same component file"};let A=this.graph.getFileVersion(r.file);if(n.documentVersion!==A)return{ok:!1,errorCode:"stale-version",reason:`Document version ${n.documentVersion} is stale or otherwise does not match source sibling file version (current: ${A})`};let T=this.graph.getFileContent(r.file),C=Je(T),P=C?bt(C,r):null,O=C?bt(C,R):null,L=P?.parentPath,U=O?.parentPath;if(!P||!O||!L||!U||L.node!==U.node||!L.isJSXFragment()&&!(L.isJSXElement()&&Fe(L)))return{ok:!1,errorCode:"unsupported-operation",reason:"Source sibling move requires two direct children of the same transparent Fragment"};let ee=L.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:I.relation,anchorLocator:he(R),selectionContext:Ln(r)}],o):{ok:!1,errorCode:"locator-miss",reason:"Source Fragment has no stable source range"}}let i=Op(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(pI(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 I=n.params.target.relation,R=i.anchorNode&&(I==="before"||I==="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:I,anchorSourceId:R?.kind==="external-entry"?R.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=ro(r,c,m);if(u&&!xc(u)&&!Pp(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 I=c,R=await this.graph.getTextWriteTarget(f.key,0);if(I?.kind==="value-binding"&&R?.kind==="value-binding"&&I.locator&&R.locator){let A=oo(I.locator),T=oo(R.locator);if(A&&T&&I.file===R.file&&yI(A.locator,T.locator)){let C=A.index,P=T.index,O=d==="before"?P-(C<P?1:0):P+(C<P?0:1);return this.buildPlan(t,n,[{order:0,file:I.file,type:"move-array-item",locator:A.locator,fromIndex:C,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=xc(u)?u:g;if(h&&xc(h)){let I=this.planRepeatTemplateInternalMove(t,n,r,s,o,d,f);if(I)return I;let R=this.planRepeatTemplateHoistMove(t,n,r,s,o,d,f);if(R)return R;let A=this.planCrossFileRepeatTemplateHoistMove(t,n,r,s,o,d,f);return A||{ok:!1,errorCode:"unsupported-operation",reason:h}}if(g)return{ok:!1,errorCode:"unsupported-operation",reason:g};let b=await this.getUpstreamBackedDescendantReason(r);if(b)return{ok:!1,errorCode:"unsupported-operation",reason:b};if(r.tag&&r.tag.toLowerCase()===r.tag){let I=Ui(s,{kind:"native-tag",tag:r.tag});if(I)return{ok:!1,errorCode:"unsupported-operation",reason:I}}if(l)return this.planCrossFileMove(t,n,r,s,o,d,f);let E=dc(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 v=[{order:0,file:r.file,type:"move-node",locator:he(r),targetParentLocator:he(s),placement:d,anchorLocator:f?he(f):void 0,selectionContext:Ln(s)}];return this.buildPlan(t,n,v,o)}planCrossFileMove(t,n,r,o,i,s,a){let c=[],l=0,d=this.graph.getFileContent(r.file),f=yc(this.graph,r)??`<${r.component} />`,m=Wf(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,b={moduleSpecifier:Ec(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:b.moduleSpecifier,imports:b.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:Ln(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:Ln(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 Lp(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 Pc from"@babel/generator";import{parse as MI}from"@babel/parser";import Ac from"@babel/traverse";import*as N from"@babel/types";import*as $t from"@babel/types";import Cc from"@babel/generator";import*as be from"@babel/types";var EI=typeof Cc=="function"?Cc:Cc.default,vI=/(?:token|secret|key|password|authorization|cookie|signature|credential)/i,kI=/^((?:https?:)?\/\/)[^/@\s]+@/i,II=/(\/(?:token|secret|api[-_]?key|password|credential|signature)\/)[^/?#]+/gi;function Vp(e,t){let n=jt(e.callee);if(!n)return null;if(n==="fetch")return Rc(e.arguments[0],"GET",t,["fetch call"]);if(n.startsWith("axios.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if($p(r))return Rc(e.arguments[0],r,t,["axios client contract"])}if(n.startsWith("ky.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if($p(r))return Rc(e.arguments[0],r,t,["ky client contract"])}return null}function Rc(e,t,n,r){if(!e||be.isSpreadElement(e)||be.isJSXNamespacedName(e))return wI(t,n,r,"missing url argument");let o=io(e);return{sourceKind:NI(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 io(e){if(be.isStringLiteral(e))return zi(e.value);if(be.isTemplateLiteral(e))return zi(CI(e));if(be.isBinaryExpression(e)&&e.operator==="+"){let t=io(e.left),n=io(e.right);return!t&&!n?void 0:zi(`${t??Nc(e.left)}${n??Nc(e.right)}`)}if(be.isMemberExpression(e)){let t=Kp(e);if(t)return`env:${t}`}if(!(be.isCallExpression(e)&&jt(e.callee)==="new URL")){if(be.isNewExpression(e)&&be.isIdentifier(e.callee,{name:"URL"})){let[t,n]=e.arguments,r=t&&!be.isSpreadElement(t)?io(t):void 0,o=n&&!be.isSpreadElement(n)?io(n):void 0;return o&&r?zi(`${o} + ${r}`):r??o}if(be.isIdentifier(e))return`:${e.name}`}}function CI(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+=Nc(r))}return t}function Nc(e){if(be.isIdentifier(e))return`:${e.name}`;if(be.isMemberExpression(e)){let t=Kp(e);if(t)return`env:${t}`}return`:${RI(e)}`}function RI(e){return EI(e,{comments:!1}).code.replace(/[^a-zA-Z0-9_$]+/g,"_").replace(/^_+|_+$/g,"")||"param"}function zi(e){let[t]=e.split("#"),[n,r]=t.split("?"),o=n.replace(kI,"$1<redacted>@").replace(II,"$1<redacted>");if(!r)return o;let i=r.split("&").map(s=>{let[a]=s.split("=");return a?vI.test(a)?`${a}=<redacted>`:`${a}=:${a}`:""}).filter(Boolean).join("&");return i?`${o}?${i}`:o}function NI(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 wI(e,t,n,r){return{sourceKind:"unknown-api",method:e,confidence:"partial",evidence:[{file:t.file,reason:[...n,r].join("; ")}]}}function $p(e){return["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(e)}function Kp(e){return!be.isMemberExpression(e.object)||!be.isIdentifier(e.object.object,{name:"process"})||!PI(e.object.property,"env")?null:be.isIdentifier(e.property)?e.property.name:be.isStringLiteral(e.property)?e.property.value:null}function PI(e,t){return be.isIdentifier(e)&&e.name===t}function jt(e){if(be.isIdentifier(e))return e.name;if(be.isMemberExpression(e)){let t=jt(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 AI=new Set(["list","listStrict","get","getStrict","getByUrl","getByUrlStrict","schema","categories"]),TI=new Set(["getConfig","submit"]);function Up(e,t){let n=FI(jt(e.callee),t);if(!n)return null;let r="cms.collections.";if(n.startsWith(r)){let i=n.slice(r.length);if(!AI.has(i))return null;let s=wc(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(!TI.has(i))return null;let s=wc(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=wc(e,0)??_I(e,0,"path")??"/cms/:path",s=OI(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 FI(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 Jp(e,t){let n=jt(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 Xp(e){let t=jt(e.callee);return typeof t=="string"&&t.startsWith("cms.field.")}function wc(e,t){let n=e.arguments[t];return $t.isStringLiteral(n)?n.value:null}function _I(e,t,n){let r=e.arguments[t];if(!$t.isObjectExpression(r))return null;for(let o of r.properties)if($t.isObjectProperty(o)&&!o.computed&&($t.isIdentifier(o.key)&&o.key.name===n||$t.isStringLiteral(o.key)&&o.key.value===n)&&$t.isStringLiteral(o.value))return o.value.value;return null}function OI(e){return/^\/collections\/([^/]+)(?:\/|$)/.exec(e)?.[1]??null}var Fc=typeof Ac=="function"?Ac:Ac.default,gM=typeof Pc=="function"?Pc:Pc.default,LI={maxFunctionDepth:8,maxImportDepth:6},DI=new Set(["src","href","alt","poster","content","title","aria-label"]);async function Zp(e){let t=e.fileCache??new Map,n=Mc(e.file,e.source,t),r={file:e.file,analysis:n,readFile:e.readFile,exists:e.exists,fileCache:t,options:{...LI,...e.options},variableCache:new Map,functionDepth:0,importDepth:0,paramSources:new Map,resolvingVariables:new Set,resolvingComponentProps:new Set,scopeVariables:dm(n,e.element.componentName)};await Qp(e.element.componentName,e.graph,r);let o=[];o.push(...await KI(e.element,e.graph,r),...await UI(e.element,e.graph,r));for(let s of e.element.textSegments){let a=await JI(s,e.element,e.graph,r);a&&o.push(Gi(a,"text","children"))}for(let s of e.element.attributes??[]){let a=VI(s,e.element);if(!a)continue;let c=await tm(s.source,e.element,e.graph,r);c&&o.push(Gi(c,a,s.name))}let i=iC(o).sort(lm);return{hasDynamicData:i.length>0,bindings:i}}async function Qp(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 qp(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 em(l.sourceFile,n);if(!f)continue;let m=Zi(f,n,{importDepth:n.importDepth+1});m.paramSources.clear(),m.scopeVariables=dm(f,l.componentName),await Qp(l.componentName,t,m);let u=await BI(l,m);for(let[g,h]of u){if(!h)continue;let b=a.get(g)??[];b.push(h),a.set(g,b)}}finally{n.resolvingComponentProps.delete(d)}}}let c=new Map;for(let[l,d]of a){let f=am(d);f.length===1&&c.set(l,f[0])}$I(o,c,n)}async function qp(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 em(e,r))?.imports.get(t);if(!s||!Pt(s.source))return!1;let a=await mm(e,s.source,r.exists);return a?a===n?!0:qp(a,s.importedName,n,r,o):!1}async function BI(e,t){let n=new Map;Fc(t.analysis.ast,{JSXElement(o){if(jI(o.node,e.sourceRange)){for(let i of o.node.openingElement.attributes)!N.isJSXAttribute(i)||!N.isJSXIdentifier(i.name)||!N.isJSXExpressionContainer(i.value)||!N.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 jI(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 em(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 Mc(e,r,t.fileCache)}function $I(e,t,n){if(N.isIdentifier(e)){t.size>0&&n.paramSources.set(e.name,Oc(Object.fromEntries(t),n.file));return}if(N.isObjectPattern(e))for(let r of e.properties){if(!N.isObjectProperty(r)||r.computed||!N.isIdentifier(r.key))continue;let o=t.get(r.key.name);if(!o)continue;let i=N.isAssignmentPattern(r.value)?r.value.left:r.value;N.isIdentifier(i)&&n.paramSources.set(i.name,ze(o))}}function VI(e,t){return e.name==="dangerouslySetInnerHTML"?"richtext":DI.has(e.name)?"attribute":t.importedFrom||/^[A-Z]/.test(t.tag)?"component-prop":null}async function KI(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 Yi(i.collectionSource,n);s&&r.push(Gi(Dn(s),"repeat-region",i.collectionExpression))}return r}async function UI(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 Yi(i.conditionSource,n);s&&r.push(Gi(Dn(s),"conditional-region",i.conditionExpression))}return r}async function JI(e,t,n,r){return tm(e.source,t,n,r)}async function tm(e,t,n,r){let o=await XI(e,t,n,r);return o||Yi(e,r)}async function XI(e,t,n,r){if(!e)return null;let o=zI(e.base,t,n);if(!o)return null;let i=await Yi(o.collectionSource,r);return i?lo(i,e.path,!0):null}function zI(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 Yi(e,t){if(!e)return null;let n=await nm(e.base,t);return n?lo(n,e.path,!1):null}async function nm(e,t){let n=t.paramSources.get(e);if(n)return ze(n);if(t.variableCache.has(e))return sC(t.variableCache.get(e)??null);if(t.resolvingVariables.has(e))return null;t.resolvingVariables.add(e);let r=await HI(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 fm(i,t);if(s){let a=Zi(s,t,{importDepth:t.importDepth+1}),c=pm(i,s);if(c){let f=(await Bn(c,[],a)).returnSource;return t.variableCache.set(e,f?ze(f):null),t.resolvingVariables.delete(e),f}let l=s.variables.get(i.importedName);if(l){let 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 HI(e,t){let n=t.analysis.stateSetters.get(e);if(!n)return null;let r=[];Fc(t.analysis.ast,{CallExpression(o){if(N.isIdentifier(o.node.callee,{name:n})){let i=o.node.arguments[0];N.isExpression(i)&&r.push(i);return}o.node.arguments.some(i=>N.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(N.isIdentifier(e))return nm(e.name,t);if(N.isMemberExpression(e)||N.isOptionalMemberExpression(e)){let n=N.isMemberExpression(e)?Jp(e,{file:t.file}):null;if(n)return sm(n);let r=await WI(e,t);if(!r)return null;let o=rC(e);return lo(r,o,!1)}if(N.isAwaitExpression(e))return N.isExpression(e.argument)?je(e.argument,t):null;if(N.isCallExpression(e))return rm(e,t);if(N.isObjectExpression(e)){let n=await om(e,t);return Object.keys(n).length>0?Oc(n,t.file):null}if(N.isConditionalExpression(e)){let n=await je(e.consequent,t),r=await je(e.alternate,t);return co(Hp(n,r))}if(N.isLogicalExpression(e)){let n=await je(e.left,t),r=await je(e.right,t);return co(Hp(n,r))}return N.isTSAsExpression(e)||N.isTSSatisfiesExpression(e)||N.isTSNonNullExpression(e)||N.isTypeCastExpression(e)||N.isParenthesizedExpression(e)?je(e.expression,t):null}async function WI(e,t){let n=e;for(;N.isMemberExpression(n)||N.isOptionalMemberExpression(n);)n=n.object;return N.isExpression(n)?je(n,t):null}async function rm(e,t){let n=Up(e,{file:t.file,imports:t.analysis.imports});if(n)return sm(n);if(Xp(e)){let f=e.arguments[0];if(f&&N.isExpression(f))return co(await je(f,t))}let r=await GI(e,t);if(r)return r;let o=Vp(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 QI(e,t);if(i)return i;let s=await qI(e,t);if(s)return s;let a=await eC(e,t);if(a)return a;let c=await tC(e,t);if(c)return c;let l=[];for(let f of e.arguments)if(N.isExpression(f)){let m=await je(f,t);m&&l.push(m)}let d=am(l);return d.length===1?co(d[0]):null}async function GI(e,t){let n=jt(e.callee);if(n!=="useQuery"&&n!=="useSuspenseQuery"&&n!=="useInfiniteQuery"&&n!=="useSWR")return null;if(n==="useSWR"){let i=ZI(e.arguments[0],t.file,"SWR key"),s=e.arguments[1];if(N.isIdentifier(s)){let a=await ao(s.name,t);if(a)return(await Bn(a.node,i?[i]:[],a.context)).returnSource??i}return i}let r=e.arguments[0];if(!N.isObjectExpression(r))return Hi(t.file,`${n} without static options`);let o=YI(r,"queryFn");if(!o)return Hi(t.file,`${n} without queryFn`);if(N.isIdentifier(o)){let i=await ao(o.name,t);return i?(await Bn(i.node,[],i.context)).returnSource:Hi(t.file,`${n} queryFn unresolved`)}return N.isArrowFunctionExpression(o)||N.isFunctionExpression(o)?(await Bn(o,[],t)).returnSource:N.isCallExpression(o)?rm(o,t):null}function YI(e,t){for(let n of e.properties){if(!N.isObjectProperty(n)||!N.isExpression(n.value))continue;if(im(n)===t)return n.value}return null}function ZI(e,t,n){return N.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 QI(e,t){if(!N.isMemberExpression(e.callee)||!N.isIdentifier(e.callee.property))return null;let n=e.callee.property.name;if(!["map","filter","slice","sort","toSorted"].includes(n))return null;let r=N.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(N.isIdentifier(o)){let i=await ao(o.name,t);if(!i)return Dn(r);let s=await Bn(i.node,[r],i.context);return{...Dn(r),...s.objectReturnMap??s.returnSource?.fieldMap?{fieldMap:s.objectReturnMap??s.returnSource.fieldMap}:{}}}if(N.isArrowFunctionExpression(o)||N.isFunctionExpression(o)){let i=await Bn(o,[r],t);return{...Dn(r),...i.objectReturnMap??i.returnSource?.fieldMap?{fieldMap:i.objectReturnMap??i.returnSource.fieldMap}:{}}}return Dn(r)}async function qI(e,t){return!N.isMemberExpression(e.callee)||!N.isIdentifier(e.callee.property,{name:"json"})||!N.isExpression(e.callee.object)?null:je(e.callee.object,t)}async function eC(e,t){return!N.isMemberExpression(e.callee)||!N.isIdentifier(e.callee.property,{name:"then"})||!N.isExpression(e.callee.object)?null:co(await je(e.callee.object,t))}async function tC(e,t){if(!N.isIdentifier(e.callee))return null;let n=await ao(e.callee.name,t);if(!n)return null;let r=[];for(let i of e.arguments){if(!N.isExpression(i)){r.push(Hi(t.file,`unsupported argument for ${e.callee.name}`));continue}let s=await je(i,t);r.push(s)}return(await Bn(n.node,r,n.context)).returnSource}async function ao(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 fm(r,t);if(!o)return null;let i=Zi(o,t,{importDepth:t.importDepth+1}),s=pm(r,o);return s?{node:s,context:i}:ao(r.importedName,i)}async function Bn(e,t,n){if(n.functionDepth>=n.options.maxFunctionDepth)return{returnSource:null};let r=Zi(n.analysis,n,{functionDepth:n.functionDepth+1});r.scopeVariables=n.analysis.functionVariables.get(e),e.params.forEach((c,l)=>{let d=t[l];d&&Tc(c,oC(d),r)});let o=nC(e),i=null,s,a=!1;for(let c of o){if(N.isObjectExpression(c)){s={...s??{},...await om(c,r)},i=i??Oc(s,n.file);continue}let l=await je(c,r);if(l){if(!i){i=l;continue}let d=_c(i,l);if(!d){a=!0,i=null;continue}i=d}}return{returnSource:a?null:i,...s?{objectReturnMap:s}:{}}}function Tc(e,t,n){if(N.isIdentifier(e)){n.paramSources.set(e.name,ze(t));return}if(N.isAssignmentPattern(e)){Tc(e.left,t,n);return}if(N.isObjectPattern(e))for(let r of e.properties){if(!N.isObjectProperty(r)||r.computed||!N.isIdentifier(r.key))continue;let o=lo(t,[{kind:"property",name:r.key.name}],!0),i=N.isAssignmentPattern(r.value)?r.value.left:r.value;Tc(i,o,n)}}function nC(e){if(N.isArrowFunctionExpression(e)&&N.isExpression(e.body))return[e.body];let t=[],n=e.body;if(!N.isBlockStatement(n))return t;let r=o=>{if(N.isFunction(o)&&o!==e)return;if(N.isReturnStatement(o)){o.argument&&N.isExpression(o.argument)&&t.push(o.argument);return}let i=N.VISITOR_KEYS[o.type];for(let s of i??[]){let a=o[s];if(Array.isArray(a))for(let c of a)N.isNode(c)&&r(c);else N.isNode(a)&&r(a)}};return r(n),t}async function om(e,t){let n={};for(let r of e.properties){if(!N.isObjectProperty(r))continue;let o=im(r);if(!o||!N.isExpression(r.value))continue;let i=await je(r.value,t);i&&(n[o]=i)}return n}function im(e){return N.isIdentifier(e.key)&&!e.computed?e.key.name:N.isStringLiteral(e.key)?e.key.value:null}function rC(e){let t=[],n=e;for(;N.isMemberExpression(n)||N.isOptionalMemberExpression(n);){let r=n.property;n.computed?N.isStringLiteral(r)?t.unshift({kind:"property",name:r.value}):N.isNumericLiteral(r)&&t.unshift({kind:"index",index:r.value}):N.isIdentifier(r)&&t.unshift({kind:"property",name:r.name}),n=n.object}return N.isIdentifier(n),t}function lo(e,t,n){if(t.length===0)return ze(e);let r=t[0];if(r?.kind==="property"&&e.fieldMap?.[r.name])return lo(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=so(o.valuePath,"data.items[]"),o.cmsFieldRoot=!1,o):i[0]==="fields"?(o.fieldPath=so(o.fieldPath,i.slice(1).join(".")),o.cmsFieldRoot=!0,o):o.cmsFieldRoot||n||o.fieldMap?(o.fieldPath=so(o.fieldPath,i.join(".")),o):(o.valuePath=so(o.valuePath,zp(t)),o)}return o.valuePath=so(o.valuePath,zp(t)),o}function zp(e){return e.map(t=>t.kind==="property"?t.name:`[${t.index}]`).join(".").replace(/\.\[/g,"[")}function so(e,t){return t?e?t.startsWith("[")?`${e}${t}`:`${e}.${t}`:t:e}function sm(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 oC(e){let t=ze(e);return t.valuePath=void 0,t.sourceType==="cms-field"&&(t.cmsFieldRoot=!1),t}function co(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 Hp(e,t){return e?t?_c(e,t):ze(e):t?ze(t):null}function _c(e,t){if(Wi(e)!==Wi(t))return null;let n=um(e.confidence,t.confidence)<=0?e.confidence:t.confidence;return{...e,confidence:n,evidence:[...e.evidence,...t.evidence]}}function am(e){let t=new Map;for(let n of e){let r=Wi(n),o=t.get(r);t.set(r,o?_c(o,n):ze(n))}return[...t.values()]}function Wi(e){let t=e.fieldMap?Object.fromEntries(Object.entries(e.fieldMap).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>[n,Wi(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 Oc(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 Hi(e,t){return{sourceKind:"unknown-api",sourceType:"api-field",confidence:"unknown",readonly:!0,evidence:[{file:e,reason:t}]}}function Gi(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 cm(e){let t=[...e].sort(lm),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 iC(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 lm(e,t){return Wp(e.targetKind)-Wp(t.targetKind)||um(e.confidence,t.confidence)||Gp(e.sourceKind)-Gp(t.sourceKind)||e.targetName.localeCompare(t.targetName)}function Wp(e){return{"repeat-region":0,"conditional-region":1,text:2,richtext:3,attribute:4,"component-prop":5}[e]}function Gp(e){return e.startsWith("vcp-cms-")?0:e==="site-api-route"?1:e==="external-api"?2:3}function um(e,t){let n={exact:0,"safe-derived":1,partial:2,unknown:3};return n[e]-n[t]}function Mc(e,t,n){let r=n.get(e);if(r?.source===t)return r;let o=MI(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 Fc(o,{ImportDeclaration(s){let a=s.node.source.value;for(let c of s.node.specifiers)N.isImportSpecifier(c)&&N.isIdentifier(c.local)?i.imports.set(c.local.name,{source:a,importedName:N.isIdentifier(c.imported)?c.imported.name:c.imported.value,localName:c.local.name,isDefault:!1}):N.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&&(N.isFunctionDeclaration(a.node)||N.isFunctionExpression(a.node)||N.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,N.isExpression(s.node.init)?s.node.init:null);if(N.isArrayPattern(s.node.id)&&N.isCallExpression(s.node.init)&&jt(s.node.init.callee)==="useState"){let[d,f]=s.node.id.elements;N.isIdentifier(d)&&N.isIdentifier(f)&&i.stateSetters.set(d.name,f.name)}N.isIdentifier(s.node.id)&&Yp(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(!N.isExportSpecifier(l))continue;let d=N.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(N.isFunctionDeclaration(a)&&a.id?.name&&i.functions.set(a.id.name,a),N.isVariableDeclaration(a))for(let l of a.declarations)N.isIdentifier(l.id)&&Yp(l.init)&&i.functions.set(l.id.name,l.init)},ExportDefaultDeclaration(s){let a=s.node.declaration;if((N.isFunctionDeclaration(a)||N.isFunctionExpression(a)||N.isArrowFunctionExpression(a))&&i.functions.set("default",a),N.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||N.isVoidPattern(e)?[]:N.isIdentifier(e)?[e.name]:N.isObjectPattern(e)?e.properties.flatMap(t=>N.isObjectProperty(t)?gr(t.value):gr(t.argument)):N.isArrayPattern(e)?e.elements.flatMap(t=>t?gr(N.isRestElement(t)?t.argument:t):[]):N.isAssignmentPattern(e)?gr(e.left):N.isRestElement(e)?gr(e.argument):[]}function Yp(e){return N.isFunctionExpression(e)||N.isArrowFunctionExpression(e)}function dm(e,t){let n=e.functions.get(t)??e.functions.get("default");return n?e.functionVariables.get(n):void 0}async function fm(e,t){let n=await mm(t.file,e.source,t.exists);if(!n)return null;let r=await t.readFile(n);return Mc(n,r,t.fileCache)}function pm(e,t){return e.isDefault?t.functions.get("default")??t.functions.get(e.localName)??null:t.functions.get(e.importedName)??null}async function mm(e,t,n){return Pt(t)?bn(e,t,n):null}function Zi(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 sC(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 Dc from"@babel/parser";import Lc from"@babel/traverse";import*as Y from"@babel/types";import{classifySiteEditPropertyName as aC}from"@vcp-dev/contracts";var Bc=typeof Lc=="function"?Lc:Lc.default;function jc(e){let t=aC(e.propertyName);if(t.owner!=="generic")return ct("invalid-property",t.diagnostic?.message??`Property '${e.propertyName}' is not a generic property`);let n=e.selectionRef;if(!n)return ct("missing-selection-ref","A repeat property target requires a complete selection reference");if(n.key!==e.element.identity.key)return ct("selection-mismatch","Selection reference does not identify the requested element");if(n.instanceIndex===void 0)return ct("missing-instance-index","A repeat property target requires an instance index");let r;try{r=Dc.parse(e.source,{sourceType:"module",plugins:["typescript","jsx"]})}catch(b){return ct("repeat-not-found",`Unable to parse repeat source: ${b instanceof Error?b.message:String(b)}`)}let o=cC(r,e.element.sourceRange);if(!o)return ct("repeat-not-found","The selected element is not inside a supported map repeat");if(!Y.isIdentifier(o.callback.params[0]))return ct("unsupported-callback","Repeat property materialization requires an identifier callback item");let i=lC(r,o.collection,e.file,e.sources);if(!i)return ct("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[b,E]of s.elements.entries()){if(!E||!Y.isObjectExpression(E)||!Sm(E))return ct("unsafe-collection","Repeat materialization requires an array of local static objects without spreads");let v=[{kind:"index",index:b}];l.push(v),d.push({kind:"value",root:a.root,path:v})}let f=d.length;if(n.instanceCount!==void 0&&n.instanceCount!==f)return ct("count-mismatch",`Selection reports ${n.instanceCount} instances but the source collection has ${f}`);let m=n.instanceIndex;if(m>=f)return ct("index-out-of-range",`Selected repeat instance ${m} is outside the source collection`);let u=s.elements[m];if(!u||!Y.isObjectExpression(u))return ct("unsafe-collection","Selected repeat item is not an object");let g=gC(e.element,e.propertyName),h=pC(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},(b,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:mC(u,e.propertyName),...g?{property:g}:{},selectionRef:n}:ct("unsafe-property-source",`Property '${e.propertyName}' has a dynamic or unsupported source in the repeat item`)}function cC(e,t){let n=[];return Bc(e,{CallExpression(r){let o=gm(r.node);o&&ym(o.callback,t)&&n.push({...o,span:hm(r.node)})},OptionalCallExpression(r){let o=gm(r.node);o&&ym(o.callback,t)&&n.push({...o,span:hm(r.node)})}}),n.sort((r,o)=>r.span-o.span),n[0]??null}function gm(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 lC(e,t,n,r){let o=uo(t);if(o&&Y.isArrayExpression(o))return{array:o,locator:{kind:"value",root:{kind:"expression",sourceRange:vm(o)}},sourceFile:n};if(!Y.isIdentifier(t))return null;let i=[];if(Bc(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=uo(i[0].init);return!s||!Y.isArrayExpression(s)?null:{array:s,locator:{kind:"value",root:{kind:"binding",name:t.name}},sourceFile:n}}return uC(e,t.name,n,r)}function uC(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=fC(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=Dc.parse(c,{sourceType:"module",plugins:["typescript","jsx"]})}catch{return null}let d=dC(l,a),f=d?uo(d):null;return!f||!Y.isArrayExpression(f)?null:{array:f,locator:{kind:"value",root:{kind:"binding",name:a}},sourceFile:s}}return null}function dC(e,t){let n=null;return Bc(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 fC(e,t,n){let r=xn(e,t);return[r,r+".tsx",r+".ts",r+".jsx",r+".js",r+"/index.tsx",r+"/index.ts",r+"/index.jsx",r+"/index.js"].find(i=>n.has(i))??null}function uo(e){return Y.isParenthesizedExpression(e)?uo(e.expression):Y.isTSAsExpression(e)?bm(e.typeAnnotation)?uo(e.expression):null:Y.isTSSatisfiesExpression(e)?null:e}function bm(e){return Y.isTSTypeReference(e)&&Y.isIdentifier(e.typeName)&&e.typeName.name==="const"}function Sm(e){return e.properties.every(t=>!Y.isObjectProperty(t)||t.computed||!Y.isExpression(t.value)?!1:Qi(t.value))}function Qi(e){if(Y.isTSAsExpression(e)&&bm(e.typeAnnotation))return Qi(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:Qi(n));if(Y.isObjectExpression(e))return Sm(e);let t=Ot(e);return t.status==="resolved"||t.status==="undefined"}function pC(e,t){let n=e.properties.filter(o=>Y.isObjectProperty(o)&&Em(o.key)===t);if(n.length>1)return null;let r=n[0];return r?Y.isExpression(r.value)?Qi(r.value)?"static":Y.isIdentifier(r.value)||Y.isMemberExpression(r.value)?"binding":null:null:"missing"}function mC(e,t){let n=e.properties.filter(o=>Y.isObjectProperty(o)&&Em(o.key)===t);if(n.length>1)return{status:"unresolved"};let r=n[0];return!r||!Y.isExpression(r.value)?{status:"undefined"}:Ot(r.value)}function gC(e,t){let n=e.attributes?.filter(r=>r.name===t)??[];return n.length===1?n[0]:void 0}function Em(e){return Y.isIdentifier(e)?e.name:Y.isStringLiteral(e)?e.value:Y.isNumericLiteral(e)?String(e.value):null}function vm(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 hm(e){return e.start==null||e.end==null?Number.MAX_SAFE_INTEGER:e.end-e.start}function ym(e,t){let n=vm(e);return xm(n.startLine,n.startColumn,t.startLine,t.startColumn)<=0&&xm(n.endLine,n.endColumn,t.endLine,t.endColumn)>=0}function xm(e,t,n,r){return e===n?t-r:e-n}function ct(e,t){return{ok:!1,errorCode:e,reason:t}}import{classifySiteEditPropertyName as nR}from"@vcp-dev/contracts";import*as Z from"@babel/types";import go from"node:path";import*as j from"@babel/types";import*as Nm from"@babel/parser";import $c from"@babel/traverse";import*as re from"@babel/types";function qi(e,t){let n=[],r=e;for(;re.isMemberExpression(r);){if(r.computed)if(re.isNumericLiteral(r.property))n.unshift({kind:"index",index:r.property.value});else if(re.isStringLiteral(r.property))n.unshift({kind:"property",name:r.property.value});else return null;else{if(!re.isIdentifier(r.property))return null;n.unshift({kind:"property",name:r.property.name})}r=r.object}return!re.isIdentifier(r)||r.name!==t?null:n}function km(e){if(re.isIdentifier(e))return{base:e.name,path:[]};if(!re.isMemberExpression(e))return null;let t=[],n=e;for(;re.isMemberExpression(n);){if(n.computed)if(re.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(re.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else{if(!re.isIdentifier(n.property))return null;t.unshift({kind:"property",name:n.property.name})}n=n.object}return re.isIdentifier(n)?{base:n.name,path:t}:null}function tt(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 Im(e){let{resolveBindingTarget:t}=e;async function n(i,s,a,c,l,d,f){if(re.isStringLiteral(i)||re.isNumericLiteral(i)||re.isBooleanLiteral(i))return i.value;if(re.isNullLiteral(i))return null;if(re.isTemplateLiteral(i))return i.expressions.length===0&&i.quasis.length===1?i.quasis[0].value.cooked??i.quasis[0].value.raw:void 0;if(re.isTSAsExpression(i)||re.isTSSatisfiesExpression(i)||re.isTSNonNullExpression(i))return await n(i.expression,s,a,c,l,d,f);if(re.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(re.isArrayExpression(i)){let m=[];for(let u of i.elements){if(!u||re.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(re.isObjectExpression(i)){let m={};for(let u of i.properties){if(!re.isObjectProperty(u)||u.computed)return;let g=null;if(re.isIdentifier(u.key)?g=u.key.name:re.isStringLiteral(u.key)&&(g=u.key.value),!g)return;if(u.shorthand){if(!re.isIdentifier(u.value))return;let b=await r(u.value,s,a,c,l,d,f);if(b===void 0)return;m[g]=b;continue}if(!re.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(re.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:tt(g.value,m.path)}}async function r(i,s,a,c,l,d,f){if(!re.isSpreadElement(i))return await n(i,s,a,c,l,d,f)}async function o(i,s,a,c,l,d,f){if(re.isIdentifier(i))return{base:i.name,path:[]};if(!re.isMemberExpression(i))return null;let m=[],u=i;for(;re.isMemberExpression(u);){if(u.computed){let g=u.property;if(re.isNumericLiteral(g))m.unshift({kind:"index",index:g.value});else if(re.isStringLiteral(g))m.unshift({kind:"property",name:g.value});else{let h=re.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(!re.isIdentifier(u.property))return null;m.unshift({kind:"property",name:u.property.name})}u=u.object}return re.isIdentifier(u)?{base:u.name,path:m}:null}return{normalizeExpressionWithScope:o,evaluateStaticExpression:n}}var wm=typeof $c=="function"?$c:$c.default,Cm=new WeakMap;function Pm(e){try{return Nm.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function es(e,t,n){let r=e.get(t);if(r?.source===n)return r.ast;let o=Pm(n);return e.set(t,{source:n,ast:o}),o}function ts(e,t){let n=null,r=-1;for(let o of fo(e).expressions){let i=o.node.loc;if(!i||!Kc(i,t))continue;let s=(o.node.end??0)-(o.node.start??0);s>=r&&(n=o,r=s)}return n}function Am(e,t){let n=null,r=Number.POSITIVE_INFINITY;for(let o of fo(e).expressions){if(!hC(o.node.loc,t))continue;let i=(o.node.end??0)-(o.node.start??0);i<=r&&(n=o,r=i)}return n}function Vc(e,t){let n=null,r=Number.POSITIVE_INFINITY;for(let o of fo(e).jsxElements){let i=o.node.loc;if(!i||!Kc(i,t))continue;let s=(o.node.end??0)-(o.node.start??0);s<=r&&(n=o,r=s)}return n}function fo(e){let t=Cm.get(e);if(t)return t;let n={expressions:[],jsxElements:[]};return wm(e,{Expression(r){n.expressions.push(r)},JSXElement(r){n.jsxElements.push(r)}}),Cm.set(e,n),n}function hC(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 Kc(e,t){let n=Rm({line:e.start.line,column:e.start.column},{line:t.startLine,column:t.startColumn}),r=Rm({line:e.end.line,column:e.end.column},{line:t.endLine,column:t.endColumn});return n>=0&&r<=0}function ns(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 Rm(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 Uc(e,t);let n=km(e);return n?n.path.reduce((r,o)=>o.kind==="property"?`${r}.${o.name}`:`${r}[${o.index}]`,n.base):""}function Uc(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function po(e,t,n){let r=null,o=Number.POSITIVE_INFINITY;for(let i of fo(e).expressions){if(Uc(i.node,t)!==n)continue;let s=(i.node.end??0)-(i.node.start??0);s<=o&&(r=i,o=s)}return r}function Tm(e,t,n,r){let o=null,i=Number.POSITIVE_INFINITY;for(let s of fo(e).expressions){if(Uc(s.node,t)!==n)continue;let a=s.node.loc;if(!a||!Kc(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 mo(e){let t=null;if(wm(e,{Program(n){t=n.scope,n.stop()}}),!t)throw new Error("Unable to determine program scope");return t}async function Vt(e,t,n){let r=n.get(e);if(r)return r;let o=await t(e),i=Pm(o),s={source:o,ast:i};return n.set(e,s),s}function yC(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 xC(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 bC(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 SC(e,t){let n=bC(e.path);if(!n)return null;let r=sr(e,t);return r?{...n,...r}:null}function EC(e,t,n,r){return e.importedFrom===t?r?e.exportName===r:!0:e.sourceFile===t&&e.tag===n}function Jc(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 Xc(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 Fm(e){let{resolveExternalExpression:t,resolveCollectionCallTarget:n,evaluateStaticExpression:r,resolveSourceInfoProvenance:o,buildExpressionSourceInfo:i}=e;async function s(u){let{currentFile:g,binding:h,readFile:b,exists:E,fileCache:v,visited:I}=u,R=`${g}::${h.kind}::${h.identifier.name}`;if(I.has(R))return null;I.add(R);try{let A=await a({currentFile:g,binding:h,readFile:b,exists:E,fileCache:v,visited:I});if(A)return A;if(h.path.isImportSpecifier()||h.path.isImportDefaultSpecifier())return await f({currentFile:g,binding:h,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,fileCache:v,visited:I});if(h.kind==="param")return null;if(h.path.isVariableDeclarator()){let T=h.path.node.init;if(!T||!j.isExpression(T))return null;let C=xC(T);if(C&&!h.path.scope.getBinding("Proxy")&&!h.path.scope.getBinding("Reflect")){let L=h.path.scope.getBinding(C),U=L?await s({...u,binding:L}):null;if(U?.kind==="static"&&U.value!==null&&!Array.isArray(U.value)&&typeof U.value=="object")return U}let P=h.path.get("init");if(P&&!Array.isArray(P)&&P.isExpression()){let L=await t({currentFile:g,expressionPath:P,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:v,visited:I});if(L)return L;if(P.isCallExpression()){let U=await n({currentFile:g,callPath:P,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:v,visited:I});if(U)return U}}let O=await r(T,h.path.scope,g,b,E,v,I);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 T=h.path.parentPath.node.declaration;if(!j.isExpression(T))return null;let C=await r(T,h.path.scope,g,b,E,v,I);return C===void 0?null:{kind:"static",file:g,root:{kind:"binding",name:h.identifier.name},value:C,sourceKind:"binding"}}return null}finally{I.delete(R)}}async function a(u){let{currentFile:g,binding:h,readFile:b,exists:E,fileCache:v,visited:I}=u;if(!h.path.isVariableDeclarator()||!h.path.get("id").isArrayPattern())return null;let R=h.path,A=R.node.init;if(!A||!j.isCallExpression(A))return null;let T=yC(A);if(!T||!j.isArrayPattern(R.node.id)||R.node.id.elements.findIndex(U=>j.isIdentifier(U)&&U.name===h.identifier.name)!==0)return null;let P=T==="useReducer"?1:0,O=A.arguments[P];if(!O||!j.isExpression(O))return null;let L=await r(O,R.scope,g,b,E,v,I);return L===void 0?null:{kind:"static",file:g,root:{kind:"hook-state",name:h.identifier.name,hook:T},value:L,sourceKind:"binding"}}async function c(u){let g=SC(u.binding,u.sourceInfo);if(!g||!u.graph)return null;let h=[...u.graph.elements.values()].filter(T=>EC(T,u.currentFile,g.componentName,g.exportName));if(h.length!==1)return null;let b=h[0],E=b.attributes?.find(T=>T.name===g.propName);if(E&&!E.source){let T=await l({caller:b,propName:g.propName,remainingPath:g.remainingPath,readFile:u.readFile,fileCache:u.fileCache});if(T)return Jc(T,{componentName:g.componentName,propName:g.propName,file:b.sourceFile})}if(!E?.source){let T=await d({caller:b,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(T)return Jc(T,{componentName:g.componentName,propName:g.propName,file:b.sourceFile});let C=$f(u.binding,g.componentName,g.propName);if(!C||C.propName!==g.propName)return null;let P=await r(C.expressionPath.node,C.expressionPath.scope,u.currentFile,u.readFile,u.exists,u.fileCache,u.visited);if(P===void 0)return null;let O=g.remainingPath;return O.length>0&&tt(P,O)===void 0?null:{kind:"value",file:u.currentFile,root:{kind:"binding",name:g.propName},path:O,sourceKind:"binding",semanticKind:"component-prop",displayExpression:C.displayPath,chainPrefix:[{kind:"component-prop",file:u.currentFile,displayName:C.displayPath,canEditHere:!0}],editMode:"upstream",diagnostics:[]}}let v=await Vt(b.sourceFile,u.readFile,u.fileCache);if(!v.ast)return null;let I=Tm(v.ast,v.source,E.source.expression,E.sourceRange)??po(v.ast,v.source,E.source.expression);if(!I)return null;let R={...E.source,expression:yr(E.source.expression,g.remainingPath),path:[...E.source.path,...g.remainingPath]},A=await o({currentFile:b.sourceFile,expressionPath:I,sourceInfo:R,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 A?Jc(A.kind==="external"?A:{...A,displayExpression:R.expression},{componentName:g.componentName,propName:g.propName,file:b.sourceFile}):null}async function l(u){let g=await Vt(u.caller.sourceFile,u.readFile,u.fileCache);if(!g.ast)return null;let h=Vc(g.ast,u.caller.sourceRange);if(!h)return null;let b=h.get("openingElement").get("attributes").find(R=>R.isJSXAttribute()&&R.node.name.type==="JSXIdentifier"&&R.node.name.name===u.propName);if(!b?.isJSXAttribute())return null;let E=b.get("value"),v=E.isStringLiteral()?E:E.isJSXExpressionContainer()?E.get("expression"):null;if(!v?.isExpression())return null;let I=ns(v.node);return I?{kind:"value",file:u.caller.sourceFile,root:{kind:"expression",sourceRange:I},path:u.remainingPath,sourceKind:"binding",semanticKind:"component-prop",displayExpression:u.propName,editMode:"upstream",diagnostics:[]}:null}async function d(u){let g=await Vt(u.caller.sourceFile,u.readFile,u.fileCache);if(!g.ast)return null;let h=Vc(g.ast,u.caller.sourceRange);if(!h)return null;let b=h.get("openingElement");for(let E of b.get("attributes")){if(!E.isJSXSpreadAttribute())continue;let v=E.get("argument");if(!v.isExpression())continue;let I=await i({expression:v.node,scope:v.scope,source:g.source,currentFile:u.caller.sourceFile,readFile:u.readFile,exists:u.exists,fileCache:u.fileCache,visited:u.visited});if(!I)continue;let R=[{kind:"property",name:u.propName},...u.remainingPath],A={...I,expression:yr(I.expression,R),path:[...I.path,...R]},T=await o({currentFile:u.caller.sourceFile,expressionPath:v,sourceInfo:A,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(T)return T.kind==="external"?T:{...T,displayExpression:A.expression}}return null}async function f(u){let{currentFile:g,binding:h,readFile:b,exists:E,fileCache:v,visited:I}=u,R=h.path.parentPath;if(!R||!R.isImportDeclaration())return null;let A=R.node.source.value;if(typeof A!="string")return null;let T=await bn(g,A,E);if(!T)return null;if(h.path.isImportDefaultSpecifier()){let ee=await Vt(T,b,v),Ne=ee.ast?Xc(ee.ast,"default"):null,Q=await m({file:T,exportName:"default",readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:v,visited:I});return!Q||Q.kind!=="static"?null:{kind:"static",file:Ne?.kind==="default-expression"?Q.file:T,root:Ne?.kind==="default-expression"?Q.root:{kind:"default-export"},value:Q.value,sourceKind:"imported-binding"}}if(!h.path.isImportSpecifier())return null;let C=h.path.node.imported,P=j.isIdentifier(C)?C.name:C.value,O=await Vt(T,b,v),L=O.ast?Xc(O.ast,P):null,U=await m({file:T,exportName:P,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:v,visited:I});return U?U.kind==="external"?U:{kind:"static",file:L?.kind==="re-export"?U.file:T,root:L?.kind==="re-export"||U.root.kind==="binding"&&U.root.name!==L?.name?U.root:{kind:"named-export",name:P},value:U.value,sourceKind:"imported-binding"}:null}async function m(u){let{file:g,exportName:h,readFile:b,exists:E,fileCache:v,visited:I}=u,R=`export::${g}::${h}`;if(!I.has(R)){I.add(R);try{let A=await Vt(g,b,v);if(!A.ast)return;let T=Xc(A.ast,h);if(!T)return;if(T.kind==="default-expression"){let L=T.expression;if(!L||!j.isIdentifier(L))return;let U=mo(A.ast).getBinding(L.name);return U?await s({currentFile:g,binding:U,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:v,visited:I})??void 0:void 0}if(T.kind==="re-export"){if(!T.source||!T.name)return;let L=await bn(g,T.source,E);return L?m({...u,file:L,exportName:T.name}):void 0}let C=T.name;if(!C)return;let P=mo(A.ast).getBinding(C);return P?await s({currentFile:g,binding:P,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:v,visited:I})??void 0:void 0}finally{I.delete(R)}}}return{resolveExportValue:m,resolveComponentPropBinding:c,resolveBindingTarget:s}}import*as W from"@babel/types";function Hc(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()||!vC(s,r)?null:{callPath:s,basePath:i}}function vC(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 Mm(e,t){let n=e.get("callee");if(!n.isMemberExpression())return null;let r=n.get("object");return Array.isArray(r)||!r.isExpression()?null:Fi(r,t)}function _m(e,t){return e?W.isNumericLiteral(e)&&Number.isInteger(e.value)?e.value:null:t}function Om(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=zc(i,t,n,r,o);return typeof s=="number"?s:void 0}function zc(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=qi(e,t);if(i)return tt(r,i);let s=qi(e,n);return s?tt(o,s):void 0}if(W.isBinaryExpression(e)&&e.operator==="-"){let i=W.isExpression(e.left)?zc(e.left,t,n,r,o):void 0,s=W.isExpression(e.right)?zc(e.right,t,n,r,o):void 0;return typeof i=="number"&&typeof s=="number"?i-s:void 0}}function kC(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 IC(e,t,n){let r=jn(e,t,n);return typeof r=="boolean"?r:void 0}function jn(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=qi(e,t);return r?tt(n,r):void 0}if(W.isUnaryExpression(e)&&e.operator==="!"){let r=jn(e.argument,t,n);return r===void 0?void 0:!r}if(W.isLogicalExpression(e)){let r=jn(e.left,t,n);if(r===void 0)return;if(e.operator==="&&")return r&&jn(e.right,t,n);if(e.operator==="||")return r||jn(e.right,t,n)}if(W.isBinaryExpression(e)){let r=W.isExpression(e.left)?jn(e.left,t,n):void 0,o=W.isExpression(e.right)?jn(e.right,t,n):void 0;if(r===void 0||o===void 0)return;switch(e.operator){case"===":return r===o;case"!==":return r!==o;case"==":return r==o;case"!=":return r!=o;default:return}}}function Lm(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 Dm(e){return e.some(t=>t.kind==="dynamic")}function CC(e){return typeof e=="string"?{kind:"property",name:e}:Number.isInteger(e)?{kind:"index",index:e}:null}function Bm(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 RC(e,t){let n=[],r=[];for(let o of t){let i=tt(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 jm(e){let{resolveBindingTarget:t,evaluateStaticExpression:n,buildExpressionSourceInfo:r,resolveSourceInfoProvenance:o}=e;async function i(u){let{currentFile:g,callPath:h,readFile:b,exists:E,fileCache:v,visited:I}=u,R=h.node.callee;if(!W.isMemberExpression(R)||!W.isIdentifier(R.property)||R.property.name!=="map")return null;let A=h.get("callee");if(!A.isMemberExpression())return null;let T=A.get("object");if(Array.isArray(T)||!T.isExpression())return null;let C=await s({currentFile:g,expressionPath:T,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:v,visited:I});return!C||!Array.isArray(C.value)||C.value.length===0?null:C}async function s(u){let{currentFile:g,expressionPath:h,readFile:b,exists:E,fileCache:v,visited:I}=u;if(h.isIdentifier()){let R=h.scope.getBinding(h.node.name);if(!R)return null;let A=await t({currentFile:g,binding:R,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:v,visited:I});return A?.kind==="static"?A:null}if(h.isCallExpression())return c({currentFile:g,callPath:h,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:v,visited:I});if(h.isTSAsExpression()||h.isTSSatisfiesExpression()||h.isTSNonNullExpression()){let R=h.get("expression");if(!Array.isArray(R)&&R.isExpression())return s({...u,expressionPath:R})}if(h.isArrayExpression()){let R=ns(h.node);if(!R)return null;let A=await n(h.node,h.scope,g,b,E,v,I);return Array.isArray(A)?{kind:"static",file:g,root:{kind:"expression",sourceRange:R},value:A,sourceKind:"binding"}:null}if(h.isMemberExpression()){let R=await r({expression:h.node,scope:h.scope,currentFile:g,readFile:b,exists:E,fileCache:v,visited:I});if(!R)return null;let A=await o({currentFile:g,expressionPath:h,sourceInfo:R,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:v,visited:I});if(!A||A.kind==="external")return null;let T=await a({currentFile:g,expressionPath:h,provenance:A,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:v,visited:I});if(!T||T.kind!=="static")return null;if(A.collectionPathMap?.length){let P=RC(T.value,A.collectionPathMap);if(P)return{kind:"static",file:A.file,root:A.root,value:P.value,sourceKind:A.sourceKind,collectionPathMap:P.collectionPathMap}}let C=tt(T.value,A.path);return Array.isArray(C)?{kind:"static",file:A.file,root:A.root,value:C,sourceKind:A.sourceKind,pathPrefix:A.path,collectionIndexMap:A.collectionIndexMap,collectionPathMap:A.collectionPathMap}:null}return null}async function a(u){let{provenance:g}=u;if(g.root.kind==="binding"){let v=u.expressionPath.scope.getBinding(g.root.name);if(!v&&g.file!==u.currentFile){let I=await Vt(g.file,u.readFile,u.fileCache);v=I.ast?mo(I.ast).getBinding(g.root.name):void 0}return v?await t({currentFile:g.file,binding:v,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 Vt(g.file,u.readFile,u.fileCache);if(!h.ast)return null;let b=Am(h.ast,g.root.sourceRange);if(!b)return null;let E=await n(b.node,b.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 b=g.get("callee");if(!b.isMemberExpression())return null;let E=b.get("object");if(Array.isArray(E)||!E.isExpression())return null;let v=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(!v||!Array.isArray(v.value))return null;let[I]=g.node.arguments;if(!W.isArrowFunctionExpression(I)&&!W.isFunctionExpression(I))return null;let R=I.params[0];if(!W.isIdentifier(R))return null;let A=kC(I);if(!A)return null;let T=[],C=[],P=[];for(let[O,L]of v.value.entries()){let U=IC(A,R.name,L);if(typeof U!="boolean")return null;if(U){T.push(L),C.push(v.collectionIndexMap?.[O]??O);let ee=v.collectionPathMap?.[O];ee&&P.push(ee)}}return{...v,value:T,pathPrefix:v.pathPrefix,collectionIndexMap:C,...P.length>0?{collectionPathMap:P}:{}}}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 b=g.get("callee");if(!b.isMemberExpression())return null;let E=b.get("object");if(Array.isArray(E)||!E.isExpression())return null;let v=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(!v||!Array.isArray(v.value))return null;let[I,R]=g.node.arguments,A=_m(I,0),T=_m(R,v.value.length);if(A===null||T===null)return null;let C=Math.max(0,A<0?v.value.length+A:A),P=Math.max(0,T<0?v.value.length+T:T),O=v.value.map((U,ee)=>v.collectionIndexMap?.[ee]??ee).slice(C,P),L=v.collectionPathMap?.slice(C,P);return{...v,value:v.value.slice(C,P),pathPrefix:v.pathPrefix,collectionIndexMap:O,...L?{collectionPathMap:L}:{}}}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 b=g.get("callee");if(!b.isMemberExpression())return null;let E=b.get("object");if(Array.isArray(E)||!E.isExpression())return null;let v=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(!v||!Array.isArray(v.value))return null;let[I]=g.node.arguments;if(!W.isArrowFunctionExpression(I)&&!W.isFunctionExpression(I))return null;let[R,A]=I.params;if(!W.isIdentifier(R)||!W.isIdentifier(A))return null;let T=v.value.map((P,O)=>({value:P,sourceIndex:v.collectionIndexMap?.[O]??O,originalIndex:O})),C=[...T];for(let P of T)for(let O of T)if(Om(I,R.name,A.name,P.value,O.value)===void 0)return null;return C.sort((P,O)=>{let L=Om(I,R.name,A.name,P.value,O.value)??0;return L===0?P.originalIndex-O.originalIndex:L}),{...v,value:C.map(P=>P.value),pathPrefix:v.pathPrefix,collectionIndexMap:C.map(P=>P.sourceIndex),...v.collectionPathMap?{collectionPathMap:C.map(P=>v.collectionPathMap?.[P.originalIndex]).filter(P=>!!P)}:{}}}async function m(u){let g=null,h,b=[];for(let v of u.segments){if(v.kind!=="dynamic")continue;let I=await r({expression:v.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(!I)return null;let R=Hc(u.expressionPath,I.base);if(!R)return null;let A=await i({currentFile:u.currentFile,callPath:R.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(!A||!Array.isArray(A.value))return null;let T=A.value.map((C,P)=>{let O=tt(A.value,[{kind:"index",index:P},...R.basePath,...I.path]);return CC(O)});if(T.some(C=>C===null)||g!==null&&g!==T.length)return null;g=T.length,h??=A.collectionIndexMap,b.push(T)}if(g===null||g===0)return null;let E=[];for(let v=0;v<g;v+=1){let I=[...u.rootPath],R=0;for(let A of u.segments){if(A.kind==="dynamic"){let T=b[R]?.[v];if(!T)return null;I.push(T),R+=1;continue}I.push({...A})}E.push(I)}return{...h?{collectionIndexMap:h}:{},collectionPathMap:E}}return{resolveRepeatCollectionTarget:i,resolveCollectionCallTarget:c,resolveDynamicMemberPathMap:m}}var{normalizeExpressionWithScope:NC,evaluateStaticExpression:rs}=Im({resolveBindingTarget:e=>qc(e)}),{resolveRepeatCollectionTarget:wC,resolveCollectionCallTarget:PC,resolveDynamicMemberPathMap:AC}=jm({resolveBindingTarget:e=>qc(e),evaluateStaticExpression:rs,buildExpressionSourceInfo:Kt,resolveSourceInfoProvenance:St}),{resolveExportValue:TC,resolveComponentPropBinding:FC,resolveBindingTarget:qc}=Fm({resolveExternalExpression:tl,resolveCollectionCallTarget:PC,evaluateStaticExpression:rs,resolveSourceInfoProvenance:St,buildExpressionSourceInfo:Kt});function Hm(e){return new Map([...e].map(t=>[t.file,{source:t.source,ast:t.ast}]))}function $m(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 Wm(e){let{file:t,source:n,segment:r,readFile:o,exists:i}=e,s=e.fileCache??new Map,a=es(s,t,n);if(!a)return null;let c=ts(a,r.sourceRange);if(!c)return null;let l=await Kt({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:o,exists:i,fileCache:s,visited:new Set});if(!l){let m=await il({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?Yc(m,hr(c.node,n)):null}let d=new Set,f=await eR({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?Yc(f,l.expression):null}async function xr(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=es(i,t,n);if(!s)return null;let a=e.sourceRange?ts(s,e.sourceRange):e.expression!==void 0?po(s,n,e.expression):null;if(!a)return null;let c=sl(a);if(!c.isIdentifier()&&!c.isMemberExpression())return null;let l=new Set,d=await Kt({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 tR({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 Yc(f,e.expression??hr(c.node,n))}async function el(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=es(i,t,n);if(!s)return lt("unsupported-expression","Unable to parse source for provenance resolution");let a=new Set;return e.target.kind==="text-segment"?_C({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}):OC({file:t,source:n,ast:s,candidate:e.target.candidate,readFile:r,exists:o,graph:e.graph,fileCache:i,visited:a})}async function Kt(e){if(Z.isIdentifier(e.expression))return{kind:"identifier",expression:e.expression.name,base:e.expression.name,path:[]};if(!Z.isMemberExpression(e.expression))return null;let t=await NC(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 Yc(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 _C(e){let{file:t,source:n,ast:r,segment:o,readFile:i,exists:s,fileCache:a,visited:c}=e,l=ts(r,o.sourceRange),d=l?await Kt({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 Vm(t,o.value);let m=await il({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"?zm(t,m):Qc(t,hr(l.node,n),m):MC({expression:l.node,scope:l.scope,currentFile:t,source:n,readFile:i,exists:s,fileCache:a,visited:c,functionCallContracts:e.functionCallContracts})}if(!l)return lt("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=Zc(l.node);if(m)return lt(m.code,m.message);let u=l.scope.getBinding(d.base);if(u?.path.isVariableDeclarator()){let g=Zc(u.path.node.init);if(g)return lt(g.code,g.message)}return u?.path.isVariableDeclarator()&&Z.isCallExpression(u.path.node.init)?LC("unsupported-expression",qm(u.path.node.init,e.functionCallContracts)):lt("unsupported-expression",`Unable to resolve provenance for expression "${d.expression}"`)}return f.kind==="external"?zm(t,f):Qc(t,d.expression,f)}async function OC(e){let{file:t,source:n,ast:r,candidate:o,readFile:i,exists:s,fileCache:a,visited:c}=e;if(!o.conditionSource)return lt("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let l=po(r,n,o.conditionExpression);if(!l)return lt("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 lt("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);if(d.kind==="external")return lt("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let f=Qc(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 Vm(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 MC(e){let t=await Ym(e);if(t.length===0)return lt("unsupported-expression",`Unsupported expression type: ${e.expression.type}`);if(DC(e.expression))return Gm(t);if(Qm(e.expression))return lt("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 lt("dynamic-key","Computed member expressions are not supported for provenance resolution");let[n]=t;return lt(n.code,n.message)}function lt(e,t){return{finalSource:null,chain:[],confidence:"unknown",editMode:"unsupported",diagnostics:[{code:e,message:t}]}}function LC(e,t){return Gm([{code:e,message:t}])}function Gm(e){return{finalSource:null,chain:[],confidence:"partial",editMode:"readonly",diagnostics:e}}function DC(e){return Z.isCallExpression(e)||Z.isConditionalExpression(e)||Z.isLogicalExpression(e)||Z.isBinaryExpression(e)}function ho(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 Ym(e){let{expression:t,scope:n,currentFile:r,readFile:o,exists:i,fileCache:s,visited:a,functionCallContracts:c}=e,l=Zc(t);if(l)return[l];if(Z.isCallExpression(t))return[{code:"unsupported-expression",message:qm(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 rs(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)?ho([...await Wc(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)?ho([...await Wc(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)?ho([...await Wc(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 Zc(e){return Qm(e)?Km("i18n helpers require a static message id string"):KC(e)?Km("CMS helpers require static entry id and field path string arguments"):null}async function Wc(...e){let t=e[e.length-1],n=e.slice(0,-1),r=[];for(let o of n)r.push(...await Ym({...t,expression:o}));return r}function BC(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:[jC(e.sourceType)]}}async function tl(e){for(let n of zC){if(!Um(e.expressionPath,n.helperNames))continue;let r=await n.resolve(e);if(r)return Xm(Jm(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(!Um(e.expressionPath,n.helperNames))continue;let r=await n.resolve(t);if(r)return Xm(Jm(r),e.externalAdapters)}return null}function jC(e){return{code:"missing-adapter",message:`No external adapter is registered for ${e}`}}function $C(e){return{code:"external-source-readonly",message:e}}function Km(e){return{code:"unsupported-expression",message:e}}function nl(e){return!e||!Z.isCallExpression(e)?null:Z.isIdentifier(e.callee)?e.callee.name:Z.isMemberExpression(e.callee)&&!e.callee.computed&&Z.isIdentifier(e.callee.object)&&Z.isIdentifier(e.callee.property)?`${e.callee.object.name}.${e.callee.property.name}`:null}function Um(e,t){if(!t||t.length===0)return!0;let n=nl(e.node);return n?t.includes(n):!1}function Jm(e){return"match"in e?{match:e.match,editMode:e.editMode,diagnostics:ho(e.diagnostics??[])}:{match:e,diagnostics:[]}}function Xm(e,t){let n=BC(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:ho([...e.diagnostics,...e.editMode==="readonly"||n.editMode==="readonly"?n.diagnostics:[]])}}function VC(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 KC(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 Zm(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 Qm(e){return Zm(e)===null}async function UC(e,t,n){let r=new Set,o=go.posix.dirname(e);for(;r.add(o),!(o==="."||o==="/");){let i=go.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"]:[go.posix.join(i,"locales"),go.posix.join(i,"messages")];for(let a of s){let c=go.posix.join(a,`${t}.json`);if(await n(c))return c}}return null}async function JC(e){let t=Zm(e.expressionPath.node);if(typeof t!="string"||t.length===0)return null;let n="en",r=await UC(e.currentFile,n,e.exists);return r?{sourceType:"i18n-message",sourceId:`${n}:${t}`,file:r,displayPath:t}:null}async function XC(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 rs(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:[$C("API mapping transforms must stay readonly until a reversible mapping strategy is registered")]}:i}var zC=[{helperNames:["getCmsField"],resolve:({expressionPath:e})=>VC(e)},{helperNames:["apiField"],resolve:e=>XC(e)},{helperNames:["t","intl.formatMessage"],resolve:({currentFile:e,expressionPath:t,exists:n})=>JC({currentFile:e,expressionPath:t,exists:n})}];function rl(e){return{...e,editMode:"readonly",diagnostics:[{code:"unsupported-expression",message:"Derived display values are readonly because no identity-preserving write target exists"}]}}function zm(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 Qc(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=qC(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 HC=[{helperName:"formatPrice",purity:"pure",sourceArgIndex:0},{helperName:"formatDate",purity:"pure",sourceArgIndex:0},{helperName:"pickLabel",purity:"pure",sourceArgIndex:0}];function ol(e,t){let n=[...HC,...t??[]];for(let r=n.length-1;r>=0;r-=1){let o=n[r];if(o?.helperName===e)return o}return null}function qm(e,t){let n=e.callee;return Z.isIdentifier(n)&&ol(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 il(e){let t=await tl(e);if(t)return t;let n=await eg({...e,expressionPath:e.expressionPath});if(n)return n;if(e.expressionPath.isTemplateLiteral()){let r=e.expressionPath.node.expressions[0],o=e.expressionPath.get("expressions.0");if(e.expressionPath.node.expressions.length===1&&r&&o&&!Array.isArray(o)&&o.isExpression()){let i=await Kt({expression:o.node,scope:o.scope,source:e.fileCache.get(e.currentFile)?.source,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(i){let s=await St({...e,expressionPath:o,sourceInfo:i});if(s&&s.kind==="value")return{...s,displayExpression:i.expression,editMode:"readonly",diagnostics:[{code:"unsupported-expression",message:"Mixed expressions are recognized but remain readonly until a safer composition editing strategy is available"}]}}}}return await ZC(e)}async function eg(e){let t=await Rt({...e,allowComposed:!1});if(t?.kind!=="source")return null;let n=sl(e.expressionPath);return n.isIdentifier()||n.isMemberExpression()?t.provenance:rl(t.provenance)}async function Rt(e){let t=sl(e.expressionPath),n=YC(e.currentFile,t.node);if(n&&e.visited.has(n))return null;n&&e.visited.add(n);try{if(t.isStringLiteral()||t.isNumericLiteral()||t.isBooleanLiteral()||t.isNullLiteral())return{kind:"none"};if(t.isIdentifier()){let r=await Kt({expression:t.node,scope:t.scope,source:e.fileCache.get(e.currentFile)?.source,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(!r)return null;let o=await St({currentFile:e.currentFile,expressionPath:t,sourceInfo:r,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});return!o||o.kind==="external"?null:{kind:"source",provenance:o}}if(t.isMemberExpression()){let r=await Kt({expression:t.node,scope:t.scope,source:e.fileCache.get(e.currentFile)?.source,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(!r)return null;let o=await St({currentFile:e.currentFile,expressionPath:t,sourceInfo:r,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});return!o||o.kind==="external"?null:{kind:"source",provenance:o}}if(t.isConditionalExpression()){let r=t.get("test"),o=t.get("consequent"),i=t.get("alternate");if(Array.isArray(r)||Array.isArray(o)||Array.isArray(i)||!r.isExpression()||!o.isExpression()||!i.isExpression())return null;let s=await Rt({...e,expressionPath:r,allowComposed:!0}),a=await Rt({...e,expressionPath:o,allowComposed:!1}),c=await Rt({...e,expressionPath:i,allowComposed:!1});return Gc(s,a,c)}if(t.isCallExpression())return WC({...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 Gc(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 Gc(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 sl(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 WC(e){let t=nl(e.expressionPath.node);if(t==="Math.round"||t==="Math.floor"||t==="Math.ceil"||t==="Math.trunc"||t==="useCountUp"){let r=e.expressionPath.get("arguments.0");return!r||Array.isArray(r)||!r.isExpression()?null:Rt({...e,expressionPath:r,allowComposed:!1})}let n=e.expressionPath.get("callee");if(n.isMemberExpression()&&!n.node.computed){let r=n.node.property;if(Z.isIdentifier(r)&&(r.name==="toFixed"||r.name==="toString")){let o=n.get("object");return Array.isArray(o)||!o.isExpression()?null:Rt({...e,expressionPath:o,allowComposed:!1})}}return null}function Gc(...e){let t=null;for(let n of e){if(!n)return null;if(n.kind!=="none"){if(!t){t=n.provenance;continue}if(!GC(t,n.provenance))return null}}return t?{kind:"source",provenance:t}:{kind:"none"}}function GC(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 YC(e,t){return t.start==null||t.end==null?null:`safe-derived:${e}:${t.start}:${t.end}`}async function ZC(e){if(!e.expressionPath.isCallExpression())return null;let t=nl(e.expressionPath.node);if(!t)return null;let n=ol(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 tg({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?rl(i):null}async function tg(e){let t=await tl({currentFile:e.currentFile,expressionPath:e.argumentPath,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(t)return t;let n=await Kt({expression:e.argumentPath.node,scope:e.argumentPath.scope,source:e.fileCache.get(e.currentFile)?.source,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(n){let r=await St({currentFile:e.currentFile,expressionPath:e.argumentPath,sourceInfo:n,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});return!r||r.kind==="external"?r:{...r,displayExpression:n.expression}}return await il({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 QC(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=ol(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 tg({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?rl(a):null}function qC(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 eR(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=Hc(e.expressionPath,t.base);if(n){let l=await wC({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=Mm(n.callPath,[...n.basePath,...t.path]);return Yr(h)?$m(e.currentFile,h.sourceId,h.displayPath):null}let d=Bm(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 tt(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 bn(e.currentFile,d.node.source.value,e.exists);if(!f)return null;let m=await TC({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 tt(m.value,u)===void 0?null:{kind:"value",file:m.file,root:m.root,path:u,sourceKind:"imported-binding",collectionIndexMap:m.collectionIndexMap}}let o=Bf(r);if(o){let l=o.expressionPath,d=await Kt({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:yr(d.expression,t.path),path:[...d.path,...t.path]}});if(f)return f}if(t.path.length===0){let f=await eg({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 FC({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 QC({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=Ai(r,t.path);if(Yr(s))return $m(e.currentFile,s.sourceId,s.displayPath);let a=await qc({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:tt(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 tR(e){let t=Lm(e.expressionPath.node);if(!t||!Dm(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 AC({...e,rootPath:n.path,segments:t.segments});return r?{...n,path:r.collectionPathMap[0]??n.path,sourceKind:"repeat-template",displayExpression:hr(e.expressionPath.node,e.fileCache.get(e.currentFile)?.source),...r.collectionIndexMap?{collectionIndexMap:r.collectionIndexMap}:{},collectionPathMap:r.collectionPathMap}:null}async function ng(e){let t=nR(e.propertyName);if(t.owner==="blocked")return mn(t.owner,t.diagnostic);if(t.owner==="class-name-source"||t.owner==="style")return mn(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 mn("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 oR(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 mn("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}:mn("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?mn("generic",{code:"remove-exposes-spread",message:`Removing '${e.propertyName}' would expose an earlier spread source`}):rR(e,s.attribute)}async function rR(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}}:mn("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"?mn("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 oR(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:iR(r,e.propertyName)}}function iR(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 mn(e,t){return{status:"blocked",owner:e,...t?{diagnostic:t}:{}}}function rg(e){let{key:t,element:n,graph:r,provenances:o}=e,i=aR(t,n,r),s=i?.tag??($n(n.tag)?n.tag:n.componentName),a=i?.identity.key??og(n,r)??t,c=uR(i),l=dR(t,n,r,o,i),d=sR(t,n,r,o,a);return{componentName:s,instanceKey:a,templateOwner:lR(i??n,s),...c.length>0?{variantKeys:c}:{},...l.length>0?{slotKeys:l}:{},editableStrategy:d,impactScope:fR(d),alternativeStrategies:pR(d)}}function sR(e,t,n,r,o){for(let i of r.values())if(i?.editMode==="upstream")return"upstream";return al(e,n)?"instance":!$n(t.tag)&&t.sourceFile!==n.routeId&&o!==e?"template":"instance"}function og(e,t){if($n(e.tag))return e.identity.key;let n=[...t.elements.values()].filter(r=>r.importedFrom===e.sourceFile&&cR(r,e.componentName));return n.length!==1?null:n[0].identity.key}function aR(e,t,n){if($n(t.tag))return t;let r=al(e,n);if(r)return r;let o=og(t,n);return o?n.elements.get(o)??null:null}function cR(e,t){return e.exportName===t||e.tag===t||e.exportName==="default"}function lR(e,t){return $n(e.tag)&&e.importedFrom?`${e.importedFrom}#${t}`:`${e.sourceFile}#${t}`}function uR(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 dR(e,t,n,r,o){let i=new Set,s=al(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&&$n(t.tag)&&t.childKeys.length>0&&i.add("children"),[...i]}function al(e,t){let n=t.elements.get(e)?.parentKey??null;for(;n;){let r=t.elements.get(n);if(!r)break;if($n(r.tag))return r;n=r.parentKey}return null}function $n(e){return/^[A-Z]/.test(e)}function fR(e){switch(e){case"template":return"component-template";case"upstream":return"upstream-source";default:return"current-instance"}}function pR(e){switch(e){case"template":return["instance"];case"upstream":return["template"];default:return["template"]}}function ag(e){let t=e.isRepeat??(e.graph?vR(e.element,e.graph):!1),n=e.propertyProvenance??new Map,r=e.repeatTargets??new Map,o=ER(e.element.attributes??[]),i=[...r.values()].some(d=>d.ok),s=o.map(d=>mR({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:kR(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 mR(e){let{attribute:t,provenance:n,repeatTarget:r}=e,o=e.selectionRef?.instanceIndex!==void 0&&r?.ok===!0?r:null,i=gR(t,n,e.isRepeat),s=["selection","template"].map(b=>({scope:b,result:ji({state:n,scope:b,operation:"set",selectionRef:e.selectionRef,isRepeat:e.isRepeat,repeatTarget:r})})),a=s.find(({result:b})=>b.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=hR(t,n,l,e.isRepeat),f=c?bR(c,e.element,t.name):void 0,m=s.filter(({result:b})=>b.ok).map(({scope:b})=>b),u=m.length>0?xR(n,o,e.element):"unsupported",g=o?"repeat-item":e.isRepeat?"repeat-template":"node",h=SR(t,n,r);if(m.length===0&&h.length===0){let b=s.find(({result:E})=>!E.ok)?.result;b&&!b.ok&&h.push({code:b.code,message:b.reason})}return{name:t.name,source:i,resolution:d,editMode:u,sourceScope:g,allowedWriteScopes:m,...f?{effectiveWriteTarget:f}:{},diagnostics:h}}function gR(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 hR(e,t,n,r){return n?ig(n.selectedResolution):t?.status==="blocked"?{status:"unresolved"}:r&&t?.status==="binding"?{status:"unresolved"}:ig(yR(e))}function yR(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 ig(e){return!e||e.status==="unresolved"?{status:"unresolved"}:e.status==="undefined"?{status:"undefined"}:{status:"resolved",value:e.value}}function xR(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 bR(e,t,n){return e.kind==="repeat-property"?{kind:"value-path",file:e.target.sourceFile,isProxy:e.target.sourceFile!==t.sourceFile,displayPath:sg({...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:sg(e.locator)}:{kind:"jsx-node",file:t.sourceFile,isProxy:!1,displayPath:t.componentName+" > "+n}}function SR(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 ER(e){let t=new Set;return e.filter(n=>t.has(n.name)?!1:(t.add(n.name),!0))}function vR(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 sg(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 kR(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 IR(e){return e==="api-field"||e==="cms-field"||e==="i18n-message"||e==="config-entry"}var CR=160;function cg(e,t,n,r={}){let o=tr(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 lg(e,t,n,r,o,i,s,a,c,l,d){let f=tr(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=mg(m.textSegments,s),b=gg(e,t,m,g,h),E=h?PR(h):void 0,v=AR(i,h),I=m.textSegments.map(C=>({index:C.index,value:C.value,editable:hg(C,g,s?.get(C.index)??null),source:o.get(C.index)??null})),R=fg(m,t),A=m.childKeys.map(C=>{let P=t.elements.get(C);return P?{key:C,tag:P.tag,label:P.tag}:null}).filter(C=>C!==null),T=[];if(m.parentKey){let C=t.elements.get(m.parentKey);if(C)for(let P of C.childKeys){if(P===e)continue;let O=t.elements.get(P);O&&T.push({key:P,tag:O.tag,label:O.tag})}}return{composition:f,key:e,tag:m.tag,componentName:m.componentName,sourceFile:m.sourceFile,sourceLocator:dg(m),label:m.tag,capabilities:b,writeTarget:i,effectiveWriteTarget:v,provenanceChain:E,componentSemantic:c,styleSource:l,conditional:a,...d?{dynamicData:d}:{},textSegments:I,boundaryKind:m.boundaryKind,isOpaque:m.isOpaque,ancestors:R,children:A,siblings:T}}function ug(e,t,n,r,o,i,s,a){let c=tr(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=mg(l.textSegments,i),u=RR(l);return{composition:c,key:e,tag:l.tag,...u?{linkSourceKind:u}:{},componentName:l.componentName,sourceFile:l.sourceFile,sourceLocator:dg(l),label:l.tag,capabilities:gg(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:hg(g,f,i?.get(g.index)??null),source:h?{kind:h.kind}:null}}),boundaryKind:l.boundaryKind,isOpaque:l.isOpaque,ancestors:fg(l,t)}}function RR(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 dg(e){return{sourceFile:e.sourceFile,componentName:e.componentName,openingElementRange:NR(e.sourceRange),structuralPath:e.identity.structuralPath,...wR(e.textSegments)}}function fg(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 NR(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function wR(e){let t=e.map(n=>n.value.trim()).filter(Boolean).join(" ").replace(/\s+/g," ").trim();return t?{textPreview:t.slice(0,CR)}:{}}function pg(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 mg(e,t){if(!t)return null;for(let n of e){let r=t.get(n.index);if(r)return r}return null}function gg(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&&yg(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 hg(e,t,n){return!e.editable||!t.canUpdateText?!1:n?yg(n.editMode):!0}function yg(e){return e==="direct"||e==="proxy"||e==="upstream"}function PR(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 AR(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}:IR(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 cl=["set-class-name-source","apply-style-draft"];function xg(e){let t=e.attributes?.find(n=>n.name==="className");if(!t)return{kind:"class-name-source",className:"",sourceKind:"missing",editable:!0,operationBoundary:cl,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:cl,sourcePath:n}}return{kind:"class-name-source",className:t.value,sourceKind:t.resolvedValue===void 0?"static-attribute":"static-expression",editable:!0,operationBoundary:cl}}function bg(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}),Sg(i,r,o,t,e)}}return{nodes:t,rootKeys:[...e.rootKeys]}}function Sg(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}),Sg(s,t,n,r,o))}}import Eg from"node:path";function ul(){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 kg(e,t,n){let r=[],o=new Set;for(let i of e.intents){let s=OR(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 os(e){let t=()=>TR(e);return e.mutex?e.mutex.runExclusive(t):t()}async function TR(e){let t=await kg(e.plan,e.overlay,e.exists);if(!t.ok)return{ok:!1,stage:"precheck",reason:t.reason,error:t,recoveryRequired:!1};let n=FR(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 ll({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 ll({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 ll({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 vg("swap",l,"Live state swap failed after durable publish.")}try{await e.finalizeCandidate?.(c)}catch(l){return vg("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 FR(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 ll(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:_R(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 vg(e,t,n){return{ok:!1,stage:e,reason:n,error:t,recoveryRequired:!0}}function _R(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 OR(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)||Eg.isAbsolute(e))return{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`};let t=Eg.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 MR=50,LR=8*1024*1024;function Ng(e,t={}){let n=[],r=[],o=t.externalAdapters??[],i=Math.max(0,t.maxUndoEntries??MR),s=Math.max(0,t.maxUndoBytes??LR);return{prepareRewritePlan:a,execute:c,executeFilePlan:l,undo:d,redo:f};async function a(C){let P=[...C.steps].sort((Q,fe)=>Q.order-fe.order),O=P.filter(Q=>Q.type!=="invoke-external-adapter");if(O.length!==P.length)return{ok:!1,errorCode:"unsupported-operation",reason:"External adapter writes require a transactional prepare/commit/rollback contract."};let L=new Set(O.map(Q=>Q.file)),U=await v(L),ee=new Map(U.map(Q=>[Q.file,Q.exists===!1?"":Q.content])),Ne;for(let Q of O){let fe=Rg(Q,ee.get(Q.file)??"");if(!fe.ok)return{ok:!1,errorCode:fe.errorCode,reason:fe.reason};ee.set(Q.file,fe.source),Ne=fe.selectionRef??Ne}return{ok:!0,filePlan:{operationId:C.operationId,kind:"source-edit",target:C.target,documentVersion:C.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}))},...Ne?{selectionRef:Ne}:{}}}async function c(C){let P=[...C.steps].sort((Oe,Yt)=>Oe.order-Yt.order),O=P.filter(Oe=>Oe.type!=="invoke-external-adapter"),L=P.filter(Oe=>Oe.type==="invoke-external-adapter"),U=new Set(O.map(Oe=>Oe.file));if(O.length>0&&L.length>0)return{ok:!1,operationId:C.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 b(C,L);let ee=await v(U),Ne=new Map;for(let Oe of ee)Ne.set(Oe.file,Oe.exists===!1?"":Oe.content);let Q;for(let Oe of O){let Yt=Ne.get(Oe.file)??"",Zt=Rg(Oe,Yt);if(!Zt.ok)return{ok:!1,operationId:C.operationId,errorCode:Zt.errorCode,reason:Zt.reason,rolledBack:!1};Ne.set(Oe.file,Zt.source),Zt.selectionRef&&(Q=Zt.selectionRef)}let fe=await R([...Ne].map(([Oe,Yt])=>({file:Oe,content:Yt,exists:!0,version:0,sha256:Ee(Yt)})),ee);return fe.ok===!1?{ok:!1,operationId:C.operationId,errorCode:fe.rolledBack?"writeback-failed":"rollback-failed",reason:fe.reason,rolledBack:fe.rolledBack}:(n.push({operationId:C.operationId,preSnapshots:ee,postSnapshots:fe.snapshots,plan:C}),m(),r.length=0,{ok:!0,operationId:C.operationId,kind:C.kind,target:C.target,resultVersion:Math.max(...fe.snapshots.map(Oe=>Oe.version)),affectedFiles:[...U],...Q?{selectionRef:Q}:{}})}async function l(C){let P=new Set(C.edits.map(fe=>fe.file)),O=await v(P),L=E(C,O);if(L)return{ok:!1,operationId:C.operationId,errorCode:"stale-version",reason:L.reason,affectedFiles:[L.file],rolledBack:!1};let U=new Map(O.map(fe=>[fe.file,fe])),ee=C.edits.find(fe=>fe.operation==="create-only"&&U.get(fe.file)?.exists!==!1);if(ee)return{ok:!1,operationId:C.operationId,errorCode:"stale-version",reason:`MATERIALIZATION_INSTANCE_CONFLICT: create-only target already exists: ${ee.file}`,affectedFiles:[ee.file],rolledBack:!1};let Ne=C.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 R(Ne,O,new Set(C.edits.filter(fe=>fe.operation==="create-only").map(fe=>fe.file)));return Q.ok===!1?{ok:!1,operationId:C.operationId,errorCode:Q.rolledBack?"writeback-failed":"rollback-failed",reason:Q.reason,rolledBack:Q.rolledBack}:(n.push({operationId:C.operationId,preSnapshots:O,postSnapshots:Q.snapshots,plan:{operationId:C.operationId,kind:C.kind,target:C.target,documentVersion:C.documentVersion,steps:[],preSnapshots:O}}),m(),r.length=0,{ok:!0,operationId:C.operationId,kind:C.kind,target:C.target,resultVersion:Math.max(...Q.snapshots.map(fe=>fe.version)),affectedFiles:[...P]})}async function d(){let C=n.at(-1);if(!C)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to undo"};let P=await R(C.preSnapshots,C.postSnapshots);return P.ok===!1?{ok:!1,operationId:C.operationId,errorCode:P.rolledBack?"writeback-failed":"rollback-failed",reason:P.reason,rolledBack:P.rolledBack}:(n.pop(),r.push(C),{ok:!0,operationId:C.operationId,kind:C.plan.kind,target:C.plan.target,resultVersion:Math.max(...P.snapshots.map(O=>O.version)),affectedFiles:C.preSnapshots.map(O=>O.file)})}async function f(){let C=r.at(-1);if(!C)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to redo"};let P=await R(C.postSnapshots,C.preSnapshots);return P.ok===!1?{ok:!1,operationId:C.operationId,errorCode:P.rolledBack?"writeback-failed":"rollback-failed",reason:P.reason,rolledBack:P.rolledBack}:(r.pop(),n.push(C),m(),{ok:!0,operationId:C.operationId,kind:C.plan.kind,target:C.plan.target,resultVersion:Math.max(...P.snapshots.map(O=>O.version)),affectedFiles:C.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((C,P)=>C+g(P),0)}function g(C){return h(C.preSnapshots)+h(C.postSnapshots)}function h(C){return C.reduce((P,O)=>P+O.file.length+O.content.length,0)}async function b(C,P){let O=[];for(let L of P){let U=L.capability??"write-text",ee=o.find(Q=>Q.sourceType===L.sourceType&&(L.adapterId===void 0||Q.adapterId===L.adapterId)&&(Q.capabilities===void 0||Q.capabilities.includes(U)));if(!ee)return{ok:!1,operationId:C.operationId,errorCode:"unsupported-operation",reason:`No external adapter registered for ${L.sourceType}`,rolledBack:!1};let Ne=await ee.execute(L);if(!Ne.ok)return{ok:!1,operationId:C.operationId,errorCode:"writeback-failed",reason:Ne.reason??`External adapter failed for ${L.sourceType}`,rolledBack:!1};O.push(L.file)}return{ok:!0,operationId:C.operationId,kind:C.kind,target:C.target,resultVersion:0,affectedFiles:O}}function E(C,P){if(C.conflictPolicy!=="compare-and-swap")return null;let O=new Map(P.map(L=>[L.file,L]));for(let L of C.edits){if(L.operation==="create-only")continue;if(L.baseContentHash===void 0)return{file:L.file,reason:`Source file ${L.file} is missing baseContentHash. Reopen the file before saving.`};let U=O.get(L.file),ee=L.baseContentHash;if(ee===null){if(U?.exists!==!1)return{file:L.file,reason:`Source file ${L.file} was created or changed before save.`};continue}if(!ee)return{file:L.file,reason:`Source file ${L.file} is missing baseContentHash. Reopen the file before saving.`};if(U?.exists===!1||U?.sha256!==ee)return{file:L.file,reason:`Source file ${L.file} changed before save. Reload or explicitly overwrite the newer version.`}}return null}async function v(C){let P=[];for(let O of C)P.push(await I(O));return P}async function I(C){if(!await e.exists(C))return{file:C,content:"",version:0,exists:!1};let O=Math.max(1,e.getVersion(C)),L=await e.readFile(C);return{file:C,content:L,version:O,exists:!0,sha256:Ee(L)}}async function R(C,P,O=new Set){let L=[];try{for(let U of C){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 A(U);let ee=e.bumpVersion(U.file);L.push(U.file),U.version=ee}}catch(U){let ee=await T(P.filter(Q=>L.includes(Q.file)));if(ee.ok===!1)return{ok:!1,reason:`Writeback failed, then rollback failed for ${ee.failedFiles.join(", ")}: ${Cg(U)}`,rolledBack:!1,instanceConflict:Ig(U)};let Ne=Ig(U);return{ok:!1,reason:`${Ne?"MATERIALIZATION_INSTANCE_CONFLICT: ":""}Writeback failed and committed files were restored: ${Cg(U)}`,rolledBack:!0,instanceConflict:Ne}}return{ok:!0,snapshots:C.map(DR)}}async function A(C){if(C.exists===!1){await e.deleteFile(C.file);return}await e.writeFile(C.file,C.content)}async function T(C){let P=[];for(let O of C)try{await A(O),e.bumpVersion(O.file)}catch{P.push(O.file)}return P.length===0?{ok:!0}:{ok:!1,failedFiles:P}}}function Ig(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="EEXIST"}function DR(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 Cg(e){return e instanceof Error?e.message:String(e)}function Rg(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(er({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-node":return He(Gn({source:t,locator:e.locator,removeWhitespace:e.removeWhitespace}));case"insert-child":return He(Yn({source:t,locator:e.parentLocator,node:e.node,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"update-text":return He(Zo({source:t,locator:e.locator,segmentIndex:e.segmentIndex,newText:e.newText}));case"update-value":return He(Fr({source:t,locator:e.locator,next:e.value}));case"update-array-item":return He(Fr({source:t,locator:e.locator,next:e.value}));case"insert-bound-array-item":return He(oi({source:t,locator:e.locator,index:e.index,value:e.value}));case"insert-jsx-expression-child":return He(qo({source:t,locator:e.parentLocator,expression:e.expression,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"remove-bound-array-item":return He(ii({source:t,locator:e.locator,index:e.index}));case"move-array-item":return He(si({source:t,locator:e.locator,fromIndex:e.fromIndex,toIndex:e.toIndex}));case"move-node":return He(Zn({source:t,locator:e.locator,targetParentLocator:e.targetParentLocator,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"move-repeat-template-child":return He(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 BR(e,t);case"set-property-changes":return He(ti({source:t,locator:e.locator,changes:e.changes}));case"set-link-target":return He(ni({source:t,locator:e.locator,link:e.link,changes:e.changes}));case"set-property-binding":return He(ri({source:t,locator:e.locator,name:e.name,object:e.object,property:e.property}));case"upsert-object-property":return He(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 BR(e,t){let{request:n}=e;if(n.newAttrRaw!==null&&!pd(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:fd({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 is,SiteEditCompositionContextSchema as jR,SiteEditCompositionSelectorSchema as $R}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 wg(e,t){throw new Ye("INVALID_COMPOSITION",e,{value:t})}function ss(e){let t=jR.safeParse(e);return t.success?t.data:wg("Invalid SiteEditCompositionContext.",e)}function Pg(e){let t=[],n=new Map,r=new Map;for(let l of e.compositions){let d=ss(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=is(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=ss(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=is(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=$R.safeParse(l);if(!d.success)return wg("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=ss(l),f=is(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=ss(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=is(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 VR,stripSiteEditRepeatInstanceKeys as Ag}from"@vcp-dev/contracts";function Tg(e){let t=new Map,n=new Map,r=new Map;for(let o of e.entries){t.set(o.key,o);let i=Ag(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 KR(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 as(e){return e?.map(t=>({...t}))}function dl(e,t){if(t===null||e?.kind!=="value-binding"||e.sourceKind!=="repeat-template")return e;let n=e.collectionIndexMap?.[t]??t,r=as(e.collectionPathMap?.[t])??as(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:as(e.path),locator:e.locator?{...e.locator,path:r}:e.locator,collectionIndexMap:e.collectionIndexMap?[...e.collectionIndexMap]:void 0,collectionPathMap:e.collectionPathMap?.map(o=>as(o)??[])}}function Fg(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)=>VR(u,g),c=(u,g,h)=>{let b=o.get(u);if(!b)return a(u,h);let E=a(u,h),v={...b,key:E,parentKey:g,childKeys:[]};return i.push(v),v.childKeys=b.childKeys.flatMap(I=>l(I,h,E)),E},l=(u,g,h)=>{if(!r.has(u))return[c(u,h,g)];let b=f(u,g),E=[];for(let v=0;v<b;v+=1)E.push(c(u,h,[...g,v]));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 b of m(u)){let E=n.get(b);if(E){for(let v of[...E.textTargets.values(),...E.elementPropertyTargets.values()])if(!(v?.kind!=="value-binding"||v.sourceKind!=="repeat-template"))for(let I of UR(v))I.length<=g.length||JR(I,g)&&h.add(I[g.length])}}return h.size>0?h.size:KR(n.get(u))}function m(u){let g=s.get(u);if(g)return g;let h=[u],b=o.get(u);for(let E of b?.childKeys??[])h.push(...m(E));return s.set(u,h),h}}function _g(e){let t=e.parts.at(-1);return typeof t?.repeatIndex=="number"?t.repeatIndex:null}function Og(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((Ag(s.key)??s.key)===n){if(s.key===t)return i;i+=1}return null}function UR(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 JR(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 Mg(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 Lg(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 Dg(e){return{path:e.path,code:e.code,message:e.message,...e.details?{details:JSON.parse(JSON.stringify(e.details))}:{}}}function XR(e){return e.map(t=>`${t.code} (${t.path}): ${t.message}`).join("; ")}var yo=class extends Error{constructor(t){let n=t.map(Dg);super(XR(n)),this.name="RouteBuildDiagnosticsError",this.diagnostics=n}};function Bg(e,t){let n=t instanceof Error&&t.message?t.message:String(t);return t instanceof yo?{routeId:e,message:n,diagnostics:t.diagnostics.map(Dg)}:{routeId:e,message:n}}function fl(e){return e.map(({routeId:t,message:n})=>`${t}: ${n}`).join("; ")}function pl(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 jg(e,t){for(let n of t){if(n.exists===!1){e.delete(n.file);continue}e.set(n.file,n.content)}}function ml(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 $g(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 qR=/^(?:src\/)?app\/.*\/?page\.[cm]?[jt]sx?$/,eN=["layout.tsx","layout.ts","layout.jsx","layout.js","layout.mjs","layout.cjs"],Vg=32,Kg=256;function tN(e){return{expectedIndexDigest:e.digest,publishedIndexDigest:e.digest,publishedCursor:e.cursor,publishedCurrentId:e.currentId}}var Ug={maxEntries:50,maxBytes:8*1024*1024};function nN(){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 rN(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 oN(){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>Ug.maxEntries||iN(e)>Ug.maxBytes;)e.shift()}}function iN(e){return e.reduce((t,n)=>t+sN(n),0)}function sN(e){return Jg(e.preSnapshots)+Jg(e.postSnapshots)+aN(e.provenance)}function aN(e){return e?new TextEncoder().encode(JSON.stringify(e)).byteLength:0}function Jg(e){return e.reduce((t,n)=>t+n.file.length+n.content.length,0)}function Xg(e,t){return{key:HR(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 ls=class extends Error{constructor(t){super(t.reason),this.result=t}},Vn=class extends Error{constructor(t){super(fl(t)),this.failedRoutes=t}};function zg(e,t){if(!e)return;let n=[...t];if(n.some(o=>o?.entries.some(i=>i.key===e.key)))return e;let r=nt(e.key)??e.key;for(let o of n){let i=o?.entries.find(s=>(nt(s.key)??s.key)===r);if(i)return{...e,key:i.key}}return e}function cN(e,t,n){if(!n)return;let r=nt(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 lN=/\.(?:[cm]?[jt]sx?)$/i,uN=/\.json$/i,dN=/\.(?:css|scss|sass)$/i,fN=/\.mdx$/i,pN=/\.ya?ml$/i;function mN(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 gN(e){return{kind:e.isProxy?"component-proxy":"jsx-node",file:e.file,componentName:e.componentName,isProxy:e.isProxy}}function hN(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=Qg(await e.listFiles(r)),i=new Map(o.files.map(a=>[a.path,a]));for(let[a,c]of n)if(yN(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 yN(e,t){return t.length===0?!0:t.some(n=>e===n||e.startsWith(`${n}/`))}function Qg(e){return Array.isArray(e)?{files:e}:e}function xN(e){if(!GR(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!==ZR||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=WR(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(lN.test(e.path)){let t=At({source:e.content,profile:En({filePath:e.path,source:e.content})});if(!t.ok)return{ok:!1,errorCode:"ast-error",message:t.diagnostic.message,details:{path:e.path}}}if(uN.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(dN.test(e.path)){let t=Hg({content:e.content,path:e.path,profile:"css"});if(!t.ok)return t}if(fN.test(e.path)){let t=Hg({content:e.content,path:e.path,profile:"mdx"});if(!t.ok)return t}if(pN.test(e.path))try{QR(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`YAML parse failed: ${Qe(t)}`,details:{path:e.path}}}return{ok:!0}}function Hg({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
12
|
`||m==="\r"))return Sr(t,`Unterminated string literal in ${t}.`);l=m===`
|
|
13
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 So(e){let t="idle",n=e.fileSystem??nN(),r=fd(),o=Pg({compositions:e.compositions,initialDocumentVersions:e.initialDocumentVersions}),i=new Map,s=new Map,a=new Set,c=null,l=e.history??(e.historyStore?Nd(e.historyStore):oN()),d=Ng(n,{externalAdapters:e.externalAdapters}),f=new Map,m=new Set,u=0,g=e.historyStore?.recoveryRequired??!1,h=ul(),b=R();function E(p){return(as.isAbsolute(p)?as.relative(e.projectRoot,p):p).replace(/\\/g,"/").replace(/^\.\//,"")}function v(p,y){let x=as.posix.dirname(p),k=y.replace(/\.(?:tsx?|jsx?)$/i,""),w=as.posix.relative(x,k);return w.startsWith(".")?w:`./${w}`}function I(p,y){return p.startLine===y.startLine&&p.startColumn===y.startColumn&&p.endLine===y.endLine&&p.endColumn===y.endColumn}async function R(){let p=e.historyStore;if(p)try{let y=await p.readTransactionJournal();if(!y)return;let x=await p.readIndex(),k=await Promise.all(y.files.map(async _=>await n.exists(_.path)?Ee(await n.readFile(_.path)):null));if($g({journal:y,index:x,observedFileDigests:k})!=="ambiguous"){await p.clearTransactionJournal(y.transactionId);let _=await p.readStatus();_.recoveryRequired||(await p.cleanupTmp(),_=await p.readStatus()),g=_.recoveryRequired;return}await p.markRecoveryRequired(`Ambiguous transaction journal ${y.transactionId} at phase ${y.phase}`),g=!0}catch(y){g=!0,await p.markRecoveryRequired(`Transaction journal recovery failed: ${Qe(y)}`).catch(()=>{})}}function A(){return t==="disposed"}e.onEvent&&r.subscribe(e.onEvent);for(let p of o.entries){let y=Xg(p.context,p.entryFile);i.set(p.key,y),T(y,y.dependencyFiles)}function T(p,y){let x=new Set(y);C(p),p.dependencyFiles=x;for(let k of p.dependencyFiles){let w=s.get(k);w||(w=new Set,s.set(k,w)),w.add(p.key)}}function C(p){for(let y of p.dependencyFiles){let x=s.get(y);x&&(x.delete(p.key),x.size===0&&s.delete(y))}p.dependencyFiles.clear()}function P(p){let y=new Set;for(let x of p)for(let k of s.get(x)??[])y.add(k);return y}function O(p){for(let y of p)if(!s.has(y))return!1;return!0}async function D(p,y,x,k,w){let _=new Map,M=Wm(w.values()),W=new Map,X=typeof n.exists=="function"?L=>n.exists(L):async()=>!1;for(let[L,B]of p.elements){let se=y.nodes.get(L);if(!se)continue;let ne=x.get(B.sourceFile)??k.get(B.sourceFile),Ne=new Map,ye=new Map,ke=new Map,we=[];for(let Se of B.textSegments){if(!ne){Ne.set(Se.index,null);continue}let Er=await Hm({file:B.sourceFile,source:ne,segment:Se,readFile:it=>n.readFile(it),exists:X,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:it,adapterId:hn,capabilities:Rs})=>({sourceType:it,adapterId:hn,capabilities:Rs})),functionCallContracts:e.functionCallContracts,fileCache:M}),Ze=await el({file:B.sourceFile,source:ne,target:{kind:"text-segment",segment:Se},readFile:it=>n.readFile(it),exists:X,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:it,adapterId:hn,capabilities:Rs})=>({sourceType:it,adapterId:hn,capabilities:Rs})),functionCallContracts:e.functionCallContracts,fileCache:M}),pt=mN(Er);Ne.set(Se.index,pt),ye.set(Se.index,Er),ke.set(Se.index,Ze),we.push({editable:Se.editable,source:pt})}let F=new Map,V=new Map;if(ne)for(let Se of B.attributes??[]){let Er=await xr({file:B.sourceFile,source:ne,sourceRange:Se.sourceRange,expression:Se.source?.expression??Se.value,sourceInfo:Se.source,readFile:pt=>n.readFile(pt),exists:X,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:pt,adapterId:it,capabilities:hn})=>({sourceType:pt,adapterId:it,capabilities:hn})),functionCallContracts:e.functionCallContracts,fileCache:M}),Ze=await ng({element:B,file:B.sourceFile,source:ne,propertyName:Se.name,readFile:pt=>n.readFile(pt),exists:X,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:pt,adapterId:it,capabilities:hn})=>({sourceType:pt,adapterId:it,capabilities:hn})),functionCallContracts:e.functionCallContracts,fileCache:M});V.set(Se.name,Ze),F.set(Se.name,Er)}let pe=pg(gN(se.writeTarget),we),ie=rg({key:L,element:B,graph:p,provenances:ke}),Pe=xg(B),De=ne?await Zp({element:B,graph:p,file:B.sourceFile,source:ne,readFile:Se=>n.readFile(Se),exists:X,fileCache:W}):void 0,ot=p.regions.find(Se=>Se.kind==="conditional-region"&&Se.childKeys.includes(L)),Qt,He=ot?.sourceCandidates?.[0];if(ne&&ot&&He?.kind==="conditional-branch"){let Se=await el({file:B.sourceFile,source:ne,target:{kind:"conditional-branch",candidate:He},readFile:Ze=>n.readFile(Ze),exists:X,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Ze,adapterId:pt,capabilities:it})=>({sourceType:Ze,adapterId:pt,capabilities:it})),functionCallContracts:e.functionCallContracts,fileCache:M});Qt={currentBranch:ot.childKeys.indexOf(L)<=0?"then":"else",availableBranches:ot.childKeys.length>1?["then","else"]:["then"],conditionExpression:He.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}))}}}_.set(L,{textSources:Ne,textTargets:ye,elementPropertyTargets:F,propertyProvenances:V,isRepeat:ON(L,p),provenances:ke,writeTarget:pe,componentSemantic:ie,styleSource:Pe,conditional:Qt,dynamicData:De})}return _}function U(p){return typeof n.getVersion=="function"?n.getVersion(p):0}function ee(p,y){let x=o.initialVersions.get(p.key)??0;for(let k of y.values())x=Math.max(x,k);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 fe(p,y,x={}){let k=i.get(p);if(!k)return null;let w=x.sourceCache??pl(f,[]),_=await Oe(k.entryFile),{graph:M,allSources:W,diagnostics:X,parsedModules:L,entryModule:B}=await Ed(k.entryFile,y,He=>n.readFile(He),typeof n.exists=="function"?He=>n.exists(He):async()=>!1,{additionalEntries:_,version:k.graph?.version??1});if(X.length>0)throw new yo(X);let se=new Map;for(let He of W.keys())se.set(He,U(He));let ne=Math.max(ee(k,se),x.minimumVersion??0);x.changed&&ne<=(k.graph?.version??0)&&(ne=(k.graph?.version??0)+1),M.version=ne;for(let[He,Se]of W)ml(w,He,Se,Kg);let Ne=await Yt(k.composition,k.entryFile,W,w);M.routeId=k.routeId,M.composition=k.composition;let ye=bg(M),ke=ad(ye,M),we=await D(M,ye,W,w,L),F=kh(M,ke,we),V=vh(we),pe=Fg(cg(M,ye,ke,{canUpdateTextByKey:F,dynamicDataSummaryByKey:V}),M,we),ie=pf({route:k.routeId,composition:k.composition,entryFile:k.entryFile,version:ne,source:y,ast:B?.ast}),Pe=mf(ie);ie.ok&&SN(pe,M,ie.projection,L);let De={...pe,composition:k.composition,...Ne?{styleContext:Ne}:{},pageComposition:Pe},ot=new Set([k.entryFile,...W.keys()]);if(Ne){ot.add(Ne.entryCss.path);for(let He of Ne.stylesheets)ot.add(He.path)}let Qt={...k,dependencyFiles:ot,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:Tg(De),detailProjections:we,fileVersions:se,styleContext:Ne};if(x.publish===!1)return Qt;br(f,w);for(let He of w.keys())m.delete(He);return T(k,ot),Object.assign(k,Qt),k}async function Oe(p){let y=[];for(let x of wN(p))typeof n.exists=="function"&&await n.exists(x)&&y.push({file:x,source:await n.readFile(x)});return y}async function Yt(p,y,x,k){let w=[];for(let[L,B]of x){if(gl(L)){w.push(L);continue}for(let se of AN(B)){let ne=Zg(L,se);ne&&w.push(ne)}}if(!w.length){for(let L of PN(y))if(await jl(L)){w.push(L);break}}let _=new Map,M=_N(w).slice(0,Vg);for(;M.length>0&&_.size<Vg;){let L=M.shift();if(_.has(L)||!gl(L))continue;let B=await Zt(L,k);if(B!==null){_.set(L,{path:L,content:B});for(let se of TN(B)){let ne=Zg(L,se);ne&&!_.has(ne)&&!M.includes(ne)&&M.push(ne)}}}let W=[..._.values()].map(L=>({...L,hash:Ee(L.content)})),X=W[0];return X?{composition:p,revision:Ee(JSON.stringify(W.map(({path:L,hash:B})=>({path:L,hash:B})))),entryCss:X,stylesheets:W.slice(1)}:null}async function Zt(p,y){let x=y.get(p);if(x!==void 0)return x;if(!await jl(p))return null;let k=await n.readFile(p);return ml(y,p,k,Kg),k}async function jl(p){return typeof n.exists=="function"?n.exists(p):!1}function vh(p){let y=new Map;for(let[x,k]of p)k.dynamicData?.bindings.length&&y.set(x,cm(k.dynamicData.bindings));return y}function kh(p,y,x){let k=new Map;for(let[w,_]of p.elements){if(!y.get(w)?.canUpdateText){k.set(w,!1);continue}let W=x.get(w),X=_.textSegments.some(L=>{if(!L.editable)return!1;let B=W?.provenances.get(L.index)??null;return!B||Ih(B)});k.set(w,X)}return k}function Ih(p){return p.editMode==="direct"||p.editMode==="proxy"||p.editMode==="upstream"}async function Po(p,y={}){let x=[...new Set(p)],k=y.affectedCompositionKeys!==void 0,w=k?new Set(y.affectedCompositionKeys):P(x);if(!k&&(w.size===0||!O(x)))for(let X of i.values())$l(X,x)&&w.add(X.key);let _=!k&&w.size===0&&x.some(Yg),M=y.publish===!1?pl(f,x):void 0,W={rebuiltRoutes:[],failedRoutes:[],...y.publish===!1?{candidateRouteStates:[],candidateSourceCache:M}:{}};for(let X of i.values())if(!(y.excludedCompositionKeys?.has(X.key)||!(w.has(X.key)||_)))try{let B=!!X.graph,se=await n.readFile(X.entryFile),ne=await fe(X.key,se,{...y,...M?{sourceCache:M}:{}});ne?.graph&&(W.rebuiltRoutes.push({documentChanged:B,composition:X.composition,routeId:X.routeId,version:ne.graph.version}),W.candidateRouteStates?.push({composition:X.composition,key:X.key,routeId:X.routeId,state:ne}))}catch(B){W.failedRoutes.push({...Bg(X.routeId,B),composition:X.composition})}return W}function Un(p){let y=[...new Set(p)],x=P(y);if(x.size>0&&O(y))return[...x];for(let k of i.values())$l(k,y)&&x.add(k.key);return[...x]}function Ch(p){let y=new Set(Un(p));return o.entries.filter(x=>y.has(x.key)).map(x=>x.context)}function Rh(p){return[...new Set(Un(p))].sort((x,k)=>x<k?-1:x>k?1:0).map(x=>o.getByKey(x)?.context).filter(x=>x!==void 0)}function Nh(p,y){let x=new Set(Un(y)),k=p.provenance?.affectedCompositions??[];if(k.length===0)return x;if([...new Set(k.map(_=>o.resolveContext(_).key))].some(_=>!x.has(_)))throw new Error("History provenance does not match the affected composition index.");return x}function wh(p,y){let x=p.composition??p.provenance?.initiatingComposition;if(x){let _=o.resolveContext(x);return{context:_.context,key:_.key}}let k=[...new Set(Un(y))];if(k.length!==1)throw new Error(`Legacy history entry cannot be attributed to a unique composition (affected composition count: ${k.length}).`);let w=o.getByKey(k[0]);if(!w)throw new Error("Legacy history entry references an unknown affected composition.");return{context:w.context,key:w.key}}function Ss(p,y){r.emit({type:"operation-completed",composition:p.composition,result:p});for(let{composition:x,version:k}of y.rebuiltRoutes)r.emit({type:"document-changed",composition:x,version:k});for(let{composition:x,message:k}of y.failedRoutes)r.emit({type:"graph-error",composition:x,message:k})}function $l(p,y){return y.some(x=>p.dependencyFiles.has(x)||p.entryFile===x||p.graph?.fileIndex.has(x))}function Vl(p){for(let y of p)a.add(y);c||A()||(c=(async()=>{t="building";let y=!1;try{for(;a.size>0;){if(A())return;await Ph();let x=[...a];a.clear();let k=await Kl(x);if(k.length===0)continue;let w=Un(k);for(let W of w){let X=i.get(W)?.composition;X&&r.emit({type:"graph-invalidated",composition:X})}let{rebuiltRoutes:_,failedRoutes:M}=await Po(k,{changed:!0});for(let{documentChanged:W,composition:X,version:L}of _)r.emit({type:"graph-ready",composition:X,version:L}),W&&r.emit({type:"document-changed",composition:X,version:L});for(let{composition:W,message:X}of M)y=!0,r.emit({type:"graph-error",composition:W,message:X})}}finally{c=null,t!=="disposed"&&(t=!y&&[...i.values()].some(x=>x.graph)?"ready":"idle"),a.size>0&&Vl([])}})())}async function Ph(){for(;u>0;)await new Promise(p=>setTimeout(p,0))}async function Kl(p){let y=[];for(let x of new Set(p)){let k=f.get(x);if(k===void 0){if(m.has(x)&&!await n.exists(x))continue;m.delete(x),y.push(x);continue}try{await n.readFile(x)!==k&&(m.delete(x),y.push(x))}catch(w){if(!bN(w))try{if(await n.exists(x))continue}catch{continue}m.add(x),y.push(x)}}return y}function Ul(p){jg(f,p);for(let y of p)y.exists===!1?m.add(y.file):m.delete(y.file)}function Jl(p){m.clear();for(let y of p)m.add(y)}async function Xl(p){let y=await Kl(p);if(y.length===0)return;let x=Un(y);for(let _ of x){let M=i.get(_)?.composition;M&&r.emit({type:"graph-invalidated",composition:M})}let{rebuiltRoutes:k,failedRoutes:w}=await Po(y,{changed:!0});for(let{documentChanged:_,composition:M,version:W}of k)r.emit({type:"graph-ready",composition:M,version:W}),_&&r.emit({type:"document-changed",composition:M,version:W});for(let{composition:_,message:M}of w)r.emit({type:"graph-error",composition:_,message:M})}async function Ah(p,y){let x=zn(p,y);if(!x?.graph)return;let k=nt(p)??p,w=x.graph.elements.get(k);w&&await Xl([w.sourceFile])}async function zl(p){let y=new Set;if(p.target.kind==="node"){let x=zn(p.target.key,p.composition),k=nt(p.target.key)??p.target.key,w=x?.graph?.elements.get(k);w&&y.add(w.sourceFile)}else if(p.target.kind==="route"){let x=i.get(o.resolveSelector(p.target.composition).key);x&&y.add(x.entryFile)}else if(p.target.kind==="page-unit"){let x=i.get(o.resolveSelector(p.target.composition).key);x&&y.add(x.entryFile)}else if(p.target.kind==="source-file")y.add(p.target.path);else if(p.target.kind==="source-batch")for(let x of p.target.paths)y.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 k of x){let w=zn(k,p.composition),_=nt(k)??k,M=w?.graph?.elements.get(_);M&&y.add(M.sourceFile)}}await Xl(y)}async function Th(p){if(p.params.kind!=="source-edit")return Es(p,"invalid-params","source-edit requires source-edit params");for(let y of p.params.edits){let x=xN(y);if(!x.ok)return Es(p,x.errorCode,x.message,x.details)}u+=1;try{let y=await Dh(p.params.edits);if(!y.ok)return Es(p,y.errorCode,y.message,y.details);await zl(p);let x={operationId:p.id,kind:"source-edit",target:p.target,documentVersion:p.documentVersion,conflictPolicy:p.params.conflictPolicy,edits:p.params.edits.map(k=>k.operation==="delete"?{operation:"delete",file:k.path,baseContentHash:k.baseContentHash??null}:{operation:"upsert",file:k.path,baseContentHash:k.baseContentHash??null,content:k.content})};return await Xn({request:p,filePlan:x})}catch(y){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(y)}}}finally{u-=1}}async function Fh(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 y=await ya({files:[...p.params.artifact.components.flatMap(k=>k.materialization.files.map(w=>({path:w.pathTemplate,content:w.content}))),...p.params.artifact.pages.flatMap(k=>k.materialization.files.map(w=>({path:w.pathTemplate,content:w.content})))],exists:k=>n.exists(k),readFile:k=>n.readFile(k)});if(!y.ok)return le(p,$.MATERIALIZATION_REJECTED,y.message);let x=await va({artifact:p.params.artifact,exists:k=>n.exists(k)});return x.ok?await Xn({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:p.target,documentVersion:p.documentVersion,conflictPolicy:"overwrite",edits:x.files},output:{kind:"insert-page-resource",package_instance_id:x.packageInstanceId,pages:x.pages},historyPolicy:"none"}):le(p,x.code==="MATERIALIZATION_CONFLICT"?$.MATERIALIZATION_CONFLICT:$.MATERIALIZATION_REJECTED,x.message,x.path?{path:x.path}:void 0)}catch(y){return le(p,$.INTERNAL_ERROR,Qe(y))}finally{u-=1}}async function _h(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 y=Qg(await n.listFiles({maxFiles:5e4,maxDepth:64}));if(y.truncated)return le(p,$.PLAN_FAILED,"Project file listing is incomplete; page deletion was refused.",{truncationReasons:y.truncated.reasons});let x=y.files.filter(({path:M})=>/\.(?:tsx?|jsx?)$/.test(M)),k=Object.fromEntries(await Promise.all(x.map(async({path:M})=>[M,await n.readFile(M)]))),w=Lf({expectedUrlPath:p.params.expectedUrlPath,files:k});if(!w.ok)return le(p,w.code==="HOME_PAGE_LOCKED"?$.HOME_PAGE_LOCKED:w.code==="ROUTE_NOT_FOUND"?$.ROUTE_NOT_FOUND:$.PLAN_FAILED,w.message);let _=await Promise.all(w.edits.map(async M=>({...M,baseContentHash:Ee(await n.readFile(M.file))})));return Xn({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:p.target,documentVersion:p.documentVersion,conflictPolicy:"compare-and-swap",edits:_},output:{kind:"delete-page-source",deleted_files:w.deletedFiles,updated_files:w.updatedFiles,preserved_shared_files:w.preservedSharedFiles,warnings:w.warnings},historyPolicy:"none"})}catch(y){return le(p,$.INTERNAL_ERROR,Qe(y))}finally{u-=1}}async function Oh(p,y){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 x=y.document,k=y.pageCompositionProjection;if(!x||x.pageComposition?.status!=="supported"||!k||k.status!=="supported")return le(p,$.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(p.documentVersion!==x.version||k.documentVersion!==x.version)return le(p,$.VERSION_STALE,`Document version ${p.documentVersion} is stale (current: ${x.version}).`);let w=p.params.node.kind==="component-call"?p.params.node.materialization:void 0;if(!w)return le(p,$.UNSUPPORTED_OPERATION,"Page-unit insertion currently requires a static materialization manifest.");let _=p.params.kind==="insert-child"?p.params.position:null,M=await ya({files:w.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 W=await rN(n,Object.keys(w.projectDependencies??{})),X=await Yd({manifest:w,generatedRoot:"components/site/generated",controlledFiles:w.files.map(L=>({pathTemplate:L.pathTemplate})),exists:L=>n.exists(L),availableHostDependencies:W,commit:async L=>{let B=await n.readFile(y.entryFile),se=y.document,ne=y.pageCompositionProjection;if(!se||se.pageComposition?.status!=="supported"||se.version!==p.documentVersion||!ne||ne.status!=="supported"||ne.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=Uh(L.instanceName),ke,we=[];if(p.params.kind==="insert-child"){if(!_||!("kind"in _)||_.kind!=="page-composition")return{ok:!0,data:le(p,$.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.")};let ie=Pa({routeId:y.routeId,entryFile:y.entryFile,currentDocumentVersion:se.version,expectedDocumentVersion:p.documentVersion,source:B,projection:ne,placementKey:_.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,Cs(ie.error.code),ie.error.message,{diagnostics:ie.error.diagnostics})};let Pe=ie.plan.rewriteStep,De;switch(Pe.kind){case"insert-root-expression":De=vi({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=Yn({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=Aa({routeId:y.routeId,composition:y.composition,entryFile:y.entryFile,currentDocumentVersion:se.version,expectedDocumentVersion:p.documentVersion,source:B,projection:ne,placementUnitKey:p.target.placementUnitKey,operation:"replace-node"});if(!ie.ok)return{ok:!0,data:le(p,Cs(ie.error.code),ie.error.message,{diagnostics:ie.error.diagnostics})};let Pe=ie.plan.rewriteStep,De;switch(Pe.kind){case"replace-root-expression":De=vi({source:B,locator:Pe.locator,expectedSourceHash:Pe.sourceHash,action:{kind:"replace",jsx:`<${ye} />`}});break;case"replace-node":De=Zo({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 ot=await Wl({routeState:y,placementUnitKey:p.target.placementUnitKey,source:B,mutatedSource:De.source});ke=ot.source,we=await Promise.all(ot.files.map(async Qt=>({operation:"delete",file:Qt,baseContentHash:Ee(await n.readFile(Qt))})))}let F=qn({source:ke,moduleSpecifier:v(y.entryFile,Ne),imports:L.entry.export.kind==="default"?[{kind:"default",local:ye}]:[{kind:"named",imported:L.entry.export.name,local:ye}]});if(!F.ok)return{ok:!0,data:le(p,$.AST_PARSE_ERROR,F.diagnostic.message)};let V=L.files.map(ie=>({operation:"create-only",file:ie.path,content:ie.content})),pe=[{operation:"upsert",file:y.entryFile,content:F.source,baseContentHash:Ee(B)},...V,...we];u+=1;try{let ie=await Xn({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:{kind:"source-file",path:y.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 Mh(p,y){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 x=y.document,k=y.pageCompositionProjection;if(!x||x.pageComposition?.status!=="supported"||!k||k.status!=="supported")return le(p,$.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(p.documentVersion!==x.version||k.documentVersion!==x.version)return le(p,$.VERSION_STALE,`Document version ${p.documentVersion} is stale (current: ${x.version}).`);let w=await n.readFile(y.entryFile),_=Aa({routeId:y.routeId,composition:y.composition,entryFile:y.entryFile,currentDocumentVersion:x.version,expectedDocumentVersion:p.documentVersion,source:w,projection:k,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(!_.ok)return le(p,Cs(_.error.code),_.error.message,{diagnostics:_.error.diagnostics});let M=_.plan.rewriteStep,W;switch(M.kind){case"move-node":W=Zn({source:w,locator:M.locator,targetParentLocator:M.targetParentLocator,placement:M.placement,...M.anchorLocator?{anchorLocator:M.anchorLocator}:{}});break;case"remove-node":W=Gn({source:w,locator:M.locator});break;case"remove-root-expression":W=vi({source:w,locator:M.locator,expectedSourceHash:M.sourceHash,action:{kind:"remove"}});break;default:W={ok:!1,source:w,diagnostic:{message:`Unsupported page-unit mutation rewrite: ${M.kind}`}}}if(!W.ok)return le(p,$.AST_PARSE_ERROR,W.diagnostic.message);let X=W.source,L=[];if(p.kind==="remove-node"){let se=await Wl({routeState:y,placementUnitKey:p.target.placementUnitKey,source:w,mutatedSource:X});X=se.source,L=await Promise.all(se.files.map(async ne=>({operation:"delete",file:ne,baseContentHash:Ee(await n.readFile(ne))})))}let B=[{operation:"upsert",file:y.entryFile,content:X,baseContentHash:Ee(w)},...L];u+=1;try{return await Xn({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:{kind:"source-file",path:y.entryFile},documentVersion:p.documentVersion,conflictPolicy:"compare-and-swap",edits:B}})}finally{u-=1}}async function Wl(p){let y={source:p.mutatedSource,files:[]},x=p.routeState.graph,k=p.routeState.pageCompositionProjection;if(!x||!k||k.status!=="supported"||!n.listFiles)return y;let _=k.placementUnitByKey.get(p.placementUnitKey)?.sourceRange;if(!_)return y;let M=[...x.elements.values()].find(F=>F.sourceFile===p.routeState.entryFile&&F.importedFrom&&I(F.sourceRange,_));if(!M?.importedFrom||!M.exportName)return y;let W=E(M.importedFrom),X="components/site/generated/";if(!W.startsWith(X))return y;let L=W.slice(X.length).split("/")[0];if(!L||!/-[0-9a-f]{8}$/i.test(L))return y;let B=`${X}${L}`;if([...x.elements.values()].filter(F=>F.sourceFile===p.routeState.entryFile&&E(F.importedFrom??"")===W).length!==1)return y;let ne=await n.listFiles({maxFiles:5e3,maxDepth:32}),Ne=Array.isArray(ne)?ne:ne.files;if(!Array.isArray(ne)&&ne.truncated)return y;let ye=Ne.map(({path:F})=>F).filter(F=>F===B||F.startsWith(`${B}/`));if(ye.length===0||!ye.includes(W))return y;for(let{path:F}of Ne)if(!(F===p.routeState.entryFile||F===B||F.startsWith(`${B}/`)))try{if((await n.readFile(F)).includes(L))return y}catch{return y}let ke=v(p.routeState.entryFile,W),we=er({source:p.mutatedSource,moduleSpecifier:ke,imports:M.exportName==="default"?[{kind:"default"}]:[{kind:"named",imported:M.exportName}]});return we.ok?{source:we.source,files:ye.sort((F,V)=>F.localeCompare(V))}:y}async function Dh(p){if(n.getFileInfo){for(let w of p)if(await n.exists(w.path)&&await n.getFileInfo(w.path)===null)return{ok:!1,errorCode:"invalid-params",message:`Source edit path must resolve to a regular non-symbolic-link file: ${w.path}`,details:{path:w.path}}}for(let w of p){if(w.operation!=="upsert"||!/^(?:src\/)?app\/globals\.css$/i.test(w.path))continue;let _=await n.exists(w.path)?await Vs(n,w.path):null;if(_?.ok){let M=zR(_.content,w.content);if(!M.ok)return{ok:!1,errorCode:"invalid-params",message:M.message,details:{path:w.path,code:M.code}}}}let y=Lh(p);if(y.length===0)return{ok:!0};let x=hN(n,p),k=So({projectRoot:e.projectRoot,fileSystem:x,compositions:[...i.values()].map(w=>({context:w.composition,entryFile:w.entryFile})),externalAdapters:e.externalAdapters,externalSourceResolvers:e.externalSourceResolvers,functionCallContracts:e.functionCallContracts,dev:e.dev});try{for(let w of y){let _=i.get(w)?.composition;if(!_)continue;let M={routeId:_.routeId,..._.effectiveTemplateId!==void 0?{templateId:_.effectiveTemplateId}:{}};await k.initializeComposition(M),k.getDocument(M)}}catch(w){return{ok:!1,errorCode:"ast-error",message:`Source edit preflight failed: ${Qe(w)}`,details:{compositionKeys:y}}}finally{k.dispose()}return{ok:!0}}function Lh(p){return p.map(x=>x.path).some(Yg)?[...i.keys()]:[]}function Es(p,y,x,k){let w=xo(y);return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Q(p),error:{code:w,message:x,...k?{details:k}:{}}}}async function vs(p){let y=[];for(let x of new Set(p))y.push(await Bh(x));return y}async function Bh(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:Ee(x)}}async function Hl(p,y,x,k){if(!e.historyStore)return null;let w=new Map(y.map(W=>[W.file,W])),_=new Map(x.map(W=>[W.file,W])),M=[...new Set([...w.keys(),..._.keys()])].sort().map(W=>{let X=w.get(W),L=_.get(W);return{path:W,preDigest:X?.exists===!1||!X?null:Ee(X.content),postDigest:L?.exists===!1||!L?null:Ee(L.content)}});return{schemaVersion:2,transactionId:`${p}:${k.expectedIndexDigest}`,operationId:p,phase:"prepared",historyTransition:k,files:M}}async function Gl(p){return!p||!e.historyStore||await e.historyStore.writeTransactionJournal(p),p}async function Jn(p){p&&e.historyStore&&await e.historyStore.clearTransactionJournal(p.transactionId)}async function ks(p,y){let x=[];try{for(let k of p)await Yl(k),typeof n.bumpVersion=="function"&&n.bumpVersion(k.file),x.push(k.file)}catch(k){let w=await jh(y.filter(_=>x.includes(_.file)));return w.ok?{ok:!1,reason:`Writeback failed and committed files were restored: ${Qe(k)}`,rolledBack:!0}:{ok:!1,reason:`Writeback failed, then rollback failed for ${w.failedFiles.join(", ")}: ${Qe(k)}`,rolledBack:!1}}return{ok:!0,snapshots:p.map($h)}}async function Yl(p){if(p.exists===!1){await n.deleteFile(p.file);return}await n.writeFile(p.file,p.content)}async function jh(p){let y=[];for(let x of p)try{await Yl(x),typeof n.bumpVersion=="function"&&n.bumpVersion(x.file)}catch{y.push(x.file)}return y.length===0?{ok:!0}:{ok:!1,failedFiles:y}}function $h(p){let y=p.exists!==!1;return{file:p.file,content:y?p.content:"",version:p.version,exists:y,...y?{sha256:Ee(p.content)}:{}}}async function Xn(p){return h.runExclusive(()=>Vh(p))}async function Vh(p){let y=p.filePlan.edits.map(F=>F.file),x=o.resolveSelector(p.request.composition),k=x.context,w=p.historyPolicy==="none"?void 0:{initiatingComposition:k,affectedCompositions:Rh(y)},_=await vs(y),M=new Map(_.filter(F=>F.exists!==!1).map(F=>[F.file,F.content])),W=Ql(),X=new Map(f),L=new Set(m),B=new Set([...i.values()].filter(F=>p.filePlan.edits.some(V=>V.operation==="delete"&&V.file===F.entryFile)).map(F=>F.key)),se=p.filePlan.edits.map(F=>F.operation==="delete"?{file:F.file,content:"",version:0,exists:!1}:{file:F.file,content:F.content,version:0,exists:!0,sha256:Ee(F.content)}),ne={operationId:p.filePlan.operationId,intents:p.filePlan.edits.map(F=>F.operation==="delete"?{kind:"delete",path:F.file}:{kind:F.operation==="create-only"?"create-only":"upsert",path:F.file,content:F.content})},Ne=null,ye=!1,ke=await rs({overlay:M,exists:F=>n.exists(F),plan:ne,buildCandidate:async({plan:F})=>({plan:F}),prepareHistory:async()=>{let F=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:_,postSnapshots:se,...p.selectionRef?{selectionRef:p.selectionRef}:{},...p.output?{output:p.output}:{},...w?{provenance:w}:{}}),V=F?.historyTransition?F.historyTransition:e.historyStore?tN(await e.historyStore.readIndex()):null;if(e.historyStore&&!V)throw new Error("Durable history did not provide an exact index transition.");return Ne=await Hl(p.request.id,_,se,V),Ne=await Gl(Ne),{history:F,historyTransition:V}},reverify:async()=>{},writeCandidate:async()=>{let F=await d.executeFilePlan(p.filePlan);if(!F.ok)throw new cs(F);return{postSnapshots:await vs(F.affectedFiles),affectedFiles:F.affectedFiles,internalResultVersion:F.resultVersion}},validateCandidate:async({candidate:F,receipt:V})=>{let pe=await Po(V.affectedFiles,{changed:!0,minimumVersion:V.internalResultVersion,publish:!1,excludedCompositionKeys:B});if(pe.failedRoutes.length>0)throw new Vn(pe.failedRoutes);let ie=eu(W,pe.candidateRouteStates??[]),Pe=ql(ie,x.key);return{...F,rebuild:pe,routeSnapshots:ie,resultVersion:Pe,...zg(p.selectionRef,ie.map(De=>De.state.document))?{selectionRef:zg(p.selectionRef,ie.map(De=>De.state.document))}:{}}},publishCandidate:async({candidate:F,history:V,receipt:pe})=>{V?.history&&(await l.publishPrepared(V.history),ye=!0);let ie=F.resultVersion??pe.internalResultVersion;return{composition:k,requestId:p.request.id,kind:p.request.kind,target:p.request.target,ok:!0,resultVersion:ie,affectedFiles:pe.affectedFiles,...p.output?{output:p.output}:{},...F.selectionRef?{selectionRef:F.selectionRef}:{}}},swapCandidate:({candidate:F,receipt:V})=>{F.routeSnapshots&&Ao(F.routeSnapshots),F.rebuild?.candidateSourceCache&&br(f,F.rebuild.candidateSourceCache),Ul(V.postSnapshots)},finalizeCandidate:async()=>{await Jn(Ne);for(let F of B)i.delete(F)},emitCommitted:({candidate:F,published:V})=>{Ss(V,F.rebuild??{rebuiltRoutes:[],failedRoutes:[]})},rollbackCandidate:async({history:F,receipt:V})=>{if(ye)throw new Error("history was published before transaction finalization failed");if(V){let pe=await ks(_,V.postSnapshots);if(!pe.ok)throw new Error(pe.reason)}Ao(W),br(f,X),Jl(L),F?.history&&await l.discardPrepared?.(F.history),await Jn(Ne)}});if(ke.ok)return ke.published;if(ke.stage==="precheck"||ke.stage==="build")try{await Jn(Ne)}catch(F){let V=await To(Qe(F));return le(p.request,V,"Unable to clear an uncommitted transaction journal.")}if(ke.recoveryRequired){let F=await To(ke.reason);return le(p.request,F===$.RECOVERY_PERSIST_FAILED?F:$.ROLLBACK_FAILED,ke.reason)}let we=ke.error;return we instanceof cs?{...le(p.request,xo(we.result.errorCode),we.result.reason),...we.result.affectedFiles?{affectedFiles:we.result.affectedFiles}:{}}:we instanceof Vn?le(p.request,$.ROUTE_REBUILD_FAILED,`Route rebuild failed and source was rolled back: ${fl(we.failedRoutes)}`,{failedRoutes:we.failedRoutes}):le(p.request,nu(ke.stage),Qe(we))}async function Zl(p){return h.runExclusive(async()=>{let y=p==="undo"?await l.prepareUndo():await l.prepareRedo();return y?Kh(p,y):{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 Kh(p,y){let x=y.entry,k=p==="undo"?x.preSnapshots:x.postSnapshots,w=p==="undo"?x.postSnapshots:x.preSnapshots,_=k.map(V=>V.file),{context:M,key:W}=wh(x,_),X=await vs(_),L=new Map(X.filter(V=>V.exists!==!1).map(V=>[V.file,V.content])),B=Re(W),se=Ql(),ne=new Map(f),Ne=new Set(m),ye=null,ke=!1,we,F=await rs({overlay:L,plan:{operationId:`${p}:${x.operationId}`,intents:k.map(V=>V.exists===!1?{kind:"delete",path:V.file}:{kind:"upsert",path:V.file,content:V.content})},buildCandidate:async()=>({}),prepareHistory:async()=>(ye=await Hl(`${p}:${x.operationId}`,X,k,y.historyTransition),ye=await Gl(ye),y),reverify:async()=>{},writeCandidate:async()=>{let V=await ks(k,w);if(!V.ok)throw new Error(V.reason);return{snapshots:V.snapshots}},validateCandidate:async({candidate:V})=>{we=Nh(x,_);let pe=await Po(_,{changed:!0,minimumVersion:B+1,publish:!1,affectedCompositionKeys:we});if(pe.failedRoutes.length>0)throw new Vn(pe.failedRoutes);let ie=eu(se,pe.candidateRouteStates??[]),Pe=ql(ie,W);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:x.kind,target:x.target,ok:!0,resultVersion:ie,affectedFiles:_,...x.output?{output:x.output}:{}}},swapCandidate:({candidate:V,receipt:pe})=>{V.routeSnapshots&&Ao(V.routeSnapshots),V.rebuild?.candidateSourceCache&&br(f,V.rebuild.candidateSourceCache),Ul(pe.snapshots)},finalizeCandidate:async()=>{await Jn(ye)},emitCommitted:({candidate:V,published:pe})=>Ss(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 ks(w,pe.snapshots);if(!ie.ok)throw new Error(ie.reason)}Ao(se),br(f,ne),Jl(Ne),V&&await l.discardPrepared?.(V),await Jn(ye)}});if(F.ok)return F.published;if(F.stage==="precheck"||F.stage==="build")try{await Jn(ye)}catch(V){let pe=await To(Qe(V));return{composition:M,requestId:p,kind:x.kind,target:x.target,ok:!1,resultVersion:B,error:{code:pe,message:"Unable to clear an uncommitted transaction journal."}}}if(F.recoveryRequired){let V=await To(F.reason);return{composition:M,requestId:p,kind:x.kind,target:x.target,ok:!1,resultVersion:B,affectedFiles:_,error:{code:V===$.RECOVERY_PERSIST_FAILED?V:$.ROLLBACK_FAILED,message:F.reason}}}return{composition:M,requestId:p,kind:x.kind,target:x.target,ok:!1,resultVersion:B,affectedFiles:_,error:{code:F.error instanceof Vn?$.ROUTE_REBUILD_FAILED:nu(F.stage),message:Qe(F.error),...F.error instanceof Vn?{details:{failedRoutes:F.error.failedRoutes}}:{}}}}function Ql(){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 ql(p,y){return p.find(k=>k.key===y)?.state.graph?.version??o.initialVersions.get(y)??0}function eu(p,y){let x=new Map(p.map(k=>[k.key,k]));for(let k of y)x.set(k.key,k);return[...x.values()]}function Ao(p){for(let y of i.values())C(y);for(let y of p){let x={...y.state,dependencyFiles:new Set(y.state.dependencyFiles),fileVersions:new Map(y.state.fileVersions)};i.set(y.key,x),T(x,x.dependencyFiles)}}async function Is(p){let y=i.get(p);if(!y)throw new Error(`Composition not found: ${p}`);if(y.graph)return;let x=await n.readFile(y.entryFile);await fe(p,x)}function zn(p,y){let x=i.get(o.resolveSelector(y).key)??null;return!x||!tu(x,p)?null:x}function tu(p,y){if(p.documentIndex?.entriesByKey.has(y)||p.graph?.elements.has(y))return!0;let x=nt(y);return x&&x!==y?p.graph?.elements.has(x)===!0:!1}function le(p,y,x,k){return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Q(p),error:{code:y,message:x,...k?{details:k}:{}}}}function nu(p){return p==="validate"?$.ROUTE_REBUILD_FAILED:p==="publish"?$.HISTORY_COMMIT_FAILED:$.WRITE_IO_ERROR}async function To(p){if(g=!0,!l.markRecoveryRequired)return $.RECOVERY_REQUIRED;try{return await l.markRecoveryRequired(p),$.RECOVERY_REQUIRED}catch{return $.RECOVERY_PERSIST_FAILED}}function Uh(p){let x=p.split(/[^a-zA-Z0-9]+/).filter(Boolean).map(k=>k.charAt(0).toUpperCase()+k.slice(1)).join("").replace(/^[^a-zA-Z_$]+/,"");return x?`Prefab${x}`:"GeneratedPrefab"}function Cs(p){return p==="VERSION_STALE"?$.VERSION_STALE:p==="CROSS_PAGE_MOVE_UNSUPPORTED"?$.CROSS_PAGE_MOVE_UNSUPPORTED:$.UNSUPPORTED_OPERATION}async function ru(p){if(p.target.kind==="route"){let x=i.get(o.resolveSelector(p.target.composition).key)??null;return x?(x.graph||await Is(x.key),x):le(p,$.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 Is(x.key),x):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 y=i.get(o.resolveSelector(p.composition).key)??null;return y?(y.graph||await Is(y.key),tu(y,p.target.key)?y: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,y){let x=o.register({context:p,entryFile:y}),k=i.get(x.key);if(k?.entryFile===y)return;k&&C(k);let w=Xg(x.context,y);i.set(x.key,w),T(w,w.dependencyFiles),r.emit({type:"graph-invalidated",composition:x.context})},unregisterComposition(p){let y=o.resolveSelector(p),x=i.get(y.key);x&&(C(x),i.delete(y.key),o.unregister(y.key),i.size===0&&(t="idle"),r.emit({type:"graph-invalidated",composition:y.context}))},getCompositionEntryFiles(){return[...i.values()].map(p=>p.entryFile)},getCompositionContext(p){return o.resolveSelector(p).context},async initializeComposition(p){let y=o.resolveSelector(p),x=i.get(y.key);if(!x)throw new Error(`Composition not registered: ${y.key}`);if(x.graph)t="ready";else{t="building";try{let k=await n.readFile(x.entryFile);await fe(y.key,k),t="ready",r.emit({type:"graph-ready",composition:y.context,version:i.get(y.key)?.graph?.version??0})}catch(k){throw t="idle",r.emit({type:"graph-error",composition:y.context,message:Qe(k)}),k}}},getDocument(p){let y=o.resolveSelector(p),x=i.get(y.key);if(!x)throw new Error(`Composition not registered: ${y.key}`);if(!x.document)throw new Error(`Composition not built: ${y.key}`);return x.document},async getHistoryStatus(){await b;let p=await l.getStatus?.();return p?{...p,recoveryRequired:g}:{canUndo:!1,canRedo:!1,undoDepth:0,redoDepth:0,recoveryRequired:g}},getObjectEditContext(p,y,x){let k=zn(p,y),w=nt(p)??p;if(k?.graph&&k.topology&&k.capabilities&&k.detailProjections){let _=k.detailProjections.get(w);if(_){let M=k.graph.elements.get(w);if(!M)throw new Error(`Key not found: ${p}`);let W=cN(p,w,x),X=new Map;if(_.isRepeat&&W?.instanceIndex!==void 0)for(let se of M.attributes??[])X.set(se.name,jc({file:M.sourceFile,source:f.get(M.sourceFile)??"",element:M,propertyName:se.name,selectionRef:W,graph:k.graph,sources:f}));let L=ag({element:M,graph:k.graph,source:f.get(M.sourceFile),documentVersion:k.graph.version,selectionRef:x,isRepeat:_.isRepeat,propertyProvenance:_.propertyProvenances,repeatTargets:X}),B=ug(w,k.graph,k.topology,k.capabilities,_.textSources,_.provenances,_.dynamicData,L);return p===w?B:Dg(B,p,k.document??null,k.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${p}`)},getRenderDetail(p,y){let x=zn(p,y),k=nt(p)??p;if(x?.graph&&x.topology&&x.capabilities&&x.detailProjections){let w=x.detailProjections.get(k);if(w){let _=lg(k,x.graph,x.topology,x.capabilities,w.textSources,w.writeTarget,w.provenances,w.conditional,w.componentSemantic,w.styleSource,w.dynamicData);return p===k?_:Mg(_,p,x.document??null,x.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${p}`)},getClassNameSource(p,y){let x=zn(p,y),k=nt(p)??p;if(!x?.graph)throw new Error(`Key not found: ${p}`);let w=x.graph.elements.get(k);if(!w)throw new Error(`Key not found: ${p}`);let _=f.get(w.sourceFile);if(_===void 0)throw new Error(`Source not loaded: ${w.sourceFile}`);return sa({key:k,route:{composition:x.composition,routeId:x.routeId,graph:x.graph,source:_}})},refreshSourceForKey:Ah,async execute(p){if(await b,g)return le(p,$.RECOVERY_REQUIRED,"The edit engine requires explicit recovery before accepting mutations.");if(p.kind==="source-edit")return Th(p);if(p.kind==="insert-page-resource")return Fh(p);if(p.kind==="delete-page-source")return _h(p);let y=await ru(p);if("ok"in y)return y;await zl(p);let x=await ru(p);if("ok"in x)return x;let k=x;if(p.target.kind==="page-unit"){let B=p;return p.kind==="insert-child"||p.kind==="replace-node"?Oh(B,k):p.kind==="move-node"||p.kind==="remove-node"?Mh(B,k):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 _=p.params,M=p.target.kind==="node"?p.target.key:null;if(_.kind==="move-node"&&"kind"in _.target&&_.target.kind==="source-sibling"){let B=_.target,se=M?k.document?.entries.find(V=>V.key===M):null,ne=k.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,we=ye?.indexOf(B.anchorKey)??-1,F=B.relation==="before"?ke-1:ke+1;if(!se||!ne||!ye||ke<0||we!==F||ne.pageCompositionActionScope?.kind!=="source-siblings"||ne.pageCompositionActionScope.siblingKeys.length!==ye.length||ne.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(!k.graph||!k.topology||!k.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 W=RN(k,k.graph,k.capabilities,f,i),X=await new Ui(W).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:xo(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,xo(se.errorCode),se.reason);let ne={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 Ss(ne,{rebuiltRoutes:[],failedRoutes:[]}),ne}let B=await d.prepareRewritePlan(L);return B.ok?await Xn({request:p,filePlan:B.filePlan,...B.selectionRef?{selectionRef:B.selectionRef}:{}}):le(p,xo(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 b,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:$.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting undo."}};u+=1;try{return await Zl("undo")}finally{u-=1}},async redo(p){if(await b,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:$.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting redo."}};u+=1;try{return await Zl("redo")}finally{u-=1}},notifyFileChanged(p){Vl([p])},getAffectedCompositions(p){return Ch(p)},subscribe(p){return r.subscribe(p)}}}function bN(e){return e instanceof Error&&"code"in e&&(e.code==="ENOENT"||e.code==="ENOTDIR")}function SN(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&&bo(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=nt(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&&bo(u.sourceRange,n.container.sourceRange)&&d){f.pageCompositionUnitKey=d.placementUnitKey;continue}let b=n.placements.find(E=>E.members.some(v=>v.sourceRange!==null&&(bo(u.sourceRange,v.sourceRange)||CN(v.sourceRange,u.sourceRange))));if(b){f.pageCompositionUnitKey=b.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)}EN(e,t,n,r)}function EN(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&&bo(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 b=s.get(g.target)??0,E=Math.min(2,b+h);E!==b&&(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!==(nt(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 b=h.match.path,E=b.parentPath;if(!E||!E.isJSXFragment()&&!(E.isJSXElement()&&Fe(E))){d(u)===1&&Hg(b)&&(m.pageCompositionActionScope={kind:"route-unit"});continue}if(!Hg(E))continue;let v=f.get(E.node)??[];v.push({entry:m,element:u,parentPath:E}),f.set(E.node,v)}for(let m of f.values()){let u=m[0];if(!u)continue;let g=u.entry.pageCompositionUnitKey,h=[],b=!!(g&&d(u.element)===1);for(let v of u.parentPath.node.children){if(vN(v))continue;if(!kN(v)){b=!1;break}let I=[...t.elements.values()].find(A=>A.sourceFile===u.element.sourceFile&&A.componentName===u.element.componentName&&bo(A.sourceRange,IN(v))),R=I?o.get(I.identity.key):null;if(!I||!R||R.parentKey||R.pageCompositionUnitKey!==g||d(I)!==1){b=!1;break}h.push(R)}if(!b||h.length!==m.length||m.some(({entry:v})=>!h.some(I=>I.key===v.key)))continue;if(h.length===1){h[0].pageCompositionActionScope={kind:"route-unit"};continue}if(h.length<2)continue;let E=h.map(v=>v.key);for(let v of h)v.pageCompositionActionScope={kind:"source-siblings",siblingKeys:E}}}function Hg(e){let t=e.parentPath;return!!(t?.isReturnStatement?.()||t?.isArrowFunctionExpression?.()&&t.node.body===e.node)}function vN(e){return!!(e&&typeof e=="object"&&e.type==="JSXText"&&!(e.value??"").trim())}function kN(e){return!!(e&&typeof e=="object"&&e.type==="JSXElement")}function IN(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 bo(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function CN(e,t){return Gg(e.startLine,e.startColumn,t.startLine,t.startColumn)<=0&&Gg(e.endLine,e.endColumn,t.endLine,t.endColumn)>=0}function Gg(e,t,n,r){return e!==n?e-n:t-r}function RN(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 b=nt(h)??h,E=t.elements.get(b);return E?l(h,E):null}).filter(h=>h!==null);let g=t.elements.get(f.baseKey);return g?g.childKeys.map(h=>{let b=t.elements.get(h);return b?l(h,b):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:sa({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 dl(e.detailProjections?.get(m.baseKey)?.textTargets.get(f)??null,m.repeatIndex)},async getElementPropertyWriteTarget(d,f){let m=c(d);return dl(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 b=e.detailProjections?.get(u.baseKey)?.propertyProvenances.get(f);if(b)return b;let E=g.attributes?.find(v=>v.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 jc({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=YR(d);return f?{baseKey:f.baseKey,repeatIndex:Og(e.document??null,d,f.baseKey,e.documentIndex)??_g(f)}:{baseKey:d,repeatIndex:null}}function l(d,f){let m=nt(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 NN={"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 xo(e){return NN[e]}function Qe(e){return e instanceof Error&&e.message?e.message:String(e)}function Yg(e){return/\.(?:[cm]?[jt]sx?|css|scss|sass|mdx|json)$/i.test(e)}function wN(e){let t=Kn(e);if(!qR.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=>eN.map(a=>`${s}/${a}`))}function PN(e){let n=Kn(e).startsWith("src/app/")?"src/app":"app";return[`${n}/globals.css`,`${n}/global.css`]}function AN(e){return qg(e,/\bimport\s+(?:[^'";]+?\s+from\s+)?["']([^"']+\.css(?:\?[^"']*)?)["']/g)}function TN(e){return qg(e,/@import\s+(?:url\(\s*)?["']([^"']+)["']/g)}function qg(e,t){let n=[];for(let r of e.matchAll(t)){let o=eh(r[1]??"");o&&n.push(o)}return n}function Zg(e,t){let n=eh(t);return!n||n.startsWith("tailwindcss")||n.startsWith("http:")||n.startsWith("https:")?null:n.startsWith("@/")?Kn(`src/${n.slice(2)}`):n.startsWith("./")||n.startsWith("../")?Kn(`${FN(e)}/${n}`):n.startsWith("/")?Kn(n.slice(1)):gl(n)?Kn(n):null}function eh(e){return e.split(/[?#]/,1)[0]?.trim()??""}function gl(e){return/\.css$/i.test(e)}function FN(e){let t=Kn(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function _N(e){return Array.from(new Set(e))}function Kn(e){let t=e.replace(/\\/g,"/").replace(/^\.\//,""),n=[];for(let r of t.split("/"))if(!(!r||r===".")){if(r===".."){n.pop();continue}n.push(r)}return n.join("/")}function ON(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 ls=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 Bo(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 jo(r?this.engine.getObjectEditContext(t,n,r):this.engine.getObjectEditContext(t,n))}getClassNameSource(t,n){return this.engine.getClassNameSource(t,n)}getSourceTree(t){return Ko(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}getSourceFile(t){return Uo(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}resolveSourceLocation(t){return Jo(t,this.engine.getRenderDetail(t.key,t.composition))}async planOperation(t){let n=DN.safeParse(t);if(!n.success)return{result:Lo(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:In(i)},a=r.getChangedFiles();if(a.length===0)return{result:s};let c=LN.parse({siteId:t.siteId,baseSnapshotId:t.baseSnapshotId,operationId:t.id,reason:`site-edit:${t.kind}`,patches:a.map(l=>BN(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 So({projectRoot:"/snapshot",fileSystem:t,compositions:this.options.compositions,onEvent:r&&this.options.onEvent?o=>{let i=$o(o,{siteId:this.options.siteId,snapshotId:this.options.snapshotId});i&&this.options.onEvent?.(i)}:void 0,dev:this.options.dev,...this.options.historyStore?{historyStore:this.options.historyStore}:{},...this.options.tenantId?{tenantId:this.options.tenantId}:{},siteId:this.options.siteId,snapshotId:this.options.snapshotId,...this.options.initialDocumentVersions?{initialDocumentVersions:this.options.initialDocumentVersions}:{}})}};function BN(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 jN(e){return new ls(e)}import{SiteEditOperationRequestSchema as KN}from"@vcp-dev/contracts";import Nt from"node:fs/promises";import qe from"node:path";import{SITE_EDIT_SOURCE_ALLOWED_DIRS as $N,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as VN}from"@vcp-dev/contracts";var us=class{constructor(t){this.options=t,this.fileSystem=this.createFileSystem(),this.engine=So({...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 Ko(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.engine.getCompositionEntryFiles()})}getSourceFile(t){return Uo(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.engine.getCompositionEntryFiles()})}resolveSourceLocation(t){return Jo(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 Nt.readFile(qe.join(n,r),"utf8")},async readFileBytes(r){return Nt.readFile(qe.join(n,r))},async getFileInfo(r){let o=qe.join(n,...r.split("/"));try{let i=await Nt.lstat(o);return!i.isFile()||i.isSymbolicLink()?null:{path:r,sizeBytes:i.size}}catch{return null}},async writeFile(r,o){await li(qe.join(n,r),o)},async createExclusive(r,o){let i=qe.join(n,r);await Nt.mkdir(qe.dirname(i),{recursive:!0});let s=await Nt.open(i,"wx");try{await s.writeFile(o,"utf8")}catch(a){throw await s.close(),await Nt.rm(i,{force:!0}),a}await s.close()},async deleteFile(r){await Nt.rm(qe.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=qe.join(n,i),a=qe.dirname(qe.join(n,o));for(;a!==s&&a.startsWith(`${s}${qe.sep}`);){try{await Nt.rmdir(a)}catch(c){if(c instanceof Error&&"code"in c&&c.code==="ENOENT"){a=qe.dirname(a);continue}break}a=qe.dirname(a)}},async exists(r){try{return await Nt.access(qe.join(n,r)),!0}catch{return!1}},async listFiles(r={}){let o=r.roots??[...VN,...$N],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=qe.join(n,...f.split("/")),h;try{h=await Nt.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 b=await Nt.readdir(g,{withFileTypes:!0});for(let E of b)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 hl(e){return new us(e)}var ds=class{constructor(t){this.options=t,this.listeners=new Set,this.engine=hl({projectRoot:t.projectRoot,fileSystem:t.fileSystem,compositions:t.compositions,onEvent:n=>{let r=$o(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:Bo(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:jo(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=KN.safeParse(r);if(!o.success)return Lo(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 UN(e){return new ds(e)}import{createHash as JN,randomUUID as wl}from"node:crypto";import _e from"node:fs/promises";import Me from"node:path";var Et=1,xl=1,XN=2,zN="index.json",WN="recovery.json",HN="transaction-journal.json",GN="document-version.json",ps={maxEntries:100,maxSessionBytes:512*1024*1024,maxEntryBytes:128*1024*1024},te={INVALID_ROOT:"INVALID_ROOT",INVALID_PATH:"INVALID_PATH",INVALID_SCHEMA:"INVALID_SCHEMA",INVALID_JSON:"INVALID_JSON",INDEX_CORRUPT:"INDEX_CORRUPT",ENTRY_CORRUPT:"ENTRY_CORRUPT",BLOB_CORRUPT:"BLOB_CORRUPT",RECOVERY_PENDING:"RECOVERY_PENDING",CAPACITY_EXCEEDED:"CAPACITY_EXCEEDED",NOT_FOUND:"NOT_FOUND"},oe=class extends Error{constructor(t,n,r){super(n),this.name="FileHistoryStoreError",this.code=t,r?.cause!==void 0&&(this.cause=r.cause)}};async function uh(e,t={}){let n=lw(e),r=fw(t.limits),o=yl(n),i=uw(n),s=await rt(i),a=await rt(o)||s;a||(await tw(n),await nw(n)),a||await pw(n);let c=await ut(n),l=new Set(a?(await xs(n)).map(f=>f.stageId):[]);a||await Eo(n,c.entryIds);let d=async()=>{if(await rt(o)||s)throw new oe(te.RECOVERY_PENDING,"history store requires explicit recovery before accepting writes")};return{rootDir:n,recoveryRequired:a,async readDocumentVersion(){return ch(n)},async writeDocumentVersion(f){if(await d(),!Number.isInteger(f)||f<0)throw new oe(te.INVALID_SCHEMA,"document version must be a non-negative integer");let m=await ch(n);await vo(yh(n),{schemaVersion:1,version:Math.max(m,f)})},async stageAppend(f,m={}){await d();let u=await nh(f,r),g={schemaVersion:xl,stageId:wl(),entryId:u.entryId,blobIds:u.blobs.map(h=>h.digest)};try{await rh(n,u),await QN(n,g,m.durableManifest!==!1)}catch(h){try{await ih(n,g)}catch(b){throw new oe(te.INDEX_CORRUPT,"staged history cleanup failed after preparation error",{cause:b})}throw h}return{stageId:g.stageId,entryId:g.entryId,blobIds:g.blobIds}},async discardStage(f){await d(),vl(f);let m=await Sl(n,f);m&&await ih(n,m)},async previewStagedAppend(f,m){return await d(),(await th(n,r,f,m)).transition},async previewCursor(f,m){await d();let u=await ut(n);return kl(u,m),bl(f,u.entryIds.length),dh(u,u.entryIds,f)},async publishStagedAppend(f,m,u){if(await d(),ms(f,"entryId"),u){vl(u);let h=await Sl(n,u);if(!h||h.entryId!==f)throw new oe(te.INVALID_SCHEMA,"history stage does not match the published entry")}let g=await th(n,r,f,m);return ah({rootDir:n,previousDigest:g.current.digest,entryIds:g.entryIds,cursor:g.cursor,afterWrite:async()=>{u?await gs(n,u):await ew(n,f),await Eo(n,g.entryIds)}})},async append(f){await d();let m=await ut(n),u=await nh(f,r),g=[...m.entryIds];m.cursor<g.length-1&&g.splice(m.cursor+1),g.push(u.entryId);try{await rh(n,u);let h=await fh(n,g,r);return await Al(n,h.entryIds,h.cursor),await Eo(n,h.entryIds),ut(n)}catch(h){throw await Eo(n,m.entryIds),h}},async readEntry(f){return ms(f,"entryId"),Io(n,f)},async readBlob(f){ms(f,"blobId");let m=await Bl(n,f),u=await mn(m,te.NOT_FOUND,"blob");return Tl(u,f,m),u},async readIndex(){return ut(n)},async readStatus(){let f=await ut(n);return{canUndo:f.undoIds.length>0,canRedo:f.redoIds.length>0,undoDepth:f.undoIds.length,redoDepth:f.redoIds.length,cursor:f.cursor,recoveryRequired:await rt(o)||await rt(i)}},async readUndoRedoIds(){let f=await ut(n);return{undoIds:f.undoIds,redoIds:f.redoIds,currentId:f.currentId}},async setCursor(f,m){await d();let u=await ut(n);return kl(u,m),bl(f,u.entryIds.length),ah({rootDir:n,previousDigest:u.digest,entryIds:u.entryIds,cursor:f})},async markRecoveryRequired(f){await rt(o)||await vo(yl(n),{schemaVersion:Et,reason:dw(f),createdAt:new Date().toISOString()})},async clearRecoveryRequired(){await _e.rm(yl(n),{force:!0})},async readTransactionJournal(){return await rt(i)?fs(i):null},async writeTransactionJournal(f){await d(),xh(f);try{await vo(i,f)}catch(u){let g=await fs(i).catch(()=>null);if(g&&Buffer.from(dt(g)).equals(Buffer.from(dt(f))))return;throw g?new oe(te.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous",{cause:u}):u}let m=await fs(i);if(!Buffer.from(dt(m)).equals(Buffer.from(dt(f))))throw new oe(te.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous")},async clearTransactionJournal(f){let m=await rt(i)?await fs(i):null;if(m&&m.transactionId!==f)throw new oe(te.INVALID_SCHEMA,"transaction journal changed concurrently");try{await _e.rm(i,{force:!0})}catch(u){if(!await rt(i))return;throw u}if(await rt(i))throw new oe(te.INDEX_CORRUPT,"transaction journal clear outcome is ambiguous");s=!1},async cleanupTmp(){await d();for(let m of l)await gs(n,m),l.delete(m);await rw(n);let f=await ut(n);await Eo(n,f.entryIds)}}}async function th(e,t,n,r){ms(n,"entryId");let o=await ut(e);kl(o,r);let i=await Io(e,n),s=[...o.entryIds];o.cursor<s.length-1&&s.splice(o.cursor+1),s.push(i.id);let a=await fh(e,s,t);return{current:o,entryIds:a.entryIds,cursor:a.cursor,transition:dh(o,a.entryIds,a.cursor)}}function dh(e,t,n){return bl(n,t.length),{expectedIndexDigest:e.digest,publishedIndexDigest:YN(t,n),publishedCursor:n,publishedCurrentId:t[n]??null}}function YN(e,t){return gn(dt({schemaVersion:Et,entryIds:e,cursor:t}))}function bl(e,t){if(!Number.isInteger(e)||e<-1||e>=t)throw new oe(te.INVALID_SCHEMA,`history cursor is out of bounds: ${e}`)}function ZN(e){if(!wt(e))return!1;let t=e.publishedCursor,n=e.publishedCurrentId;return!ft(e.expectedIndexDigest)||!ft(e.publishedIndexDigest)||!Number.isInteger(t)||t<-1||n!==null&&!ft(n)?!1:t===-1?n===null:ft(n)}async function nh(e,t){if(!e.kind.trim())throw new oe(te.INVALID_JSON,"history entry kind must not be empty");let n=[],r=[];for(let c of e.blobs??[]){if(!c.name.trim())throw new oe(te.INVALID_JSON,"history blob name must not be empty");let l=cw(c.data),d=gn(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:Et,kind:e.kind,manifest:e.manifest,blobs:r},i=dt({...o}),s=gn(i),a=i.byteLength+n.reduce((c,l)=>c+l.sizeBytes,0);if(a>t.maxEntryBytes)throw new oe(te.CAPACITY_EXCEEDED,`history entry exceeds maxEntryBytes (${a} > ${t.maxEntryBytes})`);return{entryBody:o,entryId:s,blobs:n}}async function rh(e,t){let n=Ol(e,t.entryId),r={id:t.entryId,...t.entryBody},o=[...t.blobs.map(a=>oh(Ml(e,a.digest),a.bytes,{kind:"blob",digest:a.digest},Ll(e,a.digest))),oh(n,dt(r),{kind:"entry",digest:t.entryId},Dl(e,t.entryId))],s=(await Promise.allSettled(o)).find(a=>a.status==="rejected");if(s)throw s.reason}async function oh(e,t,n,r){let o=await Rl(e)??(r?await Rl(r):null);if(o!==null){if(Buffer.compare(o,t)!==0)throw new oe(n.kind==="blob"?te.BLOB_CORRUPT:te.ENTRY_CORRUPT,`${n.kind} content mismatch for ${n.digest}`);return}await gh(e,t)}async function fh(e,t,n){let r=[...t],o=r.length-1;for(;;){if((await mh(e,r)).totalBytes<=n.maxSessionBytes&&r.length<=n.maxEntries)return{entryIds:r,cursor:o};if(o<=0||r.length===0)throw new oe(te.CAPACITY_EXCEEDED,"history store exceeds capacity limits and the current entry cannot be trimmed");r.shift(),o-=1}}async function QN(e,t,n){Pl(t);let r=_l(e,t.stageId);if(n){await vo(r,t);return}await aw(r,t)}async function Sl(e,t){let n=await Rl(_l(e,t));if(n===null)return null;let r=Co(Buffer.from(n).toString("utf8"),`history stage ${t}`),o=Pl(r);if(o.stageId!==t)throw new oe(te.INVALID_SCHEMA,`history stage id mismatch: ${t}`);return o}async function xs(e){let t=[];for(let n of await ys(Fl(e))){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);vl(r);let o=await Sl(e,r);o&&t.push(o)}return t}async function ih(e,t){Pl(t);let n=await ut(e),r=(await xs(e)).filter(s=>s.stageId!==t.stageId),o=new Set(n.entryIds),i=new Set;for(let s of n.entryIds){let a=await Io(e,s);for(let c of a.blobs)i.add(c.digest)}for(let s of r){o.add(s.entryId);for(let a of s.blobIds)i.add(a)}o.has(t.entryId)||await sh(Ol(e,t.entryId),Dl(e,t.entryId));for(let s of t.blobIds)i.has(s)||await sh(Ml(e,s),Ll(e,s));await gs(e,t.stageId),await Nl(Ro(e)),await Nl(No(e))}async function gs(e,t){await El(_l(e,t)),await qN(e)}async function qN(e){try{await _e.rmdir(Fl(e))}catch(t){if(wo(t)||wt(t)&&t.code==="ENOTEMPTY")return;throw t}}async function ew(e,t){for(let n of await xs(e))n.entryId===t&&await gs(e,n.stageId)}async function El(e){if(await _e.rm(e,{force:!0}),await rt(e))throw new oe(te.INDEX_CORRUPT,`unable to remove staged history object: ${e}`)}async function sh(e,t){await El(e),await El(t)}function Pl(e){if(!wt(e)||e.schemaVersion!==xl||typeof e.stageId!="string"||!ph(e.stageId)||!ft(e.entryId))throw new oe(te.INVALID_SCHEMA,"history stage schema is invalid");let t=hh(e.blobIds,"history stage blobIds");return{schemaVersion:xl,stageId:e.stageId,entryId:e.entryId,blobIds:t}}function vl(e){if(!ph(e))throw new oe(te.INVALID_PATH,"history stageId must be a UUID")}function ph(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 Eo(e,t){let n=new Set(t),r=new Set;for(let c of t){let l=await Io(e,c);for(let d of l.blobs)r.add(d.digest)}for(let c of await xs(e)){n.add(c.entryId);for(let l of c.blobIds)r.add(l)}let o=Ro(e),i=await ys(o);for(let c of i){if(!c.endsWith(".json"))continue;let l=lh(c.slice(0,-5));l&&!n.has(l)&&await hs(Me.join(o,c))}let s=No(e),a=await ys(s);for(let c of a){let l=lh(c);l&&!r.has(l)&&await hs(Me.join(s,c))}}async function ut(e){let t=bs(e),n=await mn(t,te.NOT_FOUND,"index"),r=Co(Buffer.from(n).toString("utf8"),"index"),o=ow(r),i=[...o.entryIds],{totalBytes:s}=await mh(e,i),a=i.slice(0,o.cursor+1).reverse(),c=i.slice(o.cursor+1);return{schemaVersion:Et,digest:o.digest,entryIds:i,cursor:o.cursor,currentId:i[o.cursor]??null,undoIds:a,redoIds:c,totalBytes:s}}async function mh(e,t){let n=0,r=new Set,o=bs(e),i=await mn(o,te.NOT_FOUND,"index");n+=i.byteLength;for(let s of t){let a=await Io(e,s),c=await bh(e,s),l=await mn(c,te.NOT_FOUND,"entry");n+=l.byteLength;for(let d of a.blobs){if(r.has(d.digest))continue;r.add(d.digest);let f=await Bl(e,d.digest),m=await mn(f,te.NOT_FOUND,"blob");Tl(m,d.digest,f),n+=m.byteLength}}return{totalBytes:n}}async function Io(e,t){let n=await bh(e,t),r=await mn(n,te.NOT_FOUND,"entry"),o=Co(Buffer.from(r).toString("utf8"),`entry ${t}`),i=iw(o);if(i.id!==t)throw new oe(te.ENTRY_CORRUPT,`entry id mismatch for ${t}`);if(gn(dt({schemaVersion:i.schemaVersion,kind:i.kind,manifest:i.manifest,blobs:i.blobs}))!==t)throw new oe(te.ENTRY_CORRUPT,`entry hash mismatch for ${t}`);for(let a of i.blobs){let c=await Bl(e,a.digest),l=await mn(c,te.NOT_FOUND,"blob");Tl(l,a.digest,c)}return i}async function Al(e,t,n){let r={schemaVersion:Et,digest:gn(dt({schemaVersion:Et,entryIds:t,cursor:n})),entryIds:t,cursor:n};await vo(bs(e),r)}function kl(e,t){if(t!==void 0&&e.digest!==t)throw new oe(te.INVALID_SCHEMA,`history index changed concurrently (expected ${t}, current ${e.digest})`)}async function ah(e){let t=gn(dt({schemaVersion:Et,entryIds:e.entryIds,cursor:e.cursor}));try{return await Al(e.rootDir,e.entryIds,e.cursor),await e.afterWrite?.(),await ut(e.rootDir)}catch(n){let r=await ut(e.rootDir).catch(()=>null);if(r?.digest===t)return r;throw r?.digest===e.previousDigest?n:new oe(te.INDEX_CORRUPT,"history index publish outcome is ambiguous",{cause:n})}}async function tw(e){await _e.mkdir(e,{recursive:!0}),await _e.mkdir(Ro(e),{recursive:!0}),await _e.mkdir(No(e),{recursive:!0}),await _e.mkdir(ko(e),{recursive:!0})}async function nw(e){await _e.rm(ko(e),{recursive:!0,force:!0}),await _e.mkdir(ko(e),{recursive:!0})}async function rw(e){let t=ko(e);await _e.mkdir(t,{recursive:!0});for(let n of await ys(t))n!=="stages"&&await _e.rm(Me.join(t,n),{recursive:!0,force:!0})}function ow(e){if(!wt(e))throw new oe(te.INDEX_CORRUPT,"index.json must be an object");if(e.schemaVersion!==Et)throw new oe(te.INVALID_SCHEMA,`unsupported index schemaVersion: ${String(e.schemaVersion)}`);let t=hh(e.entryIds,"index.entryIds"),n=e.cursor;if(!Number.isInteger(n)||n<-1||n>=t.length)throw new oe(te.INDEX_CORRUPT,"index cursor is out of bounds");let r=n,o=e.digest;if(!ft(o))throw new oe(te.INDEX_CORRUPT,"index digest is invalid");let i=gn(dt({schemaVersion:Et,entryIds:t,cursor:r}));if(o!==i)throw new oe(te.INDEX_CORRUPT,"index digest mismatch");return{schemaVersion:Et,digest:o,entryIds:t,cursor:r}}function iw(e){if(!wt(e))throw new oe(te.ENTRY_CORRUPT,"entry must be an object");if(e.schemaVersion!==Et)throw new oe(te.INVALID_SCHEMA,`unsupported entry schemaVersion: ${String(e.schemaVersion)}`);let t=e.id;if(!ft(t))throw new oe(te.ENTRY_CORRUPT,"entry id is invalid");let n=e.kind;if(typeof n!="string"||n.trim().length===0)throw new oe(te.ENTRY_CORRUPT,"entry kind is invalid");let r=Cl(e.manifest,"entry.manifest"),o=sw(e.blobs);return{id:t,schemaVersion:Et,kind:n,manifest:r,blobs:o}}function sw(e){if(!Array.isArray(e))throw new oe(te.ENTRY_CORRUPT,"entry blobs must be an array");return e.map((t,n)=>{if(!wt(t))throw new oe(te.ENTRY_CORRUPT,`entry blob ref ${n} must be an object`);let r=t.name;if(typeof r!="string"||r.trim().length===0)throw new oe(te.ENTRY_CORRUPT,`entry blob ref ${n} name is invalid`);let o=t.digest;if(!ft(o))throw new oe(te.ENTRY_CORRUPT,`entry blob ref ${n} digest is invalid`);let i=t.sizeBytes;if(!Number.isInteger(i)||i<0)throw new oe(te.ENTRY_CORRUPT,`entry blob ref ${n} sizeBytes is invalid`);return{name:r,digest:o,sizeBytes:i}})}async function vo(e,t){await gh(e,dt(t))}async function aw(e,t){let n=Me.dirname(e),r=Me.basename(e),o=Me.join(n,`.${r}.${process.pid}.${wl()}.tmp`);await _e.mkdir(n,{recursive:!0});try{await _e.writeFile(o,dt(t),{flag:"wx"}),await _e.rename(o,e)}finally{await hs(o)}}async function gh(e,t){let n=Me.dirname(e),r=Me.basename(e),o=Me.join(n,`.${r}.${process.pid}.${wl()}.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 Nl(n)}finally{await hs(o)}}function dt(e){return Buffer.from(JSON.stringify(Il(e)),"utf8")}function Il(e){if(Array.isArray(e))return e.map(t=>Il(t));if(wt(e)){let t={};for(let n of Object.keys(e).sort())t[n]=Il(e[n]);return t}return e}function Co(e,t){try{return JSON.parse(e)}catch(n){throw new oe(te.INVALID_JSON,`${t} is not valid JSON`,{cause:n})}}function Cl(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=>Cl(n,t));if(wt(e)){let n={};for(let[r,o]of Object.entries(e))n[r]=Cl(o,t);return n}break}throw new oe(te.INVALID_JSON,`${t} must be JSON-serializable`)}function hh(e,t){if(!Array.isArray(e))throw new oe(te.INDEX_CORRUPT,`${t} must be an array`);return e.map((n,r)=>{if(!ft(n))throw new oe(te.INDEX_CORRUPT,`${t}[${r}] is invalid`);return n})}function ms(e,t){if(!ft(e))throw new oe(te.INVALID_PATH,`${t} must be a sha256 digest`)}function ft(e){return typeof e=="string"&&/^sha256:[a-f0-9]{64}$/u.test(e)}function gn(e){return`sha256:${JN("sha256").update(e).digest("hex")}`}function cw(e){return typeof e=="string"?Buffer.from(e,"utf8"):Buffer.from(e)}async function mn(e,t,n){try{return await _e.readFile(e)}catch(r){throw new oe(t,`${n} not found: ${e}`,{cause:r})}}async function Rl(e){try{return await _e.readFile(e)}catch(t){if(wo(t))return null;throw t}}function Tl(e,t,n){if(gn(e)!==t)throw new oe(te.BLOB_CORRUPT,`blob hash mismatch for ${n}`)}async function rt(e){try{return await _e.access(e),!0}catch(t){if(wo(t))return!1;throw t}}async function hs(e){try{await _e.rm(e,{force:!0,recursive:!0})}catch{}}async function Nl(e){try{let t=await _e.open(e,"r");try{await t.sync()}finally{await t.close()}}catch{}}async function ys(e){try{return await _e.readdir(e)}catch(t){if(wo(t))return[];throw t}}function lw(e){if(typeof e!="string"||e.trim().length===0)throw new oe(te.INVALID_ROOT,"history store rootDir must be a non-empty string");return Me.resolve(e)}function bs(e){return Me.join(e,zN)}function yl(e){return Me.join(e,WN)}function uw(e){return Me.join(e,HN)}function yh(e){return Me.join(e,GN)}async function ch(e){try{let t=await _e.readFile(yh(e),"utf8"),n=Co(t,"document version");if(!wt(n)||n.schemaVersion!==1||!Number.isInteger(n.version)||n.version<0)throw new oe(te.INVALID_SCHEMA,"document version schema is invalid");return n.version}catch(t){if(wo(t))return 0;throw t}}async function fs(e){let t=await mn(e,te.RECOVERY_PENDING,"transaction journal"),n=Co(Buffer.from(t).toString("utf8"),"transaction journal");return xh(n),n}function xh(e){if(!wt(e)||e.schemaVersion!==XN||typeof e.transactionId!="string"||e.transactionId.length===0||typeof e.operationId!="string"||e.operationId.length===0||!["prepared","files-written","history-published"].includes(e.phase)||!ZN(e.historyTransition)||!Array.isArray(e.files))throw new oe(te.INVALID_SCHEMA,"transaction journal schema is invalid");for(let t of e.files)if(!wt(t)||typeof t.path!="string"||t.path.length===0||t.preDigest!==null&&!ft(t.preDigest)||t.postDigest!==null&&!ft(t.postDigest))throw new oe(te.INVALID_SCHEMA,"transaction journal file digest is invalid")}function dw(e){return e.replace(/[\r\n]+/g," ").slice(0,512)}function Ro(e){return Me.join(e,"entries")}function No(e){return Me.join(e,"blobs")}function ko(e){return Me.join(e,"tmp")}function Fl(e){return Me.join(ko(e),"stages")}function _l(e,t){return Me.join(Fl(e),`${t}.json`)}function Ol(e,t){return Me.join(Ro(e),`${Eh(t)}.json`)}function Ml(e,t){return Me.join(No(e),Eh(t))}function Dl(e,t){return Me.join(Ro(e),`${t}.json`)}function Ll(e,t){return Me.join(No(e),t)}async function bh(e,t){return Sh(Ol(e,t),Dl(e,t))}async function Bl(e,t){return Sh(Ml(e,t),Ll(e,t))}async function Sh(e,t){return await rt(e)?e:await rt(t)?t:e}function Eh(e){return e.slice(7)}function lh(e){let t=e.startsWith("sha256:")?e:`sha256:${e}`;return ft(t)?t:null}function wt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function wo(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function fw(e){return{maxEntries:e?.maxEntries??ps.maxEntries,maxSessionBytes:e?.maxSessionBytes??ps.maxSessionBytes,maxEntryBytes:e?.maxEntryBytes??ps.maxEntryBytes}}async function pw(e){let t=bs(e);await rt(t)||await Al(e,[],-1)}export{oe as FileHistoryStoreError,Kr as PageTemplateManagedSourceError,ds as PreviewFileSystemSiteEditEngineRuntime,_d as SITE_EDIT_RAW_COLOR_LITERAL_RE,ls as SnapshotSiteEditEngineRuntime,Cf as computeManagedPageTemplatePaths,UN as createPreviewSiteEditEngineRuntime,jN as createSiteEditEngineRuntime,vf as decodePageTemplateKey,Ua as encodePageTemplateId,sy as instrumentSiteEditRuntimeAttributes,Rf as isManagedPageTemplateSourcePath,uh as openFileHistoryStore,Zh as parseSourceModule,Qh as resolveImportBase,Mv as resolveManagedPageTemplateComposition,Ci as scanManagedPageTemplateCandidates,wf as scanSiteEditCompositionsFromFiles,Mr as scanSiteEditThemeStyleViolations};
|
|
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 So(e){let t="idle",n=e.fileSystem??nN(),r=md(),o=Pg({compositions:e.compositions,initialDocumentVersions:e.initialDocumentVersions}),i=new Map,s=new Map,a=new Set,c=null,l=e.history??(e.historyStore?Pd(e.historyStore):oN()),d=Ng(n,{externalAdapters:e.externalAdapters}),f=new Map,m=new Set,u=0,g=e.historyStore?.recoveryRequired??!1,h=ul(),b=R();function E(p){return(cs.isAbsolute(p)?cs.relative(e.projectRoot,p):p).replace(/\\/g,"/").replace(/^\.\//,"")}function v(p,y){let x=cs.posix.dirname(p),k=y.replace(/\.(?:tsx?|jsx?)$/i,""),w=cs.posix.relative(x,k);return w.startsWith(".")?w:`./${w}`}function I(p,y){return p.startLine===y.startLine&&p.startColumn===y.startColumn&&p.endLine===y.endLine&&p.endColumn===y.endColumn}async function R(){let p=e.historyStore;if(p)try{let y=await p.readTransactionJournal();if(!y)return;let x=await p.readIndex(),k=await Promise.all(y.files.map(async _=>await n.exists(_.path)?Ee(await n.readFile(_.path)):null));if($g({journal:y,index:x,observedFileDigests:k})!=="ambiguous"){await p.clearTransactionJournal(y.transactionId);let _=await p.readStatus();_.recoveryRequired||(await p.cleanupTmp(),_=await p.readStatus()),g=_.recoveryRequired;return}await p.markRecoveryRequired(`Ambiguous transaction journal ${y.transactionId} at phase ${y.phase}`),g=!0}catch(y){g=!0,await p.markRecoveryRequired(`Transaction journal recovery failed: ${Qe(y)}`).catch(()=>{})}}function A(){return t==="disposed"}e.onEvent&&r.subscribe(e.onEvent);for(let p of o.entries){let y=Xg(p.context,p.entryFile);i.set(p.key,y),T(y,y.dependencyFiles)}function T(p,y){let x=new Set(y);C(p),p.dependencyFiles=x;for(let k of p.dependencyFiles){let w=s.get(k);w||(w=new Set,s.set(k,w)),w.add(p.key)}}function C(p){for(let y of p.dependencyFiles){let x=s.get(y);x&&(x.delete(p.key),x.size===0&&s.delete(y))}p.dependencyFiles.clear()}function P(p){let y=new Set;for(let x of p)for(let k of s.get(x)??[])y.add(k);return y}function O(p){for(let y of p)if(!s.has(y))return!1;return!0}async function L(p,y,x,k,w){let _=new Map,M=Hm(w.values()),H=new Map,X=typeof n.exists=="function"?D=>n.exists(D):async()=>!1;for(let[D,B]of p.elements){let se=y.nodes.get(D);if(!se)continue;let ne=x.get(B.sourceFile)??k.get(B.sourceFile),we=new Map,ye=new Map,ke=new Map,Ie=[];for(let Se of B.textSegments){if(!ne){we.set(Se.index,null);continue}let Er=await Wm({file:B.sourceFile,source:ne,segment:Se,readFile:it=>n.readFile(it),exists:X,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:it,adapterId:yn,capabilities:Ns})=>({sourceType:it,adapterId:yn,capabilities:Ns})),functionCallContracts:e.functionCallContracts,fileCache:M}),Ze=await el({file:B.sourceFile,source:ne,target:{kind:"text-segment",segment:Se},readFile:it=>n.readFile(it),exists:X,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:it,adapterId:yn,capabilities:Ns})=>({sourceType:it,adapterId:yn,capabilities:Ns})),functionCallContracts:e.functionCallContracts,fileCache:M}),pt=mN(Er);we.set(Se.index,pt),ye.set(Se.index,Er),ke.set(Se.index,Ze),Ie.push({editable:Se.editable,source:pt})}let F=new Map,V=new Map;if(ne)for(let Se of B.attributes??[]){let Er=await xr({file:B.sourceFile,source:ne,sourceRange:Se.sourceRange,expression:Se.source?.expression??Se.value,sourceInfo:Se.source,readFile:pt=>n.readFile(pt),exists:X,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:pt,adapterId:it,capabilities:yn})=>({sourceType:pt,adapterId:it,capabilities:yn})),functionCallContracts:e.functionCallContracts,fileCache:M}),Ze=await ng({element:B,file:B.sourceFile,source:ne,propertyName:Se.name,readFile:pt=>n.readFile(pt),exists:X,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:pt,adapterId:it,capabilities:yn})=>({sourceType:pt,adapterId:it,capabilities:yn})),functionCallContracts:e.functionCallContracts,fileCache:M});V.set(Se.name,Ze),F.set(Se.name,Er)}let pe=pg(gN(se.writeTarget),Ie),ie=rg({key:D,element:B,graph:p,provenances:ke}),Pe=xg(B),Le=ne?await Zp({element:B,graph:p,file:B.sourceFile,source:ne,readFile:Se=>n.readFile(Se),exists:X,fileCache:H}):void 0,ot=p.regions.find(Se=>Se.kind==="conditional-region"&&Se.childKeys.includes(D)),Qt,We=ot?.sourceCandidates?.[0];if(ne&&ot&&We?.kind==="conditional-branch"){let Se=await el({file:B.sourceFile,source:ne,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:pt,capabilities:it})=>({sourceType:Ze,adapterId:pt,capabilities:it})),functionCallContracts:e.functionCallContracts,fileCache:M});Qt={currentBranch:ot.childKeys.indexOf(D)<=0?"then":"else",availableBranches:ot.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}))}}}_.set(D,{textSources:we,textTargets:ye,elementPropertyTargets:F,propertyProvenances:V,isRepeat:ON(D,p),provenances:ke,writeTarget:pe,componentSemantic:ie,styleSource:Pe,conditional:Qt,dynamicData:Le})}return _}function U(p){return typeof n.getVersion=="function"?n.getVersion(p):0}function ee(p,y){let x=o.initialVersions.get(p.key)??0;for(let k of y.values())x=Math.max(x,k);return Math.max(x,p.graph?.version??0)}function Ne(p){return i.get(p)?.graph?.version??o.initialVersions.get(p)??0}function Q(p){try{return Ne(o.resolveSelector(p.composition).key)}catch{return 0}}async function fe(p,y,x={}){let k=i.get(p);if(!k)return null;let w=x.sourceCache??pl(f,[]),_=await Oe(k.entryFile),{graph:M,allSources:H,diagnostics:X,parsedModules:D,entryModule:B}=await kd(k.entryFile,y,We=>n.readFile(We),typeof n.exists=="function"?We=>n.exists(We):async()=>!1,{additionalEntries:_,version:k.graph?.version??1});if(X.length>0)throw new yo(X);let se=new Map;for(let We of H.keys())se.set(We,U(We));let ne=Math.max(ee(k,se),x.minimumVersion??0);x.changed&&ne<=(k.graph?.version??0)&&(ne=(k.graph?.version??0)+1),M.version=ne;for(let[We,Se]of H)ml(w,We,Se,Kg);let we=await Yt(k.composition,k.entryFile,H,w);M.routeId=k.routeId,M.composition=k.composition;let ye=bg(M),ke=ld(ye,M),Ie=await L(M,ye,H,w,D),F=kh(M,ke,Ie),V=vh(Ie),pe=Fg(cg(M,ye,ke,{canUpdateTextByKey:F,dynamicDataSummaryByKey:V}),M,Ie),ie=pf({route:k.routeId,composition:k.composition,entryFile:k.entryFile,version:ne,source:y,ast:B?.ast}),Pe=mf(ie);ie.ok&&SN(pe,M,ie.projection,D);let Le={...pe,composition:k.composition,...we?{styleContext:we}:{},pageComposition:Pe},ot=new Set([k.entryFile,...H.keys()]);if(we){ot.add(we.entryCss.path);for(let We of we.stylesheets)ot.add(We.path)}let Qt={...k,dependencyFiles:ot,graph:M,topology:ye,capabilities:ke,document:Le,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:Tg(Le),detailProjections:Ie,fileVersions:se,styleContext:we};if(x.publish===!1)return Qt;br(f,w);for(let We of w.keys())m.delete(We);return T(k,ot),Object.assign(k,Qt),k}async function Oe(p){let y=[];for(let x of wN(p))typeof n.exists=="function"&&await n.exists(x)&&y.push({file:x,source:await n.readFile(x)});return y}async function Yt(p,y,x,k){let w=[];for(let[D,B]of x){if(gl(D)){w.push(D);continue}for(let se of AN(B)){let ne=Zg(D,se);ne&&w.push(ne)}}if(!w.length){for(let D of PN(y))if(await jl(D)){w.push(D);break}}let _=new Map,M=_N(w).slice(0,Vg);for(;M.length>0&&_.size<Vg;){let D=M.shift();if(_.has(D)||!gl(D))continue;let B=await Zt(D,k);if(B!==null){_.set(D,{path:D,content:B});for(let se of TN(B)){let ne=Zg(D,se);ne&&!_.has(ne)&&!M.includes(ne)&&M.push(ne)}}}let H=[..._.values()].map(D=>({...D,hash:Ee(D.content)})),X=H[0];return X?{composition:p,revision:Ee(JSON.stringify(H.map(({path:D,hash:B})=>({path:D,hash:B})))),entryCss:X,stylesheets:H.slice(1)}:null}async function Zt(p,y){let x=y.get(p);if(x!==void 0)return x;if(!await jl(p))return null;let k=await n.readFile(p);return ml(y,p,k,Kg),k}async function jl(p){return typeof n.exists=="function"?n.exists(p):!1}function vh(p){let y=new Map;for(let[x,k]of p)k.dynamicData?.bindings.length&&y.set(x,cm(k.dynamicData.bindings));return y}function kh(p,y,x){let k=new Map;for(let[w,_]of p.elements){if(!y.get(w)?.canUpdateText){k.set(w,!1);continue}let H=x.get(w),X=_.textSegments.some(D=>{if(!D.editable)return!1;let B=H?.provenances.get(D.index)??null;return!B||Ih(B)});k.set(w,X)}return k}function Ih(p){return p.editMode==="direct"||p.editMode==="proxy"||p.editMode==="upstream"}async function Po(p,y={}){let x=[...new Set(p)],k=y.affectedCompositionKeys!==void 0,w=k?new Set(y.affectedCompositionKeys):P(x);if(!k&&(w.size===0||!O(x)))for(let X of i.values())$l(X,x)&&w.add(X.key);let _=!k&&w.size===0&&x.some(Yg),M=y.publish===!1?pl(f,x):void 0,H={rebuiltRoutes:[],failedRoutes:[],...y.publish===!1?{candidateRouteStates:[],candidateSourceCache:M}:{}};for(let X of i.values())if(!(y.excludedCompositionKeys?.has(X.key)||!(w.has(X.key)||_)))try{let B=!!X.graph,se=await n.readFile(X.entryFile),ne=await fe(X.key,se,{...y,...M?{sourceCache:M}:{}});ne?.graph&&(H.rebuiltRoutes.push({documentChanged:B,composition:X.composition,routeId:X.routeId,version:ne.graph.version}),H.candidateRouteStates?.push({composition:X.composition,key:X.key,routeId:X.routeId,state:ne}))}catch(B){H.failedRoutes.push({...Bg(X.routeId,B),composition:X.composition})}return H}function Un(p){let y=[...new Set(p)],x=P(y);if(x.size>0&&O(y))return[...x];for(let k of i.values())$l(k,y)&&x.add(k.key);return[...x]}function Ch(p){let y=new Set(Un(p));return o.entries.filter(x=>y.has(x.key)).map(x=>x.context)}function Rh(p){return[...new Set(Un(p))].sort((x,k)=>x<k?-1:x>k?1:0).map(x=>o.getByKey(x)?.context).filter(x=>x!==void 0)}function Nh(p,y){let x=new Set(Un(y)),k=p.provenance?.affectedCompositions??[];if(k.length===0)return x;if([...new Set(k.map(_=>o.resolveContext(_).key))].some(_=>!x.has(_)))throw new Error("History provenance does not match the affected composition index.");return x}function wh(p,y){let x=p.composition??p.provenance?.initiatingComposition;if(x){let _=o.resolveContext(x);return{context:_.context,key:_.key}}let k=[...new Set(Un(y))];if(k.length!==1)throw new Error(`Legacy history entry cannot be attributed to a unique composition (affected composition count: ${k.length}).`);let w=o.getByKey(k[0]);if(!w)throw new Error("Legacy history entry references an unknown affected composition.");return{context:w.context,key:w.key}}function Es(p,y){r.emit({type:"operation-completed",composition:p.composition,result:p});for(let{composition:x,version:k}of y.rebuiltRoutes)r.emit({type:"document-changed",composition:x,version:k});for(let{composition:x,message:k}of y.failedRoutes)r.emit({type:"graph-error",composition:x,message:k})}function $l(p,y){return y.some(x=>p.dependencyFiles.has(x)||p.entryFile===x||p.graph?.fileIndex.has(x))}function Vl(p){for(let y of p)a.add(y);c||A()||(c=(async()=>{t="building";let y=!1;try{for(;a.size>0;){if(A())return;await Ph();let x=[...a];a.clear();let k=await Kl(x);if(k.length===0)continue;let w=Un(k);for(let H of w){let X=i.get(H)?.composition;X&&r.emit({type:"graph-invalidated",composition:X})}let{rebuiltRoutes:_,failedRoutes:M}=await Po(k,{changed:!0});for(let{documentChanged:H,composition:X,version:D}of _)r.emit({type:"graph-ready",composition:X,version:D}),H&&r.emit({type:"document-changed",composition:X,version:D});for(let{composition:H,message:X}of M)y=!0,r.emit({type:"graph-error",composition:H,message:X})}}finally{c=null,t!=="disposed"&&(t=!y&&[...i.values()].some(x=>x.graph)?"ready":"idle"),a.size>0&&Vl([])}})())}async function Ph(){for(;u>0;)await new Promise(p=>setTimeout(p,0))}async function Kl(p){let y=[];for(let x of new Set(p)){let k=f.get(x);if(k===void 0){if(m.has(x)&&!await n.exists(x))continue;m.delete(x),y.push(x);continue}try{await n.readFile(x)!==k&&(m.delete(x),y.push(x))}catch(w){if(!bN(w))try{if(await n.exists(x))continue}catch{continue}m.add(x),y.push(x)}}return y}function Ul(p){jg(f,p);for(let y of p)y.exists===!1?m.add(y.file):m.delete(y.file)}function Jl(p){m.clear();for(let y of p)m.add(y)}async function Xl(p){let y=await Kl(p);if(y.length===0)return;let x=Un(y);for(let _ of x){let M=i.get(_)?.composition;M&&r.emit({type:"graph-invalidated",composition:M})}let{rebuiltRoutes:k,failedRoutes:w}=await Po(y,{changed:!0});for(let{documentChanged:_,composition:M,version:H}of k)r.emit({type:"graph-ready",composition:M,version:H}),_&&r.emit({type:"document-changed",composition:M,version:H});for(let{composition:_,message:M}of w)r.emit({type:"graph-error",composition:_,message:M})}async function Ah(p,y){let x=zn(p,y);if(!x?.graph)return;let k=nt(p)??p,w=x.graph.elements.get(k);w&&await Xl([w.sourceFile])}async function zl(p){let y=new Set;if(p.target.kind==="node"){let x=zn(p.target.key,p.composition),k=nt(p.target.key)??p.target.key,w=x?.graph?.elements.get(k);w&&y.add(w.sourceFile)}else if(p.target.kind==="route"){let x=i.get(o.resolveSelector(p.target.composition).key);x&&y.add(x.entryFile)}else if(p.target.kind==="page-unit"){let x=i.get(o.resolveSelector(p.target.composition).key);x&&y.add(x.entryFile)}else if(p.target.kind==="source-file")y.add(p.target.path);else if(p.target.kind==="source-batch")for(let x of p.target.paths)y.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 k of x){let w=zn(k,p.composition),_=nt(k)??k,M=w?.graph?.elements.get(_);M&&y.add(M.sourceFile)}}await Xl(y)}async function Th(p){if(p.params.kind!=="source-edit")return vs(p,"invalid-params","source-edit requires source-edit params");for(let y of p.params.edits){let x=xN(y);if(!x.ok)return vs(p,x.errorCode,x.message,x.details)}u+=1;try{let y=await Lh(p.params.edits);if(!y.ok)return vs(p,y.errorCode,y.message,y.details);await zl(p);let x={operationId:p.id,kind:"source-edit",target:p.target,documentVersion:p.documentVersion,conflictPolicy:p.params.conflictPolicy,edits:p.params.edits.map(k=>k.operation==="delete"?{operation:"delete",file:k.path,baseContentHash:k.baseContentHash??null}:{operation:"upsert",file:k.path,baseContentHash:k.baseContentHash??null,content:k.content})};return await Xn({request:p,filePlan:x})}catch(y){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(y)}}}finally{u-=1}}async function Fh(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 y=await _o({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:[...p.params.artifact.components.flatMap(k=>k.materialization.files.map(w=>({path:w.pathTemplate,content:w.content}))),...p.params.artifact.pages.flatMap(k=>k.materialization.files.map(w=>({path:w.pathTemplate,content:w.content})))],exists:k=>n.exists(k),readFile:k=>n.readFile(k)});if(!y.ok)return le(p,$.MATERIALIZATION_REJECTED,y.message);let x=await va({artifact:p.params.artifact,exists:k=>n.exists(k)});return x.ok?await Xn({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:p.target,documentVersion:p.documentVersion,conflictPolicy:"overwrite",edits:x.files},output:{kind:"insert-page-resource",package_instance_id:x.packageInstanceId,pages:x.pages},historyPolicy:"none"}):le(p,x.code==="MATERIALIZATION_CONFLICT"?$.MATERIALIZATION_CONFLICT:$.MATERIALIZATION_REJECTED,x.message,x.path?{path:x.path}:void 0)}catch(y){return le(p,$.INTERNAL_ERROR,Qe(y))}finally{u-=1}}async function _h(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 y=Qg(await n.listFiles({maxFiles:5e4,maxDepth:64}));if(y.truncated)return le(p,$.PLAN_FAILED,"Project file listing is incomplete; page deletion was refused.",{truncationReasons:y.truncated.reasons});let x=y.files.filter(({path:M})=>/\.(?:tsx?|jsx?)$/.test(M)),k=Object.fromEntries(await Promise.all(x.map(async({path:M})=>[M,await n.readFile(M)]))),w=Df({expectedUrlPath:p.params.expectedUrlPath,files:k});if(!w.ok)return le(p,w.code==="HOME_PAGE_LOCKED"?$.HOME_PAGE_LOCKED:w.code==="ROUTE_NOT_FOUND"?$.ROUTE_NOT_FOUND:$.PLAN_FAILED,w.message);let _=await Promise.all(w.edits.map(async M=>({...M,baseContentHash:Ee(await n.readFile(M.file))})));return Xn({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:p.target,documentVersion:p.documentVersion,conflictPolicy:"compare-and-swap",edits:_},output:{kind:"delete-page-source",deleted_files:w.deletedFiles,updated_files:w.updatedFiles,preserved_shared_files:w.preservedSharedFiles,warnings:w.warnings},historyPolicy:"none"})}catch(y){return le(p,$.INTERNAL_ERROR,Qe(y))}finally{u-=1}}async function Oh(p,y){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 x=y.document,k=y.pageCompositionProjection;if(!x||x.pageComposition?.status!=="supported"||!k||k.status!=="supported")return le(p,$.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(p.documentVersion!==x.version||k.documentVersion!==x.version)return le(p,$.VERSION_STALE,`Document version ${p.documentVersion} is stale (current: ${x.version}).`);let w=p.params.node.kind==="component-call"?p.params.node.materialization:void 0;if(!w)return le(p,$.UNSUPPORTED_OPERATION,"Page-unit insertion currently requires a static materialization manifest.");let _=p.params.kind==="insert-child"?p.params.position:null,M=await _o({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:w.files.map(D=>({path:D.pathTemplate,content:D.content})),exists:D=>n.exists(D),readFile:D=>n.readFile(D)});if(!M.ok)return le(p,$.MATERIALIZATION_REJECTED,M.message);let H=await rN(n,Object.keys(w.projectDependencies??{})),X=await Yd({manifest:w,generatedRoot:"components/site/generated",controlledFiles:w.files.map(D=>({pathTemplate:D.pathTemplate})),exists:D=>n.exists(D),availableHostDependencies:H,commit:async D=>{let B=await n.readFile(y.entryFile),se=y.document,ne=y.pageCompositionProjection;if(!se||se.pageComposition?.status!=="supported"||se.version!==p.documentVersion||!ne||ne.status!=="supported"||ne.documentVersion!==se.version)return{ok:!0,data:le(p,$.VERSION_STALE,"The route changed before the page-unit insertion could commit.")};let we=D.entry.path,ye=Uh(D.instanceName),ke,Ie=[];if(p.params.kind==="insert-child"){if(!_||!("kind"in _)||_.kind!=="page-composition")return{ok:!0,data:le(p,$.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.")};let ie=Pa({routeId:y.routeId,entryFile:y.entryFile,currentDocumentVersion:se.version,expectedDocumentVersion:p.documentVersion,source:B,projection:ne,placementKey:_.placementKey,component:{source:we,exportName:D.entry.export.kind==="default"?"default":D.entry.export.name,localName:ye}});if(!ie.ok)return{ok:!0,data:le(p,Rs(ie.error.code),ie.error.message,{diagnostics:ie.error.diagnostics})};let Pe=ie.plan.rewriteStep,Le;switch(Pe.kind){case"insert-root-expression":Le=ki({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":Le=Yn({source:B,locator:Pe.parentLocator,node:Pe.node,placement:Pe.placement,...Pe.anchorLocator?{anchorLocator:Pe.anchorLocator}:{}});break;default:Le={ok:!1,source:B,diagnostic:{code:"unsupported-syntax",message:`Unsupported route composition rewrite: ${String(Pe)}`}}}if(!Le.ok)return{ok:!0,data:le(p,$.AST_PARSE_ERROR,Le.diagnostic.message)};ke=Le.source}else{let ie=Aa({routeId:y.routeId,composition:y.composition,entryFile:y.entryFile,currentDocumentVersion:se.version,expectedDocumentVersion:p.documentVersion,source:B,projection:ne,placementUnitKey:p.target.placementUnitKey,operation:"replace-node"});if(!ie.ok)return{ok:!0,data:le(p,Rs(ie.error.code),ie.error.message,{diagnostics:ie.error.diagnostics})};let Pe=ie.plan.rewriteStep,Le;switch(Pe.kind){case"replace-root-expression":Le=ki({source:B,locator:Pe.locator,expectedSourceHash:Pe.sourceHash,action:{kind:"replace",jsx:`<${ye} />`}});break;case"replace-node":Le=Qo({source:B,locator:Pe.locator,node:{jsx:`<${ye} />`}});break;default:Le={ok:!1,source:B,diagnostic:{message:`Unsupported page-unit replacement rewrite: ${Pe.kind}`}}}if(!Le.ok)return{ok:!0,data:le(p,$.AST_PARSE_ERROR,Le.diagnostic.message)};let ot=await Hl({routeState:y,placementUnitKey:p.target.placementUnitKey,source:B,mutatedSource:Le.source});ke=ot.source,Ie=await Promise.all(ot.files.map(async Qt=>({operation:"delete",file:Qt,baseContentHash:Ee(await n.readFile(Qt))})))}let F=qn({source:ke,moduleSpecifier:v(y.entryFile,we),imports:D.entry.export.kind==="default"?[{kind:"default",local:ye}]:[{kind:"named",imported:D.entry.export.name,local:ye}]});if(!F.ok)return{ok:!0,data:le(p,$.AST_PARSE_ERROR,F.diagnostic.message)};let V=D.files.map(ie=>({operation:"create-only",file:ie.path,content:ie.content})),pe=[{operation:"upsert",file:y.entryFile,content:F.source,baseContentHash:Ee(B)},...V,...Ie];u+=1;try{let ie=await Xn({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:{kind:"source-file",path:y.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 Mh(p,y){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 x=y.document,k=y.pageCompositionProjection;if(!x||x.pageComposition?.status!=="supported"||!k||k.status!=="supported")return le(p,$.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(p.documentVersion!==x.version||k.documentVersion!==x.version)return le(p,$.VERSION_STALE,`Document version ${p.documentVersion} is stale (current: ${x.version}).`);let w=await n.readFile(y.entryFile),_=Aa({routeId:y.routeId,composition:y.composition,entryFile:y.entryFile,currentDocumentVersion:x.version,expectedDocumentVersion:p.documentVersion,source:w,projection:k,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(!_.ok)return le(p,Rs(_.error.code),_.error.message,{diagnostics:_.error.diagnostics});let M=_.plan.rewriteStep,H;switch(M.kind){case"move-node":H=Zn({source:w,locator:M.locator,targetParentLocator:M.targetParentLocator,placement:M.placement,...M.anchorLocator?{anchorLocator:M.anchorLocator}:{}});break;case"remove-node":H=Gn({source:w,locator:M.locator});break;case"remove-root-expression":H=ki({source:w,locator:M.locator,expectedSourceHash:M.sourceHash,action:{kind:"remove"}});break;default:H={ok:!1,source:w,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,D=[];if(p.kind==="remove-node"){let se=await Hl({routeState:y,placementUnitKey:p.target.placementUnitKey,source:w,mutatedSource:X});X=se.source,D=await Promise.all(se.files.map(async ne=>({operation:"delete",file:ne,baseContentHash:Ee(await n.readFile(ne))})))}let B=[{operation:"upsert",file:y.entryFile,content:X,baseContentHash:Ee(w)},...D];u+=1;try{return await Xn({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:{kind:"source-file",path:y.entryFile},documentVersion:p.documentVersion,conflictPolicy:"compare-and-swap",edits:B}})}finally{u-=1}}async function Hl(p){let y={source:p.mutatedSource,files:[]},x=p.routeState.graph,k=p.routeState.pageCompositionProjection;if(!x||!k||k.status!=="supported"||!n.listFiles)return y;let _=k.placementUnitByKey.get(p.placementUnitKey)?.sourceRange;if(!_)return y;let M=[...x.elements.values()].find(F=>F.sourceFile===p.routeState.entryFile&&F.importedFrom&&I(F.sourceRange,_));if(!M?.importedFrom||!M.exportName)return y;let H=E(M.importedFrom),X="components/site/generated/";if(!H.startsWith(X))return y;let D=H.slice(X.length).split("/")[0];if(!D||!/-[0-9a-f]{8}$/i.test(D))return y;let B=`${X}${D}`;if([...x.elements.values()].filter(F=>F.sourceFile===p.routeState.entryFile&&E(F.importedFrom??"")===H).length!==1)return y;let ne=await n.listFiles({maxFiles:5e3,maxDepth:32}),we=Array.isArray(ne)?ne:ne.files;if(!Array.isArray(ne)&&ne.truncated)return y;let ye=we.map(({path:F})=>F).filter(F=>F===B||F.startsWith(`${B}/`));if(ye.length===0||!ye.includes(H))return y;for(let{path:F}of we)if(!(F===p.routeState.entryFile||F===B||F.startsWith(`${B}/`)))try{if((await n.readFile(F)).includes(D))return y}catch{return y}let ke=v(p.routeState.entryFile,H),Ie=er({source:p.mutatedSource,moduleSpecifier:ke,imports:M.exportName==="default"?[{kind:"default"}]:[{kind:"named",imported:M.exportName}]});return Ie.ok?Ie.source.includes(D)?{source:Ie.source,files:[]}:{source:Ie.source,files:ye.sort((F,V)=>F.localeCompare(V))}:y}async function Lh(p){if(n.getFileInfo){for(let w of p)if(await n.exists(w.path)&&await n.getFileInfo(w.path)===null)return{ok:!1,errorCode:"invalid-params",message:`Source edit path must resolve to a regular non-symbolic-link file: ${w.path}`,details:{path:w.path}}}for(let w of p){if(w.operation!=="upsert"||!/^(?:src\/)?app\/globals\.css$/i.test(w.path))continue;let _=await n.exists(w.path)?await Us(n,w.path):null;if(_?.ok){let M=zR(_.content,w.content);if(!M.ok)return{ok:!1,errorCode:"invalid-params",message:M.message,details:{path:w.path,code:M.code}}}}let y=Dh(p);if(y.length===0)return{ok:!0};let x=hN(n,p),k=So({projectRoot:e.projectRoot,fileSystem:x,compositions:[...i.values()].map(w=>({context:w.composition,entryFile:w.entryFile})),externalAdapters:e.externalAdapters,externalSourceResolvers:e.externalSourceResolvers,functionCallContracts:e.functionCallContracts,dev:e.dev});try{for(let w of y){let _=i.get(w)?.composition;if(!_)continue;let M={routeId:_.routeId,..._.effectiveTemplateId!==void 0?{templateId:_.effectiveTemplateId}:{}};await k.initializeComposition(M),k.getDocument(M)}}catch(w){return{ok:!1,errorCode:"ast-error",message:`Source edit preflight failed: ${Qe(w)}`,details:{compositionKeys:y}}}finally{k.dispose()}return{ok:!0}}function Dh(p){return p.map(x=>x.path).some(Yg)?[...i.keys()]:[]}function vs(p,y,x,k){let w=xo(y);return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Q(p),error:{code:w,message:x,...k?{details:k}:{}}}}async function ks(p){let y=[];for(let x of new Set(p))y.push(await Bh(x));return y}async function Bh(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:Ee(x)}}async function Wl(p,y,x,k){if(!e.historyStore)return null;let w=new Map(y.map(H=>[H.file,H])),_=new Map(x.map(H=>[H.file,H])),M=[...new Set([...w.keys(),..._.keys()])].sort().map(H=>{let X=w.get(H),D=_.get(H);return{path:H,preDigest:X?.exists===!1||!X?null:Ee(X.content),postDigest:D?.exists===!1||!D?null:Ee(D.content)}});return{schemaVersion:2,transactionId:`${p}:${k.expectedIndexDigest}`,operationId:p,phase:"prepared",historyTransition:k,files:M}}async function Gl(p){return!p||!e.historyStore||await e.historyStore.writeTransactionJournal(p),p}async function Jn(p){p&&e.historyStore&&await e.historyStore.clearTransactionJournal(p.transactionId)}async function Is(p,y){let x=[];try{for(let k of p)await Yl(k),typeof n.bumpVersion=="function"&&n.bumpVersion(k.file),x.push(k.file)}catch(k){let w=await jh(y.filter(_=>x.includes(_.file)));return w.ok?{ok:!1,reason:`Writeback failed and committed files were restored: ${Qe(k)}`,rolledBack:!0}:{ok:!1,reason:`Writeback failed, then rollback failed for ${w.failedFiles.join(", ")}: ${Qe(k)}`,rolledBack:!1}}return{ok:!0,snapshots:p.map($h)}}async function Yl(p){if(p.exists===!1){await n.deleteFile(p.file);return}await n.writeFile(p.file,p.content)}async function jh(p){let y=[];for(let x of p)try{await Yl(x),typeof n.bumpVersion=="function"&&n.bumpVersion(x.file)}catch{y.push(x.file)}return y.length===0?{ok:!0}:{ok:!1,failedFiles:y}}function $h(p){let y=p.exists!==!1;return{file:p.file,content:y?p.content:"",version:p.version,exists:y,...y?{sha256:Ee(p.content)}:{}}}async function Xn(p){return h.runExclusive(()=>Vh(p))}async function Vh(p){let y=p.filePlan.edits.map(F=>F.file),x=o.resolveSelector(p.request.composition),k=x.context,w=p.historyPolicy==="none"?void 0:{initiatingComposition:k,affectedCompositions:Rh(y)},_=await ks(y),M=new Map(_.filter(F=>F.exists!==!1).map(F=>[F.file,F.content])),H=Ql(),X=new Map(f),D=new Set(m),B=new Set([...i.values()].filter(F=>p.filePlan.edits.some(V=>V.operation==="delete"&&V.file===F.entryFile)).map(F=>F.key)),se=p.filePlan.edits.map(F=>F.operation==="delete"?{file:F.file,content:"",version:0,exists:!1}:{file:F.file,content:F.content,version:0,exists:!0,sha256:Ee(F.content)}),ne={operationId:p.filePlan.operationId,intents:p.filePlan.edits.map(F=>F.operation==="delete"?{kind:"delete",path:F.file}:{kind:F.operation==="create-only"?"create-only":"upsert",path:F.file,content:F.content})},we=null,ye=!1,ke=await os({overlay:M,exists:F=>n.exists(F),plan:ne,buildCandidate:async({plan:F})=>({plan:F}),prepareHistory:async()=>{let F=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:_,postSnapshots:se,...p.selectionRef?{selectionRef:p.selectionRef}:{},...p.output?{output:p.output}:{},...w?{provenance:w}:{}}),V=F?.historyTransition?F.historyTransition:e.historyStore?tN(await e.historyStore.readIndex()):null;if(e.historyStore&&!V)throw new Error("Durable history did not provide an exact index transition.");return we=await Wl(p.request.id,_,se,V),we=await Gl(we),{history:F,historyTransition:V}},reverify:async()=>{},writeCandidate:async()=>{let F=await d.executeFilePlan(p.filePlan);if(!F.ok)throw new ls(F);return{postSnapshots:await ks(F.affectedFiles),affectedFiles:F.affectedFiles,internalResultVersion:F.resultVersion}},validateCandidate:async({candidate:F,receipt:V})=>{let pe=await Po(V.affectedFiles,{changed:!0,minimumVersion:V.internalResultVersion,publish:!1,excludedCompositionKeys:B});if(pe.failedRoutes.length>0)throw new Vn(pe.failedRoutes);let ie=eu(H,pe.candidateRouteStates??[]),Pe=ql(ie,x.key);return{...F,rebuild:pe,routeSnapshots:ie,resultVersion:Pe,...zg(p.selectionRef,ie.map(Le=>Le.state.document))?{selectionRef:zg(p.selectionRef,ie.map(Le=>Le.state.document))}:{}}},publishCandidate:async({candidate:F,history:V,receipt:pe})=>{V?.history&&(await l.publishPrepared(V.history),ye=!0);let ie=F.resultVersion??pe.internalResultVersion;return{composition:k,requestId:p.request.id,kind:p.request.kind,target:p.request.target,ok:!0,resultVersion:ie,affectedFiles:pe.affectedFiles,...p.output?{output:p.output}:{},...F.selectionRef?{selectionRef:F.selectionRef}:{}}},swapCandidate:({candidate:F,receipt:V})=>{F.routeSnapshots&&Ao(F.routeSnapshots),F.rebuild?.candidateSourceCache&&br(f,F.rebuild.candidateSourceCache),Ul(V.postSnapshots)},finalizeCandidate:async()=>{await Jn(we);for(let F of B)i.delete(F)},emitCommitted:({candidate:F,published:V})=>{Es(V,F.rebuild??{rebuiltRoutes:[],failedRoutes:[]})},rollbackCandidate:async({history:F,receipt:V})=>{if(ye)throw new Error("history was published before transaction finalization failed");if(V){let pe=await Is(_,V.postSnapshots);if(!pe.ok)throw new Error(pe.reason)}Ao(H),br(f,X),Jl(D),F?.history&&await l.discardPrepared?.(F.history),await Jn(we)}});if(ke.ok)return ke.published;if(ke.stage==="precheck"||ke.stage==="build")try{await Jn(we)}catch(F){let V=await To(Qe(F));return le(p.request,V,"Unable to clear an uncommitted transaction journal.")}if(ke.recoveryRequired){let F=await To(ke.reason);return le(p.request,F===$.RECOVERY_PERSIST_FAILED?F:$.ROLLBACK_FAILED,ke.reason)}let Ie=ke.error;return Ie instanceof ls?{...le(p.request,xo(Ie.result.errorCode),Ie.result.reason),...Ie.result.affectedFiles?{affectedFiles:Ie.result.affectedFiles}:{}}:Ie instanceof Vn?le(p.request,$.ROUTE_REBUILD_FAILED,`Route rebuild failed and source was rolled back: ${fl(Ie.failedRoutes)}`,{failedRoutes:Ie.failedRoutes}):le(p.request,nu(ke.stage),Qe(Ie))}async function Zl(p){return h.runExclusive(async()=>{let y=p==="undo"?await l.prepareUndo():await l.prepareRedo();return y?Kh(p,y):{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 Kh(p,y){let x=y.entry,k=p==="undo"?x.preSnapshots:x.postSnapshots,w=p==="undo"?x.postSnapshots:x.preSnapshots,_=k.map(V=>V.file),{context:M,key:H}=wh(x,_),X=await ks(_),D=new Map(X.filter(V=>V.exists!==!1).map(V=>[V.file,V.content])),B=Ne(H),se=Ql(),ne=new Map(f),we=new Set(m),ye=null,ke=!1,Ie,F=await os({overlay:D,plan:{operationId:`${p}:${x.operationId}`,intents:k.map(V=>V.exists===!1?{kind:"delete",path:V.file}:{kind:"upsert",path:V.file,content:V.content})},buildCandidate:async()=>({}),prepareHistory:async()=>(ye=await Wl(`${p}:${x.operationId}`,X,k,y.historyTransition),ye=await Gl(ye),y),reverify:async()=>{},writeCandidate:async()=>{let V=await Is(k,w);if(!V.ok)throw new Error(V.reason);return{snapshots:V.snapshots}},validateCandidate:async({candidate:V})=>{Ie=Nh(x,_);let pe=await Po(_,{changed:!0,minimumVersion:B+1,publish:!1,affectedCompositionKeys:Ie});if(pe.failedRoutes.length>0)throw new Vn(pe.failedRoutes);let ie=eu(se,pe.candidateRouteStates??[]),Pe=ql(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:x.kind,target:x.target,ok:!0,resultVersion:ie,affectedFiles:_,...x.output?{output:x.output}:{}}},swapCandidate:({candidate:V,receipt:pe})=>{V.routeSnapshots&&Ao(V.routeSnapshots),V.rebuild?.candidateSourceCache&&br(f,V.rebuild.candidateSourceCache),Ul(pe.snapshots)},finalizeCandidate:async()=>{await Jn(ye)},emitCommitted:({candidate:V,published:pe})=>Es(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 Is(w,pe.snapshots);if(!ie.ok)throw new Error(ie.reason)}Ao(se),br(f,ne),Jl(we),V&&await l.discardPrepared?.(V),await Jn(ye)}});if(F.ok)return F.published;if(F.stage==="precheck"||F.stage==="build")try{await Jn(ye)}catch(V){let pe=await To(Qe(V));return{composition:M,requestId:p,kind:x.kind,target:x.target,ok:!1,resultVersion:B,error:{code:pe,message:"Unable to clear an uncommitted transaction journal."}}}if(F.recoveryRequired){let V=await To(F.reason);return{composition:M,requestId:p,kind:x.kind,target:x.target,ok:!1,resultVersion:B,affectedFiles:_,error:{code:V===$.RECOVERY_PERSIST_FAILED?V:$.ROLLBACK_FAILED,message:F.reason}}}return{composition:M,requestId:p,kind:x.kind,target:x.target,ok:!1,resultVersion:B,affectedFiles:_,error:{code:F.error instanceof Vn?$.ROUTE_REBUILD_FAILED:nu(F.stage),message:Qe(F.error),...F.error instanceof Vn?{details:{failedRoutes:F.error.failedRoutes}}:{}}}}function Ql(){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 ql(p,y){return p.find(k=>k.key===y)?.state.graph?.version??o.initialVersions.get(y)??0}function eu(p,y){let x=new Map(p.map(k=>[k.key,k]));for(let k of y)x.set(k.key,k);return[...x.values()]}function Ao(p){for(let y of i.values())C(y);for(let y of p){let x={...y.state,dependencyFiles:new Set(y.state.dependencyFiles),fileVersions:new Map(y.state.fileVersions)};i.set(y.key,x),T(x,x.dependencyFiles)}}async function Cs(p){let y=i.get(p);if(!y)throw new Error(`Composition not found: ${p}`);if(y.graph)return;let x=await n.readFile(y.entryFile);await fe(p,x)}function zn(p,y){let x=i.get(o.resolveSelector(y).key)??null;return!x||!tu(x,p)?null:x}function tu(p,y){if(p.documentIndex?.entriesByKey.has(y)||p.graph?.elements.has(y))return!0;let x=nt(y);return x&&x!==y?p.graph?.elements.has(x)===!0:!1}function le(p,y,x,k){return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Q(p),error:{code:y,message:x,...k?{details:k}:{}}}}function nu(p){return p==="validate"?$.ROUTE_REBUILD_FAILED:p==="publish"?$.HISTORY_COMMIT_FAILED:$.WRITE_IO_ERROR}async function To(p){if(g=!0,!l.markRecoveryRequired)return $.RECOVERY_REQUIRED;try{return await l.markRecoveryRequired(p),$.RECOVERY_REQUIRED}catch{return $.RECOVERY_PERSIST_FAILED}}function Uh(p){let x=p.split(/[^a-zA-Z0-9]+/).filter(Boolean).map(k=>k.charAt(0).toUpperCase()+k.slice(1)).join("").replace(/^[^a-zA-Z_$]+/,"");return x?`Prefab${x}`:"GeneratedPrefab"}function Rs(p){return p==="VERSION_STALE"?$.VERSION_STALE:p==="CROSS_PAGE_MOVE_UNSUPPORTED"?$.CROSS_PAGE_MOVE_UNSUPPORTED:$.UNSUPPORTED_OPERATION}async function ru(p){if(p.target.kind==="route"){let x=i.get(o.resolveSelector(p.target.composition).key)??null;return x?(x.graph||await Cs(x.key),x):le(p,$.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 Cs(x.key),x):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 y=i.get(o.resolveSelector(p.composition).key)??null;return y?(y.graph||await Cs(y.key),tu(y,p.target.key)?y: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,y){let x=o.register({context:p,entryFile:y}),k=i.get(x.key);if(k?.entryFile===y)return;k&&C(k);let w=Xg(x.context,y);i.set(x.key,w),T(w,w.dependencyFiles),r.emit({type:"graph-invalidated",composition:x.context})},unregisterComposition(p){let y=o.resolveSelector(p),x=i.get(y.key);x&&(C(x),i.delete(y.key),o.unregister(y.key),i.size===0&&(t="idle"),r.emit({type:"graph-invalidated",composition:y.context}))},getCompositionEntryFiles(){return[...i.values()].map(p=>p.entryFile)},getCompositionContext(p){return o.resolveSelector(p).context},async initializeComposition(p){let y=o.resolveSelector(p),x=i.get(y.key);if(!x)throw new Error(`Composition not registered: ${y.key}`);if(x.graph)t="ready";else{t="building";try{let k=await n.readFile(x.entryFile);await fe(y.key,k),t="ready",r.emit({type:"graph-ready",composition:y.context,version:i.get(y.key)?.graph?.version??0})}catch(k){throw t="idle",r.emit({type:"graph-error",composition:y.context,message:Qe(k)}),k}}},getDocument(p){let y=o.resolveSelector(p),x=i.get(y.key);if(!x)throw new Error(`Composition not registered: ${y.key}`);if(!x.document)throw new Error(`Composition not built: ${y.key}`);return x.document},async getHistoryStatus(){await b;let p=await l.getStatus?.();return p?{...p,recoveryRequired:g}:{canUndo:!1,canRedo:!1,undoDepth:0,redoDepth:0,recoveryRequired:g}},getObjectEditContext(p,y,x){let k=zn(p,y),w=nt(p)??p;if(k?.graph&&k.topology&&k.capabilities&&k.detailProjections){let _=k.detailProjections.get(w);if(_){let M=k.graph.elements.get(w);if(!M)throw new Error(`Key not found: ${p}`);let H=cN(p,w,x),X=new Map;if(_.isRepeat&&H?.instanceIndex!==void 0)for(let se of M.attributes??[])X.set(se.name,jc({file:M.sourceFile,source:f.get(M.sourceFile)??"",element:M,propertyName:se.name,selectionRef:H,graph:k.graph,sources:f}));let D=ag({element:M,graph:k.graph,source:f.get(M.sourceFile),documentVersion:k.graph.version,selectionRef:x,isRepeat:_.isRepeat,propertyProvenance:_.propertyProvenances,repeatTargets:X}),B=ug(w,k.graph,k.topology,k.capabilities,_.textSources,_.provenances,_.dynamicData,D);return p===w?B:Lg(B,p,k.document??null,k.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${p}`)},getRenderDetail(p,y){let x=zn(p,y),k=nt(p)??p;if(x?.graph&&x.topology&&x.capabilities&&x.detailProjections){let w=x.detailProjections.get(k);if(w){let _=lg(k,x.graph,x.topology,x.capabilities,w.textSources,w.writeTarget,w.provenances,w.conditional,w.componentSemantic,w.styleSource,w.dynamicData);return p===k?_:Mg(_,p,x.document??null,x.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${p}`)},getClassNameSource(p,y){let x=zn(p,y),k=nt(p)??p;if(!x?.graph)throw new Error(`Key not found: ${p}`);let w=x.graph.elements.get(k);if(!w)throw new Error(`Key not found: ${p}`);let _=f.get(w.sourceFile);if(_===void 0)throw new Error(`Source not loaded: ${w.sourceFile}`);return ca({key:k,route:{composition:x.composition,routeId:x.routeId,graph:x.graph,source:_}})},refreshSourceForKey:Ah,async execute(p){if(await b,g)return le(p,$.RECOVERY_REQUIRED,"The edit engine requires explicit recovery before accepting mutations.");if(p.kind==="source-edit")return Th(p);if(p.kind==="insert-page-resource")return Fh(p);if(p.kind==="delete-page-source")return _h(p);let y=await ru(p);if("ok"in y)return y;await zl(p);let x=await ru(p);if("ok"in x)return x;let k=x;if(p.target.kind==="page-unit"){let B=p;return p.kind==="insert-child"||p.kind==="replace-node"?Oh(B,k):p.kind==="move-node"||p.kind==="remove-node"?Mh(B,k):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 _=p.params,M=p.target.kind==="node"?p.target.key:null;if(_.kind==="move-node"&&"kind"in _.target&&_.target.kind==="source-sibling"){let B=_.target,se=M?k.document?.entries.find(V=>V.key===M):null,ne=k.document?.entries.find(V=>V.key===B.anchorKey),we=se?.pageCompositionActionScope,ye=we?.kind==="source-siblings"?we.siblingKeys:null,ke=ye?.indexOf(se?.key??"")??-1,Ie=ye?.indexOf(B.anchorKey)??-1,F=B.relation==="before"?ke-1:ke+1;if(!se||!ne||!ye||ke<0||Ie!==F||ne.pageCompositionActionScope?.kind!=="source-siblings"||ne.pageCompositionActionScope.siblingKeys.length!==ye.length||ne.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(!k.graph||!k.topology||!k.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=RN(k,k.graph,k.capabilities,f,i),X=await new Ji(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:xo(X.errorCode),message:X.reason}};let D=X.plan;if(D.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(D.steps.some(se=>se.type==="invoke-external-adapter")){let se=await d.execute(D);if(!se.ok)return le(p,xo(se.errorCode),se.reason);let ne={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 Es(ne,{rebuiltRoutes:[],failedRoutes:[]}),ne}let B=await d.prepareRewritePlan(D);return B.ok?await Xn({request:p,filePlan:B.filePlan,...B.selectionRef?{selectionRef:B.selectionRef}:{}}):le(p,xo(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 b,g)return{composition:o.entries[0].context,requestId:"undo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:Ne(o.entries[0].key),error:{code:$.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting undo."}};u+=1;try{return await Zl("undo")}finally{u-=1}},async redo(p){if(await b,g)return{composition:o.entries[0].context,requestId:"redo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:Ne(o.entries[0].key),error:{code:$.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting redo."}};u+=1;try{return await Zl("redo")}finally{u-=1}},notifyFileChanged(p){Vl([p])},getAffectedCompositions(p){return Ch(p)},subscribe(p){return r.subscribe(p)}}}function bN(e){return e instanceof Error&&"code"in e&&(e.code==="ENOENT"||e.code==="ENOTDIR")}function SN(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&&bo(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=nt(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&&bo(u.sourceRange,n.container.sourceRange)&&d){f.pageCompositionUnitKey=d.placementUnitKey;continue}let b=n.placements.find(E=>E.members.some(v=>v.sourceRange!==null&&(bo(u.sourceRange,v.sourceRange)||CN(v.sourceRange,u.sourceRange))));if(b){f.pageCompositionUnitKey=b.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)}EN(e,t,n,r)}function EN(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&&bo(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 b=s.get(g.target)??0,E=Math.min(2,b+h);E!==b&&(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!==(nt(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 b=h.match.path,E=b.parentPath;if(!E||!E.isJSXFragment()&&!(E.isJSXElement()&&Fe(E))){d(u)===1&&Wg(b)&&(m.pageCompositionActionScope={kind:"route-unit"});continue}if(!Wg(E))continue;let v=f.get(E.node)??[];v.push({entry:m,element:u,parentPath:E}),f.set(E.node,v)}for(let m of f.values()){let u=m[0];if(!u)continue;let g=u.entry.pageCompositionUnitKey,h=[],b=!!(g&&d(u.element)===1);for(let v of u.parentPath.node.children){if(vN(v))continue;if(!kN(v)){b=!1;break}let I=[...t.elements.values()].find(A=>A.sourceFile===u.element.sourceFile&&A.componentName===u.element.componentName&&bo(A.sourceRange,IN(v))),R=I?o.get(I.identity.key):null;if(!I||!R||R.parentKey||R.pageCompositionUnitKey!==g||d(I)!==1){b=!1;break}h.push(R)}if(!b||h.length!==m.length||m.some(({entry:v})=>!h.some(I=>I.key===v.key)))continue;if(h.length===1){h[0].pageCompositionActionScope={kind:"route-unit"};continue}if(h.length<2)continue;let E=h.map(v=>v.key);for(let v of h)v.pageCompositionActionScope={kind:"source-siblings",siblingKeys:E}}}function Wg(e){let t=e.parentPath;return!!(t?.isReturnStatement?.()||t?.isArrowFunctionExpression?.()&&t.node.body===e.node)}function vN(e){return!!(e&&typeof e=="object"&&e.type==="JSXText"&&!(e.value??"").trim())}function kN(e){return!!(e&&typeof e=="object"&&e.type==="JSXElement")}function IN(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 bo(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function CN(e,t){return Gg(e.startLine,e.startColumn,t.startLine,t.startColumn)<=0&&Gg(e.endLine,e.endColumn,t.endLine,t.endColumn)>=0}function Gg(e,t,n,r){return e!==n?e-n:t-r}function RN(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 b=nt(h)??h,E=t.elements.get(b);return E?l(h,E):null}).filter(h=>h!==null);let g=t.elements.get(f.baseKey);return g?g.childKeys.map(h=>{let b=t.elements.get(h);return b?l(h,b):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:ca({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 dl(e.detailProjections?.get(m.baseKey)?.textTargets.get(f)??null,m.repeatIndex)},async getElementPropertyWriteTarget(d,f){let m=c(d);return dl(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 b=e.detailProjections?.get(u.baseKey)?.propertyProvenances.get(f);if(b)return b;let E=g.attributes?.find(v=>v.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 jc({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=YR(d);return f?{baseKey:f.baseKey,repeatIndex:Og(e.document??null,d,f.baseKey,e.documentIndex)??_g(f)}:{baseKey:d,repeatIndex:null}}function l(d,f){let m=nt(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 NN={"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 xo(e){return NN[e]}function Qe(e){return e instanceof Error&&e.message?e.message:String(e)}function Yg(e){return/\.(?:[cm]?[jt]sx?|css|scss|sass|mdx|json)$/i.test(e)}function wN(e){let t=Kn(e);if(!qR.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=>eN.map(a=>`${s}/${a}`))}function PN(e){let n=Kn(e).startsWith("src/app/")?"src/app":"app";return[`${n}/globals.css`,`${n}/global.css`]}function AN(e){return qg(e,/\bimport\s+(?:[^'";]+?\s+from\s+)?["']([^"']+\.css(?:\?[^"']*)?)["']/g)}function TN(e){return qg(e,/@import\s+(?:url\(\s*)?["']([^"']+)["']/g)}function qg(e,t){let n=[];for(let r of e.matchAll(t)){let o=eh(r[1]??"");o&&n.push(o)}return n}function Zg(e,t){let n=eh(t);return!n||n.startsWith("tailwindcss")||n.startsWith("http:")||n.startsWith("https:")?null:n.startsWith("@/")?Kn(`src/${n.slice(2)}`):n.startsWith("./")||n.startsWith("../")?Kn(`${FN(e)}/${n}`):n.startsWith("/")?Kn(n.slice(1)):gl(n)?Kn(n):null}function eh(e){return e.split(/[?#]/,1)[0]?.trim()??""}function gl(e){return/\.css$/i.test(e)}function FN(e){let t=Kn(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function _N(e){return Array.from(new Set(e))}function Kn(e){let t=e.replace(/\\/g,"/").replace(/^\.\//,""),n=[];for(let r of t.split("/"))if(!(!r||r===".")){if(r===".."){n.pop();continue}n.push(r)}return n.join("/")}function ON(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 us=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=LN.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:Cn(i)},a=r.getChangedFiles();if(a.length===0)return{result:s};let c=DN.parse({siteId:t.siteId,baseSnapshotId:t.baseSnapshotId,operationId:t.id,reason:`site-edit:${t.kind}`,patches:a.map(l=>BN(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 So({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 BN(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 jN(e){return new us(e)}import{SiteEditOperationRequestSchema as KN}from"@vcp-dev/contracts";import Nt from"node:fs/promises";import qe from"node:path";import{SITE_EDIT_SOURCE_ALLOWED_DIRS as $N,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as VN}from"@vcp-dev/contracts";var ds=class{constructor(t){this.options=t,this.fileSystem=this.createFileSystem(),this.engine=So({...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 Nt.readFile(qe.join(n,r),"utf8")},async readFileBytes(r){return Nt.readFile(qe.join(n,r))},async getFileInfo(r){let o=qe.join(n,...r.split("/"));try{let i=await Nt.lstat(o);return!i.isFile()||i.isSymbolicLink()?null:{path:r,sizeBytes:i.size}}catch{return null}},async writeFile(r,o){await ui(qe.join(n,r),o)},async createExclusive(r,o){let i=qe.join(n,r);await Nt.mkdir(qe.dirname(i),{recursive:!0});let s=await Nt.open(i,"wx");try{await s.writeFile(o,"utf8")}catch(a){throw await s.close(),await Nt.rm(i,{force:!0}),a}await s.close()},async deleteFile(r){await Nt.rm(qe.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=qe.join(n,i),a=qe.dirname(qe.join(n,o));for(;a!==s&&a.startsWith(`${s}${qe.sep}`);){try{await Nt.rmdir(a)}catch(c){if(c instanceof Error&&"code"in c&&c.code==="ENOENT"){a=qe.dirname(a);continue}break}a=qe.dirname(a)}},async exists(r){try{return await Nt.access(qe.join(n,r)),!0}catch{return!1}},async listFiles(r={}){let o=r.roots??[...VN,...$N],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=qe.join(n,...f.split("/")),h;try{h=await Nt.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 b=await Nt.readdir(g,{withFileTypes:!0});for(let E of b)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 hl(e){return new ds(e)}var fs=class{constructor(t){this.options=t,this.listeners=new Set,this.engine=hl({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=KN.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:Cn(i)}}async undo(t){let n=await this.engine.undo();if(!n.ok){let r=n.error;if(!r)throw new Error("undo failed without an error payload");return{ok:!1,composition:n.composition,error:{code:r.code,message:r.message},data:{requestId:n.requestId,kind:n.kind,composition:n.composition,target:n.target,resultVersion:n.resultVersion}}}return{ok:!0,composition:n.composition,data:Cn(n)}}async redo(t){let n=await this.engine.redo();if(!n.ok){let r=n.error;if(!r)throw new Error("redo failed without an error payload");return{ok:!1,composition:n.composition,error:{code:r.code,message:r.message},data:{requestId:n.requestId,kind:n.kind,composition:n.composition,target:n.target,resultVersion:n.resultVersion}}}return{ok:!0,composition:n.composition,data:Cn(n)}}notifyFileChanged(t){this.engine.notifyFileChanged(t)}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}dispose(){this.listeners.clear(),this.engine.dispose()}};function UN(e){return new fs(e)}import{createHash as JN,randomUUID as wl}from"node:crypto";import _e from"node:fs/promises";import Me from"node:path";var Et=1,xl=1,XN=2,zN="index.json",HN="recovery.json",WN="transaction-journal.json",GN="document-version.json",ms={maxEntries:100,maxSessionBytes:512*1024*1024,maxEntryBytes:128*1024*1024},te={INVALID_ROOT:"INVALID_ROOT",INVALID_PATH:"INVALID_PATH",INVALID_SCHEMA:"INVALID_SCHEMA",INVALID_JSON:"INVALID_JSON",INDEX_CORRUPT:"INDEX_CORRUPT",ENTRY_CORRUPT:"ENTRY_CORRUPT",BLOB_CORRUPT:"BLOB_CORRUPT",RECOVERY_PENDING:"RECOVERY_PENDING",CAPACITY_EXCEEDED:"CAPACITY_EXCEEDED",NOT_FOUND:"NOT_FOUND"},oe=class extends Error{constructor(t,n,r){super(n),this.name="FileHistoryStoreError",this.code=t,r?.cause!==void 0&&(this.cause=r.cause)}};async function uh(e,t={}){let n=lw(e),r=fw(t.limits),o=yl(n),i=uw(n),s=await rt(i),a=await rt(o)||s;a||(await tw(n),await nw(n)),a||await pw(n);let c=await ut(n),l=new Set(a?(await bs(n)).map(f=>f.stageId):[]);a||await Eo(n,c.entryIds);let d=async()=>{if(await rt(o)||s)throw new oe(te.RECOVERY_PENDING,"history store requires explicit recovery before accepting writes")};return{rootDir:n,recoveryRequired:a,async readDocumentVersion(){return ch(n)},async writeDocumentVersion(f){if(await d(),!Number.isInteger(f)||f<0)throw new oe(te.INVALID_SCHEMA,"document version must be a non-negative integer");let m=await ch(n);await vo(yh(n),{schemaVersion:1,version:Math.max(m,f)})},async stageAppend(f,m={}){await d();let u=await nh(f,r),g={schemaVersion:xl,stageId:wl(),entryId:u.entryId,blobIds:u.blobs.map(h=>h.digest)};try{await rh(n,u),await QN(n,g,m.durableManifest!==!1)}catch(h){try{await ih(n,g)}catch(b){throw new oe(te.INDEX_CORRUPT,"staged history cleanup failed after preparation error",{cause:b})}throw h}return{stageId:g.stageId,entryId:g.entryId,blobIds:g.blobIds}},async discardStage(f){await d(),vl(f);let m=await Sl(n,f);m&&await ih(n,m)},async previewStagedAppend(f,m){return await d(),(await th(n,r,f,m)).transition},async previewCursor(f,m){await d();let u=await ut(n);return kl(u,m),bl(f,u.entryIds.length),dh(u,u.entryIds,f)},async publishStagedAppend(f,m,u){if(await d(),gs(f,"entryId"),u){vl(u);let h=await Sl(n,u);if(!h||h.entryId!==f)throw new oe(te.INVALID_SCHEMA,"history stage does not match the published entry")}let g=await th(n,r,f,m);return ah({rootDir:n,previousDigest:g.current.digest,entryIds:g.entryIds,cursor:g.cursor,afterWrite:async()=>{u?await hs(n,u):await ew(n,f),await Eo(n,g.entryIds)}})},async append(f){await d();let m=await ut(n),u=await nh(f,r),g=[...m.entryIds];m.cursor<g.length-1&&g.splice(m.cursor+1),g.push(u.entryId);try{await rh(n,u);let h=await fh(n,g,r);return await Al(n,h.entryIds,h.cursor),await Eo(n,h.entryIds),ut(n)}catch(h){throw await Eo(n,m.entryIds),h}},async readEntry(f){return gs(f,"entryId"),Io(n,f)},async readBlob(f){gs(f,"blobId");let m=await Bl(n,f),u=await gn(m,te.NOT_FOUND,"blob");return Tl(u,f,m),u},async readIndex(){return ut(n)},async readStatus(){let f=await ut(n);return{canUndo:f.undoIds.length>0,canRedo:f.redoIds.length>0,undoDepth:f.undoIds.length,redoDepth:f.redoIds.length,cursor:f.cursor,recoveryRequired:await rt(o)||await rt(i)}},async readUndoRedoIds(){let f=await ut(n);return{undoIds:f.undoIds,redoIds:f.redoIds,currentId:f.currentId}},async setCursor(f,m){await d();let u=await ut(n);return kl(u,m),bl(f,u.entryIds.length),ah({rootDir:n,previousDigest:u.digest,entryIds:u.entryIds,cursor:f})},async markRecoveryRequired(f){await rt(o)||await vo(yl(n),{schemaVersion:Et,reason:dw(f),createdAt:new Date().toISOString()})},async clearRecoveryRequired(){await _e.rm(yl(n),{force:!0})},async readTransactionJournal(){return await rt(i)?ps(i):null},async writeTransactionJournal(f){await d(),xh(f);try{await vo(i,f)}catch(u){let g=await ps(i).catch(()=>null);if(g&&Buffer.from(dt(g)).equals(Buffer.from(dt(f))))return;throw g?new oe(te.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous",{cause:u}):u}let m=await ps(i);if(!Buffer.from(dt(m)).equals(Buffer.from(dt(f))))throw new oe(te.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous")},async clearTransactionJournal(f){let m=await rt(i)?await ps(i):null;if(m&&m.transactionId!==f)throw new oe(te.INVALID_SCHEMA,"transaction journal changed concurrently");try{await _e.rm(i,{force:!0})}catch(u){if(!await rt(i))return;throw u}if(await rt(i))throw new oe(te.INDEX_CORRUPT,"transaction journal clear outcome is ambiguous");s=!1},async cleanupTmp(){await d();for(let m of l)await hs(n,m),l.delete(m);await rw(n);let f=await ut(n);await Eo(n,f.entryIds)}}}async function th(e,t,n,r){gs(n,"entryId");let o=await ut(e);kl(o,r);let i=await Io(e,n),s=[...o.entryIds];o.cursor<s.length-1&&s.splice(o.cursor+1),s.push(i.id);let a=await fh(e,s,t);return{current:o,entryIds:a.entryIds,cursor:a.cursor,transition:dh(o,a.entryIds,a.cursor)}}function dh(e,t,n){return bl(n,t.length),{expectedIndexDigest:e.digest,publishedIndexDigest:YN(t,n),publishedCursor:n,publishedCurrentId:t[n]??null}}function YN(e,t){return hn(dt({schemaVersion:Et,entryIds:e,cursor:t}))}function bl(e,t){if(!Number.isInteger(e)||e<-1||e>=t)throw new oe(te.INVALID_SCHEMA,`history cursor is out of bounds: ${e}`)}function ZN(e){if(!wt(e))return!1;let t=e.publishedCursor,n=e.publishedCurrentId;return!ft(e.expectedIndexDigest)||!ft(e.publishedIndexDigest)||!Number.isInteger(t)||t<-1||n!==null&&!ft(n)?!1:t===-1?n===null:ft(n)}async function nh(e,t){if(!e.kind.trim())throw new oe(te.INVALID_JSON,"history entry kind must not be empty");let n=[],r=[];for(let c of e.blobs??[]){if(!c.name.trim())throw new oe(te.INVALID_JSON,"history blob name must not be empty");let l=cw(c.data),d=hn(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:Et,kind:e.kind,manifest:e.manifest,blobs:r},i=dt({...o}),s=hn(i),a=i.byteLength+n.reduce((c,l)=>c+l.sizeBytes,0);if(a>t.maxEntryBytes)throw new oe(te.CAPACITY_EXCEEDED,`history entry exceeds maxEntryBytes (${a} > ${t.maxEntryBytes})`);return{entryBody:o,entryId:s,blobs:n}}async function rh(e,t){let n=Ol(e,t.entryId),r={id:t.entryId,...t.entryBody},o=[...t.blobs.map(a=>oh(Ml(e,a.digest),a.bytes,{kind:"blob",digest:a.digest},Dl(e,a.digest))),oh(n,dt(r),{kind:"entry",digest:t.entryId},Ll(e,t.entryId))],s=(await Promise.allSettled(o)).find(a=>a.status==="rejected");if(s)throw s.reason}async function oh(e,t,n,r){let o=await Rl(e)??(r?await Rl(r):null);if(o!==null){if(Buffer.compare(o,t)!==0)throw new oe(n.kind==="blob"?te.BLOB_CORRUPT:te.ENTRY_CORRUPT,`${n.kind} content mismatch for ${n.digest}`);return}await gh(e,t)}async function fh(e,t,n){let r=[...t],o=r.length-1;for(;;){if((await mh(e,r)).totalBytes<=n.maxSessionBytes&&r.length<=n.maxEntries)return{entryIds:r,cursor:o};if(o<=0||r.length===0)throw new oe(te.CAPACITY_EXCEEDED,"history store exceeds capacity limits and the current entry cannot be trimmed");r.shift(),o-=1}}async function QN(e,t,n){Pl(t);let r=_l(e,t.stageId);if(n){await vo(r,t);return}await aw(r,t)}async function Sl(e,t){let n=await Rl(_l(e,t));if(n===null)return null;let r=Co(Buffer.from(n).toString("utf8"),`history stage ${t}`),o=Pl(r);if(o.stageId!==t)throw new oe(te.INVALID_SCHEMA,`history stage id mismatch: ${t}`);return o}async function bs(e){let t=[];for(let n of await xs(Fl(e))){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);vl(r);let o=await Sl(e,r);o&&t.push(o)}return t}async function ih(e,t){Pl(t);let n=await ut(e),r=(await bs(e)).filter(s=>s.stageId!==t.stageId),o=new Set(n.entryIds),i=new Set;for(let s of n.entryIds){let a=await Io(e,s);for(let c of a.blobs)i.add(c.digest)}for(let s of r){o.add(s.entryId);for(let a of s.blobIds)i.add(a)}o.has(t.entryId)||await sh(Ol(e,t.entryId),Ll(e,t.entryId));for(let s of t.blobIds)i.has(s)||await sh(Ml(e,s),Dl(e,s));await hs(e,t.stageId),await Nl(Ro(e)),await Nl(No(e))}async function hs(e,t){await El(_l(e,t)),await qN(e)}async function qN(e){try{await _e.rmdir(Fl(e))}catch(t){if(wo(t)||wt(t)&&t.code==="ENOTEMPTY")return;throw t}}async function ew(e,t){for(let n of await bs(e))n.entryId===t&&await hs(e,n.stageId)}async function El(e){if(await _e.rm(e,{force:!0}),await rt(e))throw new oe(te.INDEX_CORRUPT,`unable to remove staged history object: ${e}`)}async function sh(e,t){await El(e),await El(t)}function Pl(e){if(!wt(e)||e.schemaVersion!==xl||typeof e.stageId!="string"||!ph(e.stageId)||!ft(e.entryId))throw new oe(te.INVALID_SCHEMA,"history stage schema is invalid");let t=hh(e.blobIds,"history stage blobIds");return{schemaVersion:xl,stageId:e.stageId,entryId:e.entryId,blobIds:t}}function vl(e){if(!ph(e))throw new oe(te.INVALID_PATH,"history stageId must be a UUID")}function ph(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 Eo(e,t){let n=new Set(t),r=new Set;for(let c of t){let l=await Io(e,c);for(let d of l.blobs)r.add(d.digest)}for(let c of await bs(e)){n.add(c.entryId);for(let l of c.blobIds)r.add(l)}let o=Ro(e),i=await xs(o);for(let c of i){if(!c.endsWith(".json"))continue;let l=lh(c.slice(0,-5));l&&!n.has(l)&&await ys(Me.join(o,c))}let s=No(e),a=await xs(s);for(let c of a){let l=lh(c);l&&!r.has(l)&&await ys(Me.join(s,c))}}async function ut(e){let t=Ss(e),n=await gn(t,te.NOT_FOUND,"index"),r=Co(Buffer.from(n).toString("utf8"),"index"),o=ow(r),i=[...o.entryIds],{totalBytes:s}=await mh(e,i),a=i.slice(0,o.cursor+1).reverse(),c=i.slice(o.cursor+1);return{schemaVersion:Et,digest:o.digest,entryIds:i,cursor:o.cursor,currentId:i[o.cursor]??null,undoIds:a,redoIds:c,totalBytes:s}}async function mh(e,t){let n=0,r=new Set,o=Ss(e),i=await gn(o,te.NOT_FOUND,"index");n+=i.byteLength;for(let s of t){let a=await Io(e,s),c=await bh(e,s),l=await gn(c,te.NOT_FOUND,"entry");n+=l.byteLength;for(let d of a.blobs){if(r.has(d.digest))continue;r.add(d.digest);let f=await Bl(e,d.digest),m=await gn(f,te.NOT_FOUND,"blob");Tl(m,d.digest,f),n+=m.byteLength}}return{totalBytes:n}}async function Io(e,t){let n=await bh(e,t),r=await gn(n,te.NOT_FOUND,"entry"),o=Co(Buffer.from(r).toString("utf8"),`entry ${t}`),i=iw(o);if(i.id!==t)throw new oe(te.ENTRY_CORRUPT,`entry id mismatch for ${t}`);if(hn(dt({schemaVersion:i.schemaVersion,kind:i.kind,manifest:i.manifest,blobs:i.blobs}))!==t)throw new oe(te.ENTRY_CORRUPT,`entry hash mismatch for ${t}`);for(let a of i.blobs){let c=await Bl(e,a.digest),l=await gn(c,te.NOT_FOUND,"blob");Tl(l,a.digest,c)}return i}async function Al(e,t,n){let r={schemaVersion:Et,digest:hn(dt({schemaVersion:Et,entryIds:t,cursor:n})),entryIds:t,cursor:n};await vo(Ss(e),r)}function kl(e,t){if(t!==void 0&&e.digest!==t)throw new oe(te.INVALID_SCHEMA,`history index changed concurrently (expected ${t}, current ${e.digest})`)}async function ah(e){let t=hn(dt({schemaVersion:Et,entryIds:e.entryIds,cursor:e.cursor}));try{return await Al(e.rootDir,e.entryIds,e.cursor),await e.afterWrite?.(),await ut(e.rootDir)}catch(n){let r=await ut(e.rootDir).catch(()=>null);if(r?.digest===t)return r;throw r?.digest===e.previousDigest?n:new oe(te.INDEX_CORRUPT,"history index publish outcome is ambiguous",{cause:n})}}async function tw(e){await _e.mkdir(e,{recursive:!0}),await _e.mkdir(Ro(e),{recursive:!0}),await _e.mkdir(No(e),{recursive:!0}),await _e.mkdir(ko(e),{recursive:!0})}async function nw(e){await _e.rm(ko(e),{recursive:!0,force:!0}),await _e.mkdir(ko(e),{recursive:!0})}async function rw(e){let t=ko(e);await _e.mkdir(t,{recursive:!0});for(let n of await xs(t))n!=="stages"&&await _e.rm(Me.join(t,n),{recursive:!0,force:!0})}function ow(e){if(!wt(e))throw new oe(te.INDEX_CORRUPT,"index.json must be an object");if(e.schemaVersion!==Et)throw new oe(te.INVALID_SCHEMA,`unsupported index schemaVersion: ${String(e.schemaVersion)}`);let t=hh(e.entryIds,"index.entryIds"),n=e.cursor;if(!Number.isInteger(n)||n<-1||n>=t.length)throw new oe(te.INDEX_CORRUPT,"index cursor is out of bounds");let r=n,o=e.digest;if(!ft(o))throw new oe(te.INDEX_CORRUPT,"index digest is invalid");let i=hn(dt({schemaVersion:Et,entryIds:t,cursor:r}));if(o!==i)throw new oe(te.INDEX_CORRUPT,"index digest mismatch");return{schemaVersion:Et,digest:o,entryIds:t,cursor:r}}function iw(e){if(!wt(e))throw new oe(te.ENTRY_CORRUPT,"entry must be an object");if(e.schemaVersion!==Et)throw new oe(te.INVALID_SCHEMA,`unsupported entry schemaVersion: ${String(e.schemaVersion)}`);let t=e.id;if(!ft(t))throw new oe(te.ENTRY_CORRUPT,"entry id is invalid");let n=e.kind;if(typeof n!="string"||n.trim().length===0)throw new oe(te.ENTRY_CORRUPT,"entry kind is invalid");let r=Cl(e.manifest,"entry.manifest"),o=sw(e.blobs);return{id:t,schemaVersion:Et,kind:n,manifest:r,blobs:o}}function sw(e){if(!Array.isArray(e))throw new oe(te.ENTRY_CORRUPT,"entry blobs must be an array");return e.map((t,n)=>{if(!wt(t))throw new oe(te.ENTRY_CORRUPT,`entry blob ref ${n} must be an object`);let r=t.name;if(typeof r!="string"||r.trim().length===0)throw new oe(te.ENTRY_CORRUPT,`entry blob ref ${n} name is invalid`);let o=t.digest;if(!ft(o))throw new oe(te.ENTRY_CORRUPT,`entry blob ref ${n} digest is invalid`);let i=t.sizeBytes;if(!Number.isInteger(i)||i<0)throw new oe(te.ENTRY_CORRUPT,`entry blob ref ${n} sizeBytes is invalid`);return{name:r,digest:o,sizeBytes:i}})}async function vo(e,t){await gh(e,dt(t))}async function aw(e,t){let n=Me.dirname(e),r=Me.basename(e),o=Me.join(n,`.${r}.${process.pid}.${wl()}.tmp`);await _e.mkdir(n,{recursive:!0});try{await _e.writeFile(o,dt(t),{flag:"wx"}),await _e.rename(o,e)}finally{await ys(o)}}async function gh(e,t){let n=Me.dirname(e),r=Me.basename(e),o=Me.join(n,`.${r}.${process.pid}.${wl()}.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 Nl(n)}finally{await ys(o)}}function dt(e){return Buffer.from(JSON.stringify(Il(e)),"utf8")}function Il(e){if(Array.isArray(e))return e.map(t=>Il(t));if(wt(e)){let t={};for(let n of Object.keys(e).sort())t[n]=Il(e[n]);return t}return e}function Co(e,t){try{return JSON.parse(e)}catch(n){throw new oe(te.INVALID_JSON,`${t} is not valid JSON`,{cause:n})}}function Cl(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=>Cl(n,t));if(wt(e)){let n={};for(let[r,o]of Object.entries(e))n[r]=Cl(o,t);return n}break}throw new oe(te.INVALID_JSON,`${t} must be JSON-serializable`)}function hh(e,t){if(!Array.isArray(e))throw new oe(te.INDEX_CORRUPT,`${t} must be an array`);return e.map((n,r)=>{if(!ft(n))throw new oe(te.INDEX_CORRUPT,`${t}[${r}] is invalid`);return n})}function gs(e,t){if(!ft(e))throw new oe(te.INVALID_PATH,`${t} must be a sha256 digest`)}function ft(e){return typeof e=="string"&&/^sha256:[a-f0-9]{64}$/u.test(e)}function hn(e){return`sha256:${JN("sha256").update(e).digest("hex")}`}function cw(e){return typeof e=="string"?Buffer.from(e,"utf8"):Buffer.from(e)}async function gn(e,t,n){try{return await _e.readFile(e)}catch(r){throw new oe(t,`${n} not found: ${e}`,{cause:r})}}async function Rl(e){try{return await _e.readFile(e)}catch(t){if(wo(t))return null;throw t}}function Tl(e,t,n){if(hn(e)!==t)throw new oe(te.BLOB_CORRUPT,`blob hash mismatch for ${n}`)}async function rt(e){try{return await _e.access(e),!0}catch(t){if(wo(t))return!1;throw t}}async function ys(e){try{await _e.rm(e,{force:!0,recursive:!0})}catch{}}async function Nl(e){try{let t=await _e.open(e,"r");try{await t.sync()}finally{await t.close()}}catch{}}async function xs(e){try{return await _e.readdir(e)}catch(t){if(wo(t))return[];throw t}}function lw(e){if(typeof e!="string"||e.trim().length===0)throw new oe(te.INVALID_ROOT,"history store rootDir must be a non-empty string");return Me.resolve(e)}function Ss(e){return Me.join(e,zN)}function yl(e){return Me.join(e,HN)}function uw(e){return Me.join(e,WN)}function yh(e){return Me.join(e,GN)}async function ch(e){try{let t=await _e.readFile(yh(e),"utf8"),n=Co(t,"document version");if(!wt(n)||n.schemaVersion!==1||!Number.isInteger(n.version)||n.version<0)throw new oe(te.INVALID_SCHEMA,"document version schema is invalid");return n.version}catch(t){if(wo(t))return 0;throw t}}async function ps(e){let t=await gn(e,te.RECOVERY_PENDING,"transaction journal"),n=Co(Buffer.from(t).toString("utf8"),"transaction journal");return xh(n),n}function xh(e){if(!wt(e)||e.schemaVersion!==XN||typeof e.transactionId!="string"||e.transactionId.length===0||typeof e.operationId!="string"||e.operationId.length===0||!["prepared","files-written","history-published"].includes(e.phase)||!ZN(e.historyTransition)||!Array.isArray(e.files))throw new oe(te.INVALID_SCHEMA,"transaction journal schema is invalid");for(let t of e.files)if(!wt(t)||typeof t.path!="string"||t.path.length===0||t.preDigest!==null&&!ft(t.preDigest)||t.postDigest!==null&&!ft(t.postDigest))throw new oe(te.INVALID_SCHEMA,"transaction journal file digest is invalid")}function dw(e){return e.replace(/[\r\n]+/g," ").slice(0,512)}function Ro(e){return Me.join(e,"entries")}function No(e){return Me.join(e,"blobs")}function ko(e){return Me.join(e,"tmp")}function Fl(e){return Me.join(ko(e),"stages")}function _l(e,t){return Me.join(Fl(e),`${t}.json`)}function Ol(e,t){return Me.join(Ro(e),`${Eh(t)}.json`)}function Ml(e,t){return Me.join(No(e),Eh(t))}function Ll(e,t){return Me.join(Ro(e),`${t}.json`)}function Dl(e,t){return Me.join(No(e),t)}async function bh(e,t){return Sh(Ol(e,t),Ll(e,t))}async function Bl(e,t){return Sh(Ml(e,t),Dl(e,t))}async function Sh(e,t){return await rt(e)?e:await rt(t)?t:e}function Eh(e){return e.slice(7)}function lh(e){let t=e.startsWith("sha256:")?e:`sha256:${e}`;return ft(t)?t:null}function wt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function wo(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function fw(e){return{maxEntries:e?.maxEntries??ms.maxEntries,maxSessionBytes:e?.maxSessionBytes??ms.maxSessionBytes,maxEntryBytes:e?.maxEntryBytes??ms.maxEntryBytes}}async function pw(e){let t=Ss(e);await rt(t)||await Al(e,[],-1)}export{oe as FileHistoryStoreError,Kr as PageTemplateManagedSourceError,fs as PreviewFileSystemSiteEditEngineRuntime,_d as SITE_EDIT_RAW_COLOR_LITERAL_RE,us as SnapshotSiteEditEngineRuntime,_o as checkComponentI18nHostCompatibility,Cf as computeManagedPageTemplatePaths,UN as createPreviewSiteEditEngineRuntime,jN as createSiteEditEngineRuntime,vf as decodePageTemplateKey,Ua as encodePageTemplateId,py as instrumentSiteEditRuntimeAttributes,Rf as isManagedPageTemplateSourcePath,uh as openFileHistoryStore,Zh as parseSourceModule,Qh as resolveImportBase,Mv as resolveManagedPageTemplateComposition,Ri as scanManagedPageTemplateCandidates,wf as scanSiteEditCompositionsFromFiles,Mr as scanSiteEditThemeStyleViolations};
|